CREATE OR ALTER PROCEDURE [sExamination].[pSMSHistoryGetfordashboard]                   
 @rEmployeeId Bigint,               
 @rOrgId smallint                  
              
                 
WITH EXECUTE AS CALLER                
AS                
SET NOCOUNT ON                
                
BEGIN             
Declare @rEmail nvarchar(100) set @rEmail = (select Top 1 CompanyEmail from sHrm.tEmployeeCommunications where EmployeeId=@rEmployeeId)    
    
    if (LEN(@rEmail) > 0)
	BEGIN
 SELECT  top 15                 
  AL.Id AS Id1,                
   AL.ContactId,                
  AL.AlertMessage  AS 'AlertMessage',            
   AL.AlertSubject,                
   AL.ResultMessage,                
   CASE WHEN AL.EventId>0 THEN EM.Title                
   ELSE AL.EventName                
   END AS EventName,                
   AL.SourceEvent,                
   U.DisplayTitle AS UserName,                
 --CONVERT(VARCHAR(10), AL.CreatedDateTime, 103) AS CreatedDateTime  --//as diss time not required 0051173
   AL.CreatedDateTime AS CreatedDateTime  
 FROM                
   sAlert.tAlertLog AL                
  LEFT JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId                
  INNER JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId                    
 WHERE AL.ContactId LIKE '%' + @rEmail + '%'               
 AND ((AL.OrgId=@rOrgId) OR (@rOrgId=0))          
 ANd AL.AlertModeId=1              
  ORDER BY AL.CreatedDateTime desc    
  END
END

GO


INSERT INTO [sSecurity].[tScreenValidationFieldMaster] (ScreenId, FieldId, FieldName)
SELECT 9033, 67, 'Target Group'
WHERE NOT EXISTS (
    SELECT 1 FROM sSecurity.tScreenValidationFieldMaster 
    WHERE ScreenId = 9033 AND FieldId = 67
);

INSERT INTO [sSecurity].[tScreenValidationFieldMaster] (ScreenId, FieldId, FieldName)
SELECT 9033, 68, 'Planned Examination Date'
WHERE NOT EXISTS (
    SELECT 1 FROM sSecurity.tScreenValidationFieldMaster 
    WHERE ScreenId = 9033 AND FieldId = 68
);

go


CREATE OR ALTER VIEW [sExamination].[vExtPrescriptionDetail]
AS
SELECT        PD.Id, PD.PrescriptionId, PD.StockItemId AS DrugStockItemId, SIM.Code AS StockItemCode, SIM.Title AS StockItemTitle, PD.DrugInstruction, PD.Dosage, PD.Duration, PD.IsDispensed, PD.DispensedQuantity, 
                         PD.PrescribedQuantity, PD.IsNotInStore, PD.IsDirectIssue, PD.IsObsolete, SIM.StoreLocationId, PD.DrugDosageFrequencyId, PD.DrugDosageScheduleId, PD.DrugFrequencyPattern
FROM            sExamination.tPrescriptionDetail AS PD INNER JOIN
                         sIp.vExtStockItemMaster AS SIM ON PD.StockItemId = SIM.Id
GO

EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPane1', @value=N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "PD"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 136
               Right = 257
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "SIM"
            Begin Extent = 
               Top = 138
               Left = 38
               Bottom = 268
               Right = 245
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
' , @level0type=N'SCHEMA',@level0name=N'sExamination', @level1type=N'VIEW',@level1name=N'vExtPrescriptionDetail'
GO

EXEC sys.sp_addextendedproperty @name=N'MS_DiagramPaneCount', @value=1 , @level0type=N'SCHEMA',@level0name=N'sExamination', @level1type=N'VIEW',@level1name=N'vExtPrescriptionDetail'
GO



CREATE OR ALTER PROCEDURE [sExamination].[pAddRoundEmployeeAgeWise]
(
    @rEmployeeCodes NVARCHAR(MAX) = '',
    @rRoundId INT,
    @rOrgId INT,
    @rPlannedExaminationDate DATETIME = NULL,
    @rTargetGroupId INT = NULL
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @lNextDetailNumber BIGINT
    DECLARE @lInsertedCount INT = 0

    -- Get next number
    EXEC sCommon.pTableRowIdGet 
        @rOrgId, 
        'sExamination.tSetupEmployee', 
        0, 1, 1,
        @outNextNumber = @lNextDetailNumber OUTPUT

    -- INSERT
    INSERT INTO sExamination.tSetupEmployee
    (
        Id,
        SetupId,
        EmployeeId,
        OrgId,
        PlannedExaminationDate,
        TargetGroupId
    )
    SELECT 
        @lNextDetailNumber + ROW_NUMBER() OVER (ORDER BY EM.Id) AS Id,
        @rRoundId,
        EM.Id,
        @rOrgId,
        @rPlannedExaminationDate,
        @rTargetGroupId
    FROM sHrm.tEmployeeMaster EM
    WHERE 
    (
        EM.Code IN (SELECT item FROM sCommon.fnsplit(ISNULL(@rEmployeeCodes,''),',')) 
        OR ISNULL(@rEmployeeCodes,'') = ''
    )
    AND NOT EXISTS
    (
        SELECT 1 
        FROM sExamination.tSetupEmployee SE
        WHERE SE.SetupId = @rRoundId 
        AND SE.EmployeeId = EM.Id
    )

    -- Get inserted count
    SET @lInsertedCount = @@ROWCOUNT

    -- Update next number
    SET @lNextDetailNumber = ISNULL(@lInsertedCount, 0) + @lNextDetailNumber  

    EXEC sCommon.pTableRowIdModify 
        @rOrgId, 
        @rTableTitle = 'sExamination.tSetupEmployee', 
        @rCurrentNumber = @lNextDetailNumber

    SELECT 
        1 AS IsSuccess,
        'Employees added successfully' AS Message,
        @lInsertedCount AS InsertedCount

END

go


CREATE OR ALTER PROCEDURE [sExamination].[pLoadEmployeeAgeWiseListGet]
(  
@rOrgId int = 0,
@rLocationId int,
@rFromAge int = 0, 
@rToAge int = 0,
@rBirthMonth int = 0, 
@SortColumnName NVARCHAR(MAX)= '',
@IsAscendingOrder bit= 0,
@PageNumber int = 1,
@PageSize int = 20,
@GlobalSearch NVARCHAR(MAX)= ''
)
AS  
SET NOCOUNT ON  
BEGIN
  	;WITH PageNumbers AS(
	select 
	ROW_NUMBER() OVER(
			ORDER BY CASE WHEN @SortColumnName = 'EmployeeCode' AND @IsAscendingOrder = 0 THEN t.EmployeeCode END DESC,
					 CASE WHEN @SortColumnName = 'EmployeeCode' AND @IsAscendingOrder = 1 THEN t.EmployeeCode END,
					 CASE WHEN @SortColumnName = 'EmployeeName' AND @IsAscendingOrder = 0 THEN t.EmployeeName END DESC,
					 CASE WHEN @SortColumnName = 'EmployeeName' AND @IsAscendingOrder = 1 THEN t.EmployeeName END,
					 CASE WHEN @SortColumnName = 'CompanyEmail' AND @IsAscendingOrder = 0 THEN t.CompanyEmail END DESC,
					 CASE WHEN @SortColumnName = 'CompanyEmail' AND @IsAscendingOrder = 1 THEN t.CompanyEmail END,
					 CASE WHEN @SortColumnName = 'Age' AND @IsAscendingOrder = 0 THEN t.Age END DESC,
					 CASE WHEN @SortColumnName = 'Age' AND @IsAscendingOrder = 1 THEN t.Age END,
					 CASE WHEN @SortColumnName = 'Department' AND @IsAscendingOrder = 0 THEN t.Department END DESC,
					 CASE WHEN @SortColumnName = 'Department' AND @IsAscendingOrder = 1 THEN t.Department END,
					 CASE WHEN @SortColumnName = '' THEN t.EmployeeId END DESC
	) EID,
	COUNT(*) OVER() 'RecordCount',
	* from (
 SELECT EM.Id AS EmployeeId,  
 EM.Code AS EmployeeCode,  
 ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS EmployeeName,  
 95 AS ParticipantSourceTypeId,      
 JD.OrganizationDepartmentId AS OrganizationDepartmentId,  
 DM.Title AS Department, 
 A.Age AS Age, 
 ISNULL(EC.CompanyEmail,'') as CompanyEmail
 FROM   
 sHrm.tEmployeeMaster EM
 left join sHrm.tEmployeeJobDetail JD on JD.EmployeeId = EM.Id
 left join sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
 left join sCommon.tOrganizationDepartmentMaster DM on DM.Id = JD.OrganizationDepartmentId
 left join sHrm.tEmployeeCommunications EC on EC.EmployeeId = EM.Id
 CROSS APPLY (
    SELECT Age =
        DATEDIFF(YEAR, EPD.DateOfBirth, GETDATE()) 
        - CASE 
            WHEN DATEADD(YEAR, DATEDIFF(YEAR, EPD.DateOfBirth, GETDATE()), EPD.DateOfBirth) > GETDATE() 
            THEN 1 ELSE 0 
          END
) A
 WHERE EM.OrgId = @rOrgId AND EM.StatusId = 7
 AND JD.EmployeeLocationId = @rLocationId
 AND Isnull(EM.IsObsolete,0)=0
 AND (@rFromAge = 0 OR A.Age >= @rFromAge)
    AND (@rToAge = 0 OR A.Age <= @rToAge)
    AND (@rBirthMonth = 0 OR MONTH(EPD.DateOfBirth) = @rBirthMonth)
 ) t where  (ISNULL(@GlobalSearch,'') = '' OR ISNULL(t.EmployeeCode,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										   OR ISNULL(t.EmployeeName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										   OR ISNULL(t.CompanyEmail,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										   OR ISNULL(t.Age,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										   OR ISNULL(t.Department,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%')
	)
	SELECT  *
	FROM    PageNumbers
	WHERE  (@PageSize = -1 OR EID  BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize))
END

go


CREATE OR ALTER PROCEDURE [sExamination].[pRptOHCVisitSummary]
	@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 datetime = null,
	@rToDate datetime = null,
	@rOrgId int,
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeTypeGroupId int=0,
	@rEmployeeSubTypeId int=0,
	@rEmployeeGroupId int=0,
	@rOtherTypeId int=0,
	@rVisitPurposeIds varchar(max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
	SELECT distinct @rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	@rReportId AS ReportId,
EAED.Id as ExaminationId,
	convert(varchar(10),EAED.ExaminationDate,103) as VisitDate,
	
	EmployeeCode = CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
	EmployeeName = CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.FirstName + ' ' + isnull(EM.LastName,'')
	WHEN 1001 THEN EFD.Name WHEN 1009 THEN CASE WHEN isnull(O.OtherName,'') <> '' THEN O.OtherName ELSE BM.FirstName + ' ' + isnull(BM.LastName,'') END END,
	isnull(ODM.Title,'') AS DepartmentName,
	ISNULL(EDM.Title,'') AS Designation,
	ISNULL(ELE.Title,'') AS SectionWorkStation,
	COM.Remark as ChiefComplaint,
	
ISNULL(CAST(CAST(Temperature AS INT) AS VARCHAR(10)), '0') + ' / ' +
ISNULL(CAST(CAST(Pulse AS INT) AS VARCHAR(10)), '0') + ' / ' +
'(' + ISNULL(CAST(CAST(BloodPressureSystolic AS INT) AS VARCHAR(10)), '0') + ' / ' +
ISNULL(CAST(CAST(BloodPressureDiastolic AS INT) AS VARCHAR(10)), '0') + ')' + ' / ' +
ISNULL(CAST(CAST(V.SPo2 AS INT) AS VARCHAR(10)), '0') + ' / ' +
'0' AS Vital,

	V.Remark as ClinicalFindings,
	FAM.Code as FurtherActionCode,
	isnull(O.FurtherActionRemark,'') as FurtherActionRemark,
	(CASE WHEN CM.IsCustomLog = 1 THEN '' ELSE isnull(convert(varchar(10),SA.AppointmentDate,103),'') END) as FollowupDate, 
	isnull(SA.FollowupRemark,'') as FollowupRemark,

	case when EM5.StatusId <> 10 then     
 EM5.FirstName + ' ' + isnull(EM5.LastName,'')     
     
 else '' end as DoctorName, 
 
	EAED.CreatedDateTime,
	ParticipantType = CASE EAED.ParticipantSourceTypeId WHEN 95 THEN isnull(ETM.Title,'') WHEN 1001 THEN 'Dep'	WHEN 1009 THEN isnull(BTM.Title,'') END,
	case when EAED.ParticipantSourceTypeId = 1009 then    
 case when BM.DateOfBirth = '1900-01-01' then 0 else datediff(yy,BM.DateOfBirth,getdate()) end    
 when EAED.ParticipantSourceTypeId = 1001 then    
 case when EFD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EFD.DateOfBirth,getdate()) end else    
 case when EPD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EPD.DateOfBirth,getdate()) end end AS AGE,
	Gender = CASE EAED.ParticipantSourceTypeId
	WHEN 95 THEN GM1.Title
	WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
	WHEN 1009 THEN CASE WHEN isnull(O.GenderId,0) = 0 THEN GM2.Title ELSE (select Title from sCommon.tGenderMaster where Id = O.GenderId) END END,
	isnull(CM.Id,0) as CauseId,
	isnull(CM.Title,'') AS Cause,
	CL.Title+ ' '+'('+R.ContactPerson+')' as ClinicalSummary,
	[sExamination].[fn_GetEmployeePastHistory_String](@rOrgId,EAED.ParticipantSourceId,EAED.ParticipantSourceTypeId) AS RelevantHistory,

	[sExamination].[fExistingDiseaseGet](EAED.Id) AS ProvisionalDiagnosis,	
	 [sExamination].fn_GetPrescriptionDetails(EAED.Id) as TreatmentGiven,
	D.DoctorSignature AS DoctorSignature
	
	FROM sExamination.tExamination EAED
	INNER JOIN sSecurity.tUser U ON U.Id = EAED.CreatedUserID
	INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = EAED.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id
	INNER JOIN sIp.tStoreLocationMaster SLM on EAED.StoreLocationId = SLM.Id
	LEFT JOIN sCwb.tDoctorMaster D on EAED.DoctorEmployeeId = D.EmployeeId
	--LEFT JOIN sExamination.vExtPrescription P on EAED.Id = P.SourceId	
	--LEFT JOIN sExamination.vExtPrescriptionDetail PD on P.Id = PD.PrescriptionId AND (PD.IsObsolete = 0)
	--LEFT JOIN sIp.tDrugDosageFrequencyMaster DFM on DFM.id=PD.DrugDosageFrequencyId
	--LEFT JOIN sIp.tDrugScheduleMaster DSM on DSM.id=PD.DrugDosageScheduleId
	--LEFT JOIN sIp.tStockItemMaster SIM on PD.DrugStockItemId = SIM.Id
	
	LEFT JOIN sHrm.tEmployeeMaster EM on EAED.ParticipantSourceId = EM.Id and EAED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EAED.ParticipantSourceId = EFD.Id and EAED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id	
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on EAED.ParticipantSourceId = BM.Id and EAED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CsrBenefiterTypeId = BTM.Id
	LEFT JOIN sHrm.tEmployeeJobDetail EJD on EM.Id = EJD.EmployeeId
	LEFT JOIN sHrm.tEmployeeJobDetail EJD2 on EM2.Id = EJD2.EmployeeId
	LEFT JOIN sHrm.tEmployeeLegalEntitymaster ELE ON ELE.ID= EJD.LegalEntityId
	LEFT JOIN sHrm.tEmployeeDesignationMaster EDM on EDM.Id = EJD.EmployeeDesignationId
	LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM on EAED.OrganizationDepartmentId = ODM.Id
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON ODM.DepartmentGroupId = DGM.Id	
	LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id
	LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId
	LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id=EJD.ContractorId
	LEFT JOIN sProcurement.tVendorMaster VM2 ON VM.Id=EJD2.ContractorId
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
	
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = EAED.CauseId	
	LEFT JOIN sExamination.tReferral R ON R.SourceId=EAED.Id
	LEFT JOIN sCommon.tClinicMaster CL ON CL.Id=R.ReferToClinicId	
	LEFT JOIN sExamination.tOPD O ON O.ExaminationId = EAED.Id
	 left join sExamination.tVital V on EAED.Id = V.SourceId 
	 left join sExamination.tComplaint COM on COM.SourceId = EAED.Id 
	 left join sSafety.tFurtherActionMaster FAM ON FAM.Id = O.FurtherActionId
	 left join sAppointment.tAppointment SA on EAED.Id = SA.ReferSourceId  
	 left join sHrm.tEmployeeMaster EM5 on EM5.Id = EAED.DoctorEmployeeId 
	 left join sExamination.tAccidentLog A on EAED.Id = A.ExaminationId 

	WHERE STM.MainTypeId = 8 AND isnull(EAED.IsCancel,0) = 0
	AND (EAED.StoreLocationId = @rStoreLocationId)
	AND 
	(
		(EM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EM2.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(BM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1009)
		OR
		@rEmployeeCode = ''
	)
	AND (FM.Id = @rFunctionId OR @rFunctionId = 0)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND (EAED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND (EAED.GradeId=@rGradeId OR @rGradeId=0)
	AND (EAED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 
	AND
	(
		(EJD.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rJobTitleId = 0
	)
	AND
	(
		(EJD.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeId = 0
	)	
	AND
	(			
		(EJD.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rContractorId=0
	)
	AND (EAED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)
	AND
	(
		(EPD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EFD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		((BM.GenderId = @rGenderId or O.GenderId = @rGenderId) AND EAED.ParticipantSourceTypeId = 1009)
		OR @rGenderId=0
	)
	AND (EAED.EmployeeStatusId=@rStatusId OR @rStatusId=0)
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1009)
		OR ISNULL(@rAgeTo,0)=0
	)
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1009)			
		OR ISNULL(@rAgeFrom,0)=0
	)
	AND ((EAED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EAED.ExaminationDate < @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))
	AND (SLM.LocationId = @rLocationId) 
	AND (EAED.OrgId =  @rOrgId)
	AND (EAED.CauseId=@rCaseCauseId or @rCaseCauseId=0)
	AND (EAED.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)	
	AND (ISNULL(EAED.CauseId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rVisitPurposeIds,''),','))OR ISNULL(@rVisitPurposeIds,'')='')
	OPTION(RECOMPILE)
END

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 @lEnableConfigVal varchar(5);            
	select @lEnableConfigVal = sConfig.fConfigurationValueGet('OPD.PrescriptionFrequencyPattern',@rOrgId,0,0,0)  

	--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,

	CASE 
    WHEN @lEnableConfigVal = 'false' THEN 
        DFM.Title
    ELSE 
        ISNULL(EPD.DrugFrequencyPattern, '')
	END 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 @lEnableConfigVal = 'false' THEN 
        DFM.Title
    ELSE 
        ISNULL(OSPD.DrugFrequencyPattern, '')
	END 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


CREATE OR ALTER PROCEDURE [sExamination].[pValidateAgeWiseEmployeeRound]
(
    @rEmployeeCodes NVARCHAR(MAX) = '',
    @rRoundId INT
)
AS
BEGIN

    DECLARE @rRoundGroupId INT;

    SET @rRoundGroupId = (
        SELECT SetupGroupId 
        FROM sExamination.tSetupMaster 
        WHERE Id = @rRoundId
    );

    select EM.Code, EM.FirstName from sExamination.tSetupEmployee SE
	INNER JOIN sExamination.tSetupMaster SM ON SM.Id = SE.SetupId
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = SE.EmployeeId
	WHERE SM.SetupGroupId = @rRoundGroupId
	and (EM.Code in (SELECT item FROM  sCommon.fnsplit(ISNULL(@rEmployeeCodes,''),',')) OR ISNULL(@rEmployeeCodes,'')='');

END

GO


CREATE OR ALTER PROCEDURE [sExamination].[pVisitTypeMasterAdd] 
@rId int,
@rCode nvarchar(30),
@rTitle nvarchar(100),
@rIsObsolete bit,
@rOrgId smallint,
@rCreatedUserId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sExamination.tVisitTypeMaster where Code=@rCode AND (OrgId=@rOrgId OR OrgId=1))
		BEGIN
			select -102 as Result
			RETURN
		END 

		If Exists(select Id from sExamination.tVisitTypeMaster where Title=@rTitle AND (OrgId=@rOrgId OR OrgId=1))
		BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sExamination.tVisitTypeMaster where Code=@rCode AND (OrgId=@rOrgId OR OrgId=1) AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		
		If  Exists(select Id from sExamination.tVisitTypeMaster where Title=@rTitle AND (OrgId=@rOrgId OR OrgId=1) AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
	END
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN		
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sExamination.tVisitTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO sExamination.tVisitTypeMaster
		(
			Id,Code,Title,IsObsolete,OrgId,
			CreatedUserId,CreatedDateTime
		)
		VALUES
		(
			@lNextNumber,@rCode,@rTitle,@rIsObsolete,@rOrgId,
			@rCreatedUserId,sCommon.fGetDate()
		)

		SELECT 1 AS Result
	END
	ELSE
	BEGIN
		SET @lNextNumber = @rId
		UPDATE sExamination.tVisitTypeMaster 
		SET Code=@rCode,
		Title=@rTitle,
		UpdatedUserId=@rCreatedUserId,
		UpdatedDateTime=sCommon.fGetDate(),
		IsObsolete=@rIsObsolete
		WHERE Id = @rId
		SELECT 11 AS Result
	END
	COMMIT TRANSACTION
END


GO


CREATE OR ALTER PROCEDURE [sHospitalization].[pExportClaimIntimationBasedOnDate]         
@rOrgId int,        
@rFromDate varchar(50)='',        
@rToDate varchar(50)=''        
as        
begin  
    SELECT @rFromDate = case when @rFromDate <> '' then CONVERT(varchar(10), CONVERT(date, @rFromDate, 111), 23) else '' end        
    SELECT @rToDate = case when @rToDate <> '' then CONVERT(varchar(10), CONVERT(date, @rToDate, 111), 23) else '' end        
 --         DECLARE @DateDiff int = DATEDIFF(DAY, @rFromDate, @rToDate) + 1;      
 --IF(@DateDiff > 15)      
 --BEGIN      
 -- Select 'Please select a date range within 15 days!' AS Result      
 -- Return;      
 --END      
    DECLARE @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;                      
      
    IF OBJECT_ID('tempdb..#tblIntimationAll') IS NOT NULL          
        DROP TABLE #tblIntimationAll        
            
    -- Use column names WITHOUT spaces or special characters for dynamic SQL compatibility      
    create table #tblIntimationAll          
    (          
        tid int identity(1,1),      
        AGE int,      
        BENEFICIARY_NAME varchar(max),      
        CLAIM_TYPE varchar(max),      
        DATE_OF_INTIMATION varchar(max),      
        LIKELY_DT_OF_ADMISSION varchar(max),      
        DT_OF_DISCHARGE varchar(max),      
        DT_OF_FILE_RECD varchar(max),      
        EMPLOYEE_NO varchar(max),      
        FIR_NO varchar(max),      
        GRADE varchar(max),      
        HOSPITAL_NAME varchar(max),      
        INTIMATION_NO varchar(max),      
  MESSAGE  varchar(max),      
        CONTACT1 varchar(max),      
        NATURE_OF_ILLNESS varchar(max),      
        NETWORK_CITY varchar(max),      
        PROPOSER_NAME varchar(max),      
        RELATION varchar(max),      
        STATE varchar(max),      
        STATUS_OF_INTIMATION varchar(max),      
        TPA_CARD_NO varchar(max),      
        TREATING_DOCTOR varchar(max),      
        TYPE_OF_INTIMATION varchar(max),      
        Doctors_Remarks_Comments varchar(max),      
        DoctorRemarksJSON nvarchar(max),      
        Current_Status varchar(max),      
        ASSIGNED_DOCTOR varchar(max)      
    )        
          
    -- Insert based on which table to use for Assigned Doctor      
    IF @UseNewTable = 1      
    BEGIN      
        -- Using NEW table: sHospitalization.tClaimIntimationAssignedDoctor for doctor assignment      
        insert into #tblIntimationAll        
        select       
            ISNULL(td.Age, 0) as AGE,      
            ISNULL(td.BeneficiaryName, '') as BENEFICIARY_NAME,      
            ISNULL(td.ClaimType, '') as CLAIM_TYPE,      
            ISNULL(convert(varchar, td.DateOfIntimation, 103), '') as DATE_OF_INTIMATION,      
            ISNULL(convert(varchar, td.DateOfAdmission, 103), '') as LIKELY_DT_OF_ADMISSION,      
            ISNULL(convert(varchar, td.DateOfDischarge, 103), '') as DT_OF_DISCHARGE,      
            ISNULL(convert(varchar, td.DateOfFileRecord, 103), '') as DT_OF_FILE_RECD,      
            ISNULL(td.EmpCode, '') as EMPLOYEE_NO,      
            ISNULL(td.FIRNo, '') as FIR_NO,      
            ISNULL(td.Grade, '') as GRADE,      
            ISNULL(td.HospitalName, '') as HOSPITAL_NAME,      
            ISNULL(td.IntimationNumber, '') as INTIMATION_NO,      
   ISNULL(td.Message, '') as MESSAGE,      
            ISNULL(td.mobile1, '') as CONTACT1,      
            ISNULL(td.NatureOfIllness, '') as NATURE_OF_ILLNESS,      
            ISNULL(td.NetworkCity, '') as NETWORK_CITY,      
            ISNULL(td.ProposerName, '') as PROPOSER_NAME,      
            ISNULL(td.Relation, '') as RELATION,      
            ISNULL(td.State, '') as STATE,      
            ISNULL(td.statusofintimation, '') as STATUS_OF_INTIMATION,      
            ISNULL(td.tpacardno, '') as TPA_CARD_NO,      
            ISNULL(td.TreatingDoctor, '') as TREATING_DOCTOR,      
            ISNULL(td.typeofintimation, '') as TYPE_OF_INTIMATION,      
            -- Get all remarks as comma separated with date      
            STUFF((SELECT CHAR(10) + CHAR(13) + '[' + CONVERT(varchar, 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, 2, '') as Doctors_Remarks_Comments,      
            -- Get all remarks as JSON with formatted date      
            (      
                SELECT       
                    R.Id,                            
                    R.Remark,      
                    CONVERT(varchar, R.CreatedDateTime, 103) AS CreatedDateTime,                            
                    R.CreatedUserId      
                FROM [sHospitalization].[tIntimationRemark] R                      
                WHERE R.HospitalizationIntimationDetailId = td.Id                      
                ORDER BY R.CreatedDateTime DESC                      
                FOR JSON PATH      
            ) as DoctorRemarksJSON,      
            ISNULL(td.TicketStatus, '') as Current_Status,      
            ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') as ASSIGNED_DOCTOR      
        from sHospitalization.tIntimationDetails td      
        LEFT JOIN [sHospitalization].[tClaimIntimationAssignedDoctor] AD       
            ON td.AssignedDoctorId = AD.DoctorEmployeeId AND AD.IsObsolete = 0          
        LEFT JOIN [sHrm].[tEmployeeMaster] EM       
            ON AD.DoctorEmployeeId = EM.Id AND EM.IsObsolete = 0          
        where td.OrgId = @rOrgId      
            --and (datediff(day, @rFromDate, td.DateOfIntimation) >= 0 or isnull(@rFromDate, '') = '')          
            --and (datediff(day, td.DateOfIntimation, @rToDate) >= 0 or isnull(@rToDate, '') = '')      
			 and (
                (datediff(day, @rFromDate, td.createddatetime) >= 0 or isnull(@rFromDate, '') = '')
                and (datediff(day, td.createddatetime, @rToDate) >= 0 or isnull(@rToDate, '') = '')
            )
            or (
                (datediff(day, @rFromDate, td.UpdatedDateTime) >= 0 or isnull(@rFromDate, '') = '')
                and (datediff(day, td.UpdatedDateTime, @rToDate) >= 0 or isnull(@rToDate, '') = '')
            )
            and ISNULL(td.IsObsolete, 0) = 0      
        order by td.Id asc      
    END      
    ELSE      
    BEGIN      
        -- Using OLD table: sHospitalization.tIntimationAssignedDoctor for doctor assignment      
        insert into #tblIntimationAll        
        select       
            ISNULL(td.Age, 0) as AGE,      
            ISNULL(td.BeneficiaryName, '') as BENEFICIARY_NAME,      
            ISNULL(td.ClaimType, '') as CLAIM_TYPE,      
            ISNULL(convert(varchar, td.DateOfIntimation, 103), '') as DATE_OF_INTIMATION,      
            ISNULL(convert(varchar, td.DateOfAdmission, 103), '') as LIKELY_DT_OF_ADMISSION,      
            ISNULL(convert(varchar, td.DateOfDischarge, 103), '') as DT_OF_DISCHARGE,      
            ISNULL(convert(varchar, td.DateOfFileRecord, 103), '') as DT_OF_FILE_RECD,      
            ISNULL(td.EmpCode, '') as EMPLOYEE_NO,      
            ISNULL(td.FIRNo, '') as FIR_NO,      
            ISNULL(td.Grade, '') as GRADE,      
            ISNULL(td.HospitalName, '') as HOSPITAL_NAME,      
            ISNULL(td.IntimationNumber, '') as INTIMATION_NO,      
   ISNULL(td.Message, '') as MESSAGE,      
            ISNULL(td.mobile1, '') as CONTACT1,      
            ISNULL(td.NatureOfIllness, '') as NATURE_OF_ILLNESS,      
            ISNULL(td.NetworkCity, '') as NETWORK_CITY,      
            ISNULL(td.ProposerName, '') as PROPOSER_NAME,      
            ISNULL(td.Relation, '') as RELATION,      
            ISNULL(td.State, '') as STATE,      
            ISNULL(td.statusofintimation, '') as STATUS_OF_INTIMATION,      
            ISNULL(td.tpacardno, '') as TPA_CARD_NO,      
            ISNULL(td.TreatingDoctor, '') as TREATING_DOCTOR,      
            ISNULL(td.typeofintimation, '') as TYPE_OF_INTIMATION,      
            -- Get all remarks as formatted text with date      
            STUFF((SELECT CHAR(10) + CHAR(13) + '[' + CONVERT(varchar, 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, 2, '') as Doctors_Remarks_Comments,      
            -- Get all remarks as JSON with formatted date      
            (      
                SELECT       
                    R.Id,                            
                    R.Remark,      
                    CONVERT(varchar, R.CreatedDateTime, 103) AS CreatedDateTime,                            
                    R.CreatedUserId      
                FROM [sHospitalization].[tIntimationRemark] R                      
                WHERE R.HospitalizationIntimationDetailId = td.Id                      
                ORDER BY R.CreatedDateTime DESC                      
                FOR JSON PATH      
            ) as DoctorRemarksJSON,      
            ISNULL(td.TicketStatus, '') as Current_Status,      
            ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') as ASSIGNED_DOCTOR      
        from sHospitalization.tIntimationDetails td      
        LEFT JOIN [sHospitalization].[tIntimationAssignedDoctor] AD       
            ON td.AssignedDoctorId = AD.DoctorEmployeeId AND AD.IsObsolete = 0          
        LEFT JOIN [sHrm].[tEmployeeMaster] EM       
            ON AD.DoctorEmployeeId = EM.Id AND EM.IsObsolete = 0          
        where td.OrgId = @rOrgId      
            --and (datediff(day, @rFromDate, td.DateOfIntimation) >= 0 or isnull(@rFromDate, '') = '')          
            --and (datediff(day, td.DateOfIntimation, @rToDate) >= 0 or isnull(@rToDate, '') = '')    
			 and (
                (datediff(day, @rFromDate, td.createddatetime) >= 0 or isnull(@rFromDate, '') = '')
                and (datediff(day, td.createddatetime, @rToDate) >= 0 or isnull(@rToDate, '') = '')
            )
            or (
                (datediff(day, @rFromDate, td.UpdatedDateTime) >= 0 or isnull(@rFromDate, '') = '')
                and (datediff(day, td.UpdatedDateTime, @rToDate) >= 0 or isnull(@rToDate, '') = '')
            )
            and ISNULL(td.IsObsolete, 0) = 0      
        order by td.Id asc      
    END      
        
    -- Check if API fields mapping exists for INTIMATION type      
    Declare @rIntimationAPIFieldCount int;        
    select @rIntimationAPIFieldCount = (select Count(Id) from [sExamination].[tExaminationAPIFieldsMapping] where IsObsolete = 0 and IsEnable = 1 and ExaminationType = 'Claim Intimation')        
          
    IF @rIntimationAPIFieldCount > 0        
    BEGIN        
        DECLARE @FinalResult NVARCHAR(MAX);        
        DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX);        
          
        -- Build column list with proper aliases matching temp table      
        SELECT @cols = STUFF((SELECT ',' + QUOTENAME(Fields)         
            FROM [sExamination].[tExaminationAPIFieldsMapping]        
            WHERE IsObsolete = 0 AND IsEnable = 1 and ExaminationType = 'Claim Intimation'        
            FOR XML PATH(''), TYPE        
            ).value('.', 'NVARCHAR(MAX)')         
            ,1,1,'')        
          
        -- Replace the problematic column names with actual temp table column names      
        SET @cols = REPLACE(@cols, '[Dr''s Remarks / Comments]', '[Doctors_Remarks_Comments]')      
        SET @cols = REPLACE(@cols, '[Current Status]', '[Current_Status]')      
        SET @cols = REPLACE(@cols, '[Assigned Doctor]', '[ASSIGNED_DOCTOR]')      
          
        SET @FinalResult = 'Select ' + @cols + ' FROM #tblIntimationAll';        
        EXEC sp_executesql @FinalResult;        
    END        
    ELSE        
    BEGIN        
        SELECT       
            ISNULL(AGE, 0) AS [AGE],      
            ISNULL(BENEFICIARY_NAME, '') AS [BENEFICIARY_NAME],      
            ISNULL(CLAIM_TYPE, '') AS [CLAIM_TYPE],      
            ISNULL(DATE_OF_INTIMATION, '') AS [DATE_OF_INTIMATION],      
            ISNULL(LIKELY_DT_OF_ADMISSION, '') AS [LIKELY_DT_OF_ADMISSION],      
            ISNULL(DT_OF_DISCHARGE, '') AS [DT_OF_DISCHARGE],      
            ISNULL(DT_OF_FILE_RECD, '') AS [DT_OF_FILE_RECD],      
            ISNULL(EMPLOYEE_NO, '') AS [EMPLOYEE_NO],      
            ISNULL(FIR_NO, '') AS [FIR_NO],      
            ISNULL(GRADE, '') AS [GRADE],      
            ISNULL(HOSPITAL_NAME, '') AS [HOSPITAL_NAME],      
            ISNULL(INTIMATION_NO, '') AS [INTIMATION_NO],      
   ISNULL(MESSAGE, '') AS [MESSAGE],      
            ISNULL(CONTACT1, '') AS [CONTACT1],      
            ISNULL(NATURE_OF_ILLNESS, '') AS [NATURE_OF_ILLNESS],      
            ISNULL(NETWORK_CITY, '') AS [NETWORK_CITY],      
            ISNULL(PROPOSER_NAME, '') AS [PROPOSER_NAME],      
            ISNULL(RELATION, '') AS [RELATION],      
            ISNULL(STATE, '') AS [STATE],      
            ISNULL(STATUS_OF_INTIMATION, '') AS [STATUS_OF_INTIMATION],      
            ISNULL(TPA_CARD_NO, '') AS [TPA_CARD_NO],      
            ISNULL(TREATING_DOCTOR, '') AS [TREATING_DOCTOR],      
            ISNULL(TYPE_OF_INTIMATION, '') AS [TYPE_OF_INTIMATION],      
            ISNULL(Doctors_Remarks_Comments, '') AS [Dr's Remarks / Comments],      
            ISNULL(DoctorRemarksJSON, '') AS [DoctorRemarksJSON],      
            ISNULL(Current_Status, '') AS [Current Status],      
            ISNULL(ASSIGNED_DOCTOR, '') AS [Assigned Doctor]      
        FROM #tblIntimationAll        
    END        
END

Go


CREATE OR ALTER PROCEDURE [sIncident].[pRptInjuryReport]
@FromDate datetime = null,
@ToDate datetime = null,
@ReportTypeId bigint = 0,
@SubLocationId bigint = 0,
@EmployeeCode nvarchar(50) = null,
@DepartmentId bigint = 0,
@BodyPartId bigint = 0,      
@DesignationId bigint =0,
@EmployeeTypeId bigint = 0,     	
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='',   
@orgid int,
@Company int=0,
@EmployeeName nvarchar(50) = null,
@CodeLike nvarchar(300) = null,
@UserId BIGINT,
@VisitPurpose int = 0
AS
SET NOCOUNT ON
BEGIN
	
	
SELECT ExaminationId,ExaminationDate,EmployeeName,EmployeeCode,DepartmentName,IncidentTime,IncidentDate,ReportingTime,ReportingDate,age,Gender,DoctorName,DoctorSignature,DoctorCode,
[TM Name (CAPS)] AS TMNameCAPS,
    [TM No] AS TMNo,
    [TKM Experience] AS TKMExperience,
    [Process Experience] AS ProcessExperience,
    [Shift] AS Shift,
    [Process/Line name] AS ProcessLineName,
    [TM/Apprentice/Contractor/ GAT/DAT] AS TMType,
    [Contract name (CAPS)] AS ContractNameCAPS,
    [Supervisor Name (CAPS)] AS SupervisorNameCAPS,
    [Supervisor mobile no] AS SupervisorMobileNo,
    [Member mobile No] AS MemberMobileNo,
    [Shop Manager Name] AS ShopManagerName,
    [Shop DGM Name] AS ShopDGMName,
    [How Accident occurred?] AS HowAccidentOccurred,
    [Injury details] AS InjuryDetails,
    [Injured part (in words)] AS InjuredPart,
    [Treatment detail] AS TreatmentDetail,
    [Outside hospital referred. ?] AS OutsideHospitalReferred,
    [Reason?] AS Reason,
    [Outside hospital detail: (Hospital Name / Contact Number)] AS OutsideHospitalDetail,
    [Treatment/Other update details from outside hospital, If any] AS OutsideTreatmentDetails,
    [Details regarding post-accident conditions of the member] AS PostAccidentCondition
FROM
(
SELECT Distinct IA.Id,IA.ExaminationId,
convert(varchar(10),EAED.ExaminationDate,103) as ExaminationDate,
	--case isnull(IA.ParticipantSourceTypeId,95) when 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')
	--else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end AS EmployeeName,

	CASE IA.ParticipantSourceTypeId WHEN 1009 THEN
	CASE WHEN isnull(O.OtherName,'')='' THEN
	isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') ELSE O.OtherName END
	WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END  AS EmployeeName,

	case isnull(IA.ParticipantSourceTypeId,95) when 95 then EM.Id else CS.Id end AS EmployeeId,
	case isnull(IA.ParticipantSourceTypeId,95) when 95 then isnull(EM.Code,'') else isnull(CS.Code,'') end AS EmployeeCode,	
	IA.IncidentTime,
	convert(varchar(10),IA.IncidentDate,103) as IncidentDate,
	IA.PlaceofIncident,
	ITM.Title AS IncidentType,IA.IncidentTypeId
	,IA.ReportingTime,
	convert(varchar(10),IA.ReportingDate,103) as ReportingDate,
	IA.IncidentRemark,IA.TreatmentRemark,	
    case isnull(IA.ParticipantSourceTypeId,95) when 95 then 'Employee' else 'Other' end AS EmployeeType,
	CM.Title AS Cause,
	
	ISNULL(ODM.Title,'') As DepartmentName,
	case when IA.BodySideId =4 then '' Else Isnull(BSM.Title,'') End + ' ' + eb.Title As BodyPart,	

	D.DoctorSignature AS DoctorSignature,
	(EM2.FirstName + ' ' + EM2.LastName) as DoctorName,
	EM2.Code as DoctorCode,

		case when EAED.ParticipantSourceTypeId = 1009 then    
 case when CS.DateOfBirth = '1900-01-01' then 0 else datediff(yy,CS.DateOfBirth,getdate()) end    
 when EAED.ParticipantSourceTypeId = 1001 then    
 case when EFD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EFD.DateOfBirth,getdate()) end else    
 case when EPD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EPD.DateOfBirth,getdate()) end end AS AGE,
	Gender = CASE EAED.ParticipantSourceTypeId
	WHEN 95 THEN GM1.Title
	WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
	WHEN 1009 THEN CASE WHEN isnull(O.GenderId,0) = 0 THEN GM2.Title ELSE (select Title from sCommon.tGenderMaster where Id = O.GenderId) END END,
	
	InS.FieldRemark,
        ALF.AccidentLogFieldResponse
	From sIncident.tAccident IA
	LEFT JOIN sSafety.tIncidentTypeMaster ITM ON ITM.Id=IA.IncidentTypeId
	LEFT JOIN sHrm.tEmployeeMaster EM ON IA.EmployeeId=EM.Id AND isnull(IA.ParticipantSourceTypeId,95) = 95
	LEFT JOIN sHrm.tCsrBenefiterMaster CS ON IA.EmployeeId=CS.Id AND IA.ParticipantSourceTypeId = 1009	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
	Inner join sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id=EJD.OrganizationDepartmentId
	LEFT JOIN sExamination.tExamination EAED ON EAED.Id=IA.ExaminationId 
	LEFT Join sHrm.tEmployeeCompanyMaster ECM On ECM.id=EJD.EmployeeCompanyId
	LEFT Join sHrm.tEmployeeCompanyMaster ECM1 On ECM1.id=EAED.EmployeeCompanyId
	 LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EAED.ParticipantSourceId = EFD.Id and EAED.ParticipantSourceTypeId = 1001
	LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = CS.GenderId
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = EAED.CauseId
		LEFT JOIN sExamination.tOPD O ON O.ExaminationId = EAED.Id
	left JOIN sSecurity.tUser U ON U.Id = EAED.CreatedUserID		
	LEFT JOIN sCommon.tCompanyInformationDetail CID on EAED.OrgId = CID.orgid
	LEFT join sSafety.tBodyPartMaster eb on eb.Id = IA.BodyPartId
	left join sSafety.tBodySideMaster BSM On BSM.id=IA.BodySideId	
	left join sExamination.vExtEmployeeExaminationDetail EED ON EAED.Id = EED.ExaminationId
	LEFT JOIN sExamination.tAccidentLog AL ON IA.SourceId=AL.Id	
	LEFT JOIN [sExamination].[tAccidentLogField] ALF ON ALF.ACCIDENTLOGID=AL.ID
	LEFT JOIN sSafety.tIncidentSetup InS ON  InS.Id= ALF.IncidentSetupId 
	LEFT JOIN sHrm.tEmployeeMaster EM2 ON EAED.DoctorEmployeeId=EM2.Id
    LEFT JOIN sCwb.tDoctorMaster D on d.EmployeeId = EM2.Id
   
	
		WHERE (IA.StoreLocationId=@SubLocationId or (
			@SubLocationId = 0
			AND
			IA.StoreLocationId IN (
				select LM.LocationId from sIp.tStoreLocationMaster LM 
				INNER JOIN [sSecurity].[tUserLocation] UL ON UL.StoreLocationId = LM.Id 
				where IsObsolete = 0 AND OrgId = @orgid AND UL.UserId = @UserId 
			)
		)
	)
	and isnull(EAED.iscancel,0) = 0
	and (EM.Code = @EmployeeCode or @EmployeeCode = '')
	and (EJD.OrganizationDepartmentId =@DepartmentId or @DepartmentId = 0)
	and (IA.BodyPartId =@BodyPartId or @BodyPartId = 0)
	and (EJD.EmployeeTypeId =@EmployeeTypeId or @EmployeeTypeId = 0)
	and ((IA.IncidentDate >= @FromDate) OR (ISNULL(@FromDate,'') = ''))
	and ((IA.IncidentDate <= @ToDate) OR (ISNULL(@ToDate,'') = ''))
	and (EJD.EmployeeDesignationId =@DesignationId or @DesignationId = 0)
	and (IA.EmployeeCompanyid= @Company or @Company=0)
	and ((EED.ParticipantName Like @EmployeeName +'%' ) or (ISNULL(@EmployeeName,'') = ''))
	and 
	(	
		exists (
			SELECT 1 FROM sCommon.fnsplit(@CodeLike, ',') AS SplitValues 
			WHERE LTRIM(RTRIM(ISNULL(SplitValues.item, ''))) <> '' 
			AND EM.Code = LTRIM(RTRIM(SplitValues.item))
		)
		or ISNULL(@CodeLike, '') = ''
	)
	and ((EAED.CauseId = @VisitPurpose) OR @VisitPurpose = 0)
	
	
	) AS src
PIVOT
(
    MAX(AccidentLogFieldResponse)
    FOR FieldRemark IN (
        [TM Name (CAPS)],
		[TM No],
		[TKM Experience],
		[Process Experience],
		[Shift],
		[Process/Line name],
		[TM/Apprentice/Contractor/ GAT/DAT],
		[Contract name (CAPS)],
		[Supervisor Name (CAPS)],
		[Supervisor mobile no],
		[Member mobile No],
		[Shop Manager Name],
		[Shop DGM Name],
		[How Accident occurred?],
		[Injury details],
		[Injured part (in words)],
		[Treatment detail],
		[Outside hospital referred. ?],
		[Reason?],
		[Outside hospital detail: (Hospital Name / Contact Number)],
		[Treatment/Other update details from outside hospital, If any],
		[Details regarding post-accident conditions of the member]
    )
) AS pvt

	--ORDER BY IA.IncidentDate DESC
END

GO


CREATE OR ALTER PROCEDURE [sIp].[pStockItemForPrescriptionGet]
@rOrgId int,
@rStockitemName Nvarchar(50) = '',
@rSubgroupCode Nvarchar(50) = '' ,	 
@rLocationId int,
@rSubGroupId int,
@rStockItemCategoryId int,
@rUserId bigint = null,
@rStoreLocationId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN
		Select id,code,(StockItemName+' - (' + convert(varchar,Isnull(Quantity,'0'))+')')as StockItemName,
		StockItemName as StockItemTitle, DrugInstruction,DrugInstructionId,
		Dosage,IsNotInstore,IsAllowDirectIssue,Remark,ItemSubGroupId,StockItemCategoryId,IsGroupItem
		From(
		SELECT SIM.Id,SIM.Code,SIM.Title AS StockItemName,
		ISNULL(DI.Title,'') AS DrugInstruction,
		ISNULL(SIM.DrugInstructionId,0) AS DrugInstructionId,
		ISNULL(DI.Dosage,0) AS Dosage,SIM.IsNotInstore,
		SIM.IsAllowDirectIssue,SIM.Remark,
		SIM.ItemSubGroupId,SIM.StockItemCategoryId,
		(SELECT ISNULL(SUM(AvailableQuantity),0) FROM sProcurement.tStockBatch SB 
		WHERE SB.StockItemId = SIM.Id 
		AND ((SB.StorelocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
		and AvailableQuantity > 0 ) AS Quantity,Isnull(SIM.IsGroupItem,0) as IsGroupItem
		FROM sIp.tStockItemMaster SIM 
		INNER JOIN sIp.tItemSubGroupMaster SGM ON SGM.Id = SIM.ItemSubGroupId 
		LEFT JOIN sExamination.tDrugInstructionMaster DI ON DI.Id = SIM.DrugInstructionId
		--Inner join sProcurement.tStockBatch SB on SIM.Id=SB.StockItemId
		Where SIM.OrgId = @rOrgId AND SIM.IsObsolete = 0 
		AND SIM.IsDrug = 1 AND SIM.IsBlockedForIssue = 0
		--Developer: Deval, Date: 12/10/2023, Added Inhouse and RX
		AND ((@rStockitemName = 'InHouse' AND SIM.IsNotInstore = 0) OR (@rStockitemName = 'RX' AND SIM.IsNotInstore = 1) 
		OR (SIM.Title LIKE @rStockitemName + '%' ) OR (ISNULL(@rStockitemName, '') = ''))
		--AND ((SIM.Title LIKE @rStockitemName + '%' ) OR (ISNULL(@rStockitemName, '') = '')) 
		AND ((SGM.Code LIKE @rSubgroupCode) OR (ISNULL(@rSubgroupCode, '') = ''))
		AND (SIM.LocationId = @rLocationId) AND ((SIM.ItemSubGroupId = @rSubGroupId) or @rSubGroupId = -1)
		AND ((SIM.StockItemCategoryId = @rStockItemCategoryId) or @rStockItemCategoryId = -1)
		AND SIM.StockItemCategoryId not in (select ItemCategoryId from sSecurity.tUserRestrictItemCategory where UserId = @rUserId)
		)as Final
		order by Final.StockItemName
	END
END

go


CREATE OR ALTER PROCEDURE [sSecurity].[pGetScreenValidationList]
    @ScreenId INT,
	@rOrgId INT
AS
BEGIN
BEGIN TRANSACTION;

	SELECT 
		SVFM.FieldId,
		SVFM.FieldName,
		S.Id as ScreenId,
		S.Title as ScreenName,
		Isnull(IsShow,0) as IsShow,
		Isnull(IsMandatory,0) as IsMandatory
	FROM sSecurity.tScreenValidationFieldMaster SVFM 
		LEFT JOIN sSecurity.tScreenValidation SV on SVFM.FieldId = SV.FieldId AND SV.OrgId = @rOrgId
		INNER JOIN sSecurity.tScreen S on  S.Id = SVFM.ScreenId
	WHERE (@ScreenId IS NULL OR @ScreenId = 0 OR SVFM.ScreenId = @ScreenId OR SVFM.ScreenId = 0);

COMMIT TRANSACTION;
END 

Go


IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 79)
BEGIN
    INSERT INTO [sAlert].[tEventMaster] 
    (Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
    VALUES 
    ('79', '215', 'Counselling Request', '', '', '[SendBy],[ReceivedBy]', '0', '0', NULL, NULL, '1', '0');
END
ELSE
BEGIN
    SELECT '79 Already Exists'
END

IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 77)
BEGIN
    INSERT INTO [sAlert].[tEventMaster] 
    (Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
    VALUES 
    ('77', '215', 'Counselling Done', '', '', '[SendBy],[ReceivedBy],[Remark],[CounsellingDate]', '0', '0', NULL, NULL, '1', '0');
END
ELSE
BEGIN
    SELECT '77 Already Exists'
END

IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 78)
BEGIN
    INSERT INTO [sAlert].[tEventMaster] 
    (Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
    VALUES 
    ('78', '215', 'Refer To Doctor', '', '', '[SendBy],[ReceivedBy]', '0', '0', NULL, NULL, '1', '0');
END
ELSE
BEGIN
    SELECT '78 Already Exists'
END

IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 93)
BEGIN
INSERT INTO [sAlert].[tEventMaster] 
(Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
VALUES 
(93, 217, 'Pathology', '','', '[EmpName],[DoctorName]', 0, 0, NULL, 'Pathology Report', 1, 0);
END
ELSE
BEGIN
    SELECT '93 Already Exists'
END

IF NOT EXISTS (SELECT 1 FROM [sAlert].[tEventMaster] WHERE Id = 101)
BEGIN
    INSERT INTO [sAlert].[tEventMaster]
           ([Id],[ModuleId],[Title],[Remark],[ViewName],[Fields],[IsShowRoleBasedOnFunctionality],[IsObsolete],[Template],[MailSubject],[IsAllowAutoSend],[IsSubscribe])
     VALUES
           (101,150,'Occupational Report Approval','Occupational Report Approval','Occupational Report Approval','[NextUserName],[ApproverName],[ReportCode]',0,0,NULL,NULL,1,0);
END
ELSE
BEGIN
    SELECT '101 Already Exists';
END

IF NOT EXISTS (SELECT 1 FROM [sAlert].[tEventMaster] WHERE Id = 102)
BEGIN
    INSERT INTO [sAlert].[tEventMaster]
           ([Id],[ModuleId],[Title],[Remark],[ViewName],[Fields],[IsShowRoleBasedOnFunctionality],[IsObsolete],[Template],[MailSubject],[IsAllowAutoSend],[IsSubscribe])
     VALUES
           (102,150,'Occupational Report Approval For Reporter','Occupational Report Approval For Reporter','Occupational Report Approval For Reporter','[Action],[ReporterName],[ApproverName],[ReportCode]',0,0,NULL,NULL,1,0);
END
ELSE
BEGIN
    SELECT '102 Already Exists';
END
IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 106)
BEGIN
    INSERT INTO [sAlert].[tEventMaster] 
    (Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
    VALUES 
    ('106', '203', 'Send Export Diagnosis Search', '', '', '[UserName]', '0', '0', NULL, NULL, '0', '0');
END
ELSE
BEGIN
    SELECT '106 Already Exists';
END
update [sAlert].[tEventMaster] set fields='[IncidentDate],[IncidentTime],[ReportingDate],[ReportingTime],[Unit],[PlaceofIncident],[IncidentRemark],[NatureAndExtentOfInjury],[ActivityWhileAccident],[PPEUsed],[TransportationToOHC],[TransportationFromOHC],[Cause],[BodyPart],[BodySide],[IncidentType],[LegalPoint],[Shift],[FurtherAction],[TreatmentType],
[TreatmentGivenRemark],[Code],[Name],[Age],[Company],[Department],[Designation],[VisitPurpose],[Sublocation],[DynamicFields]' where id=27

IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 107)
BEGIN
    INSERT INTO [sAlert].[tEventMaster] 
    (Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
    VALUES 
    ('107', '203', 'Send Export Employee Health Index Parameter', '', '', '[UserName]', '0', '0', NULL, NULL, '1', '0');
END
ELSE
BEGIN
    SELECT '107 Already Exists';
END


IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 108)
BEGIN
    INSERT INTO [sAlert].[tEventMaster] 
    (Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
    VALUES 
    ('108', '199', 'Hospitalization Follow-Up', '', '', '[RecipientName],[DoctorName],[Relationship],[Extension],[MobileNumber],[BeneficiaryName]', '0', '0', NULL, 'Wellness Call – Hospitalization Follow-Up', '1', '0');
END
ELSE
BEGIN
    SELECT '108 Already Exists';
END

IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 109)
BEGIN
    INSERT INTO [sAlert].[tEventMaster] 
    (Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
    VALUES 
    ('109', '199', 'Hospitalization Intimation Ticket Assigned ', '', '', '[RecipientName],[DoctorName],[Relationship],[Extension],[MobileNumber],[BeneficiaryName],[NewAssignedCount] ,[OpenFrom]', '0', '0', NULL, 'Hospitalization Intimation Ticket Assigned – Action Required', '1', '0');
END
ELSE
BEGIN
    SELECT '109 Already Exists';
END
IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 114)
BEGIN
    INSERT INTO [sAlert].[tEventMaster] 
    (Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
    VALUES 
    ('253', '114', 'Annual Health Checkup Ticket Assigned', '', '', '[AssignedDoctor],[NewAssigned],[LongOpen]', '0', '0', NULL, '', '1', '0');
END
ELSE
BEGIN
    SELECT '114 Already Exists';
END
update [sAlert].[tEventMaster] set fields='[AssignedDoctor],[NewAssigned],[LongOpen],[Pending],[HighRisk],[Mild],[Moderate]' where id=114

GO



ALTER TABLE [sExamination].[tExamination]
ADD ContractorId INT

ALTER TABLE [sExamination].[tArchieveExamination]
ADD ContractorId INT

GO




INSERT [sHrm].[tExaminationCustomColumns] ([Id], [ColumnName], [IsObsolete], [DataType], [ColumnType]) 
VALUES (382, N'Contractor', 0, N'varchar(500)', 1)

GO



INSERT [sSecurity].[tDashletMaster] ([Id], [Title], [IsObsolete], [TaskId], [DashletTypeMaster]) 
VALUES (60, N'Employee Patient Register', 0, 1, 1)

GO

INSERT [sSecurity].[tDashletMaster] ([Id], [Title], [IsObsolete], [TaskId], [DashletTypeMaster]) 
VALUES (61, N'Pharmacy Queue Listing', 0, 1, 1)

GO


ALTER TABLE sWellness.tMHIScoreUpdation ADD InsertType SMALLINT DEFAULT 1

ALTER TABLE sWellness.tMHIScoreUpdation ADD HBA1CCategory NVARCHAR(20) DEFAULT NULL

ALTER TABLE sWellness.tMHIScoreUpdation ADD LDLCategory NVARCHAR(20) DEFAULT NULL

ALTER TABLE sWellness.tMHIScoreUpdation ADD BMICategory NVARCHAR(20) DEFAULT NULL

ALTER TABLE sWellness.tMHIScoreUpdation ADD BPCategory NVARCHAR(20) DEFAULT NULL

ALTER TABLE sWellness.tMHIScoreUpdation ADD StressCategory NVARCHAR(20) DEFAULT NULL

ALTER TABLE sWellness.tMHIScoreUpdation ADD LifestyleCategory NVARCHAR(20) DEFAULT NULL

GO



ALTER FUNCTION [dbo].[fAbnormalFindingsHealthIndicator]
(
    @rExaminationId BIGINT
)
RETURNS TABLE
AS
RETURN
(
    WITH DataCTE AS
    (
        SELECT
            EXM.Id AS ExaminationId,
            PA.HealthIndicatorId,
            DV.BMI,
            DV.BloodPressureSystolic,
            DV.BloodPressureDiastolic,

            D.HB,
            D.HBA1C,
            D.[SERUM CREATININE],
            D.[SERUM URIC ACID],
            D.[TRIGLYCERIDE],
            D.LDL,
            D.TSH,
            D.PSA,
            D.TMT,
            D.ECHO,
            D.ECG,
            D.SONOGRAPHY,
            D.XRAY

        FROM sSupport.tProviderAppointment PA
        INNER JOIN sExamination.tExamination EXM 
            ON EXM.ParticipantSourceId = PA.PatientSourceId 
            AND EXM.SetupId = PA.SetupId
        LEFT JOIN sExamination.tVital DV ON DV.SourceId = EXM.Id

        LEFT JOIN
        (
            SELECT *
            FROM
            (
                SELECT 
                    TR.SourceId AS ExaminationId,
                    SPM.Title,
                    TRD.ServiceValue
                FROM sOrderEntry.tStaticTestParameterMaster SPM
                INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.StaticTestParameterId = SPM.Id
                INNER JOIN sOrderEntry.tTestDetail TTD ON TTD.TestParameterId = TPM.Id
                INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestDetailId = TTD.Id
                INNER JOIN sExamination.tTestRequest TR ON TR.Id = TRD.TestRequestId
                WHERE SPM.Id IN (3,5,19,20,21,25,31,32,33,34,38,107,104,105,109,108,2,27,49,166,54,58)
            ) X
            PIVOT
            (
                MIN(ServiceValue) FOR Title IN
                (
                    [HB],[HBA1C],[SERUM CREATININE],[SERUM URIC ACID],
                    [TRIGLYCERIDE],[LDL],[TSH],[PSA],
                    [TMT],[ECHO],[ECG],[SONOGRAPHY],[XRAY]
                )
            ) P
        ) D ON D.ExaminationId = EXM.Id

        WHERE EXM.Id = @rExaminationId
    )

    SELECT 
        D1.ExaminationId,

        STUFF
        (
            (
                SELECT '<br/>' + HtmlText
                FROM
				(
					SELECT 
						HtmlText,
						CASE 
							WHEN HtmlText LIKE '%color:red%' THEN 1
							WHEN HtmlText LIKE '%color:blue%' THEN 2
							WHEN HtmlText LIKE '%color:orange%' THEN 3
							WHEN HtmlText LIKE '%color:indigo%' THEN 4
							ELSE 5
						END AS SortOrder
					FROM
					(
						SELECT
						/* ================= BMI ================= */
						CASE 
						WHEN Param = 'BMI' AND ISNUMERIC(Value) = 1 THEN
							'<b style="color:' +
							CASE 
								WHEN CAST(Value AS FLOAT) >= 36 THEN 'red'
								WHEN CAST(Value AS FLOAT) BETWEEN 30 AND 35 THEN 'orange'
								WHEN CAST(Value AS FLOAT) BETWEEN 26 AND 29.99 THEN 'indigo'
								ELSE 'black'
							END + '">BMI-' + Value + '</b>'

						/* ================= BP ================= */
						WHEN Param = 'BP' AND ISNUMERIC(Value) = 1 AND ISNUMERIC(Diastolic) = 1 THEN
							'<b style="color:' +
							CASE 
								WHEN CAST(Value AS FLOAT) > 160 OR CAST(Diastolic AS FLOAT) > 110 THEN 'red'
								WHEN CAST(Value AS FLOAT) BETWEEN 150 AND 160 OR CAST(Diastolic AS FLOAT) BETWEEN 100 AND 110 THEN 'orange'
								WHEN CAST(Value AS FLOAT) BETWEEN 140 AND 149 OR CAST(Diastolic AS FLOAT) BETWEEN 90 AND 99 THEN 'indigo'
								ELSE 'black'
							END + '">BP(Sys/Dia)-' + Value + '/' + Diastolic + '</b>'

						/* ================= HB ================= */
						WHEN Param = 'HB' AND ISNUMERIC(Value) = 1 THEN
							'<b style="color:' +
							CASE 
								WHEN CAST(Value AS FLOAT) < 8 AND CAST(Value AS FLOAT) > 0 THEN 'red'
								WHEN CAST(Value AS FLOAT) BETWEEN 8 AND 9.99 THEN 'orange'
								WHEN CAST(Value AS FLOAT) BETWEEN 10 AND 11.99 THEN 'indigo'
								ELSE 'black'
							END + '">HB-' + Value + '</b>'

						/* ================= HBA1C ================= */
						WHEN Param = 'HBA1C' AND ISNUMERIC(Value) = 1 THEN
							'<b style="color:' +
							CASE 
								WHEN CAST(Value AS FLOAT) > 10 THEN 'red'
								WHEN CAST(Value AS FLOAT) BETWEEN 8 AND 10 THEN 'orange'
								WHEN CAST(Value AS FLOAT) BETWEEN 6.5 AND 7.99 THEN 'indigo'
								ELSE 'black'
							END + '">HBA1C-' + Value + '</b>'

						/* ================= SERUM CREATININE ================= */
						WHEN Param = 'SERUM CREATININE' AND ISNUMERIC(Value) = 1 THEN
							'<b style="color:' +
							CASE 
								WHEN CAST(Value AS FLOAT) > 2 THEN 'red'
								WHEN CAST(Value AS FLOAT) BETWEEN 1.5 AND 2 THEN 'orange'
								WHEN CAST(Value AS FLOAT) BETWEEN 1.3 AND 1.49 THEN 'indigo'
								ELSE 'black'
							END + '">SERUM CREATININE-' + Value + '</b>'

						/* ================= SERUM URIC ACID ================= */
						WHEN Param = 'SERUM URIC ACID' AND ISNUMERIC(Value) = 1 THEN
							'<b style="color:' +
							CASE 
								WHEN CAST(Value AS FLOAT) > 9.5 THEN 'red'
								WHEN CAST(Value AS FLOAT) BETWEEN 7.7 AND 9.4 THEN 'orange'
								WHEN CAST(Value AS FLOAT) BETWEEN 6.5 AND 7.69 THEN 'indigo'
								ELSE 'black'
							END + '">SERUM URIC ACID-' + Value + '</b>'

						/* ================= TRIGLYCERIDE ================= */
						WHEN Param = 'TRIGLYCERIDE' AND ISNUMERIC(Value) = 1 THEN
							'<b style="color:' +
							CASE 
								WHEN CAST(Value AS FLOAT) > 500 THEN 'red'
								WHEN CAST(Value AS FLOAT) BETWEEN 200 AND 500 THEN 'orange'
								WHEN CAST(Value AS FLOAT) BETWEEN 150 AND 199.99 THEN 'indigo'
								ELSE 'black'
							END + '">TRIGLYCERIDE-' + Value + '</b>'

						/* ================= LDL ================= */
						WHEN Param = 'LDL' AND ISNUMERIC(Value) = 1 THEN
							'<b style="color:' +
							CASE 
								WHEN CAST(Value AS FLOAT) > 200 THEN 'red'
								WHEN CAST(Value AS FLOAT) BETWEEN 150 AND 200 THEN 'orange'
								WHEN CAST(Value AS FLOAT) BETWEEN 101 AND 149.99 THEN 'indigo'
								ELSE 'black'
							END + '">LDL-' + Value + '</b>'

						/* ================= TSH ================= */
						WHEN Param = 'TSH' AND ISNUMERIC(Value) = 1 THEN
							'<b style="color:' +
							CASE 
								WHEN CAST(Value AS FLOAT) > 50 THEN 'red'
								WHEN CAST(Value AS FLOAT) BETWEEN 11 AND 50 THEN 'orange'
								WHEN CAST(Value AS FLOAT) BETWEEN 5.6 AND 10.99 THEN 'indigo'
								ELSE 'black'
							END + '">TSH-' + Value + '</b>'

						/* ================= PSA ================= */
						WHEN Param = 'PSA' AND ISNUMERIC(Value) = 1 THEN
							'<b style="color:' +
							CASE 
								WHEN CAST(Value AS FLOAT) > 10 THEN 'red'
								WHEN CAST(Value AS FLOAT) > 5 THEN 'orange'
								ELSE 'black'
							END + '">PSA-' + Value + '</b>'

						/* ================= BLUE ================= */
						WHEN Param IN ('TMT','ECHO','ECG','SONOGRAPHY','XRAY')
						THEN '<b style="color:' +
							CASE 
								WHEN Value IN ('Positive','Abnormal') THEN 'blue'
								ELSE 'black'
							END + '">' + Param + '-' + Value + '</b>'
						END AS HtmlText

						FROM DataCTE
						CROSS APPLY
						(
							VALUES
							('BMI', CAST(BMI AS NVARCHAR(50)), NULL),
							('BP', CAST(BloodPressureSystolic AS NVARCHAR(50)), CAST(BloodPressureDiastolic AS NVARCHAR(50))),
							('HB', HB, NULL),
							('HBA1C', HBA1C, NULL),
							('SERUM CREATININE', [SERUM CREATININE], NULL),
							('SERUM URIC ACID', [SERUM URIC ACID], NULL),
							('TRIGLYCERIDE', [TRIGLYCERIDE], NULL),
							('LDL', LDL, NULL),
							('TSH', TSH, NULL),
							('PSA', PSA, NULL),
							('TMT', TMT, NULL),
							('ECHO', ECHO, NULL),
							('ECG', ECG, NULL),
							('SONOGRAPHY', SONOGRAPHY, NULL),
							('XRAY', XRAY, NULL)
						) P(Param, Value, Diastolic)

						WHERE Value IS NOT NULL AND LTRIM(RTRIM(Value)) <> ''
					) A
					WHERE HtmlText IS NOT NULL
				) B
				ORDER BY SortOrder
				FOR XML PATH(''), TYPE
				).value('.', 'NVARCHAR(MAX)')
			,1,5,'') AS AbnormalFindingHtml

    FROM DataCTE D1
    GROUP BY D1.ExaminationId
);

GO


ALTER VIEW [sExamination].[vExtEmployeeExaminationDetail]
AS
SELECT        EM.Id AS EmployeeId, E.Id AS ExaminationId, E.OrgId, MTM.Id AS MainTypeId, MTM.Title AS MainTypeName, E.StoreLocationId, SLM.Title AS StoreLocationName, SLM.LocationId, EPD.DateOfBirth, EPD.IdentificationMark1, 
                         EPD.IdentificationMark2, EPD.BloodGroupId, EJD.EmployeeDesignationId, EJD.DateOfJoining, LM.Title AS LocationName, E.OrganizationDepartmentId, ISNULL(D.Title, '') AS DepartmentName, D.DepartmentGroupId, E.SetupId, 
                         ISNULL(SM.RoundNumber, 0) AS RoundNumber, ISNULL(SM.Title, 0) AS RoundName, E.StatusId, S.Title AS StatusName, E.ExaminationDate, E.ParticipantSourceTypeId, E.ParticipantSourceId, E.DoctorEmployeeId, 
                         EM.Code AS ParticipantCode, EM.FirstName, EM.MiddleName, EM.FirstName + ' ' + EM.LastName AS ParticipantName, 'SELF' AS RelationName, GM.Title AS Gender, GM.Id AS GenderId, 
                         CASE WHEN (CASE WHEN isnull(Users.DisplayTitle, '') <> '' THEN Users.DisplayTitle ELSE ISNULL(EM3.FirstName, '') + ' ' + ISNULL(EM3.LastName, '') END) 
                         = 'SysSuperAdmin' THEN '' ELSE (CASE WHEN isnull(Users.DisplayTitle, '') <> '' THEN Users.DisplayTitle ELSE ISNULL(EM3.FirstName, '') + ' ' + ISNULL(EM3.LastName, '') END) END AS DoctorName, 
                         ISNULL(EJD.EmployeeJobTitleId, 0) AS EmployeeJobTitleId, ISNULL(E.EmployeeDesignationId, 0) AS EmployeeExaminationDesignationId, ISNULL(EJD.ContractorId, 0) AS ContractorId, ISNULL(EJD.EmployeeCompanyId, 0) 
                         AS EmployeeCompanyId, ISNULL(EJD.EmployeeTypeId, 0) AS EmployeeTypeId, ISNULL(EJD.SkillId, 0) AS SkillId, ISNULL(E.ProcessTypeId, 0) AS ProcessTypeId, ISNULL(EJD.EmployeeStoreLocationId, 0) 
                         AS EmployeeStoreLocationId, ISNULL(EJD.EmployeeLocationId, 0) AS EmployeeLocationId, CASE E.ParticipantSourceTypeId WHEN 95 THEN ETM.Title WHEN 1001 THEN 'Dep' WHEN 1009 THEN 'Oth' END AS ParticipantType, 
                         SM.Title AS SetupName, ISNULL(EJD.GradeId, 0) AS GradeId, ISNULL(ETM.EmployeeTypeGroupId, 0) AS EmployeeTypeGroupId, ISNULL(EJD.EmployeeSubTypeId, 0) AS EmployeeSubTypeId, ISNULL(EJD.EmployeeGroupId, 0) 
                         AS EmployeeGroupId, ISNULL(EM.TargetGroupId, 0) AS EmployeeTargetGroupId, ISNULL(TGM.Title, '') AS EmployeeTargetGroupName, ISNULL(LEM.Title, '') AS EmployeeLegalEntity, ISNULL(LEM.Id, '') 
                         AS EmployeeLegalEntityId, ISNULL(EPD.UIDNumber, '-') AS UIDNumber, ISNULL(E.TargetGroupId, 0) AS ExaminationTargetGroupId, ISNULL(DPM.Title, '') AS EmployeeDesignatedPosition, 
						 ISNULL(E.ContractorId, 0) AS ExaminationContractorId
FROM            sExamination.tExamination AS E INNER JOIN
                         sHrm.tEmployeeMaster AS EM ON EM.Id = E.ParticipantSourceId AND E.ParticipantSourceTypeId = 95 LEFT OUTER JOIN
                         sHrm.tEmployeePersonalDetail AS EPD ON EPD.EmployeeId = EM.Id INNER JOIN
                         sCommon.tGenderMaster AS GM ON GM.Id = EPD.GenderId INNER JOIN
                         sHrm.tEmployeeJobDetail AS EJD ON EM.Id = EJD.EmployeeId LEFT OUTER JOIN
                         sCommon.tOrganizationDepartmentMaster AS D ON D.Id = E.OrganizationDepartmentId AND D.IsObsolete = 0 LEFT OUTER JOIN
                         sHrm.tEmployeeMaster AS EM1 ON EM1.Id = E.DoctorEmployeeId INNER JOIN
                         sExamination.tSetupMaster AS SM ON SM.Id = E.SetupId INNER JOIN
                         sExamination.tSubTypeMaster AS STM ON STM.Id = SM.SubTypeId INNER JOIN
                         sExamination.tMainTypeMaster AS MTM ON STM.MainTypeId = MTM.Id INNER JOIN
                         sIp.tStoreLocationMaster AS SLM ON SLM.Id = E.StoreLocationId INNER JOIN
                         sCommon.tLocationMaster AS LM ON LM.Id = SLM.LocationId INNER JOIN
                         sExamination.tStatusMaster AS S ON S.Id = E.StatusId LEFT OUTER JOIN
                         sHrm.tEmployeeTypeMaster AS ETM ON ETM.Id = EJD.EmployeeTypeId LEFT OUTER JOIN
                         sHrm.tEmployeeMaster AS EM3 ON EM3.Id = E.DoctorEmployeeId LEFT OUTER JOIN
                         sSecurity.tUser AS Users ON Users.Id = E.CreatedUserId LEFT OUTER JOIN
                         sHrm.tTargetGroupMaster AS TGM ON TGM.Id = EM.TargetGroupId LEFT OUTER JOIN
                         sHrm.tEmployeeLegalEntitymaster AS LEM ON LEM.Id = E.LegalEntityId LEFT OUTER JOIN
                         sHrm.tDesignatedPositionMaster AS DPM ON DPM.Id = EJD.DesignatedPositionId


GO


CREATE TYPE [sWellness].[udt_MHIBulkCategoryImport] AS TABLE(
	[EmployeeCode] [nvarchar](50) NOT NULL,
	[HBA1CCategory] [smallint] NULL,
	[LDLCategory] [smallint] NULL,
	[BMICategory] [smallint] NULL,
	[BPCategory] [smallint] NULL,
	[StressCategory] [smallint] NULL,
	[LifestyleCategory] [smallint] NULL
)


GO

CREATE OR ALTER PROCEDURE [sCommon].[pGetAllEmployeeOfLocation]
(
	@rLocationId INT,
	@rOrgId SMALLINT
)
AS
SET NOCOUNT ON;
BEGIN
	SELECT DISTINCT
		EM.Code AS EmployeeCode
	FROM 
		[sHrm].[tEmployeeJobDetail] EJD
	INNER JOIN
		[sHrm].[tEmployeeMaster] EM
	ON
		EM.Id = EJD.EmployeeId
	WHERE 
		EJD.EmployeeLocationId  = @rLocationId
	AND
		EJD.OrgId =  @rOrgId
	AND
		EM.StatusId = 7
	ORDER BY
		EM.Code
END

GO


CREATE OR ALTER PROCEDURE [sCommon].[pRptCompanyInformationInternalGet]	
	@rReportId [int] = 0,
	@rStoreLocationId [int] = 0,
	@rUserDisplayTitle varchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
		SELECT
			    CI.Id,
				case when CI.id=4001 or CI.id=6001 then CI.Title Else LM.Title END AS LocationName,
				LM.NameOfOrganization AS NameOfOrganization,
				LM.SmallAddress1,
				LM.SmallAddress2,
				CI.Code,
				CI.Title,
				CI.ParentCompanyName,
				CI.StreetOne + ', ' + CI.CityName AS FirstLine,
				--  StateName + ', ' + 
				--	CountryName + ', TIN No: ' + TinNumber AS SecondLine,
				--	'Tel: ' + PhoneNumberOffice AS ThirdLine,
				'Website: ' + CI.HomePage AS FourthLine,
				CI.StreetOne,
				CI.StreetTwo,
				CI.StreetThree,
				CI.StreetFour,
				CI.CityName,
				CI.StateName,
				CI.CountryName,
				CI.ZipCode,
				CI.PhoneNo,
				--CityName + ' ' + StateName AS CityState,
				--CountryName  + ' ' + ZipCode AS CountryZip,
				--ContactPerson,
				--PhoneNumberHome,
				--PhoneNumberOffice,
				--PhoneNumberMobile,
				--EmailPrimary,
				--EmailAlternative,
				--HomePage,
				SL.Title as SubLocation,
			    (SELECT CASE @rReportId when 20477 then 'Referral Certificate' 
				when 20476 then 'OPD Prescription List' 
				ELSE (ISNULL(RS.Title,R.Title)) END as ReportTitle
			     FROM sCommon.tReport R 
					 LEFT JOIN sCommon.tReportStateTitle RS On R.Id = RS.ReportId 				
					 LEFT JOIN (SELECT StateId FROM  sCommon.tLocationMaster LM 
					 INNER JOIN sIp.tStoreLocationMaster SL ON SL.LocationId = LM.id WHERE SL.Id = @rStoreLocationId
				) SLM  
				ON SLM.StateId = RS.StateId
				         
				WHERE ((R.Id = @rReportId) OR (@rReportId = 0))) AS ReportTitle,
				(SELECT R.ReportName FROM sCommon.tReport R 
					 LEFT JOIN sCommon.tReportStateTitle RS On R.Id = RS.ReportId 				
					 LEFT JOIN (SELECT StateId FROM  sCommon.tLocationMaster LM 
					 INNER JOIN sIp.tStoreLocationMaster SL ON SL.LocationId = LM.id WHERE SL.Id = @rStoreLocationId
				) SLM  
				ON SLM.StateId = RS.StateId
				         
			WHERE ((R.Id = @rReportId) OR (@rReportId = 0))) AS ReportName,
			CID.logo as Logo,
			 
			@rUserDisplayTitle as UserDisplayTitle	 
			FROM sIp.tStoreLocationMaster SL INNER JOIN sCommon.tLocationMaster LM					  			
			ON SL.LocationId = LM.Id INNER JOIN sCommon.tCompanyInformation CI 
			ON LM.OrgId = CI.Id	INNER JOIN sCommon.tCompanyInformationDetail CID
			on ci.ID = CID.orgid
			WHERE ((SL.Id = @rStoreLocationId) OR (ISNULL(@rStoreLocationId, 0) = 0))
			order by CI.Id Desc,LM.Title 
END
GO


ALTER proc [sExamination].[pCommonExaminationHistoryListGetCustomSearch]
@rPageIndex int,
@rOrgId [int],  
@rDepartmentId nvarchar(max)='' , 
@rSetupId nvarchar(max)='' ,  
@rCode [nvarchar](20),  
@rName [nvarchar](50),  
@rDesignationId nvarchar(max)='' ,
@rMainTypeId int,
@rStatusId nvarchar(max)='' ,
@rStoreLocationId int,
@rFromDate Date = '',
@rToDate Date = '',
@rHealthIndicatorId int,
@rTag int,
@rEmployeeStoreLocationId int=0,
@rCompanyId nvarchar(max)='' ,
@lPageSize int = 10,
@rDOJ date = '',
@rEmployeeTypeGroupId int = 0,
@rFlag int = 0 , ---PME Contract Worker change by Nidhi Pandey
@rContractorId nvarchar(max)=''     

as
begin
	select @rCode = case when @rCode = '*' then '' else @rCode end
	select @rName = case when @rName = '*' then '' else @rName end
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rName = sCommon.fSearchStringGet(@rName)
	declare @tbltmp table(tid int identity(1,1),eid bigint)
	
	IF @rMainTypeId = 9
	BEGIN
		insert into @tbltmp(eid)
		SELECT E.Id
		FROM sExamination.tExamination E		
		inner join sExamination.tSetupMaster SM on E.SetupId = SM.Id
		inner join sExamination.tDiagnosis D ON D.SourceId= E.Id
		inner join sExamination.tExaminationRequest ER ON E.Id = ER.ExaminationId		
		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 EM2 on EFD.EmployeeId = EM2.Id
		inner join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=E.ParticipantSourceId
		left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id
		left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId
		  left join sProcurement.tVendorMaster CONT on CONT.Id =EJD.ContractorId         
				
		WHERE ((ISNULL(D.HealthindicatorId,0)=0	AND @rTag != 1) OR (@rTag = 1 AND ISNULL(D.HealthindicatorId,0) >= 0)) 
		AND E.OrgId = @rOrgId
		AND (EM.Code Like @rCode or EM2.Code Like @rCode or CS.Code Like @rCode OR ISNULL(@rCode,'') = '' OR ISNULL(@rCode,'') = '*')
		AND (EM.FirstName Like @rName  + '%' or EFD.Name like @rName  + '%' or CS.FirstName like @rName  + '%' OR ISNULL(@rName,'') = '' OR ISNULL(@rName,'') = '*')
		AND ((E.OrganizationDepartmentId in (SELECT item FROM sCommon.fnsplit(@rDepartmentId,','))) OR (ISNULL(@rDepartmentId,'') = ''))
		AND ((E.EmployeeDesignationId in (SELECT item FROM sCommon.fnsplit(@rDesignationId,','))) OR (ISNULL(@rDesignationId,'') = ''))
		AND (ER.SubTypeId = @rMainTypeId) AND ((E.SetupId  IN(SELECT item FROM sCommon.fnsplit(@rSetupId,','))) OR (ISNULL(@rSetupId,'') = ''))  
		AND ((E.StatusId in (SELECT item FROM sCommon.fnsplit(@rStatusId,','))) OR (ISNULL(@rStatusId,'') = ''))
		AND (E.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)
		AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))	
		AND ((D.HealthIndicatorId = @rHealthIndicatorId) OR (ISNULL(@rHealthIndicatorId,0) = 0))
		AND ((E.EmployeeCompanyId in (SELECT item FROM sCommon.fnsplit(@rCompanyId,','))) OR (ISNULL(@rCompanyId,'') = ''))
		and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)
		AND ((cast(EJD.DateOfJoining as date) = cast(@rDOJ as date)) OR (ISNULL(@rDOJ,'') = ''))
		   AND ((CONT.Id in (SELECT item FROM sCommon.fnsplit(@rContractorId,','))) OR (ISNULL(@rContractorId,'') = ''))  
		AND EM.IsObsolete=0 AND EM2.IsObsolete=0
		order by E.ExaminationDate desc
		
		insert into @tbltmp(eid)
		SELECT E.Id
		FROM sExamination.tExamination E
		inner join sExamination.tSetupMaster SM	on E.SetupId = SM.Id
		inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
		LEFT JOIN sExamination.tDiagnosis D ON D.SourceId = 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 CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009
		left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		
		inner join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=E.ParticipantSourceId
		left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id
		left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId
		  left join sProcurement.tVendorMaster CONT on CONT.Id =EJD.ContractorId         
		
		WHERE ((ISNULL(D.HealthindicatorId,0)=0 AND @rTag != 1) OR (@rTag = 1 AND ISNULL(D.HealthindicatorId,0) >= 0) 
		or (D.HealthindicatorId is null)) AND E.OrgId = @rOrgId
		AND (EM.Code Like @rCode or EM2.Code Like @rCode or CS.Code Like @rCode OR ISNULL(@rCode,'') = '' OR ISNULL(@rCode,'') = '*')
		AND (EM.FirstName Like @rName  + '%' or EFD.Name like @rName  + '%' or CS.FirstName like @rName  + '%' OR ISNULL(@rName,'') = '' OR ISNULL(@rName,'') = '*')
		AND ((E.OrganizationDepartmentId in (SELECT item FROM sCommon.fnsplit(@rDepartmentId,','))) OR (ISNULL(@rDepartmentId,'') = ''))
		AND ((E.EmployeeDesignationId in (SELECT item FROM sCommon.fnsplit(@rDesignationId,','))) OR (ISNULL(@rDesignationId,'') = ''))
		AND ((E.StatusId in (SELECT item FROM sCommon.fnsplit(@rStatusId,','))) OR (ISNULL(@rStatusId,'') = ''))
		AND ((E.EmployeeCompanyId IN(SELECT item FROM sCommon.fnsplit(@rCompanyId,','))) OR (isnull(@rCompanyId,'') = ''))
		
		AND (STM.MainTypeId = @rMainTypeId) AND ((E.SetupId  IN(SELECT item FROM sCommon.fnsplit(@rSetupId,','))) OR (ISNULL(@rSetupId,'') = ''))
		AND (E.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) 
		AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))	
		AND ((D.HealthIndicatorId = @rHealthIndicatorId) OR (ISNULL(@rHealthIndicatorId,0) = 0))
		and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)
		AND ((cast(EJD.DateOfJoining as date) = cast(@rDOJ as date)) OR (ISNULL(@rDOJ,'') = ''))
		   AND ((CONT.Id in (SELECT item FROM sCommon.fnsplit(@rContractorId,','))) OR (ISNULL(@rContractorId,'') = ''))  
		order by E.ExaminationDate desc
		
		select t1.* from (		
			SELECT E.Id,
			convert(varchar(10),E.ExaminationDate,103) as ExaminationDate,
			EDM.Title as Designation,
			ODM.Title as Department,
			SM.RoundNumber,
			ParticipantCode = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.Code
			when E.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,
			ParticipantName = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.FirstName + ' ' + isnull(EM.LastName,'')
			when E.ParticipantSourceTypeId = 1001 then EFD.Name else CS.FirstName + ' ' + isnull(CS.LastName,'') end,
			Gender = CASE WHEN E.ParticipantSourceTypeId = 95 then GM.Title
			when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
			else GM2.Title end,
			'Post Accident' as Setup,
			ST.Title as [Status],
			isnull(E.ProcessTypeId,0) as ProcessId,
			PT.Title as ProcessType,
			MobileNumber as MobileNo,
			CompanyEmail,
			D.HealthindicatorId,
			E.ParticipantSourceTypeId,
			E.ParticipantSourceId,
			E.SetupId,
			E.StatusId,
			Age = CASE WHEN E.ParticipantSourceTypeId = 95 then isnull(datediff(yy,EP.DateOfBirth,getdate()),0)
			when E.ParticipantSourceTypeId = 1001 then isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)
			else isnull(datediff(yy,CS.DateOfBirth,getdate()),0) end,
			GenderId = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.GenderId
			when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
			else CS.GenderId end,
			DateOfBirth = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.DateOfBirth
			when E.ParticipantSourceTypeId = 1001 then EFD.DateOfBirth
			else CS.DateOfBirth end,
			V.Height,
			EP.IsBirthDateUnknown,
			isnull(E.CriteiraGroupId,0) as CriteriaGroupId,
			isnull(E.TargetGroupId,0) as TargetGroupId,
			TG.Title as TargetGroup,
			E.OrganizationDepartmentId as DepartmentId,
			E.EmployeeDesignationId as DesignationId

			FROM sExamination.tExamination E	
		
			inner join @tbltmp t on t.eid = E.Id
			inner join sExamination.tSetupMaster SM	on E.SetupId = SM.Id
			INNER JOIN sExamination.tDiagnosis D ON D.SourceId= E.Id
			INNER JOIN sExamination.tExaminationRequest ER ON E.Id = ER.ExaminationId 
			left join sCommon.tProcessTypeMaster PT	on PT.Id = E.ProcessTypeId
			left join sHrm.tEmployeeDesignationMaster EDM on E.EmployeeDesignationId = EDM.Id
			left join sCommon.tOrganizationDepartmentMaster ODM on E.OrganizationDepartmentId = ODM.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
			left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId
			left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId
			left join sExamination.tStatusMaster ST on E.StatusId = ST.Id
			left join sCommon.tGenderMaster GM on EP.GenderId = GM.Id
			left join sCommon.tGenderMaster GM2 on CS.GenderId = GM.Id
			left join sExamination.tVital V on V.SourceId = E.Id
			left join sHrm.tTargetGroupMaster TG on TG.Id = E.TargetGroupId    
			--where tid between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)		
		) t1
		
		union all
		
		select t2.* from(
			SELECT E.Id AS Id,
			convert(varchar(10),E.ExaminationDate,103) as ExaminationDate,
			EDM.Title as Designation,
			ODM.Title as Department,
			SM.[RoundNumber],
			ParticipantCode = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.Code
			when E.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,
			ParticipantName = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.FirstName + ' ' + isnull(EM.LastName,'')
			when E.ParticipantSourceTypeId = 1001 then EFD.Name else CS.FirstName + ' ' + isnull(CS.LastName,'') end,
			Gender = CASE WHEN E.ParticipantSourceTypeId = 95 then GM.Title
			when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
			else GM2.Title end,
			Setup = SM.Title,
			ST.Title as [Status],
			E.ProcessTypeId as ProcessId,
			PT.Title as ProcessType,
			MobileNumber as MobileNo,
			CompanyEmail,
			D.HealthindicatorId,
			E.ParticipantSourceTypeId,
			E.ParticipantSourceId,
			E.SetupId,
			E.StatusId,
			Age = CASE WHEN E.ParticipantSourceTypeId = 95 then isnull(datediff(yy,EP.DateOfBirth,getdate()),0)
			when E.ParticipantSourceTypeId = 1001 then isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)
			else isnull(datediff(yy,CS.DateOfBirth,getdate()),0) end,
			GenderId = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.GenderId
			when E.ParticipantSourceTypeId = 1001 then ISNULL(EFD.GenderId,'')
			else CS.GenderId end,
			DateOfBirth = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.DateOfBirth
			when E.ParticipantSourceTypeId = 1001 then EFD.DateOfBirth
			else CS.DateOfBirth end,
			V.Height,
			EP.IsBirthDateUnknown,
			isnull(E.CriteiraGroupId,0) as CriteriaGroupId,
			isnull(E.TargetGroupId,0) as TargetGroupId,
			TG.Title as TargetGroup,
			E.OrganizationDepartmentId as DepartmentId,
			E.EmployeeDesignationId as DesignationId
			FROM sExamination.tExamination E	
		
			inner join @tbltmp t on t.eid = E.Id	
			inner join sExamination.tSetupMaster SM	on E.SetupId = SM.Id
			LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= E.Id
			left join sCommon.tProcessTypeMaster PT	on PT.Id=E.ProcessTypeId
			left join sHrm.tEmployeeDesignationMaster EDM on E.EmployeeDesignationId = EDM.Id
			left join sCommon.tOrganizationDepartmentMaster ODM on E.OrganizationDepartmentId = ODM.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
			left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId
			left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId
			left join sExamination.tStatusMaster ST on E.StatusId = ST.Id
			left join sCommon.tGenderMaster GM on EP.GenderId = GM.Id
			left join sCommon.tGenderMaster GM2 on CS.GenderId = GM.Id
			left join sExamination.tVital V on V.SourceId = E.Id
			left join sHrm.tTargetGroupMaster TG on TG.Id = E.TargetGroupId

			--where tid between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)		
		) t2
	end
	ELSE
	BEGIN
	  if(@rFlag = 1)
	  BEGIN
		insert into @tbltmp(eid)
		SELECT E.Id
		FROM sExamination.tExamination E
		inner join sExamination.tSetupMaster SM	on E.SetupId = SM.Id
		inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
		LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= 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 CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009
		left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		inner join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=E.ParticipantSourceId
		left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id
		left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId
		  left join sProcurement.tVendorMaster CONT on CONT.Id =EJD.ContractorId         

		WHERE ((ISNULL(D.HealthindicatorId,0)=0 AND @rTag != 1)	OR (@rTag = 1 AND ISNULL(D.HealthindicatorId,0) >= 0)
		or (D.HealthindicatorId is null)) AND E.OrgId = @rOrgId
		AND (EM.Code Like @rCode or EM2.Code Like @rCode or CS.Code Like @rCode OR ISNULL(@rCode,'') = '' OR ISNULL(@rCode,'') = '*')
		AND (EM.FirstName Like @rName  + '%' or EFD.Name like @rName  + '%' or CS.FirstName like @rName  + '%' OR ISNULL(@rName,'') = '' OR ISNULL(@rName,'') = '*')
		AND ((E.OrganizationDepartmentId in (SELECT item FROM sCommon.fnsplit(@rDepartmentId,','))) OR (ISNULL(@rDepartmentId,'') = ''))
		AND ((E.EmployeeDesignationId in (SELECT item FROM sCommon.fnsplit(@rDesignationId,','))) OR (ISNULL(@rDesignationId,'') = ''))
		AND (STM.MainTypeId = @rMainTypeId) AND ((E.SetupId  IN(SELECT item FROM sCommon.fnsplit(@rSetupId,','))) OR (ISNULL(@rSetupId,'') = ''))
		AND ((E.StatusId in (SELECT item FROM sCommon.fnsplit(@rStatusId,','))) OR (ISNULL(@rStatusId,'') = ''))
		AND (E.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) 
		AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))	
		AND ((D.HealthIndicatorId = @rHealthIndicatorId) OR (ISNULL(@rHealthIndicatorId,0) = 0))
		AND ((E.EmployeeCompanyId in (SELECT item FROM sCommon.fnsplit(@rCompanyId,','))) OR (ISNULL(@rCompanyId,'') = ''))
		and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)
		AND ((cast(EJD.DateOfJoining as date) = cast(@rDOJ as date)) OR (ISNULL(@rDOJ,'') = ''))
		   AND ((CONT.Id in (SELECT item FROM sCommon.fnsplit(@rContractorId,','))) OR (ISNULL(@rContractorId,'') = ''))  
		AND Isnull(EM.IsObsolete,0)=0 AND Isnull(EM2.IsObsolete,0)=0
		AND EM.TargetGroupId = 10002
		order by E.ExaminationDate desc
		
		SELECT E.Id,
		convert(varchar(10),E.ExaminationDate,103) as ExaminationDate,
		EDM.Title as Designation,
		ODM.Title as Department,
		SM.[RoundNumber],
		ParticipantCode = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.Code
		when E.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,
		ParticipantName = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.FirstName + ' ' + isnull(EM.LastName,'')
		when E.ParticipantSourceTypeId = 1001 then EFD.Name else CS.FirstName + ' ' + isnull(CS.LastName,'') end,
		Gender = CASE WHEN E.ParticipantSourceTypeId = 95 then GM.Title
		when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
		else GM2.Title end,
		Setup = SM.Title,
		ST.Title as [Status],
		IsBirthDateUnknown,
		isnull(E.ProcessTypeId,0) as ProcessId,
		PT.Title as ProcessType,
		MobileNumber as MobileNo,
		CompanyEmail,
		D.HealthindicatorId,
		E.ParticipantSourceTypeId,
		E.ParticipantSourceId,
		E.SetupId,
		E.StatusId,
		Age = CASE WHEN E.ParticipantSourceTypeId = 95 then isnull(datediff(yy,EP.DateOfBirth,getdate()),0)
		when E.ParticipantSourceTypeId = 1001 then isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)
		else isnull(datediff(yy,CS.DateOfBirth,getdate()),0) end,
		GenderId = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.GenderId
		when E.ParticipantSourceTypeId = 1001 then ISNULL(EFD.GenderId,0)
		else CS.GenderId end,
		DateOfBirth = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.DateOfBirth
		when E.ParticipantSourceTypeId = 1001 then EFD.DateOfBirth
		else CS.DateOfBirth end,
		V.Height,
		IsBirthDateUnknown,
		isnull(E.CriteiraGroupId,0) as CriteriaGroupId,
		isnull(E.TargetGroupId,0) as TargetGroupId,
		TG.Title as TargetGroup,
		E.OrganizationDepartmentId as DepartmentId,
		E.EmployeeDesignationId as DesignationId

		FROM sExamination.tExamination E		
		inner join @tbltmp t on t.eid = E.Id
		inner join sExamination.tSetupMaster SM	on E.SetupId = SM.Id
		LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= E.Id 
		left join sCommon.tProcessTypeMaster PT	on PT.Id=E.ProcessTypeId
		left join sHrm.tEmployeeDesignationMaster EDM on E.EmployeeDesignationId = EDM.Id
		left join sCommon.tOrganizationDepartmentMaster ODM on E.OrganizationDepartmentId = ODM.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
		left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId
		left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId
		left join sExamination.tStatusMaster ST on E.StatusId = ST.Id
		left join sCommon.tGenderMaster GM on EP.GenderId = GM.Id
		left join sCommon.tGenderMaster GM2 on CS.GenderId = GM.Id
		left join sExamination.tVital V on V.SourceId = E.Id
		left join sHrm.tTargetGroupMaster TG on TG.Id = E.TargetGroupId
	 
		--where tid between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)
		order by tid	
	  End
	  else
	  BEGIN
		insert into @tbltmp(eid)
		SELECT E.Id
		FROM sExamination.tExamination E
		inner join sExamination.tSetupMaster SM	on E.SetupId = SM.Id
		inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
		LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= 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 CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009
		left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		inner join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=E.ParticipantSourceId
		left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id
		left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId
		  left join sProcurement.tVendorMaster CONT on CONT.Id =EJD.ContractorId         

		WHERE ((ISNULL(D.HealthindicatorId,0)=0 AND @rTag != 1)	OR (@rTag = 1 AND ISNULL(D.HealthindicatorId,0) >= 0)
		or (D.HealthindicatorId is null)) AND E.OrgId = @rOrgId
		AND (EM.Code Like @rCode or EM2.Code Like @rCode or CS.Code Like @rCode OR ISNULL(@rCode,'') = '' OR ISNULL(@rCode,'') = '*')
		AND (EM.FirstName Like @rName  + '%' or EFD.Name like @rName  + '%' or CS.FirstName like @rName  + '%' OR ISNULL(@rName,'') = '' OR ISNULL(@rName,'') = '*')
		AND ((E.OrganizationDepartmentId in (SELECT item FROM sCommon.fnsplit(@rDepartmentId,','))) OR (ISNULL(@rDepartmentId,'') = ''))
		AND ((E.EmployeeDesignationId in (SELECT item FROM sCommon.fnsplit(@rDesignationId,','))) OR (ISNULL(@rDesignationId,'') = ''))
		AND (STM.MainTypeId = @rMainTypeId) AND ((E.SetupId  IN(SELECT item FROM sCommon.fnsplit(@rSetupId,','))) OR (ISNULL(@rSetupId,'') = ''))
		AND ((E.StatusId in (SELECT item FROM sCommon.fnsplit(@rStatusId,','))) OR (ISNULL(@rStatusId,'') = ''))
		AND (E.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) 
		AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))	
		AND ((D.HealthIndicatorId = @rHealthIndicatorId) OR (ISNULL(@rHealthIndicatorId,0) = 0))
		AND ((E.EmployeeCompanyId in (SELECT item FROM sCommon.fnsplit(@rCompanyId,','))) OR (ISNULL(@rCompanyId,'') = ''))
		   AND ((CONT.Id in (SELECT item FROM sCommon.fnsplit(@rContractorId,','))) OR (ISNULL(@rContractorId,'') = ''))  
		and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)
		AND ((cast(EJD.DateOfJoining as date) = cast(@rDOJ as date)) OR (ISNULL(@rDOJ,'') = ''))
		AND Isnull(EM.IsObsolete,0)=0 AND Isnull(EM2.IsObsolete,0)=0
		order by E.ExaminationDate desc
		
		SELECT E.Id,
		convert(varchar(10),E.ExaminationDate,103) as ExaminationDate,
		EDM.Title as Designation,
		ODM.Title as Department,
		SM.[RoundNumber],
		ParticipantCode = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.Code
		when E.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,
		ParticipantName = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.FirstName + ' ' + isnull(EM.LastName,'')
		when E.ParticipantSourceTypeId = 1001 then EFD.Name else CS.FirstName + ' ' + isnull(CS.LastName,'') end,
		Gender = CASE WHEN E.ParticipantSourceTypeId = 95 then GM.Title
		when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
		else GM2.Title end,
		Setup = SM.Title,
		ST.Title as [Status],
		IsBirthDateUnknown,
		isnull(E.ProcessTypeId,0) as ProcessId,
		PT.Title as ProcessType,
		MobileNumber as MobileNo,
		CompanyEmail,
		D.HealthindicatorId,
		E.ParticipantSourceTypeId,
		E.ParticipantSourceId,
		E.SetupId,
		E.StatusId,
		Age = CASE WHEN E.ParticipantSourceTypeId = 95 then isnull(datediff(yy,EP.DateOfBirth,getdate()),0)
		when E.ParticipantSourceTypeId = 1001 then isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)
		else isnull(datediff(yy,CS.DateOfBirth,getdate()),0) end,
		GenderId = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.GenderId
		when E.ParticipantSourceTypeId = 1001 then ISNULL(EFD.GenderId,0)
		else CS.GenderId end,
		DateOfBirth = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.DateOfBirth
		when E.ParticipantSourceTypeId = 1001 then EFD.DateOfBirth
		else CS.DateOfBirth end,
		V.Height,
		IsBirthDateUnknown,
		isnull(E.CriteiraGroupId,0) as CriteriaGroupId,
		isnull(E.TargetGroupId,0) as TargetGroupId,
		TG.Title as TargetGroup,
		E.OrganizationDepartmentId as DepartmentId,
		E.EmployeeDesignationId as DesignationId

		FROM sExamination.tExamination E		
		inner join @tbltmp t on t.eid = E.Id
		inner join sExamination.tSetupMaster SM	on E.SetupId = SM.Id
		LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= E.Id 
		left join sCommon.tProcessTypeMaster PT	on PT.Id=E.ProcessTypeId
		left join sHrm.tEmployeeDesignationMaster EDM on E.EmployeeDesignationId = EDM.Id
		left join sCommon.tOrganizationDepartmentMaster ODM on E.OrganizationDepartmentId = ODM.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
		left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId
		left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId
		left join sExamination.tStatusMaster ST on E.StatusId = ST.Id
		left join sCommon.tGenderMaster GM on EP.GenderId = GM.Id
		left join sCommon.tGenderMaster GM2 on CS.GenderId = GM.Id
		left join sExamination.tVital V on V.SourceId = E.Id
		left join sHrm.tTargetGroupMaster TG on TG.Id = E.TargetGroupId
	 
		--where tid between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)
		order by tid	
	  End
	end
	
	--select @lTotalRec = count(*) from @tbltmp
	
	--if @lTotalRec % @lPageSize = 0
	--	set @lTotalPage = @lTotalRec / @lPageSize
	--else
	--	set @lTotalPage =  @lTotalRec / @lPageSize + 1
		
	--select @lTotalPage as TotalPage,@lTotalRec as TotalRec
end

GO


CREATE OR ALTER PROCEDURE [sExamination].[pExaminationAdd]
@rId bigint,
@rOrgId smallint,
@rParticipantSourceTypeId smallint,
@rParticipantSourceId bigint,
@rOrganizationDepartmentId int,
@rSetupId bigint,
@rMainTypeId int,
@rRoundNumber int = 0,
@rStatusId int,
@rExaminationDate date,
@rDoctorEmployeeId bigint  = NULL,
@rCreatedUserId bigint,
@rUpdatedUserId bigint = 0,
@rParentExaminationId bigint = Null,
@rStoreLocationId bigint,
@rCauseId int = null,
@rProcessTypeId int,
@rImportId bigint = null,
@rCriteriaGroupId int = null,
@rEmployeeStatusId int,
@rTargetGroupId int = null,
@rDoctorFlag int = null,
@rPastHistorySelf nvarchar(2000) = '',
@rHistoryMother nvarchar(2000) = '',
@rHistoryFather nvarchar(2000) = '',
@rDataEntryTemplateId bigint = 0,
@rMedicalAgencyId int = 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
		Declare @rExistingId  bigint = 0
		--Declare @lFromDate datetime
		--Declare @lToDate datetime
		--SET @lFromDate=(select FromDate from sExamination.tSetupMaster WHERE Id=@rSetupId AND StoreLocationId=@rStoreLocationId AND OrgId=@rOrgId)
		--SET @lToDate=(select ToDate from sExamination.tSetupMaster WHERE Id=@rSetupId AND StoreLocationId=@rStoreLocationId AND OrgId=@rOrgId)
		
		--IF(@rMainTypeId = 1 OR @rMainTypeId=6 OR @rMainTypeId=7)
		--BEGIN
		--	IF(@rExaminationDate < @lFromDate OR @rExaminationDate >@lToDate)
		--	BEGIN
		--		SELECT -2 AS RESULT
		--		RETURN
		--	END
		--END
		
	     SELECT @rExistingId = ID  FROM [sExamination].[tExamination] WHERE ParticipantSourceTypeId = @rParticipantSourceTypeId AND ParticipantSourceId = @rParticipantSourceId AND SetupId = @rSetupId
		 
		 IF(@rMainTypeId = 1 OR @rMainTypeId = 2 OR @rMainTypeId = 4 OR @rMainTypeId = 6 OR @rMainTypeId = 7)
		  SET @rId = @rExistingId		  
		  
		IF(@rDoctorEmployeeId <= 0)
			SET @rDoctorEmployeeId = NULL
			
		if isnull(@rOrganizationDepartmentId,0) = 0 and @rParticipantSourceTypeId = 95
		begin
			select @rOrganizationDepartmentId = OrganizationDepartmentId from sHrm.tEmployeeJobDetail where EmployeeId = @rParticipantSourceId
		end
		
		DECLARE @lNextNumber bigint,@lEmployeeCompanyId int,@lTargetGroupId int,@lEmployeeDesignationId int,@lGradeId int,@lLegalEntityId int,@lIsTargetGroupRestrictInHR bit
		DECLARE @lRawMaterialUsed nvarchar(50), @lDangerousProcess nvarchar(50), @lHazardousProcess nvarchar(50),@lEmployeeContractorId int;

		select @lEmployeeCompanyId = EmployeeCompanyId,@lEmployeeDesignationId=EmployeeDesignationId,@lLegalEntityId=LegalEntityId ,
		@lRawMaterialUsed = RawMaterialUsed,@lDangerousProcess = DangerousProcess, @lHazardousProcess = HazardousProcess, @lEmployeeContractorId = ContractorId
		from sHrm.tEmployeeJobDetail where employeeId = @rParticipantSourceId and (@rParticipantSourceTypeId = 95 or @rParticipantSourceTypeId = 1001)

		select @lGradeId = GradeId from sHrm.vEmployeeCommonDetail where EmployeeId = @rParticipantSourceId and (@rParticipantSourceTypeId = 95 or @rParticipantSourceTypeId = 1001)

		select @lIsTargetGroupRestrictInHR=isnull(IsTargetGroupRestrictInHR,0) from sExamination.tSetupmaster where id=@rSetupId
		
		if @rProcessTypeId > 0
		begin
			update sHrm.tEmployeeJobDetail set ProcessTypeId = @rProcessTypeId where EmployeeId = @rParticipantSourceId
		end
		
		if Isnull(@rOrganizationDepartmentId,0) > 0 and @rParticipantSourceTypeId = 95
		begin
			update sHrm.tEmployeeJobDetail set OrganizationDepartmentId = Isnull(@rOrganizationDepartmentId,0) where EmployeeId = @rParticipantSourceId
		end

		if (@rTargetGroupId > 0 and Isnull(@lIsTargetGroupRestrictInHR,0)=0)
		begin
			--if not exists(select * from sHrm.tEmployeeMaster where Id = @rParticipantSourceId and isnull(TargetGroupId,0) = 0)
			--begin
				update sHrm.tEmployeeMaster set TargetGroupId = @rTargetGroupId where Id = @rParticipantSourceId
			--end
		end
		
		select @lTargetGroupId = @rTargetGroupId
		
		
		IF (@rId = 0)
		--IF EXISTS (SELECT 1 FROM [sExamination].[tExamination] WHERE ParticipantSourceTypeId = @rParticipantSourceTypeId
		--AND ParticipantSourceId = @rParticipantSourceId AND SetupId = @rSetupId)
		BEGIN
			--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sExamination.tExamination', 0, 1, 1,@outNextNumber = @lNextNumber output
			
			INSERT INTO [sExamination].[tExamination] 
			(
				OrgId,ParticipantSourceTypeId,ParticipantSourceId,OrganizationDepartmentId,SetupId,
				RoundNumber,StatusId,ExaminationDate,DoctorEmployeeId,CreatedUserId,CreatedDateTime,
				UpdatedUserId,UpdatedDateTime,ParentExaminationId,StoreLocationId,CauseId,ProcessTypeId,
				EmployeeCompanyId,TargetGroupId,EmployeeDesignationId,MedicalAgencyId,CriteiraGroupId,EmployeeStatusId,GradeId,LegalEntityId,
				HazardousProcess, DangerousProcess,RawMaterialUsed,PastHistorySelf,HistoryMother,HistoryFather,
				DataEntryTemplateId,ContractorId
			)
			VALUES
			(
				@rOrgId,@rParticipantSourceTypeId,@rParticipantSourceId,@rOrganizationDepartmentId,
				@rSetupId,@rRoundNumber,1,@rExaminationDate,@rDoctorEmployeeId,@rCreatedUserId,sCommon.fGetDate(),
				@rUpdatedUserId,sCommon.fGetDate(),@rParentExaminationId,@rStoreLocationId,@rCauseId,@rProcessTypeId,
				@lEmployeeCompanyId,@lTargetGroupId,@lEmployeeDesignationId,@rMedicalAgencyId,
				CASE WHEN @rCriteriaGroupId = -1 then NULL else @rCriteriaGroupId end,@rEmployeeStatusId,@lGradeId,@lLegalEntityId,
				@lHazardousProcess,@lDangerousProcess,@lRawMaterialUsed,@rPastHistorySelf,@rHistoryMother,@rHistoryFather,
				@rDataEntryTemplateId,@lEmployeeContractorId
			)
			
			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 = count(1) from sExamination.tExamination where isnull(Examinationnumber,'') <> ''
			--and DATEDIFF(day,CONVERT(date, CreatedDateTime, 105),CONVERT(date, sCommon.fGetDate(), 105))>=0 and SetupId = @rSetupId
			--and StoreLocationId = @rStoreLocationId
			select @cnt = Max(Right(ISNULL(Examinationnumber,00000),13)) from sExamination.tExamination where isnull(Examinationnumber,'') <> ''
			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 sExamination.tExamination 
				where isnull(Examinationnumber,'') <> '' 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(8,@rOrgId) = @rSetupId then
			--'OPD-' + convert(varchar,sCommon.fGetDate(),112)  + RIGHT(100000 + (@cnt) ,5) else '' end

			--- mantis : 0036445, Nidhi Pandey; DT - 13/09/2024
			--DECLARE @dateValue DATETIME = sCommon.fGetDate()  -- Replace with your sCommon.fGetDate() if needed
			--DECLARE @updateddateValue VARCHAR(20);
			--SET @updateddateValue = 
			--CONVERT(VARCHAR(8), @dateValue, 112) +  -- yyyyMMdd format
			--REPLACE(CONVERT(VARCHAR(8), @dateValue, 114), ':', '') +  -- HHmmss format
			--RIGHT('000' + CAST(DATEPART(MILLISECOND, @dateValue) AS VARCHAR(3)), 3)

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

			update sExamination.tExamination set Examinationnumber = @prefix where Id = @lNextNumber
		END
		ELSE
		BEGIN
			SET @lNextNumber = @rId
			UPDATE [sExamination].[tExamination] SET OrgId = @rOrgId,ParticipantSourceTypeId  = @rParticipantSourceTypeId,
			ParticipantSourceId  = @rParticipantSourceId,OrganizationDepartmentId = @rOrganizationDepartmentId,
			ExaminationDate = @rExaminationDate,DoctorEmployeeId = case when isnull(@rDoctorFlag,0) = 1 then DoctorEmployeeId else @rDoctorEmployeeId end,
			RoundNumber =  @rRoundNumber,StatusId =  1,ParentExaminationId = @rParentExaminationId,CauseId = @rCauseId,UpdatedUserId =  case when @rUpdatedUserId>0 then @rUpdatedUserId else @rCreatedUserId end,
			UpdatedDateTime = sCommon.fGetDate(),ProcessTypeId=@rProcessTypeId,EmployeeCompanyId=@lEmployeeCompanyId,
			CriteiraGroupId = CASE WHEN @rCriteriaGroupId = -1 then NULL else @rCriteriaGroupId end,
			EmployeeStatusId=@rEmployeeStatusId,GradeId=@lGradeId,TargetGroupId=@lTargetGroupId,LegalEntityId=@lLegalEntityId,
			PastHistorySelf=@rPastHistorySelf,HistoryMother=@rHistoryMother,HistoryFather=@rHistoryFather,DataEntryTemplateId=@rDataEntryTemplateId,MedicalAgencyId=@rMedicalAgencyId
			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,'OPD_Main_DBError',5000,@exceptiondetail,sCommon.fGetDate(),@rCreatedUserId	
		SELECT -1 AS RESULT
		return
	END CATCH	
	
END


GO


CREATE OR ALTER PROCEDURE [sExamination].[pGetAHCAutomationDataForMHI] 
(
	@rSetupGroupId INT,
	@rSetupId INT,
	@rStoreLocationId INT,
	@rOrgId SMALLINT,
	@rUserId BIGINT
)
AS
BEGIN

	WITH ExamCTE AS
	(
		SELECT 
			Exam.Id,
			Exam.ParticipantSourceTypeId,
			Exam.ParticipantSourceId,
			Exam.StoreLocationId
		FROM 
			[sExamination].[tSetupGroupMaster] SGM
		INNER JOIN 
			[sExamination].[tSetupMaster] SM ON SM.SetupGroupId = SGM.Id 
		INNER JOIN 
			[sExamination].[tExamination] Exam ON Exam.SetupId = SM.Id AND Exam.ParticipantSourceTypeId = 95 AND Exam.StatusId = 4
		WHERE
			SGM.Id = @rSetupGroupId 
		AND 
			((@rSetupId = 0) OR (@rSetupId = SM.Id)) AND Exam.IsPublish = 1
		AND
			((@rStoreLocationId = 0) OR (@rStoreLocationId = SM.StoreLocationId))
		AND
			SGM.OrgId =  @rOrgId
	),

	ExamFiltered AS
	(
		SELECT 
			E.*
		FROM 
			ExamCTE E
		INNER JOIN 
			[sSecurity].[tUserLocation] USR
		ON 
			USR.StoreLocationId = E.StoreLocationId
		WHERE 
			USR.UserId = @rUserId
	),

	LabData AS
	(
		SELECT 
			TR.SourceId,
			MAX(CASE WHEN TPM.StaticTestParameterId = 25 THEN CASE WHEN TRD.ServiceValue NOT LIKE '%[^0-9.]%' AND TRD.ServiceValue <> '' THEN CAST(TRD.ServiceValue AS NUMERIC(10,2)) END END) AS HBA1C,
			MAX(CASE WHEN TPM.StaticTestParameterId = 34 THEN CASE WHEN TRD.ServiceValue NOT LIKE '%[^0-9.]%' AND TRD.ServiceValue <> '' THEN CAST(TRD.ServiceValue AS NUMERIC(10,2)) END END) AS LDL
		FROM 
			[sExamination].[tTestRequest] TR
		INNER JOIN 
			[sExamination].[tTestRequestDetail] TRD 
		ON 
			TRD.TestRequestId = TR.Id
		INNER JOIN 
			[sOrderEntry].[tTestDetail] TD 
		ON 
			TD.Id = TRD.TestDetailId
		INNER JOIN 
			[sOrderEntry].[tTestParameterMaster] TPM 
		ON 
			TPM.Id = TD.TestParameterId
		INNER JOIN 
			ExamFiltered E 
		ON 
			E.Id = TR.SourceId 
		WHERE 
			TPM.StaticTestParameterId IN (25, 34) AND  TRD.ServiceValue <> '' AND  TRD.ServiceValue NOT LIKE '%[^0-9.]%'
		GROUP BY 
			TR.SourceId
	)

	SELECT 
		E.ParticipantSourceTypeId,
		E.ParticipantSourceId,
		EM.Code AS EmployeeCode,
		Vital.BloodPressureSystolic AS SystolicBP,
		Vital.BloodPressureDiastolic AS DiastolicBP,
		Vital.BMI AS BMI,
		L.HBA1C AS HBA1C,
		L.LDL AS LDL,
		MHI.Stress AS Stress,
		MHI.Lifestyle AS LifeStyle
	FROM 
		[ExamFiltered] E
	LEFT JOIN 
		[sExamination].[tVital] Vital
	ON 
		Vital.SourceId = E.Id
	LEFT JOIN 
		[sWellness].[tMHIScore] MHI
	ON 
		MHI.EmployeeId = E.ParticipantSourceId
	LEFT JOIN 
		[LabData] L	
	ON 
		L.SourceId = E.Id
	INNER JOIN
		[sHRM].[tEmployeeMaster] EM
	ON
		EM.Id = E.ParticipantSourceId
END

GO


CREATE OR ALTER PROCEDURE [sExamination].[pGetAHCAutomationSchedulerDataForMHI] 
(
	@rSetupGroupId INT,
	@rSetupId INT,
	@rStoreLocationId INT,
	@rOrgId SMALLINT,
	@rUserId BIGINT
)
AS
BEGIN

	WITH ExamCTE AS
	(
		SELECT 
			Exam.Id,
			Exam.ParticipantSourceTypeId,
			Exam.ParticipantSourceId,
			Exam.StoreLocationId
		FROM 
			[sExamination].[tSetupGroupMaster] SGM
		INNER JOIN 
			[sExamination].[tSetupMaster] SM ON SM.SetupGroupId = SGM.Id 
		INNER JOIN 
			[sExamination].[tExamination] Exam ON Exam.SetupId = SM.Id AND Exam.ParticipantSourceTypeId = 95 AND Exam.StatusId = 4
		WHERE
			SGM.Id = @rSetupGroupId 
		AND 
			((@rSetupId = 0) OR (@rSetupId = SM.Id)) AND Exam.IsPublish = 1
		AND
			((@rStoreLocationId = 0) OR (@rStoreLocationId = SM.StoreLocationId))
		AND
			SGM.OrgId =  @rOrgId
	),

	ExamFiltered AS
	(
		SELECT 
			E.*
		FROM 
			ExamCTE E
		INNER JOIN 
			[sSecurity].[tUserLocation] USR
		ON 
			USR.StoreLocationId = E.StoreLocationId
		WHERE 
			((@rUserId = 0) OR (USR.UserId = @rUserId))
	),

	LabData AS
	(
		SELECT 
			TR.SourceId,
			MAX(CASE WHEN TPM.StaticTestParameterId = 25 THEN CASE WHEN TRD.ServiceValue NOT LIKE '%[^0-9.]%' AND TRD.ServiceValue <> '' THEN CAST(TRD.ServiceValue AS NUMERIC(10,2)) END END) AS HBA1C,
			MAX(CASE WHEN TPM.StaticTestParameterId = 34 THEN CASE WHEN TRD.ServiceValue NOT LIKE '%[^0-9.]%' AND TRD.ServiceValue <> '' THEN CAST(TRD.ServiceValue AS NUMERIC(10,2)) END END) AS LDL
		FROM 
			[sExamination].[tTestRequest] TR
		INNER JOIN 
			[sExamination].[tTestRequestDetail] TRD 
		ON 
			TRD.TestRequestId = TR.Id
		INNER JOIN 
			[sOrderEntry].[tTestDetail] TD 
		ON 
			TD.Id = TRD.TestDetailId
		INNER JOIN 
			[sOrderEntry].[tTestParameterMaster] TPM 
		ON 
			TPM.Id = TD.TestParameterId
		INNER JOIN 
			ExamFiltered E 
		ON 
			E.Id = TR.SourceId 
		WHERE 
			TPM.StaticTestParameterId IN (25, 34) AND  TRD.ServiceValue <> '' AND  TRD.ServiceValue NOT LIKE '%[^0-9.]%'
		GROUP BY 
			TR.SourceId
	)

	SELECT DISTINCT
		E.ParticipantSourceTypeId,
		E.ParticipantSourceId,
		EM.Code AS EmployeeCode,
		Vital.BloodPressureSystolic AS SystolicBP,
		Vital.BloodPressureDiastolic AS DiastolicBP,
		Vital.BMI AS BMI,
		L.HBA1C AS HBA1C,
		L.LDL AS LDL,
		MHI.Stress AS Stress,
		MHI.Lifestyle AS LifeStyle
	FROM 
		[ExamFiltered] E
	LEFT JOIN 
		[sExamination].[tVital] Vital
	ON 
		Vital.SourceId = E.Id
	LEFT JOIN 
		[sWellness].[tMHIScore] MHI
	ON 
		MHI.EmployeeId = E.ParticipantSourceId
	LEFT JOIN 
		[LabData] L	
	ON 
		L.SourceId = E.Id
	INNER JOIN
		[sHRM].[tEmployeeMaster] EM
	ON
		EM.Id = E.ParticipantSourceId
END

GO


CREATE OR ALTER PROCEDURE [sExamination].[pGetAnnualHealthCheckupTicketAssignedAllDoctor]          
(          
    @rOrgId INT,          
    @rTemplate NVARCHAR(MAX),          
    @rMailSubject NVARCHAR(MAX),          
    @rProviderAppointmentIds NVARCHAR(MAX) = '',          
    @rEventId INT        
)          
AS        
BEGIN          
    SET NOCOUNT ON;        

    SELECT          
        EM.Id,        
        ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS EmployeeName,        
        EC.CompanyEmail AS ToDoctor,        
        STUFF((        
            SELECT DISTINCT ',' + EC2.CompanyEmail        
            FROM sSupport.tProviderAppointment A2        
            INNER JOIN sHrm.tEmployeeCommunications EC_A2         
                ON EC_A2.EmployeeId = A2.AssignToDoctorId        
            LEFT JOIN sExamination.tSetupEmployee SE2         
                ON SE2.SetupId = A2.SetupId         
                AND SE2.EmployeeId = A2.PatientSourceId         
                AND SE2.SiteDoctorId = A2.AssignToDoctorId        
            LEFT JOIN sHrm.tEmployeeCommunications EC2         
                ON EC2.EmployeeId = SE2.CentralDoctorId        
            WHERE EC_A2.CompanyEmail = EC.CompanyEmail        
              AND SE2.EmployeeId IS NOT NULL        
              AND EC2.CompanyEmail IS NOT NULL        
            FOR XML PATH(''), TYPE        
        ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS CCDoctor        
    INTO #DoctorAssignmentSummary        
    FROM sSupport.tProviderAppointment A        
    INNER JOIN sHrm.tEmployeeMaster EM        
        ON EM.Id = A.AssignToDoctorId        
    INNER JOIN sHrm.tEmployeeCommunications EC         
        ON EC.EmployeeId = A.AssignToDoctorId        
    WHERE A.StatusId <> 591        
      AND ISNULL(A.AssignToDoctorId, 0) <> 0        
      AND (ISNULL(A.Id,0) IN (SELECT CAST(item AS INT) FROM sCommon.fnsplit(ISNULL(@rProviderAppointmentIds,''),',')) OR ISNULL(@rProviderAppointmentIds,'')='')        
    GROUP BY EM.Id, EM.FirstName, EM.LastName, EC.CompanyEmail;        

    SELECT          
        D.Id,        
        D.ToDoctor,        
        D.CCDoctor,        
        D.EmployeeName,        
        SUM(CASE WHEN A.AssignDate >= DATEADD(HOUR, -48, GETDATE()) THEN 1 ELSE 0 END) AS NewAssigned,        
        SUM(CASE WHEN A.AssignDate < DATEADD(HOUR, -48, GETDATE()) THEN 1 ELSE 0 END) AS LongOpen,  
        SUM(CASE WHEN A.HealthIndicatorId = 608 THEN 1 ELSE 0 END) AS HighRisk,  
        SUM(CASE WHEN A.HealthIndicatorId = 607 THEN 1 ELSE 0 END) AS Pending,  
        SUM(CASE WHEN A.HealthIndicatorId = 611 THEN 1 ELSE 0 END) AS Mild,  
        SUM(CASE WHEN A.HealthIndicatorId = 612 THEN 1 ELSE 0 END) AS Moderate  
    INTO #CountDoctorAssign        
    FROM sSupport.tProviderAppointment A        
    INNER JOIN #DoctorAssignmentSummary D ON D.Id = A.AssignToDoctorId        
    WHERE A.StatusId <> 591  
    GROUP BY D.Id, D.ToDoctor, D.CCDoctor, D.EmployeeName;        

    -- Corrected final SELECT with proper CROSS APPLY syntax
    SELECT          
        C.Id,        
        C.ToDoctor AS EmailId,        
        C.CCDoctor AS strCC,        
        C.NewAssigned,   
        C.LongOpen,       
        C.Pending,        
        C.HighRisk,     
        C.Mild,        
        C.Moderate,     
        @rMailSubject AS Subject,        
        CA2.MsgText
    FROM #CountDoctorAssign C       
    CROSS APPLY (
        SELECT REPLACE(
               REPLACE(
               REPLACE(
               REPLACE(
               REPLACE(
               REPLACE(
               REPLACE(
                   @rTemplate,
                   '[AssignedDoctor]', C.EmployeeName),
                   '[NewAssigned]', ISNULL(NULLIF(CAST(C.NewAssigned AS NVARCHAR(20)), '0'), '')),
                   '[LongOpen]', ISNULL(NULLIF(CAST(C.LongOpen AS NVARCHAR(20)), '0'), '')),
                   '[Pending]', ISNULL(NULLIF(CAST(C.Pending AS NVARCHAR(20)), '0'), '')),
                   '[HighRisk]', ISNULL(NULLIF(CAST(C.HighRisk AS NVARCHAR(20)), '0'), '')),
                   '[Mild]', ISNULL(NULLIF(CAST(C.Mild AS NVARCHAR(20)), '0'), '')),
                   '[Moderate]', ISNULL(NULLIF(CAST(C.Moderate AS NVARCHAR(20)), '0'), ''))
    ) CA1(Msg1)   -- table alias with column alias
    CROSS APPLY (
        SELECT REPLACE(
               REPLACE(
               REPLACE(
               REPLACE(
               REPLACE(
               REPLACE(
               REPLACE(
               REPLACE(
                   CA1.Msg1,
                   '<p>New Assigned: </p>', ''),
                   '<p>Long Open: </p>', ''),
                   '<p>Pending: </p>', ''),
                   '<p>High Risk: </p>', ''),
                   '<p>Mild: </p>', ''),
                   '<p>Moderate: </p>', ''),
                   '<p>&nbsp;</p>', ''),
                   '<p> </p>', '')
    ) CA2(MsgText)   -- table alias with column alias
    WHERE ISNULL(C.ToDoctor, '') <> '';    

    IF OBJECT_ID('tempdb..#DoctorAssignmentSummary') IS NOT NULL              
        DROP TABLE #DoctorAssignmentSummary;        
    IF OBJECT_ID('tempdb..#CountDoctorAssign') IS NOT NULL              
        DROP TABLE #CountDoctorAssign;        
END;

GO


CREATE OR ALTER PROCEDURE [sExamination].[pGetDiagnosisUpdateDataForMHI] 
(
	@ExaminationIds VARCHAR(MAX),
	@rOrgId SMALLINT
)
AS
BEGIN

	;WITH ExamIds AS
	(
		SELECT CAST(value AS BIGINT) AS ExaminationId
		FROM [dbo].[SplitString](@ExaminationIds, ',')
	)

	SELECT
		E.ParticipantSourceTypeId,
		E.ParticipantSourceId,
		EM.Code AS EmployeeCode,
		V.BloodPressureSystolic AS SystolicBP,
		V.BloodPressureDiastolic AS DiastolicBP,
		V.BMI AS BMI,
		H.HBA1C AS HBA1C,
		L.LDL AS LDL,
		MHI.Stress AS Stress,
		MHI.Lifestyle AS LifeStyle
	FROM ExamIds EI
	INNER JOIN sExamination.tExamination E ON E.Id = EI.ExaminationId AND E.ParticipantSourceTypeId = 95 AND E.StatusId = 4 AND E.IsPublish = 1
	INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id = E.ParticipantSourceId AND EM.OrgID = 1002
	LEFT JOIN sWellness.tMHIScore MHI ON MHI.EmployeeId = EM.Id 
	LEFT JOIN sExamination.tVital V ON V.SourceId = E.Id

	OUTER APPLY
	(
		SELECT TOP 1
			CAST(ISNULL(TRD.ServiceValue,0) AS NUMERIC(10,2)) AS HBA1C
		FROM sExamination.tTestRequest TR
		INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id
		INNER JOIN sOrderEntry.tTestDetail TD ON TD.Id = TRD.TestDetailId
		INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
		WHERE TR.SourceId = E.Id
		  AND TPM.StaticTestParameterId = 25
		  AND CAST(TRD.ServiceValue AS FLOAT) > 0
		ORDER BY TRD.Id DESC
	) H

	OUTER APPLY
	(
		SELECT TOP 1
			CAST(ISNULL(TRD.ServiceValue,0) AS NUMERIC(10,2)) AS LDL
		FROM sExamination.tTestRequest TR
		INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id
		INNER JOIN sOrderEntry.tTestDetail TD ON TD.Id = TRD.TestDetailId
		INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
		WHERE TR.SourceId = E.Id
		  AND TPM.StaticTestParameterId = 34
		  AND CAST(TRD.ServiceValue AS FLOAT) > 0
		ORDER BY TRD.Id DESC
	) L;
END


GO


ALTER proc [sExamination].[pGetEmployeeExaminationVisitDatasNg_New]
@rExaminationId bigint,
@rPageIndex int,
@rflg int,
@rPatientType int,
@rorg int,
@rexamID bigint
as
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
begin
	declare @header varchar(max)='',@res varchar(max)='',@lpaging varchar(max)='',@TotalRecords int,@PageSize int=500
	declare @rParticipantSourceTypeId int,@rEmployeeId bigint,@rOrgId int
	
	select @rParticipantSourceTypeId = @rPatientType,@rEmployeeId = @rExaminationId,@rOrgId = @rorg	
	
	declare @tbltmp table(tid int identity(1,1),exid bigint)
	create table #tbltmparchive (tid int identity(1,1),exid bigint)

	if @rflg = 1
	begin
		insert into @tbltmp
		select ED.Id from sExamination.tExamination ED
		left join sExamination.tDiagnosis D ON ED.Id=D.SourceId
		where ((ED.Id = @rexamID) or (@rexamID = 0))
		and OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
		and ParticipantSourceTypeId = @rParticipantSourceTypeId
		and ED.Id not in (select SourceId from sExamination.tPrescription Where IsDirect = 1)
		order by ED.Id desc
		OPTION (RECOMPILE)

		insert into #tbltmparchive
		select ED.Id from sExamination.tArchieveExamination ED
		left join sExamination.tArchieveDiagnosis D ON ED.Id=D.SourceId
		where ((ED.Id = @rexamID) or (@rexamID = 0))
		and OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
		and ParticipantSourceTypeId = @rParticipantSourceTypeId
		and ED.Id not in (select SourceId from sExamination.tArchievePrescription Where IsDirect = 1)
		order by ED.Id desc
		OPTION (RECOMPILE)
	end
	else
	begin
		insert into @tbltmp
		select ED.Id from sExamination.tExamination ED
		inner join sExamination.tSetupMaster SM on ED.SetupId = SM.Id
		inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
		left join sExamination.tDiagnosis D ON ED.Id=D.SourceId
		where ((ED.Id = @rexamID) or (@rexamID = 0))
		and ED.OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
		and ParticipantSourceTypeId = @rParticipantSourceTypeId and STM.MainTypeId = 8
		and ED.Id not in (select SourceId from sExamination.tPrescription Where IsDirect = 1)
		order by ED.Id desc
		OPTION (RECOMPILE)

		insert into #tbltmparchive
		select ED.Id from sExamination.tArchieveExamination ED
		inner join sExamination.tSetupMaster SM on ED.SetupId = SM.Id
		inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
		left join sExamination.tArchieveDiagnosis D ON ED.Id=D.SourceId
		where ((ED.Id = @rexamID) or (@rexamID = 0))
		and ED.OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
		and ParticipantSourceTypeId = @rParticipantSourceTypeId and STM.MainTypeId = 8
		and ED.Id not in (select SourceId from sExamination.tArchievePrescription Where IsDirect = 1)
		order by ED.Id desc
		OPTION (RECOMPILE)
	end
	
	select @TotalRecords = count(*)	from @tbltmp
	select @TotalRecords = @TotalRecords + count(*)	from #tbltmparchive
	select @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@rPageindex,@TotalRecords,@PageSize)

	--select * from @tbltmp
		
	select  isnull(Mt.Title,'') as MtTitle,
	 isnull(SL.Title,'') as SLTitle ,
	 convert(varchar(10),isnull(ED.ExaminationDate,''),103) as EDExamnationDate, 
	 isnull(SM.Title,'') as SMTitle,
    case when STM.MainTypeId = 8 then
	Convert(varchar(1000),isnull(sExamination.fDiseaseGet(ED.Id),'')) else Convert(varchar(1000),isnull(D.DiagnosisRemark,'')) end as DiagnosisRemark,
    case when STM.MainTypeId = 8 then 'Remark - ' + isnull(VIT.Remark, '') + CHAR(13) + CHAR(10) + 'FollowUp Remark - ' + isnull(APP.FollowupRemark, '')
	else convert(varchar(1000),isnull(D.RecommendationEnglish,'')) END as RecommendationEnglish, 
    convert(varchar,ED.Id) as EDId,
    convert(varchar,ED.ParticipantSourceId) as ParticipantSourceId,
    convert(varchar,ED.ParticipantSourceTypeId) as ParticipantSourceTypeId,
    case when ED.ParticipantSourceTypeId = 95 then convert(varchar,EP.GenderId)
    when ED.ParticipantSourceTypeId = 1001 then convert(varchar,EFD.GenderId) else
    convert(varchar,CS.GenderId) end  as GenderId,
    case when ED.ParticipantSourceTypeId = 95 then convert(varchar,isnull(datediff(yy,EP.DateOfBirth,getdate()),0))
    when ED.ParticipantSourceTypeId = 1001 then convert(varchar,isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)) else
    convert(varchar,isnull(datediff(yy,CS.DateOfBirth,getdate()),0)) end as Age,
    convert(varchar,STM.MainTypeId) as MainTypeId, convert(varchar,SM.Id) as SetupId,
	ParticipantCode = CASE ED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN CS.Code END,
	ParticipantName = CASE ED.ParticipantSourceTypeId WHEN 1009 THEN
	(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'')) end)
	WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END,
	ISNULL(ED.ExaminationNumber,'') AS ExaminationNumber
    from sExamination.tExamination ED
    inner join sIp.tStoreLocationMaster SL on ED.StoreLocationId = SL.Id
    inner join sExamination.tSetupMaster SM on ED.SetupId = SM.Id
	inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
	inner join sExamination.tMainTypeMaster Mt on STM.MainTypeId = Mt.Id
	left join sHrm.tEmployeeMaster EM on EM.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 95
	left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 1001
	left join sHrm.tCSRBenefiterMaster CS on CS.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	LEFT JOIN sExamination.tVital VIT ON VIT.SourceId = ED.Id
	LEFT JOIN sAppointment.tAppointment APP ON APP.ReferSourceId = ED.Id
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= ED.Id
	left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId
	left join sExamination.tDiagnosis D ON ED.Id=D.SourceId
	inner join @tbltmp tmp On tmp.exid = ED.Id
	where ((ED.Id = @rexamID) or (@rexamID = 0))
	and ED.OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
	and ParticipantSourceTypeId = @rParticipantSourceTypeId
	and ED.Id not in (select SourceId from sExamination.tPrescription Where IsDirect = 1)
	and tid	between ((@PageSize * (@rPageindex-1)) + 1) and (@PageSize * @rPageindex)
	and ISNULL(ED.IsCancel, 0) = 0
	order by ED.ExaminationDate desc
	OPTION (RECOMPILE)
	
	

	select 
	 isnull(Mt.Title,'') as MtTitle ,
	 isnull(SL.Title,'') as SLTitle,
	 convert(varchar(10),isnull(ED.ExaminationDate,''),103) as EDExamnationDate,
	 isnull(SM.Title,'') as SMTitle,
	 case when STM.MainTypeId = 8 then
	 Convert(varchar(1000),isnull(sExamination.fDiseaseGet(ED.Id),'')) else convert(varchar(1000),isnull(D.DiagnosisRemark,'')) end as DiagnosisRemark ,
	 case when STM.MainTypeId = 8 then 'Remark - ' + isnull(VIT.Remark, '') + CHAR(13) + CHAR(10) + 'FollowUp Remark - ' + isnull(APP.FollowupRemark, '')
	 else Convert(varchar(1000),isnull(D.RecommendationEnglish,'')) END as RecommendationEnglish,
	 convert(varchar,ED.Id)as EDId,
     convert(varchar,ED.ParticipantSourceId)as ParticipantSourceId,
     convert(varchar,ED.ParticipantSourceTypeId) as ParticipantSourceTypeId ,
     case when ED.ParticipantSourceTypeId = 95 then convert(varchar,EP.GenderId)
    when ED.ParticipantSourceTypeId = 1001 then convert(varchar,EFD.GenderId) else
    convert(varchar,CS.GenderId) end as GenderId,
    case when ED.ParticipantSourceTypeId = 95 then convert(varchar,isnull(datediff(yy,EP.DateOfBirth,getdate()),0))
    when ED.ParticipantSourceTypeId = 1001 then convert(varchar,isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)) else
    convert(varchar,isnull(datediff(yy,CS.DateOfBirth,getdate()),0)) end as Age,
    convert(varchar,STM.MainTypeId) as STMMainTypeId, convert(varchar,SM.Id) as SetupId,
	ParticipantCode = CASE ED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN CS.Code END,
	ParticipantName = CASE ED.ParticipantSourceTypeId WHEN 1009 THEN
	(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'')) end)
	WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END,
	ISNULL(ED.ExaminationNumber,'') AS ExaminationNumber
    from sExamination.tArchieveExamination ED
    inner join sIp.tStoreLocationMaster SL on ED.StoreLocationId = SL.Id
    inner join sExamination.tSetupMaster SM on ED.SetupId = SM.Id
	inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id	
	inner join sExamination.tMainTypeMaster Mt on STM.MainTypeId = Mt.Id
	left join sHrm.tEmployeeMaster EM on EM.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 95
	left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 1001
	left join sHrm.tCSRBenefiterMaster CS on CS.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	LEFT JOIN sExamination.tVital VIT ON VIT.SourceId = ED.Id
	LEFT JOIN sAppointment.tAppointment APP ON APP.ReferSourceId = ED.Id
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= ED.Id
	left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId
	left join sExamination.tArchieveDiagnosis D ON ED.Id=D.SourceId,#tbltmparchive 
	where exid = ED.Id and ((ED.Id = @rexamID) or (@rexamID = 0))
	and ED.OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
	and ParticipantSourceTypeId = @rParticipantSourceTypeId
	and ED.Id not in (select SourceId from sExamination.tArchievePrescription Where IsDirect = 1)
	and tid	between ((@PageSize * (@rPageindex-1)) + 1) and (@PageSize * @rPageindex)
	order by ED.ExaminationDate desc
	OPTION (RECOMPILE)
	
	select @res = isnull(@res,'')
	select @res as result,@lpaging as paging
	OPTION (RECOMPILE)
	Drop Table #tbltmparchive
	SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off
end

GO


CREATE OR ALTER PROCEDURE [sExamination].[pGetEmployeeTestParameter] 
(
	@rOrgId SMALLINT,
	@rEmployeeCode NVARCHAR(100)
)
AS
SET NOCOUNT ON;
BEGIN

	DECLARE @EmployeeId BIGINT =
	(
		SELECT Id 
		FROM [sHrm].[tEmployeeMaster] 
		WHERE Code = @rEmployeeCode
	)

	DECLARE @lLatestVitalDisplayConfigVal VARCHAR(10) = 'False'

	IF(@EmployeeId IS NULL OR @EmployeeId = 0)
	BEGIN
		RETURN;
	END

	CREATE TABLE #EmployeeExamination
	(
		EId BIGINT PRIMARY KEY,
		ExaminationDate DATE,
		Round NVARCHAR(1000),
		RoundGroup NVARCHAR(1000)
	)

	INSERT INTO #EmployeeExamination
	SELECT 
		Exam.Id,
		Exam.ExaminationDate,
		SM.Title,
		SGM.Title
	FROM [sExamination].[tExamination] Exam
	INNER JOIN
		[sExamination].[tSetupMaster] SM 
	ON 
		SM.Id = Exam.SetupId
	INNER JOIN
		[sExamination].[tSetupGroupMaster] SGM 
	ON 
		SGM.Id = SM.SetupGroupId
	WHERE Exam.ParticipantSourceId = @EmployeeId

	---------------------------------------------------
	-- 2. Centralized Test Data
	---------------------------------------------------
	CREATE TABLE #TestData
	(
		EId BIGINT,
		ExaminationDate DATE,
		StaticTestParameterId INT,
		ServiceValue NVARCHAR(100)
	)

	INSERT INTO #TestData
	SELECT 
		E.Id,
		E.ExaminationDate,
		TP.StaticTestParameterId,
		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
	INNER JOIN sExamination.tSetupMaster SM ON SM.Id = E.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM ON STM.Id = SM.SubTypeId
	WHERE 
		E.ParticipantSourceId = @EmployeeId
		AND E.ParticipantSourceTypeId = 95
		AND ISNULL(TRD.ServiceValue,'') <> ''
		AND ((@lLatestVitalDisplayConfigVal = 'True') OR (@lLatestVitalDisplayConfigVal = 'False' AND STM.MainTypeId != 8))
		AND TP.StaticTestParameterId IN (2,19,20,21,25,27,31,32,33,34,38,49,54,126,127)

	CREATE NONCLUSTERED INDEX IX_TestData 
	ON #TestData (StaticTestParameterId, ExaminationDate DESC)

	SELECT 
		EE.ExaminationDate,
		EE.Round,
		EE.RoundGroup,
		ISNULL(CONVERT(DECIMAL(10,2), ROUND(D.HealthIndex,2)),0) AS HealthIndex,
		ISNULL(Vtl.BMI,0) AS BMI,
		ISNULL(Vtl.BloodPressureSystolic,0) AS BPSystolic,
		ISNULL(Vtl.BloodPressureDiastolic,0) AS BPDiastolic,
		ISNULL(HBData.HB,0) AS HB,
		ISNULL(HBA1CData.HBA1C,0) AS HBA1C,
		ISNULL(Vtl.BodyWeight,0) AS Weight,
		ISNULL(CholData.Cholesterol,0) AS Cholesterol,
		ISNULL(FBSData.FBS,0) AS FBS,
		ISNULL(HDLData.HDL,0) AS HDL,
		ISNULL(LDLData.LDL,0) AS LDL,
		ISNULL(PPBSData.PPBS,0) AS PPBS,
		ISNULL(RBSData.RBS,0) AS RBS,
		ISNULL(CreatinineData.SerumCreatinine,0) AS SerumCreatinine,
		ISNULL(UricAcidData.UricAcid,0) AS SerumUricAcid,
		ISNULL(SGPTData.SGPT,0) AS SGPT,
		ISNULL(TriglycerideData.Triglyceride,0) AS Triglyceride,
		ISNULL(TSHData.TSH,0) AS TSH,
		ISNULL(B12Data.VitaminB12,0) AS VitaminB12,
		ISNULL(D3Data.VitaminD3,0) AS VitaminD3
	FROM 
		#EmployeeExamination EE
	LEFT JOIN 
		[sExamination].[tVital] Vtl ON Vtl.SourceId = EE.EId
	LEFT JOIN 
		[sExamination].[tExamination] E ON E.Id = EE.EId AND E.ParticipantSourceTypeId = 95
	LEFT JOIN 
		[sExamination].[tDiagnosis] D ON D.SourceId = E.Id AND ISNULL(D.HealthIndex,0) > 0
	LEFT JOIN 
		[sExamination].[tSetupMaster] SM  ON SM.Id = E.SetupId
	LEFT JOIN 
		[sExamination].[tSubTypeMaster] STM ON STM.Id = SM.SubTypeId AND STM.MainTypeId = 1
	OUTER APPLY	-- FBS (19)
	(
		SELECT TOP 1 TD.ServiceValue AS FBS
		FROM #TestData TD WHERE TD.StaticTestParameterId = 19 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) FBSData

	OUTER APPLY -- HBA1C (25)
	(
		SELECT TOP 1 TD.ServiceValue AS HBA1C
		FROM #TestData TD WHERE TD.StaticTestParameterId = 25 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) HBA1CData

	OUTER APPLY -- LDL (34)
	(
		SELECT TOP 1 TD.ServiceValue AS LDL
		FROM #TestData TD WHERE TD.StaticTestParameterId = 34 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) LDLData

	OUTER APPLY -- Cholesterol (31)
	(
		SELECT TOP 1 TD.ServiceValue AS Cholesterol
		FROM #TestData TD WHERE TD.StaticTestParameterId = 31 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) CholData

	OUTER APPLY -- RBS (21)
	(
		SELECT TOP 1 TD.ServiceValue AS RBS
		FROM #TestData TD WHERE TD.StaticTestParameterId = 21 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) RBSData

	OUTER APPLY -- HB (2)
	(
		SELECT TOP 1 TD.ServiceValue AS HB
		FROM #TestData TD WHERE TD.StaticTestParameterId = 2 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) HBData

	OUTER APPLY -- HDL (2)
	(
		SELECT TOP 1 TD.ServiceValue AS HDL
		FROM #TestData TD WHERE TD.StaticTestParameterId = 33 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) HDLData

	OUTER APPLY -- PPBS (20)
	(
		SELECT TOP 1 TD.ServiceValue AS PPBS
		FROM #TestData TD WHERE TD.StaticTestParameterId = 20 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) PPBSData

	OUTER APPLY -- SERUM CREATININE (27)
	(
		SELECT TOP 1 TD.ServiceValue AS SerumCreatinine
		FROM #TestData TD WHERE TD.StaticTestParameterId = 27 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) CreatinineData

	OUTER APPLY -- SERUM URIC ACID (49)
	(
		SELECT TOP 1 TD.ServiceValue AS UricAcid
		FROM #TestData TD WHERE TD.StaticTestParameterId = 49 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) UricAcidData

	OUTER APPLY -- SGPT (38)
	(
		SELECT TOP 1 TD.ServiceValue AS SGPT
		FROM #TestData TD WHERE TD.StaticTestParameterId = 38 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) SGPTData

	OUTER APPLY -- Triglyceride (32)
	(
		SELECT TOP 1 TD.ServiceValue AS Triglyceride
		FROM #TestData TD WHERE TD.StaticTestParameterId = 32 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) TriglycerideData

	OUTER APPLY -- TSH (54)
	(
		SELECT TOP 1 TD.ServiceValue AS TSH
		FROM #TestData TD WHERE TD.StaticTestParameterId = 54 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) TSHData
	
	OUTER APPLY -- Vitamin B12 (126)
	(
		SELECT TOP 1 TD.ServiceValue AS VitaminB12
		FROM #TestData TD WHERE TD.StaticTestParameterId = 126 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) B12Data
	
	OUTER APPLY -- Vitamin D3 (127)
	(
		SELECT TOP 1 TD.ServiceValue AS VitaminD3
		FROM #TestData TD WHERE TD.StaticTestParameterId = 127 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) D3Data

	ORDER BY EE.ExaminationDate DESC
	
	DROP TABLE #EmployeeExamination
	DROP TABLE #TestData

END

GO


CREATE OR ALTER PROCEDURE [sExamination].[pGetRoundGroupStatusDataForMHI] 
(
    @rMainTypeId INT,
    @rSetupGroupId INT,
    @rSetupIds NVARCHAR(MAX),
    @rUserId BIGINT,
    @rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;
 
	-- STEP 1: Split SetupIds once

	SELECT TRY_CAST(value AS BIGINT) AS SetupId
	INTO #SetupIds
	FROM dbo.SplitString(@rSetupIds, ',')
	WHERE @rSetupIds IS NOT NULL;

	CREATE INDEX IX_#SetupIds ON #SetupIds(SetupId);
 
	-- STEP 2: Filter base data early (very important)

	SELECT 
		STP.Id AS SetupId,
		STP.Title,
		EXM.Id AS ExaminationId,
		EXM.ParticipantSourceId,
		EXM.ParticipantSourceTypeId,
		EXM.StoreLocationId
	INTO 
		#ExamBase
	FROM 
		sExamination.tSetupMaster STP
	INNER JOIN 
		sExamination.tExamination EXM ON EXM.SetupId = STP.Id AND EXM.ParticipantSourceTypeId = 95 AND EXM.StatusId = 4 AND EXM.IsPublish = 1
	INNER JOIN 
		sExamination.tSubTypeMaster STM ON STM.Id = STP.SubTypeId
	INNER JOIN 
		sSecurity.tUserLocation USR ON USR.StoreLocationId = EXM.StoreLocationId
	WHERE 
			STP.OrgId = @rOrgId
		AND STP.IsObsolete = 0 AND (STM.MainTypeId = @rMainTypeId OR @rMainTypeId = 0)
		AND STP.SetupGroupId = @rSetupGroupId AND USR.UserId = @rUserId
		AND (@rSetupIds IS NULL OR STP.Id IN (SELECT SetupId FROM #SetupIds));
 
	CREATE CLUSTERED INDEX IX_#ExamBase ON #ExamBase(ExaminationId);

	SELECT 
		TR.SourceId AS ExaminationId,
		MAX(CASE WHEN TPM.StaticTestParameterId = 25 THEN CAST(TRD.ServiceValue AS NUMERIC(10,2)) END) AS HBA1C,
		MAX(CASE WHEN TPM.StaticTestParameterId = 34 THEN CAST(TRD.ServiceValue AS NUMERIC(10,2)) END) AS LDL
	INTO 
		#LabData
	FROM
		[sExamination].[tTestRequest] TR
	INNER JOIN 
		[sExamination].[tTestRequestDetail] TRD ON TRD.TestRequestId = TR.Id
	INNER JOIN 
		[sOrderEntry].[tTestDetail] TD ON TD.Id = TRD.TestDetailId
	INNER JOIN 
		[sOrderEntry].[tTestParameterMaster] TPM ON TPM.Id = TD.TestParameterId
	INNER JOIN 
		#ExamBase EB ON EB.ExaminationId = TR.SourceId 
	WHERE 
		TPM.StaticTestParameterId IN (25,34) AND CAST(TRD.ServiceValue AS FLOAT) > 0
	GROUP BY
		TR.SourceId;
 
	CREATE CLUSTERED INDEX IX_#LabData ON #LabData(ExaminationId);
 
	-- STEP 4: Final select

	SELECT 
		EB.ParticipantSourceTypeId,
		EB.ParticipantSourceId,
		EM.Code AS EmployeeCode,
		Vital.BloodPressureSystolic AS SystolicBP,
		Vital.BloodPressureDiastolic AS DiastolicBP,
		Vital.BMI AS BMI,
		LD.HBA1C AS HBA1C,
		LD.LDL AS LDL,
		MHI.Stress AS Stress,
		MHI.Lifestyle AS LifeStyle
	FROM 
		#ExamBase EB
	INNER JOIN 
		[sIp].[tStoreLocationMaster] SLM ON SLM.Id = EB.StoreLocationId
	LEFT JOIN 
		[sExamination].[tVital] Vital ON Vital.SourceId = EB.ExaminationId
	LEFT JOIN 
		[sWellness].[tMHIScore] MHI ON MHI.EmployeeId = EB.ParticipantSourceId AND EXISTS ( SELECT 1 FROM [sExamination].[tExamination] E WHERE E.Id = EB.ExaminationId)
	LEFT JOIN 
		#LabData LD ON LD.ExaminationId = EB.ExaminationId
	INNER JOIN
		[sHrm].[tEmployeeMaster] EM ON EM.Id = EB.ParticipantSourceId
	--WHERE
	--	MHI.Stress > 0 OR MHI.Lifestyle > 0

	DROP TABLE #SetupIds
	DROP TABLE #LabData
	DROP TABLE #ExamBase

END

GO


ALTER PROC [sExamination].[pImportALLExaminationDatas]  
@rstrExaminationXML varchar(max),      
@rstrVitalXML varchar(max),      
@rstrDiseaseXML varchar(max),      
@rstrHabitXML varchar(max),      
@rstrHistoryXML varchar(max),      
@rstrDiagnosisXML varchar(max),      
@rstrTestXML varchar(max),      
@rMainTypeId int,      
@rstr varchar(50),      
@rstrGeneralXML varchar(max),      
@rstrPulmonary varchar(max) = null,      
@rstrAudiometry varchar(max) = null,     
@rIsTemplateReview bit = 0,  
@rUserId bigint      
as      
begin       
 declare @loXMLExamination xml,@loXMLVital xml,@loXMLDisease xml,@loXMLHabit xml,@loXMLHistory xml,      
 @loXMLDiagnisis xml,@loXMLTest xml,@loXMLGeneral xml,@loXMLPulmonary xml,@loXMLAudiometry xml      
       
 declare @exceptiondetail varchar(max),@orgid int      
       
  
  
 set @orgid =(select Top 1 Orgid from sExamination.tExamination order by Id desc)   --added cause some cases orgid is picking 0  
   
    -- Mantis: 0036720 by Shivam (20-09-2024)  
 Declare @rConfigBloodGroup int, @rConfigColorVision int = 0, @TitleColorVision NVARCHAR(20), @IdColorVision int;   
 select @rConfigBloodGroup =   
  CASE  
   WHEN sConfig.fConfigurationValueGet('Examination.BloodGroupCarryForwardFromHR',@orgid,0,0,0) = 'True'   
   THEN 1 ELSE 0   
  END  
  
 select @rConfigColorVision =   
  CASE  
   WHEN sConfig.fConfigurationValueGet('Examination.GeneralTestColorVisionCarryForward',@orgid,0,0,0) = 'True'   
   THEN 1 ELSE 0   
  END  
  
 BEGIN TRY       
  SET @loXMLExamination = CAST(@rstrExaminationXML AS xml)      
  SET @loXMLVital = CAST(@rstrVitalXML AS xml)      
  SET @loXMLDisease = CAST(@rstrDiseaseXML AS xml)      
  SET @loXMLHabit = CAST(@rstrHabitXML AS xml)      
  SET @loXMLHistory = CAST(@rstrHistoryXML AS xml)      
  SET @loXMLDiagnisis = CAST(@rstrDiagnosisXML AS xml)       
  SET @loXMLTest = CAST(@rstrTestXML AS xml)      
  SET @loXMLGeneral = CAST(@rstrGeneralXML as xml)      
  SET @loXMLPulmonary = CAST(@rstrPulmonary as xml)      
  SET @loXMLAudiometry = CAST(@rstrAudiometry AS xml)      
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select '',0,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  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">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
 IF OBJECT_ID('tempdb..#tbltmpExamination') IS NOT NULL      
 DROP TABLE #tbltmpExamination      
      
  Create table #tbltmpExamination      
  (      
   tid int identity(1,1),e_ParticipantSourceId bigint,e_StoreLocationId int,e_SetupId int,e_NatureId int,      
   e_ExaminationDate varchar(50),e_DoctorName varchar(300),e_DoctorId bigint,e_ProcessTypeId int,e_CriteriaGroupId int,      
   e_CompanyId int,e_TargetGroupId int,e_DesignationId int,e_GradeId int,e_DepartmentId int,e_OrgId int,e_examinationid bigint,      
   e_MedicalId int,e_SetupGroupId int,e_ProcessId int,e_TargetId int,e_ColorVisionId int,e_LegalEntityId int,e_PastHistorySelf nvarchar(2000),
   e_ContractorId int,e_IsNewDiabetic bit, e_IsNewHypertension bit
  )     
  insert into #tbltmpExamination      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@LocationId','int') as LocationId,      
  T.c.value('@SetupId','int') as SetupId,      
  T.c.value('@NatureId','int') as NatureId,      
  T.c.value('@Examination_Date','varchar(200)') as Examination_Date,      
  T.c.value('@Doctor','varchar(200)') as Doctor,      
  T.c.value('@DoctorId','varchar(200)') as DoctorId,      
  0,0,0,0,0,0,0,0,null,T.c.value('@MedicalId','int') as MedicalId,null,      
  T.c.value('@ProcessId','int') as ProcessId,      
  T.c.value('@TargetGroupId','int') as TargetGroupId,      
  T.c.value('@ColorVisionId','int') as ColorVisionId,0,'',null,0,0
  from @loXMLExamination.nodes('/Examinations/Examination')T(c)      
        
  update #tbltmpExamination set       
  e_ProcessTypeId = JD.ProcessTypeId,      
  e_TargetGroupId = EM.TargetGroupId,      
  e_CompanyId = JD.EmployeeCompanyId,e_DesignationId = JD.EmployeeDesignationId,e_GradeId = JD.GradeId,      
  e_DepartmentId = JD.OrganizationDepartmentId,e_OrgId = EM.OrgId,e_LegalEntityId=JD.LegalEntityId, 
  e_ContractorId = JD.ContractorId 
  from #tbltmpExamination inner join sHrm.tEmployeeMaster EM on e_ParticipantSourceId = EM.Id      
  inner join sHrm.tEmployeeJobDetail JD on e_ParticipantSourceId = JD.EmployeeId      
          
  update JD Set JD.ProcessTypeId=t.e_ProcessId      
  from sHrm.tEmployeeJobDetail JD      
  inner join #tbltmpExamination t on t.e_ParticipantSourceId = JD.EmployeeId      
  where Isnull(t.e_ProcessId,0)>0      
        
  update JD Set JD.TargetGroupId=t.e_TargetId      
  from shrm.temployeemaster JD      
  inner join #tbltmpExamination t on t.e_ParticipantSourceId = JD.Id      
  inner join sExamination.tSetupMaster SM on SM.Id =t.e_SetupId      
  where Isnull(t.e_TargetId,0)>0 and Isnull(SM.IsTargetGroupRestrictInHR,0)=0      
      
      
  update #tbltmpExamination set e_SetupGroupId = SetupGroupId from sExamination.tSetupMaster where e_SetupId = Id      
         
  MERGE sHrm.tEmployeePersonalDetail AS Target USING       
  (      
   SELECT e_ParticipantSourceId,e_ColorVisionId,tid      
   FROM #tbltmpExamination TT LEFT JOIN sHrm.tEmployeePersonalDetail T ON TT.e_ParticipantSourceId = T.EmployeeId      
  ) AS Source ON Target.EmployeeId = Source.e_ParticipantSourceId      
  WHEN MATCHED THEN      
   UPDATE SET Target.ColorVisionId = case when Isnull(e_ColorVisionId,0) > 0 then e_ColorVisionId else ColorVisionId end; -- as per discussion with raju sir on 18/02/2020 done by MS (Mentis Issue no:10840)      
          
  IF (@rConfigColorVision = 1)  
  BEGIN  
   --SELECT e_ParticipantSourceId, e_ColorVisionId FROM #tbltmpExamination TTE;  
  
   UPDATE EPD   
   SET ColorVisionId = TE.e_ColorVisionId  
   FROM sHrm.tEmployeePersonalDetail EPD  
   LEFT JOIN #tbltmpExamination TE   
    ON TE.e_ParticipantSourceId = EPD.EmployeeId  
   WHERE EPD.EmployeeId = TE.e_ParticipantSourceId and Isnull(TE.e_ColorVisionId,0) > 0 ;  
  END  
  
  declare @cntExam int,@incExam int      
  select @cntExam = count(*),@incExam = 1 from #tbltmpExamination      
        
  update #tbltmpExamination set e_examinationid = Id from sExamination.tExamination where ParticipantSourceId = e_ParticipantSourceId      
  and ParticipantSourceTypeId = 95 and e_SetupId = SetupId      
  IF OBJECT_ID('tempdb..#tbltmpExaminationNull') IS NOT NULL      
  DROP TABLE #tbltmpExaminationNull      
  Create table #tbltmpExaminationNull(tid int identity(1,1),e_ParticipantSourceId bigint,e_SetupId int)      
  insert into #tbltmpExaminationNull      
  select e_ParticipantSourceId,e_SetupId from #tbltmpExamination where isnull(e_examinationid,0) <> 0      
         
  declare @lNextNumber bigint,@lFromNextNumber bigint,@lOrgId int,@lCount int,@IsExaminationDateEdit varchar(200)      
  select top 1 @lOrgId = e_orgid from #tbltmpExamination      
  
  ;WITH LastExaminations AS (
	SELECT
		EXM.*,
		ROW_NUMBER() OVER (
			PARTITION BY EXM.ParticipantSourceId, EXM.ParticipantSourceTypeId 
			ORDER BY EXM.ExaminationDate DESC
		) AS rn
	FROM sExamination.tExamination EXM
	Where EXM.SetupId <> [sCommon].[fGetIntIdForOrg](8, @lOrgId)
	)
	UPDATE t
	SET 
	t.e_IsNewDiabetic = DIA.IsNewDiabatic,
	t.e_IsNewHypertension = DIA.IsNewHypertension
	FROM #tbltmpExamination t
	INNER JOIN LastExaminations EXM
		ON EXM.ParticipantSourceId = t.e_ParticipantSourceId AND EXM.ParticipantSourceTypeId = 95 AND EXM.rn = 1
	INNER JOIN sExamination.tDiagnosis DIA 
		ON DIA.SourceId = EXM.Id
         
  --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tExamination', 0, 1, 1,@outNextNumber = @lNextNumber output       
  --SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tExamination AS Target USING       
  (      
   SELECT Id,e_ParticipantSourceId,e_StoreLocationId,e_SetupId,e_NatureId,      
   e_ExaminationDate,e_DoctorName,e_DoctorId,e_ProcessTypeId,e_CriteriaGroupId,      
   e_CompanyId,e_TargetGroupId,e_DesignationId,e_GradeId,e_DepartmentId,e_OrgId,        
 e_examinationid,e_MedicalId,e_ProcessId,e_TargetId,tid,e_LegalEntityId,e_PastHistorySelf,e_ContractorId      
   FROM #tbltmpExamination TT LEFT JOIN sExamination.tExamination T ON TT.e_examinationid = T.Id      
  ) AS Source ON Target.Id = Source.e_examinationid      
  WHEN MATCHED THEN      
   UPDATE SET Target.OrgId = e_orgid,Target.ParticipantSourceTypeId  = 95,      
   Target.ParticipantSourceId  = e_ParticipantSourceId,Target.OrganizationDepartmentId = e_DepartmentId,      
   Target.ExaminationDate = case when ((select UPPER(RTRIM(LTRIM(Isnull(CS.ItemValue,CM.ItemValue)))) ------- Nidhi Pandey; Dt- 27/09/2022, Mantis Issue - 21006 --------    
        from sConfig.tConfigurationMaster CM    
        LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id     
        where CM.ItemKey='Examination.IsExamintionDateEdit' and SourceId = e_StoreLocationId) = 'TRUE') then     
        (case when len(e_ExaminationDate) = 10 then convert(Datetime, e_ExaminationDate, 104) else CONVERT(VARCHAR(10), e_ExaminationDate, 103) end)     
        else Target.ExaminationDate END,      
   Target.DoctorEmployeeId = e_DoctorId,    
   Target.RoundNumber =  0,      
   Target.StatusId =  (CASE WHEN @rIsTemplateReview = 1 AND Target.StatusId = 4 THEN 4 ELSE 1 END),  
   ParentExaminationId = 0,CauseId = null,Target.UpdatedUserId =  1,      
   Target.UpdatedDateTime = sCommon.fGetDate(),      
   Target.ProcessTypeId = case when isnull(e_ProcessId,0) = 0 then e_ProcessTypeId else e_ProcessId end,      
   Target.EmployeeCompanyId = e_CompanyId,Target.GradeId = e_GradeId,      
   Target.TargetGroupId = case when isnull(e_TargetId,0) = 0 then e_TargetGroupId else e_TargetId end,      
   Target.EmployeeDesignationId = e_DesignationId,      
   Target.CriteiraGroupId = e_CriteriaGroupId,      
   Target.MedicalAgencyId = case when e_MedicalId = 0 then MedicalAgencyId else e_MedicalId end,      
   Target.CreatedUserId = @rUserId,      
   Target.LegalEntityId=e_LegalEntityId    
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    OrgId,ParticipantSourceTypeId,ParticipantSourceId,OrganizationDepartmentId,SetupId,      
    RoundNumber,StatusId,ExaminationDate,DoctorEmployeeId,CreatedUserId,CreatedDateTime,      
    UpdatedUserId,UpdatedDateTime,ParentExaminationId,StoreLocationId,CauseId,ProcessTypeId,MedicalAgencyId,      
    EmployeeCompanyId,TargetGroupId,EmployeeDesignationId,CriteiraGroupId,GradeId,LegalEntityId,ContractorId    
   )      
   VALUES      
   (      
    --@lFromNextNumber + tid,      
    e_OrgId,95,e_ParticipantSourceId,e_DepartmentId,      
    e_SetupId,0,1,case when len(e_ExaminationDate) = 10 then convert(Datetime, e_ExaminationDate, 104) else CONVERT(VARCHAR(11), e_ExaminationDate) end,      
    e_DoctorId,@rUserId,sCommon.fGetDate(),      
    @rUserId,sCommon.fGetDate(),0,e_StoreLocationId,null,case when isnull(e_ProcessId,0) = 0 then e_ProcessTypeId else e_ProcessId end,      
    e_MedicalId,e_CompanyId,      
    case when isnull(e_TargetId,0) = 0 then e_TargetGroupId else e_TargetId end,      
    e_DesignationId,e_CriteriaGroupId,e_GradeId,e_LegalEntityId,e_ContractorId
   );        
         
  select @cntExam = count(*),@incExam = 1 from #tbltmpExamination      
        
  update #tbltmpExamination set e_examinationid = Id from sExamination.tExamination where ParticipantSourceId = e_ParticipantSourceId      
  and ParticipantSourceTypeId = 95 and e_SetupId = SetupId
        
  --select @lCount = COUNT(1) FROM #tbltmpExamination       
  --SET @lNextNumber  = @lCount + @lFromNextNumber       
  --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tExamination', @rCurrentNumber = @lNextNumber        
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrExaminationXML,1,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  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">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
 IF OBJECT_ID('tempdb..#tbltmpVitals') IS NOT NULL      
 DROP TABLE #tbltmpVitals      
      
  Create table #tbltmpVitals      
  (      
   tid int identity(1,1),v_ParticipantSourceId bigint,v_Height varchar(200),v_Weight varchar(200),      
   v_Pulse varchar(200),v_BPSys varchar(200),v_BPDia varchar(200),v_Respiration varchar(200),v_AbdominalGirth varchar(200),      
   v_ChestExpansion varchar(200),v_Waist varchar(200),v_Hip varchar(200),v_ElbowWidth varchar(200),v_Temperature varchar(200),      
   v_id bigint,v_NatureId int,v_examinationid bigint,v_SetupId int,v_OrgId int,v_Inhalation varchar(200),v_Exhalation varchar(200), v_Remark varchar(300)  
  )      
  insert into #tbltmpVitals      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@Height','varchar(200)') as Height,      
  T.c.value('@Weight','varchar(200)') as Weight,      
  T.c.value('@Pulse','varchar(200)') as Pulse,      
  T.c.value('@BPSys','varchar(200)') as BPSys,      
  T.c.value('@BPDia','varchar(200)') as BPDia,      
  T.c.value('@Respiration','varchar(200)') as Respiration,      
  T.c.value('@AbdominalGirth','varchar(200)') as AbdominalGirth,      
  T.c.value('@ChestExpansion','varchar(200)') as ChestExpansion,      
  T.c.value('@Waist','varchar(200)') as Waist,      
  T.c.value('@Hip','varchar(200)') as Hip,      
  T.c.value('@ElbowWidth','varchar(200)') as ElbowWidth,      
  T.c.value('@Temperature','varchar(200)') as Temperature,null,0,0,0,0,      
  T.c.value('@Inhalation','varchar(200)') as Inhalation,      
  T.c.value('@Exhalation','varchar(200)') as Exhalation,     
  T.c.value('@Vital_Remark','varchar(300)') as Vital_Remark  
  from @loXMLVital.nodes('/Vitals/Vital')T(c)      
        
        
  update #tbltmpVitals set v_NatureId = e_NatureId,v_SetupId = e_SetupId,v_OrgId = e_OrgId,v_examinationid = e_examinationid      
  from #tbltmpExamination where e_ParticipantSourceId = v_ParticipantSourceId --and #tbltmpVitals.tid=#tbltmpExamination.tid      
        
  update #tbltmpVitals set v_id = Id from sExamination.tVital inner join #tbltmpExamination on e_examinationid = SourceId      
  inner join #tbltmpVitals on v_examinationId = e_examinationid      
          
  --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tVital', 0, 1, 1,@outNextNumber = @lNextNumber output       
  --SET @lFromNextNumber = @lNextNumber - 1      
  --BloodPressureSystolic = case when isnull(Source.v_BPSys,'') <> '' then Source.v_BPSys else BloodPressureSystolic end,      
  --BloodPressureDiastolic = case when isnull(Source.v_BPDia,'') <> '' then Source.v_BPDia else BloodPressureDiastolic end,        
  -- changes as per Mentis NO:0007538 2018-10-06      
  MERGE sExamination.tVital AS Target USING       
  (      
   SELECT Id,V_id,v_Height,v_Weight,      
   v_Pulse,v_BPSys,v_BPDia,v_Respiration,v_AbdominalGirth,      
   v_ChestExpansion,v_Waist,v_Hip,v_ElbowWidth,v_Temperature,      
   v_NatureId,v_examinationid,v_SetupId,v_OrgId,v_Inhalation,v_Exhalation,tid,v_Remark      
   FROM #tbltmpVitals TT LEFT JOIN sExamination.tVital T ON TT.v_id = T.Id      
  ) AS Source ON Target.Id = Source.v_Id      
  WHEN MATCHED THEN      
   UPDATE SET Pulse = case when isnull(Source.v_pulse,'') <> '' then Source.v_pulse else Pulse end,         
   BloodPressureSystolic = case when isnull(Source.v_BPSys,'') <> '' then Source.v_BPSys else BloodPressureSystolic end,      
   BloodPressureDiastolic = case when isnull(Source.v_BPDia,'') <> '' then Source.v_BPDia else BloodPressureDiastolic end,      
   NatureOfWorkId = Source.v_NatureId,Temperature = case when isnull(Source.v_Temperature,'') <> '' then Source.v_Temperature else Temperature end,      
   Respiration = case when isnull(Source.v_Respiration,'') <> '' then Source.v_Respiration else Respiration end,      
   Height = case when isnull(Source.v_Height,'') <> '' then Source.v_Height else Height end,      
   BodyWeight = case when isnull(Source.v_Weight,'') <> '' then Source.v_Weight else BodyWeight end,      
   BMI = case when Source.v_Height <> '' and Source.v_Weight <> '' then ROUND((CASE WHEN (Source.v_Height) = 0 THEN 0       
   ELSE CONVERT(DECIMAL(14, 6), ((Source.v_Weight) / CAST(SQUARE((CASE WHEN (Source.v_Height) <= 0 THEN 1 ELSE CAST((Source.v_Height)      
   AS DECIMAL(9, 6)) END)/ 100) AS DECIMAL(9, 6)))) END), 3) else BMI end,      
   ChestExpansion = case when isnull(v_Exhalation,'') <> '' and isnull(v_Inhalation,'') <> '' then      
   convert(float,v_Inhalation) - convert(float,v_Exhalation) else ChestExpansion end,      
   ElbowWidth = case when isnull(Source.v_ElbowWidth,'') <> '' then Source.v_ElbowWidth else ElbowWidth end,      
   Waist = case when isnull(Source.v_Waist,'') <> '' then Source.v_Waist else Waist end,      
   Hip = case when isnull(Source.v_Hip,'') <> '' then Source.v_Hip else Hip end,      
   AbdominalGirth = case when isnull(Source.v_AbdominalGirth,'') <> '' then Source.v_AbdominalGirth else AbdominalGirth end,      
   ChestExpansionInhalation = case when isnull(v_Inhalation,'') <> '' then v_Inhalation else ChestExpansionInhalation end,      
   ChestExpansionExhalation = case when isnull(v_Exhalation,'') <> '' then v_Exhalation else ChestExpansionExhalation end,  
   Remark = case when isnull(Source.v_Remark,'') <> '' then Source.v_Remark else Remark end  
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    Id,SourceId,SourceTypeId,NatureOfWorkId,Pulse,Temperature,BloodPressureSystolic,BloodPressureDiastolic,Respiration,Height,      
    BodyWeight,BMI,ChestExpansion,AbdominalGirth,ElbowWidth,Waist,Hip,IsObsolete,CreatedUserId,CreatedDateTime,OrgId,      
    ChestExpansionInhalation,ChestExpansionExhalation,Remark    
   )      
   VALUES      
   (      
    v_examinationid,v_examinationid,1002,v_NatureId,      
    case when isnull(v_pulse,'') = '' then null else v_pulse end,      
    case when isnull(v_Temperature,'')='' then null else v_Temperature end,          
    v_BPSys,      
    v_BPDia,       
    case when isnull(v_Respiration,'')='' then null else v_Respiration end,      
    case when isnull(v_Height,'')='' then null else v_Height end,      
    case when isnull(v_Weight,'')='' then null else v_Weight end,      
    case when v_Height <> '' and v_Weight <> '' then ROUND((CASE WHEN (v_height) = 0 THEN 0       
    ELSE CONVERT(DECIMAL(14, 2),((v_Weight) / CAST(SQUARE((CASE WHEN (v_height) <= 0 THEN 1 ELSE CAST((v_height) AS DECIMAL(9, 2)) END)/ 100) AS DECIMAL(9, 2)))) END), 3) else 0 end,      
    case when isnull(v_Exhalation,'') <> '' and isnull(v_Inhalation,'') <> '' then      
    convert(float,v_Inhalation) - convert(float,v_Exhalation) else null end,      
    case when isnull(v_AbdominalGirth,'')='' then null else v_AbdominalGirth end,      
    case when isnull(v_ElbowWidth,'') = '' then null else v_ElbowWidth end,      
    case when isnull(v_Waist,'')='' then null else v_Waist end,      
    case when isnull(v_Hip,'')='' then null else v_Hip end,0,1,sCommon.fGetDate(),v_OrgId,      
    case when isnull(v_Inhalation,'') <> '' then v_Inhalation else null end,      
    case when isnull(v_Exhalation,'') <> '' then v_Exhalation else null end,  
 isnull(Source.v_Remark, '')  
   );      
          
  --select @lCount = COUNT(1) FROM #tbltmpVitals       
  --SET @lNextNumber  = @lCount + @lFromNextNumber       
  --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tVital', @rCurrentNumber = @lNextNumber       
        
  update #tbltmpVitals set v_id = Id from sExamination.tVital inner join #tbltmpExamination on e_examinationid = SourceId inner join #tbltmpVitals on v_examinationId = e_examinationid       
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrVitalXML,2,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  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">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tbltmpDiagnosis') IS NOT NULL      
  DROP TABLE #tbltmpDiagnosis      
      
  Create table #tbltmpDiagnosis      
  (      
   tid int identity(1,1),d_ParticipantSourceId bigint,d_Diagnosis varchar(1000),      
   d_Recommendation varchar(1000),d_examinationid bigint,d_id bigint,d_date varchar(50)      
  )      
  insert into #tbltmpDiagnosis      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@Diagnosis','varchar(200)') as Diagnosis,      
T.c.value('@Recommendation','varchar(200)') as Recommendation,0,null,''      
  from @loXMLDiagnisis.nodes('/Diagnosiss/Diagnosis')T(c)      
        
  update #tbltmpDiagnosis set d_examinationid = e_examinationid,d_date = e_examinationdate from #tbltmpExamination where e_ParticipantSourceId = d_ParticipantSourceId --and #tbltmpDiagnosis.tid=#tbltmpExamination.tid      
  update #tbltmpDiagnosis set d_id = Id from sExamination.tDiagnosis inner join #tbltmpDiagnosis on d_examinationid = SourceId      
          
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tDiagnosis', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
          
  MERGE sExamination.tDiagnosis AS Target USING       
  (      
   SELECT Id,d_id,d_Diagnosis,d_Recommendation,d_date,d_examinationid,ROW_NUMBER () OVER (ORDER BY T.Id) as rno,      
   (      
    SELECT MAX(T.Id) FROM sExamination.tDiagnosis t      
   ) as maxid      
   FROM #tbltmpDiagnosis TT LEFT JOIN sExamination.tDiagnosis T ON TT.d_id = T.Id      
  ) AS Source ON Target.Id = Source.d_Id      
  WHEN MATCHED THEN      
   UPDATE SET DiagnosisRemark = case when isnull(d_Diagnosis,'') <> '' then [sSetup].[fPortalXMLTagsReplaceReverse](d_Diagnosis) else DiagnosisRemark end,      
   RecommendationEnglish = case when isnull(d_Recommendation,'') <> '' then [sSetup].[fPortalXMLTagsReplaceReverse](d_Recommendation) else RecommendationEnglish end      
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    [Id],[SourceId],[DiagnosisRemark],[RecommendationEnglish],[FitUnfitId],FitnessDate      
   )      
   VALUES      
   (      
    @lFromNextNumber + rno,d_examinationid,[sSetup].[fPortalXMLTagsReplaceReverse](d_Diagnosis),      
    [sSetup].[fPortalXMLTagsReplaceReverse](d_Recommendation),1,case when len(d_date) = 10 then convert(Datetime, d_date, 104)      
    else CONVERT(VARCHAR(11),d_date) end      
   );      
          
  select @lCount = COUNT(1) FROM #tbltmpDiagnosis       
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tDiagnosis', @rCurrentNumber = @lNextNumber      
  update #tbltmpDiagnosis set d_id = Id from sExamination.tDiagnosis inner join #tbltmpDiagnosis on d_examinationid = SourceId       
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrDiagnosisXML,3,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  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">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tbltmpHabitss') IS NOT NULL      
  DROP TABLE #tbltmpHabitss      
      
  create table #tbltmpHabitss      
  (      
   tid int identity(1,1),h_ParticipantSourceId bigint,h_Alcohol varchar(200),h_Chewer varchar(200),h_Smoker varchar(200),      
   h_AlcoholSocial varchar(200),h_Drug varchar(200),h_AlcoholId int,h_ChewerId int,h_SmokerId int,h_AlcoholSocialId int,      
   h_DrugId int,h_ParticipantAraId bigint,h_AlcoholName varchar(200),h_ChewerName varchar(200),h_SmokerName varchar(200),      
   h_AlcoholSocialName varchar(200),h_DrugName varchar(200),h_examinationid bigint,h_OrgId int,h_HabitId bigint,      
   h_HabitDetailAlcohol bigint,h_HabitDetailChewer bigint,h_HabitDetailSmoker bigint,h_HabitDetialAlcoholSocial bigint,      
   h_HabitDetailDrug bigint,h_AreaId int      
  )      
  insert into #tbltmpHabitss      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@Alcohol','varchar(200)') as Alcohol,      
  T.c.value('@Chewer','varchar(200)') as Chewer,      
  T.c.value('@Smoker','varchar(200)') as Smoker,      
  T.c.value('@AlcoholSocial','varchar(200)') as AlcoholSocial,      
  T.c.value('@Drug','varchar(200)') as Drug,0,0,0,0,0,null,      
  case T.c.value('@Alcohol','varchar(200)') when 'y' then 'Alcohol' when 'yes' then 'Alcohol' when '1' then 'Alcohol' else '' end,      
  case T.c.value('@Chewer','varchar(200)') when 'y' then 'Chewer' when 'yes' then 'Chewer' when '1' then 'Chewer' else '' end,      
  case T.c.value('@Smoker','varchar(200)') when 'y' then 'Smoker' when 'yes' then 'Smoker' when '1' then 'Smoker' else '' end,      
  case T.c.value('@AlcoholSocial','varchar(200)') when 'y' then 'Alcohol-Social' when 'yes' then 'Alcohol-Social' when '1' then 'Alcohol-Social' else '' end,      
  case T.c.value('@Drug','varchar(200)') when 'y' then 'Drugs' when 'yes' then 'Drugs' when '1' then 'Drugs' else '' end,      
  0,0,null,null,null,null,null,null,0      
  from @loXMLHabit.nodes('/Habits/Habit')T(c)       
          
  update #tbltmpHabitss set h_examinationid = e_examinationid,h_OrgId = e_orgid from #tbltmpExamination where e_ParticipantSourceId = h_ParticipantSourceId      
          
  declare @cnt int = 0       
  select @cnt = count(*) from #tbltmpHabitss        
  IF OBJECT_ID('tempdb..#tbltmpHabitsNull') IS NOT NULL    DROP TABLE #tbltmpHabitsNull      
  Create table #tbltmpHabitsNull      
  (      
   tid int identity(1,1),hh_ParticipantSourceId bigint,hh_ExaminationId bigint,hh_SetupId int,      
   hh_OrgId int,hh_HabitHygineId bigint      
  )      
  insert into #tbltmpHabitsNull      
  select H.h_ParticipantSourceId,null,E.e_SetupId,H.h_OrgId,null      
  from #tbltmpHabitss H      
  inner join #tbltmpExaminationNull E on E.e_ParticipantSourceId = H.h_ParticipantSourceId      
  where isnull(h_AlcoholName,'') = '' and isnull(h_ChewerName,'') = ''      
  and isnull(h_SmokerName,'') = '' and isnull(h_AlcoholSocialName,'') = ''      
  and isnull(h_DrugName,'') = ''      
        
  update #tbltmpHabitsNull set hh_ExaminationId = e_examinationid from #tbltmpExamination where e_ParticipantSourceId = hh_ParticipantSourceId      
  IF OBJECT_ID('tempdb..#tbltmpHabitDetailsNull') IS NOT NULL      
  DROP TABLE #tbltmpHabitDetailsNull      
  create table #tbltmpHabitDetailsNull      
  (      
   tid int identity(1,1),hd_HabitId int,hd_OrgId int,hd_ParticipantSourceId bigint,      
   hd_HabitHygineId bigint      
  )      
  insert into #tbltmpHabitDetailsNull      
  select HD.HabitId,HD.OrgId,H.hh_ParticipantSourceId,null      
  from sExamination.tHabitHygineDetail HD       
    INNER JOIN sExamination.tHabitHygine HH ON HD.HabitHygineId = HH.Id      
  INNER JOIN sExamination.tExamination E ON E.Id = HH.SourceId      
  INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id      
  INNER JOIN sExamination.tSubTypeMaster STM ON SM.SubTypeId = STM.Id      
  INNER JOIN #tbltmpHabitsNull H ON E.ParticipantSourceId = H.hh_ParticipantSourceId      
  AND STM.MainTypeId <> 8 and HH.IsObsolete = 0      
  WHERE      
      
      
 HH.OrgId = @lOrgId AND HD.OrgId = @lOrgId      
  AND (HH.SourceTypeId = 1002)      
  AND HH.SourceId =      
  (      
   Select MAX(E.Id) as ExaminationId      
   FROM sExamination.tHabitHygine HH      
   INNER JOIN sExamination.tExamination E ON E.Id = HH.SourceId      
   INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id      
   INNER JOIN sExamination.tSubTypeMaster STM ON SM.SubTypeId = STM.Id      
   INNER JOIN #tbltmpHabitsNull H ON E.ParticipantSourceId = H.hh_ParticipantSourceId      
   AND STM.MainTypeId <> 8 and HH.IsObsolete = 0      
  )      
      
      
      
      
        
  declare @HabitCnt int      
  select @HabitCnt = count(*) from #tbltmpHabitDetailsNull      
        
  if @HabitCnt > 0      
  begin      
   declare @lConfigId int,@lConfigVal varchar(100),@lConfFlag int        
   select @lConfigId = Id,@lConfigVal = ItemValue from sConfig.tConfigurationMaster where ItemKey = 'Examination.IsLastHabitDetailAuto'      
         
   select @lConfFlag = case when @lConfigVal = 'True' then 1 else 0 end      
         
   if @lConfFlag = 1      
   begin      
    update #tbltmpHabitsNull set hh_HabitHygineId = Id from sExamination.tHabitHygine where SourceId = hh_ExaminationId      
       
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tHabitHygine', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1   
  
    MERGE sExamination.tHabitHygine AS Target USING       
    (      
     SELECT tid,hh_ExaminationId,hh_OrgId,hh_HabitHygineId      
     FROM #tbltmpHabitsNull TT LEFT JOIN sExamination.tHabitHygine T ON TT.hh_HabitHygineId = T.Id         
    ) AS Source ON Target.Id = Source.hh_HabitHygineId      
    WHEN MATCHED THEN      
     UPDATE SET IsObsolete = 0      
    WHEN NOT MATCHED THEN      
     INSERT      
     (      
      [Id],SourceTypeId,SourceId,OrgId,IsObsolete      
     )      
     VALUES      
     (      
      @lFromNextNumber + tid,1002,hh_ExaminationId,hh_OrgId,0      
     );      
       
 select @lCount = COUNT(1) FROM #tbltmpHabitsNull       
 SET @lNextNumber  = @lCount + @lFromNextNumber       
 exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tHabitHygine', @rCurrentNumber = @lNextNumber      
  
    update #tbltmpHabitsNull set hh_HabitHygineId = Id from sExamination.tHabitHygine where SourceId = hh_ExaminationId      
    update #tbltmpHabitDetailsNull set hd_HabitHygineId = hh_HabitHygineId from #tbltmpHabitsNull      
    where hd_ParticipantSourceId = hh_ParticipantSourceId      
          
    MERGE sExamination.tHabitHygineDetail AS Target USING       
    (      
     SELECT tid,hd_HabitHygineId,hd_OrgId,hd_HabitId      
     FROM #tbltmpHabitDetailsNull TT LEFT JOIN sExamination.tHabitHygineDetail T ON TT.hd_HabitHygineId = T.HabitHygineId      
     and TT.hd_HabitId = T.HabitId      
    ) AS Source ON Target.HabitHygineId = Source.hd_HabitHygineId and Target.HabitId = Source.hd_HabitId      
    WHEN MATCHED THEN      
     UPDATE SET IsObsolete = 0      
    WHEN NOT MATCHED THEN      
     INSERT      
     (      
      HabitHygineId,HabitId,OrgId,IsObsolete      
     )      
     VALUES      
     (      
      hd_HabitHygineId,hd_HabitId,hd_OrgId,0      
     );      
   end      
  end      
         
  if @cnt > 0      
  begin      
   if exists (select 1 from #tbltmpHabitss where (isnull(h_Alcohol,'') <> '' or h_Chewer <> ''      
   or h_Smoker <> '' or h_AlcoholSocial <> '' or h_Drug <> ''))      
   begin      
    DELETE HD      
    FROM sExamination.tHabitHygineDetail HD      
    INNER JOIN sExamination.tHabitHygine H ON HD.HabitHygineId = H.Id      
    INNER JOIN #tbltmpHabitss S on S.h_examinationid = H.SourceId      
   end      
  end      
      
        
      
  update #tbltmpHabitss set h_examinationid = e_examinationid,h_OrgId = e_orgid from #tbltmpExamination where e_ParticipantSourceId = h_ParticipantSourceId         
  update #tbltmpHabitss set h_AreaId = PA.Id from [sExamination].[tAreaMaster] PA where PA.Title = 'Habit Hygine' and OrgId = h_OrgId         
  update #tbltmpHabitss set h_AlcoholId = h.Id from sExamination.tHabitTypeMaster as h where h_AlcoholName = h.Title COLLATE SQL_Latin1_General_CP1_CI_AS and h.OrgId = h_OrgId         
  update #tbltmpHabitss set h_ChewerId = Id from sExamination.tHabitTypeMaster where h_ChewerName = Title COLLATE SQL_Latin1_General_CP1_CI_AS and OrgId = h_OrgId        
  update #tbltmpHabitss set h_SmokerId = Id from sExamination.tHabitTypeMaster where h_SmokerName = Title COLLATE SQL_Latin1_General_CP1_CI_AS and OrgId = h_OrgId      
  update #tbltmpHabitss set h_AlcoholSocialId = Id from sExamination.tHabitTypeMaster where h_AlcoholSocialName = Title COLLATE SQL_Latin1_General_CP1_CI_AS and OrgId = h_OrgId      
  update #tbltmpHabitss set h_DrugId = Id from sExamination.tHabitTypeMaster where h_DrugName = Title COLLATE SQL_Latin1_General_CP1_CI_AS and OrgId = h_OrgId       
  update #tbltmpHabitss set h_HabitId = Id from sExamination.tHabitHygine where h_examinationid = SourceId and OrgId = h_OrgId      
        
  update #tbltmpHabitss set h_HabitDetailAlcohol = HD.Id from sExamination.tHabitHygine H left join sExamination.tHabitHygineDetail HD      
  on H.Id = HD.HabitHygineId where SourceId = h_examinationid and HD.HabitId = h_AlcoholId      
        
  update #tbltmpHabitss set h_HabitDetailChewer = HD.Id from sExamination.tHabitHygine H left join sExamination.tHabitHygineDetail HD      
  on H.Id = HD.HabitHygineId where SourceId = h_examinationid and HD.HabitId = h_ChewerId      
        
  update #tbltmpHabitss set h_HabitDetailSmoker = HD.Id from sExamination.tHabitHygine H left join sExamination.tHabitHygineDetail HD      
  on H.Id = HD.HabitHygineId where SourceId = h_examinationid and HD.HabitId = h_SmokerId      
        
  update #tbltmpHabitss set h_HabitDetialAlcoholSocial = HD.Id from sExamination.tHabitHygine H left join sExamination.tHabitHygineDetail HD      
  on H.Id = HD.HabitHygineId where SourceId = h_examinationid and HD.HabitId = h_AlcoholSocialId      
        
  update #tbltmpHabitss set h_HabitDetailDrug = HD.Id from sExamination.tHabitHygine H left join sExamination.tHabitHygineDetail HD      
  on H.Id = HD.HabitHygineId where SourceId = h_examinationid and HD.HabitId = h_DrugId      
         
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tHabitHygine', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tHabitHygine AS Target USING       
  (      
   SELECT tid,Id,h_HabitId,h_examinationId,h_OrgId,h_AreaId,h_AlcoholId,h_ChewerId,h_SmokerId,h_AlcoholSocialId,h_DrugId      
   FROM #tbltmpHabitss TT LEFT JOIN sExamination.tHabitHygine T ON TT.h_HabitId = T.Id      
   where (h_AlcoholId > 0 or h_ChewerId > 0 or h_SmokerId > 0 or h_AlcoholSocialId > 0 or h_DrugId > 0)      
  ) AS Source ON Target.Id = Source.h_HabitId      
  WHEN MATCHED THEN      
   UPDATE SET IsObsolete = 0      
  WHEN NOT MATCHED THEN     
   INSERT      
   (      
    [Id],SourceTypeId,SourceId,OrgId,IsObsolete      
   )      
   VALUES      
   (      
    @lFromNextNumber + tid,1002,h_examinationId,h_OrgId,0      
   );      
          
  select @lCount = COUNT(1) FROM #tbltmpHabitss       
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tHabitHygine', @rCurrentNumber = @lNextNumber      
        
  update #tbltmpHabitss set h_HabitId = Id from sExamination.tHabitHygine where h_examinationid = SourceId and OrgId = h_OrgId      
        
  insert into sExamination.tHabitHygineDetail(HabitHygineId,HabitId,OrgId,IsObsolete)      
  select h_HabitId,h_AlcoholId,h_OrgId,0 from #tbltmpHabitss TH left join sExamination.tHabitHygineDetail HD on TH.h_HabitId = HD.HabitHygineId      
  and HD.HabitId = TH.h_AlcoholId where h_HabitDetailAlcohol is null and h_AlcoholId is not null and h_AlcoholId > 0      
        
  insert into sExamination.tHabitHygineDetail(HabitHygineId,HabitId,OrgId,IsObsolete)      
  select h_HabitId,h_ChewerId,h_OrgId,0 from #tbltmpHabitss TH left join sExamination.tHabitHygineDetail HD on TH.h_HabitId = HD.HabitHygineId      
  and HD.HabitId = TH.h_chewerId where h_HabitDetailChewer is null and h_ChewerId is not null and h_ChewerId > 0      
         
  insert into sExamination.tHabitHygineDetail(HabitHygineId,HabitId,OrgId,IsObsolete)      
  select h_HabitId,h_SmokerId,h_OrgId,0 from #tbltmpHabitss TH left join sExamination.tHabitHygineDetail HD on TH.h_HabitId = HD.HabitHygineId      
  and HD.HabitId = TH.h_SmokerId where h_HabitDetailSmoker is null and h_SmokerId is not null and h_SmokerId > 0      
         
  insert into sExamination.tHabitHygineDetail(HabitHygineId,HabitId,OrgId,IsObsolete)      
  select h_HabitId,h_AlcoholSocialId,h_OrgId,0 from #tbltmpHabitss TH left join sExamination.tHabitHygineDetail HD on TH.h_HabitId = HD.HabitHygineId      
  and HD.HabitId = TH.h_AlcoholSocialId where h_HabitDetialAlcoholSocial is null and h_AlcoholSocialId is not null and h_AlcoholSocialId > 0      
        
  insert into sExamination.tHabitHygineDetail(HabitHygineId,HabitId,OrgId,IsObsolete)      
  select h_HabitId,h_DrugId,h_OrgId,0 from #tbltmpHabitss TH left join sExamination.tHabitHygineDetail HD on TH.h_HabitId = HD.HabitHygineId      
  and HD.HabitId = TH.h_DrugId where h_HabitDetailDrug is null and h_DrugId is not null and h_DrugId > 0      
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrHabitXML,4,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  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">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tbltmpDisease') IS NOT NULL      
  DROP TABLE #tbltmpDisease      
      
  create table #tbltmpDisease      
  (      
   tid int identity(1,1),d_ParticipantSourceId bigint,d_DiseaseName varchar(500),      
   d_ExaminationId bigint,d_OrgId int,d_AreaId int,d_ParticipantAreaId bigint,d_ExistingDiseaseId bigint,d_OtherDisease varchar(2000)      
  )      
  insert into #tbltmpDisease      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  replace(T.c.value('@ExistingDiseaseSelf','varchar(500)'),'+',',') as DiseaseSelf,0,0,0,0,null,    --mantis:0033673 by shivam(15/05/2024)  
replace(T.c.value('@ExistingOtherDiseaseSelf','varchar(2000)'),'+',',') as OtherDiseaseSelf      
  from @loXMLDisease.nodes('/Diseases/Disease')T(c)       
      
  update #tbltmpDisease set d_ExaminationId = e_examinationid,d_OrgId = e_OrgId from #tbltmpExamination where e_ParticipantSourceId = d_ParticipantSourceId      
        
      
  IF OBJECT_ID('tempdb..#tbltmpDiseaseNull') IS NOT NULL      
  DROP TABLE #tbltmpDiseaseNull      
  Create table #tbltmpDiseaseNull      
  (      
   tid int identity(1,1),dd_ParticipantSourceId bigint,dd_ExaminationId bigint,dd_SetupId int,      
   dd_OrgId int,dd_ExistingDiseaseId bigint      
  )      
  insert into #tbltmpDiseaseNull      
  select H.d_ParticipantSourceId,null,E.e_SetupId,H.d_OrgId,null      
  from #tbltmpDisease H      
  inner join #tbltmpExamination E on E.e_ParticipantSourceId = H.d_ParticipantSourceId      
  --where isnull(d_DiseaseName,'') = ''      
        
  update #tbltmpDiseaseNull set dd_ExaminationId = e_examinationid from #tbltmpExamination where e_ParticipantSourceId = dd_ParticipantSourceId      
        
        
  --select * from #tbltmpExaminationNull      
  --select * from #tbltmpExamination      
  set @cnt = 0      
  select @cnt = count(d_ExistingDiseaseId) from #tbltmpDisease      
        
  if @cnt > 0      
  begin      
   DELETE Hw      
   FROM sExamination.tExistingDiseaseDetail Hw      
   INNER JOIN sExamination.tExistingDisease H ON Hw.ExistingDiseaseId = H.Id      
   INNER JOIN #tbltmpDisease S on S.d_ExaminationId = H.SourceId      
   --where d_DiseaseName <> ''      
  end      
      
  IF OBJECT_ID('tempdb..#tbltmpDiseaseDetailsNull') IS NOT NULL      
  DROP TABLE #tbltmpDiseaseDetailsNull      
  Create table #tbltmpDiseaseDetailsNull       
  (      
   tid int identity(1,1),ed_HabitId int,ed_OrgId int,ed_ParticipantSourceId bigint,      
   ed_ExistingDiseaseId bigint,ed_IsSelfDeclared bit,ed_IsDiagnosed bit  
  )      
  insert into #tbltmpDiseaseDetailsNull      
  select Distinct HD.DiseaseId,HD.OrgId,H.dd_ParticipantSourceId,null,ISNULL(HD.IsSelfDeclared, 0),ISNULL(HD.IsDiagnosed, 0)  
  from sExamination.tExistingDiseaseDetail HD       
  INNER JOIN sExamination.tExistingDisease HH ON HD.ExistingDiseaseId = HH.Id      
  INNER JOIN sExamination.tExamination E ON E.Id = HH.SourceId      
  INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id      
  INNER JOIN sExamination.tSubTypeMaster STM ON SM.SubTypeId = STM.Id      
  INNER JOIN #tbltmpDiseaseNull H ON E.ParticipantSourceId = H.dd_ParticipantSourceId  
  INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = HD.DiseaseId  
  WHERE HH.OrgId = @lOrgId AND HD.OrgId = @lOrgId AND STM.MainTypeId <> 8      
  AND HH.SourceTypeId = 1002  
  AND DM.IsCarryForward = 1  
  AND HH.SourceId in      
  (      
   Select ExaminationId from(      
   Select  Max(E.id) as ExaminationId,E.ParticipantSourceId      
   FROM sExamination.tExistingDisease HH      
   INNER JOIN sExamination.tExamination E ON E.Id = HH.SourceId      
   INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id      
   INNER JOIN sExamination.tSubTypeMaster STM ON SM.SubTypeId = STM.Id      
   INNER JOIN #tbltmpDiseaseNull H ON E.ParticipantSourceId = H.dd_ParticipantSourceId      
   where STM.MainTypeId <> 8 and H.dd_ExaminationId <>E.id         
   Group by E.ParticipantSourceId) as temp      
  )      
        
  declare @DiseaseCnt int      
  select @DiseaseCnt = count(*) from #tbltmpDiseaseDetailsNull      
  --select * from #tbltmpDiseaseNull      
  --select * from #tbltmpDiseaseDetailsNull      
  if @DiseaseCnt > 0      
  begin      
   select @lConfigId = 0,@lConfigVal = '',@lConfFlag = 0      
   select @lConfigId = Id,@lConfigVal = ItemValue from sConfig.tConfigurationMaster where ItemKey = 'Examination.IsLastExistingDiseaseDetailAuto'      
         
   select @lConfFlag = case when @lConfigVal = 'True' then 1 else 0 end      
         
   if @lConfFlag = 1      
   begin      
    update #tbltmpDiseaseNull set dd_ExistingDiseaseId = Id from sExamination.tExistingDisease where SourceId = dd_ExaminationId      
    update #tbltmpDiseaseNull set dd_ExistingDiseaseId = 0 from sExamination.tExistingDisease where dd_ExistingDiseaseId IS null      
    --select * from #tbltmpDiseaseNull      
    exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tExistingDisease', 0, 1, 1,@outNextNumber = @lNextNumber output       
    SET @lFromNextNumber = @lNextNumber - 1       
      
    MERGE sExamination.tExistingDisease AS Target USING       
    (      
     SELECT tid,dd_ExaminationId,dd_OrgId,dd_ExistingDiseaseId      
     FROM #tbltmpDiseaseNull TT LEFT JOIN sExamination.tExistingDisease T ON ISNULL(TT.dd_ExistingDiseaseId,0) = T.Id and T.SourceId=TT.dd_ExaminationId        
    ) AS Source ON Target.Id = ISNULL(Source.dd_ExistingDiseaseId,0) and Target.SourceId=Source.dd_ExaminationId      
    WHEN MATCHED THEN      
     UPDATE SET IsObsolete = 0      
    WHEN NOT MATCHED THEN      
     INSERT      
     (      
      [Id],SourceTypeId,SourceId,OrgId,IsObsolete      
     )      
     VALUES      
     (      
      @lFromNextNumber + tid,1002,dd_ExaminationId,dd_OrgId,0      
     );      
          
    select @lCount = COUNT(1) FROM #tbltmpDiseaseNull      
    SET @lNextNumber  = @lCount + @lFromNextNumber       
    exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tExistingDisease', @rCurrentNumber = @lNextNumber      
      
    update #tbltmpDiseaseNull set dd_ExistingDiseaseId = Id from sExamination.tExistingDisease where SourceId = dd_ExaminationId      
          
    update #tbltmpDiseaseDetailsNull set ed_ExistingDiseaseId = dd_ExistingDiseaseId from #tbltmpDiseaseNull      
    where ed_ParticipantSourceId = dd_ParticipantSourceId      
    --print 'tbltmpDiseaseDetailsNull'      
     --select * from #tbltmpDiseaseDetailsNull      
      
    MERGE sExamination.tExistingDiseaseDetail AS Target USING       
    (      
     SELECT tid,ed_ExistingDiseaseId,ed_OrgId,ed_HabitId,ed_IsSelfDeclared,ed_IsDiagnosed   
     FROM #tbltmpDiseaseDetailsNull TT LEFT JOIN sExamination.tExistingDiseaseDetail T ON TT.ed_ExistingDiseaseId = T.ExistingDiseaseId      
     and TT.ed_HabitId = T.DiseaseId      
    ) AS Source ON Target.ExistingDiseaseId = Source.ed_ExistingDiseaseId and Target.DiseaseId = Source.ed_HabitId      
    WHEN MATCHED THEN      
     UPDATE SET IsObsolete = 0      
    WHEN NOT MATCHED THEN      
     INSERT      
     (      
      ExistingDiseaseId,DiseaseId,OrgId,IsObsolete,IsSelfDeclared,IsDiagnosed  
     )      
     VALUES      
     (      
      ed_ExistingDiseaseId,ed_HabitId,ed_OrgId,0,ed_IsSelfDeclared,ed_IsDiagnosed  
     );      
   end      
  end      
        
  update #tbltmpDisease set d_ExaminationId = e_examinationid,d_OrgId = e_OrgId from #tbltmpExamination where e_ParticipantSourceId = d_ParticipantSourceId      
  IF OBJECT_ID('tempdb..#tbltmpDiseaseN') IS NOT NULL      
  DROP TABLE #tbltmpDiseaseN      
  create table #tbltmpDiseaseN(tid int identity(1,1),d_ParticipantSourceId bigint,d_ExaminationId bigint,d_OrgId int,d_DiseaseName varchar(200),      
  d_Name varchar(200),d_AreaId int,d_ParticipantAreaId bigint,d_DiseaseId int,d_ExistingDiseaseId bigint,d_ExisitingDiseaseDetailId bigint)      
  insert into #tbltmpDiseaseN      
  select d_ParticipantSourceId,d_ExaminationId,d_orgId,Item,'Existing Disease',null,null,null,null,null      
  from #tbltmpDisease cross apply dbo.fSplitStr(d_DiseaseName,',') where Item <> ''      
        
  update #tbltmpDiseaseN set d_AreaId = Id from [sExamination].[tAreaMaster] where d_Name = Title COLLATE SQL_Latin1_General_CP1_CI_AS and OrgId = d_OrgId       
  update #tbltmpDiseaseN set d_DiseaseId = Id from sExamination.tDiseaseMaster where LTRIM(RTRIM(d_DiseaseName)) = Title COLLATE SQL_Latin1_General_CP1_CI_AS and OrgId = d_OrgId      
  update #tbltmpDiseaseN set d_ExistingDiseaseId = Id from sExamination.tExistingDisease where SourceId = d_ExaminationId      
  update #tbltmpDiseaseN set d_ExisitingDiseaseDetailId = Id from sExamination.tExistingDiseaseDetail where ExistingDiseaseId = d_ExistingDiseaseId      
  and DiseaseId = d_DiseaseId      
        
  update e set e.d_AreaId = DD.d_AreaId, e.d_ParticipantAreaId = DD.d_ParticipantAreaId,      
  e.d_ExistingDiseaseId = DD.d_ExistingDiseaseId from #tbltmpDiseaseN DD      
  inner join #tbltmpDisease e on e.d_ExaminationId = DD.d_ExaminationId      
           
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tExistingDisease', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tExistingDisease AS Target USING       
  (      
   SELECT tid,Id,TT.d_ExistingDiseaseId,TT.d_OrgId,TT.d_ExaminationId,TT.d_OtherDisease,TT.d_DiseaseName      
   FROM #tbltmpDisease TT LEFT JOIN sExamination.tExistingDisease T ON TT.d_ExistingDiseaseId = T.Id      
   where (isnull(TT.d_DiseaseName,'') <> '' or isnull(TT.d_OtherDisease,'') <> '')      
  ) AS Source ON Target.Id = Source.d_ExistingDiseaseId and Target.Sourceid = Source.d_ExaminationId      
  WHEN MATCHED THEN      
   UPDATE SET IsObsolete = 0,Remark = d_OtherDisease      
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    [Id],SourceTypeId,SourceId,OrgId,IsObsolete,Remark      
   )      
   VALUES      
   (      
    @lFromNextNumber + tid,1002,d_ExaminationId,d_OrgId,0,d_OtherDisease      
   );      
         
  --select @lCount = COUNT(1) FROM @tbltmpHabits       
  select @lCount = COUNT(1) FROM #tbltmpDisease      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tExistingDisease', @rCurrentNumber = @lNextNumber      
        
  update #tbltmpDisease set d_ExistingDiseaseId = Id from sExamination.tExistingDisease where SourceId = d_ExaminationId      
  update #tbltmpDiseaseN  set #tbltmpDiseaseN.d_ExistingDiseaseId = #tbltmpDisease.d_ExistingDiseaseId       
  from #tbltmpDisease where #tbltmpDiseaseN.d_ParticipantSourceId = #tbltmpDisease.d_ParticipantSourceId      
          
  --insert into sExamination.tExistingDiseaseDetail(ExistingDiseaseId,DiseaseId,OrgId,IsObsolete,Remark)      
  --select d_ExistingDiseaseId,d_DiseaseId,d_OrgId,0,'' from #tbltmpDiseaseN N left join sExamination.tExistingDiseaseDetail D      
  --on D.ExistingDiseaseId = N.d_ExistingDiseaseId and D.DiseaseId = N.d_DiseaseId and d_ExisitingDiseaseDetailId is null and DiseaseId is not null      
  --select * from #tbltmpDiseaseN      
  MERGE sExamination.tExistingDiseaseDetail AS Target USING      
  (      
   select d_ExistingDiseaseId,d_DiseaseId,d_OrgId      
   from #tbltmpDiseaseN N       
   left join sExamination.tExistingDiseaseDetail D on D.ExistingDiseaseId = N.d_ExistingDiseaseId       
   and D.DiseaseId = N.d_DiseaseId and d_ExisitingDiseaseDetailId is null and DiseaseId is not null      
  ) As Source ON Target.ExistingDiseaseId = Source.d_ExistingDiseaseId and Target.DiseaseId=Source.d_DiseaseId       
  WHEN MATCHED THEN      
   UPDATE SET IsObsolete = 0      
  WHEN NOT MATCHED THEN      
  INSERT      
  (      
   ExistingDiseaseId,DiseaseId,OrgId,IsObsolete,Remark,IsSelfDeclared,IsDiagnosed  
  )      
  VALUES      
  (      
   d_ExistingDiseaseId,d_DiseaseId,d_OrgId,0,'',1,0  
  );      
      
  update #tbltmpDiseaseN set d_ExisitingDiseaseDetailId = Id from sExamination.tExistingDiseaseDetail where ExistingDiseaseId = d_ExistingDiseaseId      
  and DiseaseId = d_DiseaseId      
    
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tExistingDisease', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1  
  
--Mantis: 0042443, To Add Existing Diabetic or Hypertension if previous Examination is new diabetic or new hypertension.
  MERGE sExamination.tExistingDisease AS Target USING       
  (      
   select texm.e_examinationid as d_ExaminationId, ROW_NUMBER() OVER (ORDER BY texm.e_examinationid) AS RowNum
   from #tbltmpExamination texm
	  where texm.e_IsNewDiabetic = 1 or texm.e_IsNewHypertension = 1  
  ) AS Source ON Target.Sourceid = Source.d_ExaminationId
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    [Id],SourceTypeId,SourceId,OrgId,IsObsolete,Remark      
   )      
   VALUES      
   (      
    @lFromNextNumber + RowNum,1002,d_ExaminationId,@lOrgId,0,''    
   );
         
  --select @lCount = COUNT(1) FROM @tbltmpHabits       
  select @lCount = COUNT(1) FROM #tbltmpExamination texm where texm.e_IsNewDiabetic = 1 or texm.e_IsNewHypertension = 1      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tExistingDisease', @rCurrentNumber = @lNextNumber

  MERGE sExamination.tExistingDiseaseDetail AS Target USING      
  (      
	  select ED.Id as d_ExistingDiseaseId, ED.OrgId as d_OrgId, * from #tbltmpExamination texm
	  inner join sExamination.tExistingDisease ED ON ED.SourceId = texm.e_examinationid
	  where texm.e_IsNewDiabetic = 1 
  ) As Source ON Target.ExistingDiseaseId = Source.d_ExistingDiseaseId and Target.DiseaseId = [sCommon].[fGetIntIdForOrg](7, @lOrgId)
  WHEN NOT MATCHED THEN
  INSERT      
  (      
   ExistingDiseaseId,DiseaseId,OrgId,IsObsolete,Remark,IsSelfDeclared,IsDiagnosed  
  )      
  VALUES      
  (      
   d_ExistingDiseaseId,[sCommon].[fGetIntIdForOrg](7, @lOrgId),d_OrgId,0,'',0,1  
  );

   MERGE sExamination.tExistingDiseaseDetail AS Target USING      
  (      
	  select ED.Id as d_ExistingDiseaseId, ED.OrgId as d_OrgId, * from #tbltmpExamination texm
	  inner join sExamination.tExistingDisease ED ON ED.SourceId = texm.e_examinationid
	  where texm.e_IsNewHypertension = 1
  ) As Source ON Target.ExistingDiseaseId = Source.d_ExistingDiseaseId and Target.DiseaseId = [sCommon].[fGetIntIdForOrg](13, @lOrgId)
  WHEN NOT MATCHED THEN
  INSERT      
  (      
   ExistingDiseaseId,DiseaseId,OrgId,IsObsolete,Remark,IsSelfDeclared,IsDiagnosed  
  )      
  VALUES      
  (      
   d_ExistingDiseaseId,[sCommon].[fGetIntIdForOrg](13, @lOrgId),d_OrgId,0,'',0,1
  );

 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrDiseaseXML,5,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  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">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  declare @tbltmpHistory table       
  (      
   tid int identity(1,1),h_ParticipantSourceId bigint,h_Self varchar(2000),h_Mother varchar(200),      
   h_Father varchar(200),h_Brother varchar(200),h_Sister varchar(200),h_Surgery varchar(2000),h_ExaminationId bigint,h_OrgId int,      
   h_ParticipantAreaId bigint,h_AreaId int,AreaName varchar(200),h_HistoryId bigint, h_TreatmentHistoryRemark varchar(2000),h_PastHistoryRemark varchar(2000),  
   h_PastMedicalHistorySelf varchar(2000),h_HistoryMother varchar(2000),h_HistoryFather varchar(2000)  
  )      
  insert into @tbltmpHistory      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  replace(T.c.value('@PastHistorySelf','varchar(2000)'),'+',',') as PastHistorySelf,      
  replace(T.c.value('@PastHistoryMother','varchar(200)'),'+',',') as PastHistoryMother,      
  replace(T.c.value('@PastHistoryFather','varchar(200)'),'+',',') as PastHistoryFather,      
  replace(T.c.value('@PastHistoryBrother','varchar(200)'),'+',',') as PastHistoryBrother,      
  replace(T.c.value('@PastHistorySister','varchar(200)'),'+',',') as PastHistorySister,      
  T.c.value('@PastSurgicalHistorySelf','varchar(2000)') as Surgery,0,0,null,null,'Past History',null,T.c.value('@TreatmentHistoryRemark','varchar(2000)') as TreatmentHistoryRemark      
  ,T.c.value('@PastHistoryRemark','varchar(2000)') as PastHistoryRemark,  
  T.c.value('@PastMedicalHistorySelf','varchar(2000)') as PastMedicalHistorySelf,  --mantis:0033673 by shivam(15/05/2024)  
  T.c.value('@HistoryMother','varchar(2000)') as HistoryMother, --Mantis: 0032861, Date: 13/04/2024 by Deval  
  T.c.value('@HistoryFather','varchar(2000)') as HistoryFather --Mantis: 0032861, Date: 13/04/2024 by Deval  
  from @loXMLHistory.nodes('/Historys/History')T(c)
        
  update t  set h_ExaminationId = e_examinationid,h_OrgId = e_OrgId  
  from @tbltmpHistory as t      
  inner join #tbltmpExamination e on t.h_ParticipantSourceId=e.e_ParticipantSourceId --and t.tid=e.tid      
  --where e_ParticipantSourceId = h_ParticipantSourceId         

  -----start update PastHistorySelf-----      
      
  MERGE sExamination.tExamination AS Target USING       
  (      
   SELECT Isnull(T.h_Self,'') h_Self,Isnull(h_PastMedicalHistorySelf,'') h_PastMedicalHistorySelf, TT.e_examinationid,  
   Isnull(T.h_HistoryMother,'') h_HistoryMother,Isnull(T.h_HistoryFather,'') h_HistoryFather  
   FROM #tbltmpExamination TT INNER JOIN @tbltmpHistory T ON TT.e_examinationid = T.h_ExaminationId  
  ) AS Source ON Target.Id = Source.e_examinationid  
  WHEN MATCHED THEN  
   UPDATE SET Target.PastHistorySelf = h_Self +   
    CASE   
        WHEN h_Self != '' AND h_PastMedicalHistorySelf != '' THEN ', '   
        ELSE ''   
    END  + h_PastMedicalHistorySelf, --Mantis:0032687 by shivam on 11/04/2024  
   Target.HistoryMother = h_HistoryMother, Target.HistoryFather = h_HistoryFather; --Mantis: 0032861, Date: 13/04/2024 by Deval  
      
      
  -----end update PastHistorySelf-----      
      
      
  update @tbltmpHistory set h_AreaId = Id from sExamination.tAreaMaster where AreaName = Title and h_OrgId = OrgId         
  update @tbltmpHistory set h_HistoryId = Id from sExamination.tHistory where h_ParticipantSourceId = ParticipantSourceId         
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tHistory', 0, 1, 1,@outNextNumber = @lNextNumber output      
  SET @lFromNextNumber = @lNextNumber - 1      
        
  update @tbltmpHistory set h_HistoryId = Id from sExamination.tHistory where ParticipantSourceId = h_ParticipantSourceId     
        
  MERGE sExamination.tHistory AS Target USING       
  (      
   SELECT tid,Id,h_HistoryId,h_ParticipantSourceId,h_OrgId,h_AreaId,h_Surgery,h_TreatmentHistoryRemark,h_PastHistoryRemark      
   FROM @tbltmpHistory TT       
   LEFT JOIN sExamination.tHistory T ON TT.h_HistoryId = T.Id        
  ) AS Source ON Target.Id = Source.h_HistoryId      
  WHEN MATCHED THEN      
   UPDATE SET IsObsolete = 0,TreatmentHistoryRemark = h_TreatmentHistoryRemark,Remark = h_PastHistoryRemark,IsSurgeryDone = case when h_Surgery <> '' then 1 else 0 end,      
   SurgeryRemark = case when h_Surgery <> '' then       
   case when charindex(h_Surgery,SurgeryRemark)>0 then SurgeryRemark else      
   case when isnull(SurgeryRemark,'')  <> '' then isnull(SurgeryRemark,'') + '+' + h_Surgery else h_Surgery end end else SurgeryRemark end        
      
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    [Id],ParticipantSourceId,OrgId,IsObsolete,ParticipantSourceTypeId,IsSurgeryDone,SurgeryRemark, TreatmentHistoryRemark, Remark      
   )      
   VALUES      
   (      
    @lFromNextNumber + tid,h_ParticipantSourceId,h_OrgId,0,95,case when h_Surgery <> '' then 1 else 0 end,h_Surgery,h_TreatmentHistoryRemark, h_PastHistoryRemark      
   );      
         
  select @lCount = COUNT(1) FROM @tbltmpHistory      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tHistory', @rCurrentNumber = @lNextNumber
        
  update @tbltmpHistory set h_HistoryId = Id from sExamination.tHistory where ParticipantSourceId = h_ParticipantSourceId      
  IF OBJECT_ID('tempdb..#tbltmpHistorySelf') IS NOT NULL      
  DROP TABLE #tbltmpHistorySelf      
  create table #tbltmpHistorySelf      
  (      
   tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,HistoryDetailId bigint,RelationId int,      
   ExaminationId bigint,s_OrgId int,PatientId bigint,AreaId int,AreaName varchar(200),ParticipantAreaId bigint,Name varchar(200),      
   h_Surgery varchar(1000)      
  )      
  insert into #tbltmpHistorySelf      
  select 0,h_HistoryId,0,1,h_ExaminationId,h_OrgId,h_ParticipantSourceId,h_AreaId,'Past History',h_ParticipantAreaId,Item,h_Surgery      
  from @tbltmpHistory cross apply dbo.fSplitStr(h_Self,',') where Item <> ''      
        
  IF OBJECT_ID('tempdb..#tbltmpHistoryMother') IS NOT NULL      
  DROP TABLE #tbltmpHistoryMother      
  create table #tbltmpHistoryMother      
  (      
   tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,HistoryDetailId bigint,RelationId int,      
   ExaminationId bigint,m_OrgId int,PatientId bigint,AreaId int,AreaName varchar(200),ParticipantAreaId bigint,Name varchar(200),      
   h_Surgery varchar(1000)      
  )      
  insert into #tbltmpHistoryMother      
  select 0,h_HistoryId,0,3,h_ExaminationId,h_OrgId,h_ParticipantSourceId,h_AreaId,'Past History',h_ParticipantAreaId,Item,h_Surgery      
  from @tbltmpHistory cross apply dbo.fSplitStr(h_Mother,',') where Item <> ''      
         
  IF OBJECT_ID('tempdb..#tbltmpHistoryFather') IS NOT NULL      
  DROP TABLE #tbltmpHistoryFather      
  create table #tbltmpHistoryFather      
  (      
   tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,HistoryDetailId bigint,RelationId int,      
   ExaminationId bigint,f_OrgId int,PatientId bigint,AreaId int,AreaName varchar(200),ParticipantAreaId bigint,Name varchar(200),      
   h_Surgery varchar(1000)      
  )      
  insert into #tbltmpHistoryFather      
  select 0,h_HistoryId,0,2,h_ExaminationId,h_OrgId,h_ParticipantSourceId,h_AreaId,'Past History',h_ParticipantAreaId,Item,h_Surgery      
  from @tbltmpHistory cross apply dbo.fSplitStr(h_Father,',') where Item <> ''      
        
  IF OBJECT_ID('tempdb..#tbltmpHistoryBrother') IS NOT NULL      
  DROP TABLE #tbltmpHistoryBrother      
  create table #tbltmpHistoryBrother      
  (      
   tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,HistoryDetailId bigint,RelationId int,      
   ExaminationId bigint,f_OrgId int,PatientId bigint,AreaId int,AreaName varchar(200),ParticipantAreaId bigint,Name varchar(200),      
   h_Surgery varchar(1000)      
  )      
  insert into #tbltmpHistoryBrother      
  select 0,h_HistoryId,0,2,h_ExaminationId,h_OrgId,h_ParticipantSourceId,h_AreaId,'Past History',h_ParticipantAreaId,Item,h_Surgery      
  from @tbltmpHistory cross apply dbo.fSplitStr(h_Brother,',') where Item <> ''      
        
  IF OBJECT_ID('tempdb..#tbltmpHistorySister') IS NOT NULL      
  DROP TABLE #tbltmpHistorySister      
  create table #tbltmpHistorySister      
  (      
   tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,HistoryDetailId bigint,RelationId int,      
   ExaminationId bigint,f_OrgId int,PatientId bigint,AreaId int,AreaName varchar(200),ParticipantAreaId bigint,Name varchar(200),      
   h_Surgery varchar(1000)      
  )      
  insert into #tbltmpHistorySister      
  select 0,h_HistoryId,0,2,h_ExaminationId,h_OrgId,h_ParticipantSourceId,h_AreaId,'Past History',h_ParticipantAreaId,Item,h_Surgery      
  from @tbltmpHistory cross apply dbo.fSplitStr(h_Sister,',') where Item <> ''      
         
  update #tbltmpHistorySelf set h_DiseaseId = Id from sExamination.tDiseaseMaster where Name = Title COLLATE SQL_Latin1_General_CP1_CI_AS and s_OrgId = OrgId      
  update #tbltmpHistoryMother set h_DiseaseId = Id from sExamination.tDiseaseMaster where Name = Title COLLATE SQL_Latin1_General_CP1_CI_AS and m_OrgId = OrgId      
  update #tbltmpHistoryFather set h_DiseaseId = Id from sExamination.tDiseaseMaster where Name = Title COLLATE SQL_Latin1_General_CP1_CI_AS and f_OrgId = OrgId      
  update #tbltmpHistoryBrother set h_DiseaseId = Id from sExamination.tDiseaseMaster where Name = Title COLLATE SQL_Latin1_General_CP1_CI_AS and f_OrgId = OrgId      
  update #tbltmpHistorySister set h_DiseaseId = Id from sExamination.tDiseaseMaster where Name = Title COLLATE SQL_Latin1_General_CP1_CI_AS and f_OrgId = OrgId      
        
  update #tbltmpHistorySelf set HistoryDetailId = Id from sExamination.tHistoryDetail      
  where HistoryId = h_HistoryId and s_OrgId = OrgId and DiseaseId = h_DiseaseId and RelationshipId=1      
        
  update #tbltmpHistoryMother set HistoryDetailId = Id from sExamination.tHistoryDetail      
  where HistoryId = h_HistoryId and m_OrgId = OrgId and DiseaseId = h_DiseaseId and RelationshipId=2      
        
  update #tbltmpHistoryFather set HistoryDetailId = Id from sExamination.tHistoryDetail      
  where HistoryId = h_HistoryId and f_OrgId = OrgId and DiseaseId = h_DiseaseId and RelationshipId=3      
        
  update #tbltmpHistoryBrother set HistoryDetailId = Id from sExamination.tHistoryDetail      
  where HistoryId = h_HistoryId and f_OrgId = OrgId and DiseaseId = h_DiseaseId and RelationshipId=4      
        
  update #tbltmpHistoryBrother set HistoryDetailId = Id from sExamination.tHistoryDetail      
  where HistoryId = h_HistoryId and f_OrgId = OrgId and DiseaseId = h_DiseaseId and RelationshipId=5      
         
  set @cnt = 0      
  select @cnt = count(*) from #tbltmpHistorySelf      
        
   --mentis issue no:0014229 MS - 2020-02-02       
  if @cnt > 0      
  begin      
   --select * from #tbltmpHistorySelf      
   delete from #tbltmpHistorySelf where isnull(HistoryDetailId,0)>0      
   --DELETE HD      
   --FROM sExamination.tHistoryDetail HD      
   --INNER JOIN sExamination.tHistory H ON HD.HistoryId = H.Id      
   --INNER JOIN #tbltmpHistorySelf S on S.PatientId = H.ParticipantSourceId      
   --where RelationshipId = 1      
  end      
        
  set @cnt = 0      
  select @cnt = count(*) from #tbltmpHistoryMother      
        
  if @cnt > 0      
  begin      
   DELETE HD      
   FROM sExamination.tHistoryDetail HD      
   INNER JOIN sExamination.tHistory H ON HD.HistoryId = H.Id      
   INNER JOIN #tbltmpHistoryMother S on S.PatientId = H.ParticipantSourceId      
   where RelationshipId = 3      
  end      
        
  set @cnt = 0      
  select @cnt = count(*) from #tbltmpHistoryFather      
        
  if @cnt > 0      
  begin      
   DELETE HD      
   FROM sExamination.tHistoryDetail HD      
   INNER JOIN sExamination.tHistory H ON HD.HistoryId = H.Id      
   INNER JOIN #tbltmpHistoryFather S on S.PatientId = H.ParticipantSourceId      
   where RelationshipId = 2      
  end      
        
  set @cnt = 0      
  select @cnt = count(*) from #tbltmpHistoryBrother      
        
  if @cnt > 0      
  begin      
   DELETE HD      
   FROM sExamination.tHistoryDetail HD      
   INNER JOIN sExamination.tHistory H ON HD.HistoryId = H.Id      
   INNER JOIN #tbltmpHistoryBrother S on S.PatientId = H.ParticipantSourceId      
   where RelationshipId = 7      
  end      
        
  set @cnt = 0      
  select @cnt = count(*) from #tbltmpHistorySister      
        
  if @cnt > 0      
  begin      
   DELETE HD      
   FROM sExamination.tHistoryDetail HD      
   INNER JOIN sExamination.tHistory H ON HD.HistoryId = H.Id      
   INNER JOIN #tbltmpHistorySister S on S.PatientId = H.ParticipantSourceId      
   where RelationshipId = 8      
  end      
        
  IF OBJECT_ID('tempdb..#tbltmpHistorySelfN') IS NOT NULL      
  DROP TABLE #tbltmpHistorySelfN          
  create table #tbltmpHistorySelfN(tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,s_OrgId int)      
  insert into #tbltmpHistorySelfN      
  select distinct h_DiseaseId,h_HistoryId,s_OrgId from #tbltmpHistorySelf where h_DiseaseId is not null and h_DiseaseId > 0 and h_HistoryId is not null      
        
  IF OBJECT_ID('tempdb..#tbltmpHistoryMotherN') IS NOT NULL      
  DROP TABLE #tbltmpHistoryMotherN      
  create table #tbltmpHistoryMotherN(tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,s_OrgId int)      
  insert into #tbltmpHistoryMotherN      
  select distinct h_DiseaseId,h_HistoryId,m_OrgId from #tbltmpHistoryMother where h_DiseaseId is not null and h_DiseaseId > 0 and h_HistoryId is not null      
        
  IF OBJECT_ID('tempdb..#tbltmpHistoryFatherN') IS NOT NULL      
  DROP TABLE #tbltmpHistoryFatherN      
  create table #tbltmpHistoryFatherN(tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,s_OrgId int)      
  insert into #tbltmpHistoryFatherN      
  select distinct h_DiseaseId,h_HistoryId,f_OrgId from #tbltmpHistoryFather where h_DiseaseId is not null and h_DiseaseId > 0 and h_HistoryId is not null      
        
  IF OBJECT_ID('tempdb..#tbltmpHistoryBrotherN') IS NOT NULL      
  DROP TABLE #tbltmpHistoryBrotherN      
  create table #tbltmpHistoryBrotherN(tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,s_OrgId int)      
  insert into #tbltmpHistoryBrotherN      
  select distinct h_DiseaseId,h_HistoryId,f_OrgId from #tbltmpHistoryBrother where h_DiseaseId is not null and h_DiseaseId > 0 and h_HistoryId is not null      
        
  IF OBJECT_ID('tempdb..#tbltmpHistorySisterN') IS NOT NULL      
  DROP TABLE #tbltmpHistorySisterN      
  create table #tbltmpHistorySisterN(tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,s_OrgId int)      
  insert into #tbltmpHistorySisterN      
  select distinct h_DiseaseId,h_HistoryId,f_OrgId from #tbltmpHistorySister where h_DiseaseId is not null and h_DiseaseId > 0 and h_HistoryId is not null      
        
  insert into sExamination.tHistoryDetail(HistoryId,RelationshipId,DiseaseId,OrgId,IsObsolete)      
  select h_HistoryId,1,h_DiseaseId,s_OrgId,0 from #tbltmpHistorySelfN      
        
  insert into sExamination.tHistoryDetail(HistoryId,RelationshipId,DiseaseId,OrgId,IsObsolete)      
  select h_HistoryId,3,h_DiseaseId,s_OrgId,0 from #tbltmpHistoryMotherN      
        
  insert into sExamination.tHistoryDetail(HistoryId,RelationshipId,DiseaseId,OrgId,IsObsolete)      
  select h_HistoryId,2,h_DiseaseId,s_OrgId,0 from #tbltmpHistoryFatherN      
        
  insert into sExamination.tHistoryDetail(HistoryId,RelationshipId,DiseaseId,OrgId,IsObsolete)      
  select h_HistoryId,7,h_DiseaseId,s_OrgId,0 from #tbltmpHistoryBrotherN      
        
  insert into sExamination.tHistoryDetail(HistoryId,RelationshipId,DiseaseId,OrgId,IsObsolete)      
  select h_HistoryId,8,h_DiseaseId,s_OrgId,0 from #tbltmpHistorySisterN      
      
  -- mentis issue no:0014229 MS - 2020-02-02 for duplicate records delete      
  delete       
  from sExamination.tHistoryDetail      
  where id not in(      
  select MAx(ID) as Id       
  from sExamination.tHistoryDetail      
  Group by HistoryId,RelationshipId,DiseaseId,OrgId        
  )      
      
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrHistoryXML,6,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  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">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tbltmpTests') IS NOT NULL      
  DROP TABLE #tbltmpTests      
      
  create table #tbltmpTests       
  (      
   tid int identity(1,1),t_ParticipantSourceId bigint,t_TestDetailId int,t_Result varchar(300),t_Remark varchar(500),      
   t_ExaminationId bigint,t_OrgId int,t_TestId int,t_TestRequestId bigint,t_TestRequestDetailId bigint,      
   t_ParticipantAreaId bigint,t_ParamId int,t_TestDetailIdMain int      
  )      
  insert into #tbltmpTests      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@TestDetailId','int') as TestDetailId,      
  T.c.value('@Result','varchar(300)') as Result,      
  left(T.c.value('@Remark','varchar(700)'),200) as Remark,      
  null,null,null,null,null,null,null,null      
  from @loXMLTest.nodes('/Tests/Test')T(c)      
        
  IF EXISTS (SELECT 1 FROM sys.indexes WHERE NAME = N'IX_tTestRequestDetail')      
  DROP INDEX IX_tTestRequestDetail ON sExamination.tTestRequestDetail      
  CREATE INDEX IX_tTestRequestDetail ON sExamination.tTestRequestDetail (Id,TestRequestId,TestDetailId)      
          
  update #tbltmpTests set t_ExaminationId = e_examinationid,t_OrgId = e_OrgId from #tbltmpExamination where e_ParticipantSourceId = t_ParticipantSourceId      
  update #tbltmpTests set t_TestDetailIdMain = sCommon.fGetIntIdForOrg(t_TestDetailId,t_OrgId) WHERE t_TestDetailId<1000 -- FOR STATIC TEST BY MS 2022-07-21    
  update #tbltmpTests set t_TestDetailIdMain = t_TestDetailId  WHERE t_TestDetailId>1000 -- FOR Manualy Added TEST BY MS 2022-07-21    
  update #tbltmpTests set t_TestId = TestId,t_ParamId = TestParameterId from sOrderEntry.tTestDetail where Id = t_TestDetailIdMain       
  update #tbltmpTests set t_TestRequestId = Id from sExamination.tTestRequest where t_TestId = TestId and SourceId = t_ExaminationId and OrgId = t_OrgId      
  update #tbltmpTests set t_TestRequestDetailId = Id from sExamination.tTestRequestDetail      
  where t_TestRequestId = TestRequestId and t_TestDetailIdMain = TestDetailId      
  OPTION(RECOMPILE)      
        
  declare @tbl table(tid int identity(1,1),t_TestId int,ExId bigint,t_PartId bigint)      
  insert into @tbl      
  select distinct t_TestId,t_ExaminationId,t_ParticipantAreaId from #tbltmpTests where t_TestId is not null      
          
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequest', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
         
  MERGE sExamination.tTestRequest AS Target USING       
  (      
   SELECT Id,TestId as AreaId,SourceId,ExId,TT.t_TestId,tid      
   FROM @tbl TT LEFT JOIN sExamination.tTestRequest T ON TT.ExId = T.SourceId AND TestId = t_TestId      
  ) AS Source ON Target.SourceId = Source.ExId AND Target.TestId = Source.t_TestId      
  WHEN MATCHED THEN      
   UPDATE SET IsObsolete = 0      
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    OrgId,Id,SourceTypeId,SourceId,IsObsolete,TestId      
   )      
   VALUES     (      
    @lOrgId,@lFromNextNumber + tid,1002,ExId,0,t_TestId      
   );      
         
  select @lCount = COUNT(1) FROM @tbl      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tTestRequest', @rCurrentNumber = @lNextNumber      
        
  update #tbltmpTests set t_TestRequestId = Id from sExamination.tTestRequest where SourceId = t_ExaminationId      
  and TestId = t_TestId and OrgId = t_OrgId      
        
  --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output       
  --SET @lFromNextNumber = @lNextNumber - 1      
         
  IF OBJECT_ID('tempdb..#tbltmpTestsN') IS NOT NULL      
  DROP TABLE #tbltmpTestsN      
  create table #tbltmpTestsN       
  (      
   tid int identity(1,1),t_ParticipantSourceId bigint,t_TestDetailId int,t_Result varchar(300),t_Remark varchar(500),      
   t_ExaminationId bigint,t_OrgId int,t_TestId int,t_TestRequestId bigint,t_TestRequestDetailId bigint,      
   t_ParticipantAreaId bigint,t_ParamId int,t_TestDetailIdMain int      
  )      
  insert into #tbltmpTestsN       
  (      
   t_ParticipantSourceId,t_TestDetailId,t_Result,t_Remark,      
   t_ExaminationId,t_OrgId,t_TestId,t_TestRequestId,t_TestRequestDetailId,      
   t_ParticipantAreaId,t_ParamId,t_TestDetailIdMain      
 )      
  select t_ParticipantSourceId,t_TestDetailId,t_Result,left(t_Remark,200),t_ExaminationId,t_OrgId,t_TestId,t_TestRequestId,t_TestRequestDetailId,      
  t_ParticipantAreaId,t_ParamId,t_TestDetailIdMain from #tbltmpTests where t_ParamId is not null and t_TestId is not null and t_TestRequestId is not null      
          
  MERGE sExamination.tTestRequestDetail AS Target USING       
  (      
   SELECT tid,Id,TestRequestId,TestDetailId,t_TestDetailId,t_TestRequestId,t_Result,t_ParamId,t_Remark,t_TestDetailIdMain      
   FROM #tbltmpTestsN TT LEFT JOIN sExamination.tTestRequestDetail T ON TT.t_TestRequestId = TestRequestId and TestDetailId = t_TestDetailIdMain      
  ) AS Source ON Target.TestRequestId = Source.t_TestRequestId AND Target.TestDetailId = Source.t_TestDetailIdMain      
  WHEN MATCHED THEN      
   UPDATE SET ServiceValue = [sSetup].[fPortalXMLTagsReplaceReverse](t_Result),      
   Remark = [sSetup].[fPortalXMLTagsReplaceReverse](t_Remark)      
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    OrgId,TestRequestId,TestDetailId,ServiceValue,Remark      
   )      
   VALUES      
   (      
    @lOrgId,t_TestRequestId,t_TestDetailIdMain,      
    [sSetup].[fPortalXMLTagsReplaceReverse](t_Result),[sSetup].[fPortalXMLTagsReplaceReverse](t_Remark)      
   );      
         
  --select @lCount = COUNT(1) FROM #tbltmpTestsN       
  --SET @lNextNumber  = @lCount + @lFromNextNumber       
  --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tTestRequestDetail', @rCurrentNumber = @lNextNumber        
        
  update #tbltmpTests set t_TestRequestDetailId = Id from sExamination.tTestRequestDetail      
  where t_TestRequestId = TestRequestId and t_TestDetailIdMain = TestDetailId      
        
  update w set w.IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](w.Id,w.ServiceValue),
  w.Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](w.Id,w.ServiceValue) = 0 THEN '' ELSE w.Diagnosis END
  from sExamination.tTestRequestDetail w inner join #tbltmpTests t on t.t_TestRequestDetailId = w.Id      
        
  IF OBJECT_ID('tempdb..#tbltmpRatio') IS NOT NULL      
  DROP TABLE #tbltmpRatio      
  create table #tbltmpRatio(tid int identity(1,1),r_TestRequestDetailId bigint,r_TestDetailId int,      
  r_ParameterId int,r_Res varchar(200),r_ExaminationId bigint,r_TestRequestId bigint,r_TestId int)      
  insert into #tbltmpRatio      
  select t_TestRequestDetailId,t_TestDetailIdMain,t_ParamId,t_Result,t_ExaminationId,t_TestRequestId,t_TestId from #tbltmpTests      
  where t_ParamId in (sCommon.fGetIntIdForOrg(34,@lOrgId),sCommon.fGetIntIdForOrg(33,@lOrgId),sCommon.fGetIntIdForOrg(31,@lOrgId)      
  ,sCommon.fGetIntIdForOrg(32,@lOrgId))        
        
  IF OBJECT_ID('tempdb..#tbltmpRatioN') IS NOT NULL      
  DROP TABLE #tbltmpRatioN      
  create table #tbltmpRatioN(tid int identity(1,1),n_ExaminationId bigint,n_StoreLocationId int)      
  insert into #tbltmpRatioN      
  select distinct r_ExaminationId,null from #tbltmpRatio      
        
  update w set w.n_StoreLocationId = e.e_StoreLocationId from #tbltmpRatioN w inner join #tbltmpExamination e on w.n_ExaminationId = e.e_examinationid      
        
  declare @lRatioCnt int,@lRationIncr int,@lConfValueAuto int      
  select @lRationIncr = 1,@lRatioCnt = count(*) from #tbltmpRatioN      
        
  --select * from #tbltmpRatio      
        
      
  while @lRationIncr <= @lRatioCnt      
  begin      
   declare @lExaminationId bigint,@lTestId int,@lTestRequestId bigint,@lTestDetail1Id int,@lTestDetail2Id int      
   declare @lTestDetail3Id int,@lTestDetail4Id int,@lStoreLocationId int,@lLocationId int,@lUserId bigint      
   declare @lLDLVal varchar(300),@lHDLVal varchar(300),@lCHOLEVal varchar(300),@lTryVal varchar(300)     
   declare @lVLDL varchar(300)='',@lLDL varchar(300)=''      
         
   select @lExaminationId = n_ExaminationId,@lStoreLocationId = n_StoreLocationId from #tbltmpRatioN where tid = @lRationIncr      
   select @lLocationId = LocationId from sIp.tStoreLocationMaster where Id = @lStoreLocationId      
   select @lUserId = CreatedUserId from sExamination.tExamination where Id = @lExaminationId      
         
   select @lConfValueAuto = case when      
   sConfig.fConfigurationValueGet('Examination.IsLipidParameterAutoCalculate',@lOrgId,@lStoreLocationId,@lLocationId,@lUserId) = 'True' then 1 else 0 end      
         
   select @lLDLVal = r_Res,@lTestRequestId = r_TestRequestId,@lTestId = r_TestId from #tbltmpRatio      
   where r_ExaminationId = @lExaminationId and r_ParameterId = sCommon.fGetIntIdForOrg(34,@lOrgId)      
         
   select @lHDLVal = r_Res,@lTestRequestId = r_TestRequestId,@lTestId = r_TestId from #tbltmpRatio      
   where r_ExaminationId = @lExaminationId and r_ParameterId = sCommon.fGetIntIdForOrg(33,@lOrgId)      
         
   select @lCHOLEVal = r_Res,@lTestRequestId = r_TestRequestId,@lTestId = r_TestId from #tbltmpRatio      
   where r_ExaminationId = @lExaminationId and r_ParameterId = sCommon.fGetIntIdForOrg(31,@lOrgId)      
         
   select @lTryVal = r_Res,@lTestRequestId = r_TestRequestId,@lTestId = r_TestId from #tbltmpRatio      
   where r_ExaminationId = @lExaminationId and r_ParameterId = sCommon.fGetIntIdForOrg(32,@lOrgId)      
         
   if @lTryVal <> '' and @lHDLVal <> '' and @lCHOLEVal <> ''      
   begin      
    select @lVLDL = convert(float,@lTryVal) / 5      
    select @lLDL = convert(float,@lCHOLEVal) - convert(float,@lHDLVal) - convert(float,@lVLDL)      
    select @lLDLVal = @lLDL      
   end      
         
   select @lTestDetail1Id = Id from sOrderEntry.tTestDetail where TestParameterId = sCommon.fGetIntIdForOrg(36,@lOrgId)      
   select @lTestDetail2Id = Id from sOrderEntry.tTestDetail where TestParameterId = sCommon.fGetIntIdForOrg(37,@lOrgId)      
   select @lTestDetail3Id = Id from sOrderEntry.tTestDetail where TestParameterId = sCommon.fGetIntIdForOrg(35,@lOrgId)      
   select @lTestDetail4Id = Id from sOrderEntry.tTestDetail where TestParameterId = sCommon.fGetIntIdForOrg(34,@lOrgId)      
         
   if exists (select 1 from sExamination.tTestRequestDetail where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail1Id)      
   begin      
    update sExamination.tTestRequestDetail set       
    ServiceValue = case when @lLDLVal <> '' and @lHDLVal <> '' and @lLDLVal <> '0' and @lHDLVal <> '0' then      
    convert(varchar,convert(decimal(12,2),convert(float,@lLDLVal) / convert(float,@lHDLVal))) else '' end      
    where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail1Id      
          
    update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
    where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail1Id      
   end      
   else      
   begin      
    --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output      
          
    insert into sExamination.tTestRequestDetail      
    (      
     TestRequestId,TestDetailId,ServiceValue,OrgId      
    )      
    select @lTestRequestId,@lTestDetail1Id,      
    case when @lLDLVal <> '' and @lHDLVal <> '' and @lLDLVal <> '0' and @lHDLVal <> '0' then      
    convert(varchar,convert(decimal(12,2),convert(float,@lLDLVal) / convert(float,@lHDLVal))) else '' end,@lOrgId      
          
    update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
    where Id = SCOPE_IDENTITY()      
   end      
         
   if exists (select 1 from sExamination.tTestRequestDetail where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail2Id)      
   begin      
    update sExamination.tTestRequestDetail set      
    ServiceValue = case when @lHDLVal <> '' and @lCHOLEVal <> '' and @lHDLVal <> '0' and @lCHOLEVal <> '0' then      
    convert(varchar,convert(decimal(12,2),convert(float,@lCHOLEVal) / convert(float,@lHDLVal))) else '' end      
    where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail2Id      
          
    update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
    where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail2Id      
   end      
   else      
   begin      
    --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output      
          
    insert into sExamination.tTestRequestDetail      
    (      
     TestRequestId,TestDetailId,ServiceValue,OrgId      
    )      
    select @lTestRequestId,@lTestDetail2Id,      
    case when @lHDLVal <> '' and @lCHOLEVal <> '' and @lHDLVal <> '0' and @lCHOLEVal <> '0' then      
    convert(varchar,convert(decimal(12,2),convert(float,@lCHOLEVal) / convert(float,@lHDLVal))) else '' end,@lOrgId      
          
    update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
    where Id = SCOPE_IDENTITY()      
   end      
   print @lVLDL      
   Print @lLDL      
   if @lConfValueAuto = 1      
   begin      
    if exists (select 1 from sExamination.tTestRequestDetail where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail3Id)      
    begin      
     update sExamination.tTestRequestDetail set ServiceValue = @lVLDL      
     where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail3Id      
           
     update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	 Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
     where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail3Id      
    end      
    else      
    begin      
     --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output      
           
     insert into sExamination.tTestRequestDetail      
     (      
      TestRequestId,TestDetailId,ServiceValue,OrgId      
     )      
     select @lTestRequestId,@lTestDetail3Id,@lVLDL,@lOrgId      
           
     update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	 Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
     where Id = SCOPE_IDENTITY()      
    end      
          
    if exists (select 1 from sExamination.tTestRequestDetail where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail4Id)      
    begin      
     update sExamination.tTestRequestDetail set ServiceValue = @lLDL      
     where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail4Id      
           
     update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	 Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
     where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail4Id      
    end      
    else      
    begin      
     --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output      
           
     insert into sExamination.tTestRequestDetail      
     (      
      TestRequestId,TestDetailId,ServiceValue,OrgId      
     )      
     select @lTestRequestId,@lTestDetail4Id,@lLDL,@lOrgId      
           
     update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	 Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
     where Id = SCOPE_IDENTITY()      
    end      
   end      
         
   select @lRationIncr = @lRationIncr + 1      
  end      
        
  --added by ms- for getting correct abnormal flag update for first time insert records      
  update #tbltmpRatio set r_TestRequestDetailId = Id from sExamination.tTestRequestDetail where TestRequestId = r_TestRequestId      
  and TestDetailId = r_TestDetailId      
  -- finish      
      
  update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
  Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
  from sExamination.tTestRequestDetail inner join #tbltmpRatio on r_TestRequestDetailId = Id      
   
 --select @rConfigBloodGroup  
  IF(@rConfigBloodGroup = 1)  
  BEGIN  
  --select * from #tbltmpTests  
  UPDATE EPD  
   SET BloodGroupId = (SELECT Id FROM sCommon.tBloodGroupMaster WHERE Title = TMPT.t_Result)  
   FROM sHrm.tEmployeePersonalDetail EPD  
   INNER JOIN sExamination.tExamination E ON E.ParticipantSourceId = EPD.EmployeeId  
   INNER JOIN sExamination.tTestRequest TR ON TR.SourceId = E.Id  
   INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id  
   INNER JOIN sOrderEntry.tTestDetail TD ON TD.Id = TRD.TestDetailId  
   INNER JOIN #tbltmpTests TMPT ON TMPT.t_TestDetailIdMain = TD.Id  
   INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId  
   WHERE TPM.StaticTestParameterId = 1;  
  END  
  
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrTestXML,7,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  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">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tblGeneral') IS NOT NULL      
  DROP TABLE #tblGeneral      
      
  create table #tblGeneral      
  (      
   tid int identity(1,1),g_EmpId bigint,g_ParamId int,g_Res varchar(1000),g_Rem varchar(1500),      
   g_ExamId bigint,g_TestId int,g_OrgId int,g_GeneralDetId bigint,g_GenId bigint      
  )      
  insert into #tblGeneral      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@ParameterId','int') as ParameterId,      
  T.c.value('@Result','varchar(1000)') as Result,      
  T.c.value('@Remark','varchar(1500)') as Remark,null,null,null,null,null      
  from @loXMLGeneral.nodes('/General/Clinic')T(c) where T.c.value('@Result','varchar(1000)') <> ''      
        
  update #tblGeneral set g_ExamId = e_examinationid,g_OrgId = e_OrgId from #tbltmpExamination where e_ParticipantSourceId = g_EmpId      
  update #tblGeneral set g_ParamId = Id,g_TestId = GeneralTemplateId from sExamination.tGeneralTemplateParameter      
  where StaticGeneralTemplateParameterId = g_ParamId and OrgId = g_OrgId     
    
  update #tblGeneral set g_ParamId = Id,g_TestId = GeneralTemplateId from sExamination.tGeneralTemplateParameter      
  where StaticGeneralTemplateParameterId IS NuLL and Id = g_ParamId and OrgId = g_OrgId   -- if staticgeneralparamterid is null ; Nidhi Pandey DT - 22/04/2024;mantis - 0032971  
     
    
  IF OBJECT_ID('tempdb..#tblGeneralN') IS NOT NULL      
  DROP TABLE #tblGeneralN      
      
  create table #tblGeneralN(tid int identity(1,1),n_TestId int,n_Exid bigint,n_OrgId int,n_PartAreaId bigint,n_GeneralId bigint)      
  insert into #tblGeneralN      
  select distinct g_TestId,g_ExamId,g_OrgId,null,null from #tblGeneral      
         
  update #tblGeneralN set n_GeneralId = Id from sExamination.tGeneralTemplateExamination where GeneralTemplateId = n_TestId      
  and SourceId = n_Exid      
       
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tGeneralTemplateExamination', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tGeneralTemplateExamination AS Target USING       
  (      
   SELECT Id,n_TestId,n_Exid,n_OrgId,n_GeneralId,tid      
   FROM #tblGeneralN TT LEFT JOIN sExamination.tGeneralTemplateExamination T ON TT.n_GeneralId = T.Id        
  ) AS Source ON Target.Id = Source.n_GeneralId       
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    [Id],SourceId,SourceTypeId,GeneralTemplateId,OrgId      
   )      
   VALUES      
   (      
    @lFromNextNumber + tid,n_Exid,1002,n_TestId,n_OrgId      
   );      
         
  select @lCount = COUNT(1) FROM #tblGeneralN      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tGeneralTemplateExamination', @rCurrentNumber = @lNextNumber      
        
  update #tblGeneralN set n_GeneralId = Id from sExamination.tGeneralTemplateExamination where GeneralTemplateId = n_TestId      
  and SourceId = n_Exid      
        
  update #tblGeneral set g_GenId = n_GeneralId from #tblGeneralN where g_TestId = n_TestId and g_ExamId = n_Exid      
  update #tblGeneral set g_GeneralDetId = Id from sExamination.tGeneralTemplateExaminationDetail      
  where GeneralTemplateExaminationId = g_GenId and GeneralTemplateParameterId = g_ParamId      
  OPTION(RECOMPILE)      
        
  --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tGeneralTemplateExaminationDetail', 0, 1, 1,@outNextNumber = @lNextNumber output       
  --SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tGeneralTemplateExaminationDetail AS Target USING       
  (      
   SELECT Id,g_ParamId,g_GeneralDetId,g_Res,g_Rem,g_GenId,tid      
   FROM #tblGeneral TT LEFT JOIN sExamination.tGeneralTemplateExaminationDetail T ON TT.g_GeneralDetId = T.Id        
  ) AS Source ON Target.Id = Source.g_GeneralDetId      
  WHEN MATCHED THEN      
   UPDATE SET ParameterValue = [sSetup].[fPortalXMLTagsReplaceReverse](g_Res),Remark = [sSetup].[fPortalXMLTagsReplaceReverse](g_Rem)      
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    GeneralTemplateExaminationId,GeneralTemplateParameterId,ParameterValue,Remark      
   )      
   VALUES      
   (      
    g_GenId,g_ParamId,[sSetup].[fPortalXMLTagsReplaceReverse](g_Res),[sSetup].[fPortalXMLTagsReplaceReverse](g_Rem)      
   );      
         
  --select @lCount = COUNT(1) FROM #tblGeneral      
  --SET @lNextNumber  = @lCount + @lFromNextNumber       
  --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tGeneralTemplateExaminationDetail', @rCurrentNumber = @lNextNumber      
        
  update #tblGeneral set g_GeneralDetId = Id from sExamination.tGeneralTemplateExaminationDetail      
  where GeneralTemplateExaminationId = g_GenId and GeneralTemplateParameterId = g_ParamId      
        
  update sExamination.tGeneralTemplateExaminationDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForGeneralN](TRD.Id,TRD.ParameterValue)      
  from sExamination.tGeneralTemplateExaminationDetail TRD inner join #tblGeneral tt on TRD.Id = tt.g_GeneralDetId      
  OPTION(RECOMPILE)      
        
  IF OBJECT_ID('tempdb..#tblExaminationGeneral') IS NOT NULL      
  begin    
 DROP TABLE #tblExaminationGeneral      
  end    
    
  create table #tblExaminationGeneral      
  (      
   tid int identity(1,1),g_ParticipantSourceId bigint,g_SetupId int,g_OrgId int,g_ExaminationId bigint      
  )      
  insert into #tblExaminationGeneral      
  select e_ParticipantSourceId,e_SetupId,e_OrgId,e_examinationid from #tbltmpExamination      
      
  select top 1 @lOrgId = g_OrgId from #tblExaminationGeneral      
   --select * from #tblExaminationGeneral     
  IF OBJECT_ID('tempdb..#tblGeneralTests') IS NOT NULL      
  DROP TABLE #tblGeneralTests      
  create table #tblGeneralTests      
  (      
   tid int identity(1,1),g_ExaminationId bigint,g_TestId int,g_ParticipantAreaId bigint,g_GeneralTemplateExaminationId bigint,      
   g_StaticId int      
  )      
  insert into #tblGeneralTests      
  select g_ExaminationId,Id,null,null,Id from #tblExaminationGeneral cross apply sExamination.tStaticGeneralTemplateMaster       
        
  update #tblGeneralTests set g_TestId = sCommon.fGetIntIdForOrg(g_TestId,@lOrgId)      
        
  update #tblGeneralTests set g_GeneralTemplateExaminationId = Id from sExamination.tGeneralTemplateExamination      
  where g_ExaminationId = SourceId and g_TestId = GeneralTemplateId      
         
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tGeneralTemplateExamination', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tGeneralTemplateExamination AS Target USING       
  (      
   SELECT Id,g_TestId,g_GeneralTemplateExaminationId,g_ExaminationId,tid as rno,      
   (      
    SELECT MAX(T.Id) FROM sExamination.tGeneralTemplateExamination t      
   ) as maxid      
   FROM #tblGeneralTests TT LEFT JOIN sExamination.tGeneralTemplateExamination T ON TT.g_GeneralTemplateExaminationId = T.Id        
  ) AS Source ON Target.Id = Source.g_GeneralTemplateExaminationId       
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    [Id],SourceId,SourceTypeId,GeneralTemplateId,OrgId      
   )      
   VALUES      
   (      
    @lFromNextNumber + rno,g_ExaminationId,1002,g_TestId,@lOrgId      
   );      
        
  select @lCount = COUNT(1) FROM #tblGeneralTests      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tGeneralTemplateExamination', @rCurrentNumber = @lNextNumber      
          
  update #tblGeneralTests set g_GeneralTemplateExaminationId = Id from sExamination.tGeneralTemplateExamination      
  where g_ExaminationId = SourceId and g_TestId = GeneralTemplateId      
        IF OBJECT_ID('tempdb..#tblGeneralParameters') IS NOT NULL      
  DROP TABLE #tblGeneralParameters       
  create table #tblGeneralParameters      
  (      
   tid int identity(1,1),p_GeneralTemplateExaminationId bigint,p_GeneralTemplateExaminationDetailId bigint,      
   p_ParameterId int,p_Result varchar(max),p_IsDefault bit      
  )      
  insert into #tblGeneralParameters      
  select distinct g_GeneralTemplateExaminationId,null,SP.Id,null,isnull(GP.IsNotDefault,0) from #tblGeneralTests cross apply #tblExaminationGeneral      
  cross apply sExamination.tStaticGeneralTemplateParameter SP inner join sExamination.tGeneralTemplateParameter GP      
  on SP.Id = GP.StaticGeneralTemplateParameterId      
  where g_StaticId = StaticGeneralTemplateId and GP.OrgId = @lOrgId and isnull(ImportCode,'') = '' --and isnull(GP.IsNotDefault,0) = 0      
          
  update #tblGeneralParameters set p_Result = Title from sExamination.tStaticGeneralTemplateParameterList      
  where p_ParameterId = StaticGeneralTemplateParameterId and IsNormal = 1      
        
  update #tblGeneralParameters set p_ParameterId = sCommon.fGetIntIdForOrg(p_ParameterId,@lOrgId)      
        
  update #tblGeneralParameters set p_GeneralTemplateExaminationDetailId = Id from sExamination.tGeneralTemplateExaminationDetail      
  where p_GeneralTemplateExaminationId = GeneralTemplateExaminationId and p_ParameterId = GeneralTemplateParameterId      
  OPTION(RECOMPILE)      
         
  --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tGeneralTemplateExaminationDetail', 0, 1, 1,@outNextNumber = @lNextNumber output       
  --SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tGeneralTemplateExaminationDetail AS Target USING       
  (      
   SELECT Id,p_GeneralTemplateExaminationId,p_GeneralTemplateExaminationDetailId,p_Result,p_ParameterId,p_IsDefault,tid as rno,      
   (      
    SELECT MAX(T.Id) FROM sExamination.tGeneralTemplateExaminationDetail t      
   ) as maxid      
   FROM #tblGeneralParameters TT LEFT JOIN sExamination.tGeneralTemplateExaminationDetail T ON TT.p_GeneralTemplateExaminationDetailId = T.Id        
  ) AS Source ON Target.Id = Source.p_GeneralTemplateExaminationDetailId       
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    GeneralTemplateExaminationId,GeneralTemplateParameterId,ParameterValue      
   )      
   VALUES      
   (      
    p_GeneralTemplateExaminationId,p_ParameterId,      
    case when isnull(p_IsDefault,0) = 1 then '' else isnull(p_Result,'Normal') end      
   );      
        
  --select @lCount = COUNT(1) FROM #tblGeneralParameters      
  --SET @lNextNumber  = @lCount + @lFromNextNumber       
  --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tGeneralTemplateExaminationDetail', @rCurrentNumber = @lNextNumber      
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrGeneralXML,8,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  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">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tblPulmonary') IS NOT NULL      
  DROP TABLE #tblPulmonary      
      
  create table #tblPulmonary      
  (      
   tid int identity(1,1),pl_ParticipantId bigint,pl_Fvc varchar(100),pl_Fev1 varchar(100),      
   pl_PEFR varchar(100),pl_FVCP varchar(100),pl_FEV1P varchar(100),pl_FEV3P varchar(100),pl_PEFP varchar(100),      
   pl_FEF2575P varchar(100),pl_FEF212P varchar(100),pl_FEF25P varchar(100),pl_FEF50P varchar(100),pl_FEF75P varchar(100),   
   pl_Fev6 varchar(100), pl_FEV6P varchar(100),  
   pl_SVCP varchar(100),pl_ExaminationId bigint,pl_OrgId int,pl_FVCPer float,pl_FEV1Per float,pl_FVCbFEV1per float,      
   pl_PEFRper float,pl_Id bigint,pl_PartId bigint,pl_store int,pl_FEV5Ob float,pl_FEV1ByFEV5 float,pl_MVV float,pl_MVVP varchar(100),      
   pl_FEV1ByFVCObserved float,pl_MVVPer float, pl_FEV6Per float, pl_FEV6bFEV1per float, pl_FEV1ByFEV6Observed float,
   pl_PulmonaryRemark nvarchar(2000), p1_IntensityId nvarchar(100), p1_IntensityResultId nvarchar(100), p1_IsDoneManually bit
  )      
  insert into #tblPulmonary      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@FVC','varchar(100)') as FVC,      
  T.c.value('@FEV1','varchar(100)') as FEV1,      
  T.c.value('@PEFR','varchar(100)') as PEFR,      
  T.c.value('@FVCP','varchar(100)') as FVCP,      
  T.c.value('@FEV1P','varchar(100)') as FEV1P,      
  T.c.value('@FEV3P','varchar(100)') as FEV3P,      
  T.c.value('@PEFP','varchar(100)') as PEFP,      
  T.c.value('@FEF2575P','varchar(100)') as FEF2575P,      
  T.c.value('@FEF212P','varchar(100)') as FEF212P,      
  T.c.value('@FEF25P','varchar(100)') as FEF25P,      
  T.c.value('@FEF50P','varchar(100)') as FEF50P,      
  T.c.value('@FEF75P','varchar(100)') as FEF75P,      
  T.c.value('@FEV6','varchar(100)') as FEV6,  
  T.c.value('@FEV6P','varchar(100)') as FEV6P,  
  T.c.value('@SVCP','varchar(100)') as SVCP,      
  null,null,null,null,null,null,null,null,null,null,null,null,  
  T.c.value('@MVVP','varchar(100)') as MVVP,null,null,null,null,null,
  T.c.value('@PulmonaryRemark','varchar(100)') as PulmonaryRemark,
  T.c.value('@IntensityId','varchar(100)') as IntensityId,
  T.c.value('@IntensityResultId','varchar(100)') as IntensityResultId,0
  from @loXMLPulmonary.nodes('/Pulmonarys/Pulmonary')T(c)      
        
  Delete From #tblPulmonary where Isnull(pl_Fvc,'')='' and Isnull(pl_Fev1,'')='' and Isnull(pl_PEFR,'')='' and       
  Isnull(pl_FVCP,'')='' and Isnull(pl_FEV1P,'')='' and Isnull(pl_FEV3P,'')='' and Isnull(pl_PEFP,'')='' and      
  Isnull(pl_FEF2575P,'')='' and Isnull(pl_FEF212P,'')='' and Isnull(pl_FEF25P,'')='' And Isnull(pl_FEF50P,'')='' And      
  Isnull(pl_FEF75P,'')='' And Isnull(pl_SVCP,'')='' And Isnull(pl_MVVP,'')='' and Isnull(pl_Fev6,'')='' and Isnull(pl_FEV6P,'')=''
  AND Isnull(pl_PulmonaryRemark,'')='' AND Isnull(p1_IntensityId,'')='' AND Isnull(p1_IntensityResultId,'')=''
              
  update #tblPulmonary set pl_ExaminationId = e_examinationid,pl_OrgId = e_OrgId,pl_store = e_StoreLocationId      
  from #tbltmpExamination where e_ParticipantSourceId = pl_ParticipantId      
        
  update #tblPulmonary set pl_Id = Id from sExamination.tPulmonary where SourceId = pl_ExaminationId       

  update #tblPulmonary set p1_IsDoneManually = 1 from sExamination.tPulmonary where Isnull(p1_IntensityResultId,'') <> ''
        
  update #tblPulmonary set pl_FVCPer = case when isnull(pl_Fvc,'') <> '' and isnull(pl_FVCP,'') <> ''      
  and isnull(pl_Fvc,'') <> '0' and isnull(pl_FVCP,'') <> '0' then ((convert(float,pl_Fvc) * 100) / convert(float,pl_FVCP)) else null end      
        
  update #tblPulmonary set pl_FEV1Per = case when isnull(pl_Fev1,'') <> '' and isnull(pl_FEV1P,'') <> ''      
  and isnull(pl_Fev1,'') <> '0' and isnull(pl_FEV1P,'') <> '0' then ((convert(float,pl_Fev1) * 100) / convert(float,pl_FEV1P)) else null end      
        
  update #tblPulmonary set pl_FVCbFEV1per = case when isnull(pl_FEV1P,'') <> '' and isnull(pl_FVCP,'') <> ''      
  and isnull(pl_Fev1,'') <> '' and isnull(pl_Fvc,'') <> '' and isnull(pl_FEV1P,'') <> '0' and isnull(pl_FVCP,'') <> '0'      
  and isnull(pl_Fev1,'') <> '0' and isnull(pl_Fvc,'') <> '0' then      
  (((convert(float,pl_Fev1) * 100) / convert(float,pl_Fvc)) * 100 / (((convert(float,pl_FEV1P) * 100) / convert(float,pl_FVCP))))      
  else null end      
          
  update #tblPulmonary set pl_PEFRPer = case when isnull(pl_PEFR,'') <> '' and isnull(pl_PEFP,'') <> ''      
  and isnull(pl_PEFR,'') <> '0' and isnull(pl_PEFP,'') <> '0' then ((convert(float,pl_PEFR) * 100) / convert(float,pl_PEFP)) else null end      
        
  update #tblPulmonary set pl_FEV5Ob = case when isnull(pl_Fev1,'') <> '' and isnull(pl_Fev1,'') <> '0' then Convert(float,pl_Fev1) / 1.8 else null end      
      
  update #tblPulmonary set pl_FEV1ByFEV5 = case when isnull(pl_Fev1,'') <> '0' and isnull(pl_Fev1,'') <> ''      
  and isnull(pl_FEV5Ob,'') <> '0' and isnull(pl_FEV5Ob,'') <> '' then pl_Fev1 / pl_FEV5Ob else null end      
        
  update #tblPulmonary set pl_MVV = case when isnull(pl_Fev1,'') <> '0.00' and isnull(pl_Fev1,'') <> '' then (convert(float,pl_Fev1) * 35) else null end      
        
  update #tblPulmonary set pl_MVVPer = case when isnull(pl_MVV,'') <> '0.00' and isnull(pl_MVV,'') <> ''      
  and isnull(pl_MVVP,'') <> '0.00' and isnull(pl_MVVP,'') <> '' then (convert(float,pl_MVV) * 100 / convert(float,pl_MVVP)) else null end      
        
  update #tblPulmonary set pl_FEV1ByFVCObserved = case when isnull(pl_Fev1,'') <> '0.00' and isnull(pl_Fev1,'') <> ''      
  and isnull(pl_Fvc,'') <> '0.00' and isnull(pl_Fvc,'') <> '' then (convert(float,pl_Fev1) / convert(float,pl_Fvc)) else null end      
  
  update #tblPulmonary set pl_FEV6Per = case when isnull(pl_Fev6,'') <> '' and isnull(pl_FEV6P,'') <> ''      
  and isnull(pl_Fev6,'') <> '0' and isnull(pl_FEV6P,'') <> '0' then ((convert(float,pl_Fev6) * 100) / convert(float,pl_FEV6P)) else null end  
  
  update #tblPulmonary set pl_FEV6bFEV1per = case when isnull(pl_FEV1P,'') <> '' and isnull(pl_FEV6P,'') <> ''      
  and isnull(pl_Fev1,'') <> '' and isnull(pl_FEV6,'') <> '' and isnull(pl_FEV1P,'') <> '0' and isnull(pl_FEV6P,'') <> '0'      
  and isnull(pl_Fev1,'') <> '0' and isnull(pl_FEV6,'') <> '0' then      
  (((convert(float,pl_Fev1) * 100) / convert(float,pl_FEV6)) * 100 / (((convert(float,pl_FEV1P) * 100) / convert(float,pl_FEV6P))))      
  else null end  
  
  update #tblPulmonary set pl_FEV1ByFEV6Observed = case when isnull(pl_Fev1,'') <> '0.00' and isnull(pl_Fev1,'') <> ''      
  and isnull(pl_FEV6,'') <> '0.00' and isnull(pl_FEV6,'') <> '' then (convert(float,pl_Fev1) / convert(float,pl_FEV6)) else null end  
         
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tPulmonary', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tPulmonary AS Target USING       
  (      
   SELECT Id,pl_Fvc,pl_Fev1,pl_FVCP,pl_FEV1P,pl_FEV3P,pl_PEFP,pl_FEF2575P,pl_FEF212P,pl_FEF25P,pl_FEF50P,      
   pl_FEF75P,pl_SVCP,pl_ExaminationId,pl_OrgId,pl_FVCPer,pl_FEV1Per,pl_FVCbFEV1per,pl_Id,pl_store,pl_PEFR,pl_PEFRPer,      
   pl_FEV5Ob,pl_FEV1ByFEV5,pl_MVV,pl_MVVP,pl_FEV1ByFVCObserved,tid,  
   pl_Fev6,pl_FEV6P,pl_FEV6Per,pl_FEV1ByFEV6Observed,pl_FEV6bFEV1per,pl_PulmonaryRemark, 
   p1_IntensityId, p1_IntensityResultId, p1_IsDoneManually  
   FROM #tblPulmonary TT LEFT JOIN sExamination.tPulmonary T ON TT.pl_Id = T.Id        
  ) AS Source ON Target.Id = Source.pl_Id      
  WHEN MATCHED THEN      
   UPDATE SET [FVCPredicted] = case when isnull(pl_FVCP,'') = '' then null else pl_FVCP end,      
   [FVCObserved] = case when isnull(pl_Fvc,'') = '' then null else pl_Fvc end,      
   [PerOfPredictedFVC] = pl_FVCPer,[FEV1Predicted] = case when isnull(pl_FEV1P,'') = '' then null else pl_FEV1P end,      
   [FEV1Observed] = case when isnull(pl_Fev1,'') = '' then null else pl_Fev1 end,      
   [PerOfFEV1] = pl_FEV1Per,[FEV3Predicted] = case when isnull(pl_FEV3P,'') = '' then null else pl_FEV3P end,      
   [PEFRPredicted] = case when isnull(pl_PEFP,'') = '' then null else pl_PEFP end,      
   [PerPEFR] = case when isnull(pl_PEFRPer,'') = '' then null else pl_PEFRPer end,      
   [PEFRObserved] = case when isnull(pl_PEFR,'') = '' then null else pl_PEFR end,      
   [FEF2575Predicted] = case when isnull(pl_FEF2575P,'') = '' then null else pl_FEF2575P end,      
   [FEF212Predicted] = case when isnull(pl_FEF212P,'') = '' then null else pl_FEF212P end,      
   [FEF25Predicted] = case when isnull(pl_FEF25P,'') = '' then null else pl_FEF25P end,      
   [FEF50Predicted] = case when isnull(pl_FEF50P,'') = '' then null else pl_FEF50P end,      
   [FEF75Predicted] = case when isnull(pl_FEF75P,'') = '' then null else pl_FEF75P end,      
   [PerOfFEV1ByFVC] = pl_FVCbFEV1per,SVCPredicted = case when isnull(pl_SVCP,'') = '' then null else pl_SVCP end,      
   IsDone =case when isnull(pl_Fvc,'') <> '' and isnull(pl_Fev1,'') <> '' then 1 else 0 end,      
   StoreLocationId = pl_store,FEV5Observed = pl_FEV5Ob,PerOfFEV1ByFEV5 = pl_FEV1ByFEV5,MVVObserved = pl_MVV,      
   MVVPredicted = case when isnull(pl_MVVP,'') = '' then null else pl_MVVP end,      
   Fev1ByFVCObserved = case when isnull(pl_FEV1ByFVCObserved,'') = '' then null else pl_FEV1ByFVCObserved end,  
   FEV6Observed = case when isnull(pl_Fev6,'') = '' then null else pl_Fev6 end,  
   FEV6Predicted = case when isnull(pl_FEV6P,'') = '' then null else pl_FEV6P end,  
   PerOfFEV6 = case when isnull(pl_FEV6Per,'') = '' then null else pl_FEV6Per end,  
   FEV1FEV6Observed = case when isnull(pl_FEV1ByFEV6Observed,'') = '' then null else pl_FEV1ByFEV6Observed end,  
   PerOfFEV1FEV6 = case when isnull(pl_FEV6bFEV1per,'') = '' then null else pl_FEV6bFEV1per end,
   PulmonaryRemark = case when isnull(pl_PulmonaryRemark,'') = '' then null else pl_PulmonaryRemark end,
   PulmonaryResulIntensity = case when isnull(p1_IntensityId,'') = '' then null else p1_IntensityId end,
   PulmonaryResult = case when isnull(p1_IntensityResultId,'') = '' then null else p1_IntensityResultId end,
   IsDoneManually = case when isnull(p1_IsDoneManually,0) = 0 then 0 else p1_IsDoneManually end
  WHEN NOT MATCHED THEN  
   INSERT      
   (      
    [Id],[SourceTypeId],[SourceId],[FVCPredicted],[FVCObserved],[PerOfPredictedFVC],[FEV1Predicted],[FEV1Observed],[PerOfFEV1],      
    [FEV3Predicted],[PEFRPredicted],[FEF2575Predicted],[FEF212Predicted],[FEF25Predicted],[FEF50Predicted],      
    [FEF75Predicted],[PerOfFEV1ByFVC],SVCPredicted,IsDone,StoreLocationId,PerPEFR,PEFRObserved,FEV5Observed,      
    PerOfFEV1ByFEV5,MVVObserved,MVVPredicted,Fev1ByFVCObserved,FEV6Observed,FEV6Predicted,PerOfFEV6,FEV1FEV6Observed,PerOfFEV1FEV6,
	PulmonaryRemark, PulmonaryResulIntensity, PulmonaryResult, IsDoneManually
   )      
   VALUES      
   (      
    @lFromNextNumber + tid,1002,pl_ExaminationId,case when isnull(pl_FVCP,'') = '' then null else pl_FVCP end,      
    case when isnull(pl_Fvc,'') = '' then null else pl_Fvc end,pl_FVCPer,      
    case when isnull(pl_FEV1P,'') = '' then null else pl_FEV1P end,      
    case when isnull(pl_Fev1,'') = '' then null else pl_Fev1 end,pl_FEV1Per,      
    case when isnull(pl_FEV3P,'') = '' then null else pl_FEV3P end,      
    case when isnull(pl_PEFP,'') = '' then null else pl_PEFP end,      
    case when isnull(pl_FEF2575P,'') = '' then null else pl_FEF2575P end,      
    case when isnull(pl_FEF212P,'') = '' then null else pl_FEF212P end,      
    case when isnull(pl_FEF25P,'') = '' then null else pl_FEF25P end,      
    case when isnull(pl_FEF50P,'') = '' then null else pl_FEF50P end,      
    case when isnull(pl_FEF75P,'') = '' then null else pl_FEF75P end,pl_FVCbFEV1per,      
    case when isnull(pl_SVCP,'') = '' then null else pl_SVCP end,      
    case when isnull(pl_Fvc,'') <> '' and isnull(pl_Fev1,'') <> '' then 1 else 0 end,pl_store,      
    case when isnull(pl_PEFRPer,'') = '' then null else pl_PEFRPer end,      
    case when isnull(pl_PEFR,'') = '' then null else pl_PEFR end,      
    case when isnull(pl_FEV5Ob,'') = '' then null else pl_FEV5Ob end,      
    pl_FEV1ByFEV5,pl_MVV,case when isnull(pl_MVVP,'') = '' then null else pl_MVVP end,      
    case when isnull(pl_FEV1ByFVCObserved,'') = '' then null else pl_FEV1ByFVCObserved end,  
	case when isnull(pl_Fev6,'') = '' then null else pl_Fev6 end,  
	case when isnull(pl_FEV6P,'') = '' then null else pl_FEV6P end,  
	case when isnull(pl_FEV6Per,'') = '' then null else pl_FEV6Per end,  
	case when isnull(pl_FEV1ByFEV6Observed,'') = '' then null else pl_FEV1ByFEV6Observed end,  
	case when isnull(pl_FEV6bFEV1per,'') = '' then null else pl_FEV6bFEV1per end,
	case when isnull(pl_PulmonaryRemark,'') = '' then null else pl_PulmonaryRemark end,
	case when isnull(p1_IntensityId,'') = '' then null else p1_IntensityId end,
	case when isnull(p1_IntensityResultId,'') = '' then null else p1_IntensityResultId end,
	case when isnull(p1_IsDoneManually,0) = 0 then 0 else p1_IsDoneManually end
   );  
        
   --update w set PulmonaryResult = item1,PulmonaryResulIntensity = item2 from sExamination.tPulmonary w      
   --inner join #tblPulmonary p on p.pl_ExaminationId = w.SourceId cross apply [sExamination].[fGetPulmonaryResults_NEW](w.SourceId)      
         
   -- update by MS On 26-03-2019 For Diffranciate Adani and Click2Health      
   update w set PulmonaryResult = item1,PulmonaryResulIntensity = item2 from sExamination.tPulmonary w      
        inner join #tblPulmonary p on p.pl_ExaminationId = w.SourceId cross apply [sExamination].[fGetPulmonaryResult](w.SourceId)      
      where (isnull(p.p1_IntensityId,'') = '' and isnull(p.p1_IntensityResultId,'') = '')

  select @lCount = max(tid) FROM #tblPulmonary      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tPulmonary', @rCurrentNumber = @lNextNumber      
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrPulmonary,9,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  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">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tbltmpAudiometry') IS NOT NULL      
  DROP TABLE #tbltmpAudiometry      
      
  create table #tbltmpAudiometry      
  (      
   tid int identity(1,1),a_ParticipantSourceId bigint,a_LocationId int,a_SetupId int,      
   a_LeftAcRemarkId int,a_RightAcRemarkId int,a_By_Rule int,a_AudioLeftACIds varchar(max),a_AudioRightACIds varchar(max),      
   a_AudioLeftBCIds varchar(max),a_AudioRightBCIds varchar(max),a_ExaminationId bigint,a_ParticipantAreaId bigint,      
   a_AudiometryId bigint,a_OrgId int,a_SetupGroupId int,a_LeftManualRemark nvarchar(2000),a_RightManualRemark nvarchar(2000),
   a_LeftAcResultId int, a_LeftBcResultId int, a_RightAcResultId int, a_RightBcResultId int
  )
         
  insert into #tbltmpAudiometry      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@LocationId','int') as LocationId,      
  T.c.value('@SetupId','int') as SetupId,      
  T.c.value('@LeftAcRemarkId','int') as LeftAcRemarkId,      
  T.c.value('@RightAcRemarkId','int') as RightAcRemarkId,      
  case when T.c.value('@By_Rule','varchar(10)') = 'y' or T.c.value('@By_Rule','varchar(10)') = 'yes' or T.c.value('@By_Rule','varchar(10)') = '1' then 1 else 0 end as By_Rule,      
  T.c.value('@AudioLeftACIds','varchar(max)') as e_AudioLeftACIds,      
  T.c.value('@AudioRightACIds','varchar(max)') as AudioRightACIds,      
  T.c.value('@AudioLeftBCIds','varchar(max)') as AudioLeftBCIds,      
  T.c.value('@AudioRightBCIds','varchar(max)') as AudioRightBCIds,      
  null,null,null,null,null,
  T.c.value('@LeftManualRemark','varchar(2000)') as LeftManualRemark,
  T.c.value('@RightManualRemark','varchar(2000)') as RightManualRemark,
  T.c.value('@LeftAcResultId','int') as LeftAcResultId,
  T.c.value('@LeftBcResultId','int') as LeftBcResultId,
  T.c.value('@RightAcResultId','int') as RightAcResultId,
  T.c.value('@RightBcResultId','int') as RightBcResultId
  from @loXMLAudiometry.nodes('/Examinations/Examination')T(c)      
        
  Delete From #tbltmpAudiometry Where Isnull(a_LeftAcRemarkId,'')='' and Isnull(a_RightAcRemarkId,'')='' and Isnull(a_By_Rule,'')='' and      
  Isnull(a_AudioLeftACIds,'')='' and Isnull(a_AudioRightACIds,'')='' and Isnull(a_AudioLeftBCIds,'')='' and Isnull(a_AudioRightBCIds,'')=''
  and Isnull(a_LeftManualRemark,'')='' and Isnull(a_RightManualRemark,'')='' and Isnull(a_LeftAcResultId,'0')='0' and Isnull(a_LeftBcResultId,'0')='0'
  and Isnull(a_RightAcResultId,'0')='0' and Isnull(a_RightBcResultId,'0')='0'

  update #tbltmpAudiometry set a_ExaminationId = e_examinationid,a_OrgId = e_OrgId      
  from #tbltmpExamination where e_ParticipantSourceId = a_ParticipantSourceId      
        
  declare @lAudioAreaId int,@lConfValue int,@i int      
  select top 1 @lOrgId = e_OrgId from #tbltmpExamination    select @lAudioAreaId = Id from [sExamination].[tAreaMaster] where Title = 'Audiometry' and OrgId = @lOrgId      
  select @lAudioAreaId = isnull(@lAudioAreaId,0)       
        
  if @lAudioAreaId = 0      
  begin      
   insert into [sExamination].[tAreaMaster]      
   (      
    Id,Title,Remark,AreaTypeId,AreaGroupId,IsObsolete,PagePath,OrderIndex,ImagePath,OrgId      
   )      
   select sCommon.fGetIntIdForOrg(23,@lOrgId),'Audiometry','p',2,4,0,      
   '~/Pages/Examination/Audiometry.aspx',23,'~/Images/Icon 16x16/icon_outpatient.gif',@lOrgId      
  end      
  IF OBJECT_ID('tempdb..#tbltmpExaminationN') IS NOT NULL      
  DROP TABLE #tbltmpExaminationN      
  create table #tbltmpExaminationN      
  (      
   tid int identity(1,1),e_ParticipantSourceId bigint,e_LocationId int,e_SetupId int,      
   e_LeftAcRemarkId int,e_RightAcRemarkId int,e_By_Rule int,e_AudioLeftACIds varchar(max),e_AudioRightACIds varchar(max),      
   e_AudioLeftBCIds varchar(max),e_AudioRightBCIds varchar(max),e_ExaminationId bigint,e_ParticipantAreaId bigint,      
   e_AudiometryId bigint,e_OrgId int,e_LeftManualRemark nvarchar(2000),e_RightManualRemark nvarchar(2000),
   e_LeftAcResultId int, e_LeftBcResultId int, e_RightAcResultId int, e_RightBcResultId int      
  )      
        
  insert into #tbltmpExaminationN      
  select a_ParticipantSourceId ,a_LocationId ,a_SetupId ,      
  a_LeftAcRemarkId ,a_RightAcRemarkId ,a_By_Rule ,a_AudioLeftACIds ,a_AudioRightACIds ,      
  a_AudioLeftBCIds ,a_AudioRightBCIds ,a_ExaminationId ,a_ParticipantAreaId ,      
  a_AudiometryId ,a_OrgId, a_LeftManualRemark,a_RightManualRemark,
   a_LeftAcResultId, a_LeftBcResultId, a_RightAcResultId, a_RightBcResultId from #tbltmpAudiometry where a_ExaminationId is not null      
          
  update #tbltmpExaminationN set e_AudiometryId = Id from sExamination.tAudiometry where SourceId = e_ExaminationId      
        
         
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tAudiometry', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
          
  MERGE sExamination.tAudiometry AS Target USING       
  (      
   SELECT tid,Id,e_AudiometryId,e_ExaminationId,e_OrgId,e_LeftAcRemarkId,e_RightAcRemarkId,e_By_Rule      
   FROM #tbltmpExaminationN TT LEFT JOIN sExamination.tAudiometry T ON TT.e_AudiometryId = T.Id and e_ExaminationId is not null      
  ) AS Source ON Target.Id = Source.e_AudiometryId      
  WHEN MATCHED THEN      
   UPDATE SET IsByRuleLeft = e_By_Rule,AudiometryResultRemarkLeftId = e_LeftAcRemarkId,      
   IsByRuleRight = e_By_Rule,AudiometryResultRemarkRightId = e_RightAcRemarkId,IsDoneLeft = e_By_Rule,IsDoneRight = e_By_Rule      
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    [Id],SourceId,IsByRuleLeft,AudiometryResultRemarkLeftId,IsByRuleRight,AudiometryResultRemarkRightId,IsDoneLeft,      
    IsDoneRight,SourceTypeId,IsByExaminationLeft,IsByExaminationRight,OrgId      
   )      
   VALUES      
   (      
    @lFromNextNumber + tid,e_ExaminationId,e_By_Rule,e_LeftAcRemarkId,e_By_Rule,e_RightAcRemarkId,e_By_Rule,e_By_Rule,1002,0,0,e_OrgId      
   );      
         
  select @lCount = max(tid) FROM #tbltmpExaminationN       
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tAudiometry', @rCurrentNumber = @lNextNumber      
        
  update #tbltmpExaminationN set e_AudiometryId = Id from sExamination.tAudiometry where SourceId = e_ExaminationId      
        
  IF OBJECT_ID('tempdb..#tbltmpAudiometryN') IS NOT NULL      
  DROP TABLE #tbltmpAudiometryN              
  create table #tbltmpAudiometryN(tid int identity(1,1),a_AudiometryId bigint,a_FreqId int,LeftAcValue varchar(100),      
  RightAcValue varchar(100),LeftBcValue varchar(100),RightBcValue varchar(100),AudiometryDetailId bigint)      
  insert into #tbltmpAudiometryN      
  select e_AudiometryId,val1,val2,null,null,null,null      
 from #tbltmpExaminationN cross apply dbo.fnc_SplitWord(e_AudioLeftACIds,'MAPSTATEPARAMKEYTWO')      
  cross apply dbo.fnc_BifurcateString(ISNULL(word,''),'MAPSTATEPARAMKEYONE') WHERE word <> '' and e_AudiometryId is not null      
          
  update #tbltmpAudiometryN set RightAcValue = val2 from #tbltmpExaminationN cross apply dbo.fnc_SplitWord(e_AudioRightACIds,'MAPSTATEPARAMKEYTWO')      
  cross apply dbo.fnc_BifurcateString(ISNULL(word,''),'MAPSTATEPARAMKEYONE')      
  where a_FreqId = val1 and word <> '' and e_AudiometryId is not null and e_AudiometryId=a_AudiometryId      
        
  update #tbltmpAudiometryN set LeftBcValue = val2 from #tbltmpExaminationN cross apply dbo.fnc_SplitWord(e_AudioLeftBCIds,'MAPSTATEPARAMKEYTWO')      
  cross apply dbo.fnc_BifurcateString(ISNULL(word,''),'MAPSTATEPARAMKEYONE')      
  where a_FreqId = val1 and word <> '' and e_AudiometryId is not null and e_AudiometryId=a_AudiometryId      
        
  update #tbltmpAudiometryN set RightBcValue = val2 from #tbltmpExaminationN cross apply dbo.fnc_SplitWord(e_AudioRightBCIds,'MAPSTATEPARAMKEYTWO')      
  cross apply dbo.fnc_BifurcateString(ISNULL(word,''),'MAPSTATEPARAMKEYONE')      
  where a_FreqId = val1 and word <> '' and e_AudiometryId is not null and e_AudiometryId=a_AudiometryId      
         
  update #tbltmpAudiometryN set AudiometryDetailId = Id from sExamination.tAudiometryDetail      
  where a_AudiometryId = AudiomentryId and a_FreqId = FrequencyId      
        
  update #tbltmpAudiometryN set LeftAcValue = null where isnull(LeftAcValue,'') = ''      
  update #tbltmpAudiometryN set RightAcValue = null where isnull(RightAcValue,'') = ''      
  update #tbltmpAudiometryN set LeftBcValue = null where isnull(LeftBcValue,'') = ''      
  update #tbltmpAudiometryN set RightBcValue = null where isnull(RightBcValue,'') = ''      
        
        
  declare @MaxAudio bigint,@lCurrentN bigint      
  select @MaxAudio = max(Id) from sExamination.tAudiometryDetail      
  select @lCurrentN = CurrentNumber from sCommon.tTableRowId where TableTitle = 'sExamination.tAudiometryDetail' and OrgId = @lOrgId      
  if @MaxAudio > @lCurrentN      
  begin      
   update sCommon.tTableRowId set CurrentNumber = @MaxAudio where TableTitle = 'sExamination.tAudiometryDetail' and OrgId = @lOrgId      
  end      
  
  Declare @lConfValueDynamic varchar(10);  
    
  select @lConfValueDynamic = Isnull(CS.ItemValue,CM.ItemValue)  
  from sConfig.tConfigurationMaster CM  
  LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id   
  where CM.ItemKey = 'Examination.AudiometryFrequency'  
         
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tAudiometryDetail', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
         
  MERGE sExamination.tAudiometryDetail AS Target USING       
  (      
   SELECT tid,Id,AudiometryDetailId,a_FreqId,LeftAcValue,RightAcValue,LeftBcValue,RightBcValue,a_AudiometryId      
   FROM #tbltmpAudiometryN TT LEFT JOIN sExamination.tAudiometryDetail T ON TT.AudiometryDetailId = T.Id      
  ) AS Source ON Target.Id = Source.AudiometryDetailId  
  WHEN MATCHED THEN  
   UPDATE SET   
    AcValueLeft = CASE WHEN @lConfValueDynamic = 'Dynamic' AND ISNULL(Source.LeftAcValue, '') = '' THEN Target.AcValueLeft ELSE Source.LeftAcValue END,  
    AcValueRight = CASE WHEN @lConfValueDynamic = 'Dynamic' AND ISNULL(Source.RightAcValue, '') = '' THEN Target.AcValueRight ELSE Source.RightAcValue END,      
    BcValueLeft = CASE WHEN @lConfValueDynamic = 'Dynamic' AND ISNULL(Source.LeftBcValue, '') = '' THEN Target.BcValueLeft ELSE Source.LeftBcValue END,  
    BcValueRight = CASE WHEN @lConfValueDynamic = 'Dynamic' AND ISNULL(Source.RightBcValue, '') = '' THEN Target.BcValueRight ELSE Source.RightBcValue END  
  WHEN NOT MATCHED THEN      
   INSERT      
   (  
    [Id],AudiomentryId,FrequencyId,AcValueLeft,BcValueLeft,AcValueRight,BcValueRight,OrgId      
   )      
   VALUES      
   (      
    @lFromNextNumber + tid,a_AudiometryId,a_FreqId,LeftAcValue,LeftBcValue,RightAcValue,RightBcValue,@lOrgId      
   );  
         
  select @lCount = max(tid) FROM #tbltmpAudiometryN       
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tAudiometryDetail', @rCurrentNumber = @lNextNumber      
          
  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.AudiometryFrequencyCount'  

  Declare @lAudiometryResultRemarkManualConf nvarchar(10);

  select @lAudiometryResultRemarkManualConf = Isnull(CS.ItemValue,CM.ItemValue)       
  from sConfig.tConfigurationMaster CM
  LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id
  where CM.ItemKey = 'Examination.IsAudiometryResultRemarkManualUpdate'
        
  select @lCount = count(1),@i = 1 from #tbltmpExaminationN      
  while @i <= @lCount      
  begin      
   declare @lAudiomentryId bigint,@lSumAcLeft int,@lSumBcLeft int,@lSumAcRight int,@lSumBcRight int      
   declare @lSumAcLeftDivide decimal(12,2),@lSumBcLeftDivide decimal(12,2),@lSumAcRightDivide decimal(12,2),@lSumBcRightDivide decimal(12,2);  
   declare @lCountAcLeft int, @lCountBcLeft int, @lCountAcRight int, @lCountBcRight int;  
  
   select @lAudiomentryId = e_AudiometryId from #tbltmpExaminationN where tid = @i;  
  
 IF @lConfValueDynamic = 'Dynamic'  
 BEGIN  
   select @lSumAcLeft = ISNULL(sum(convert(int,AcValueLeft)), 0) from sExamination.tAudiometryDetail where AudiomentryId = @lAudiomentryId and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)  
   select @lSumBcLeft = ISNULL(sum(convert(int,BcValueLeft)), 0) from sExamination.tAudiometryDetail where AudiomentryId = @lAudiomentryId and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)  
   select @lSumAcRight = ISNULL(sum(convert(int,AcValueRight)), 0) from sExamination.tAudiometryDetail where AudiomentryId = @lAudiomentryId and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)  
   select @lSumBcRight = ISNULL(sum(convert(int,BcValueRight)), 0) from sExamination.tAudiometryDetail where AudiomentryId = @lAudiomentryId and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)  
  
   select @lCountAcLeft = Count(AcValueLeft) from sExamination.tAudiometryDetail   
         where AudiomentryId = @lAudiomentryId   
         and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)   
         and (AcValueLeft != 0 and AcValueLeft is not null)  
  
   select @lCountBcLeft = Count(BcValueLeft) from sExamination.tAudiometryDetail   
         where AudiomentryId = @lAudiomentryId   
         and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)  
         and (BcValueLeft != 0 and BcValueLeft is not null)  
  
   select @lCountAcRight = Count(AcValueRight) from sExamination.tAudiometryDetail   
         where AudiomentryId = @lAudiomentryId   
         and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)  
         and (AcValueRight != 0 and AcValueRight is not null)  
  
   select @lCountBcRight = Count(BcValueRight) from sExamination.tAudiometryDetail   
         where AudiomentryId = @lAudiomentryId   
         and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)  
         and (BcValueRight != 0 and BcValueRight is not null)  
  
   select @lSumAcLeftDivide = convert(decimal(12,2),@lSumAcLeft) / convert(decimal(12,2), (Case @lCountAcLeft When 0 then 1 ELSE @lCountAcLeft END))  
   select @lSumBcLeftDivide = convert(decimal(12,2),@lSumBcLeft) / convert(decimal(12,2), (Case @lCountBcLeft When 0 then 1 ELSE @lCountBcLeft END))  
   select @lSumAcRightDivide = convert(decimal(12,2),@lSumAcRight) / convert(decimal(12,2), (Case @lCountAcRight When 0 then 1 ELSE @lCountAcRight END))  
   select @lSumBcRightDivide = convert(decimal(12,2),@lSumBcRight) / convert(decimal(12,2), (Case @lCountBcRight When 0 then 1 ELSE @lCountBcRight END))  
 END  
 ELSE  
 BEGIN  
    if @lConfValue = 3      
    begin      
  select @lSumAcLeft = sum(convert(int,LeftAcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (500,1000,2000)      
  select @lSumBcLeft = sum(convert(int,LeftBcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (500,1000,2000)      
  select @lSumAcRight = sum(convert(int,RightAcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (500,1000,2000)      
  select @lSumBcRight = sum(convert(int,RightBcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (500,1000,2000)      
    end  
    else if @lConfValue = 5  
    begin      
  select @lSumAcLeft = sum(convert(int,LeftAcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (250,500,1000,2000,4000)      
  select @lSumBcLeft = sum(convert(int,LeftBcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (250,500,1000,2000,4000)      
  select @lSumAcRight = sum(convert(int,RightAcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (250,500,1000,2000,4000)      
  select @lSumBcRight = sum(convert(int,RightBcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (250,500,1000,2000,4000)      
    end      
  
    select @lSumAcLeftDivide = convert(decimal(12,2),@lSumAcLeft) / convert(decimal(12,2),@lConfValue)      
    select @lSumBcLeftDivide = convert(decimal(12,2),@lSumBcLeft) / convert(decimal(12,2),@lConfValue)      
    select @lSumAcRightDivide = convert(decimal(12,2),@lSumAcRight) / convert(decimal(12,2),@lConfValue)      
    select @lSumBcRightDivide = convert(decimal(12,2),@lSumBcRight) / convert(decimal(12,2),@lConfValue)   
    END  
     
   update sExamination.tAudiometry set AudiometryAcResultLeftId = case when @lSumAcLeftDivide = 0 then 0      
   when @lSumAcLeftDivide <= 25 then 1      
   when @lSumAcLeftDivide > 26 and @lSumAcLeftDivide <= 40 then 3      
   when @lSumAcLeftDivide > 41 and @lSumAcLeftDivide <= 55 then 4      
   when @lSumAcLeftDivide > 56 and @lSumAcLeftDivide <= 70 then 5      
   when @lSumAcLeftDivide > 71 and @lSumAcLeftDivide <= 90 then 6      
   when @lSumAcLeftDivide > 90 then 7      
   else 0 end,AudiometryBcResultLeftId = case when @lSumBcLeftDivide = 0 then 0      
   when @lSumBcLeftDivide <= 25 then 1      
   when @lSumBcLeftDivide > 26 and @lSumBcLeftDivide <= 40 then 3      
   when @lSumBcLeftDivide > 41 and @lSumBcLeftDivide <= 55 then 4      
   when @lSumBcLeftDivide > 56 and @lSumBcLeftDivide <= 70 then 5      
   when @lSumBcLeftDivide > 71 and @lSumBcLeftDivide <= 90 then 6      
   when @lSumBcLeftDivide > 90 then 7      
   else 0 end,AudiometryAcResultRightId = case when @lSumAcRightDivide = 0 then 0      
   when @lSumAcRightDivide <= 25 then 1      
   when @lSumAcRightDivide > 26 and @lSumAcRightDivide <= 40 then 3      
   when @lSumAcRightDivide > 41 and @lSumAcRightDivide <= 55 then 4      
   when @lSumAcRightDivide > 56 and @lSumAcRightDivide <= 70 then 5      
   when @lSumAcRightDivide > 71 and @lSumAcRightDivide <= 90 then 6      
   when @lSumAcRightDivide > 90 then 7      
   else 0 end,AudiometryBcResultRightId = case when @lSumBcRightDivide = 0 then 0      
   when @lSumBcRightDivide <= 25 then 1      
   when @lSumBcRightDivide > 26 and @lSumBcRightDivide <= 40 then 3      
   when @lSumBcRightDivide > 41 and @lSumBcRightDivide <= 55 then 4      
   when @lSumBcRightDivide > 56 and @lSumBcRightDivide <= 70 then 5      
   when @lSumBcRightDivide > 71 and @lSumBcRightDivide <= 90 then 6      
   when @lSumBcRightDivide > 90 then 7      
   else 0 end,AcRightDb = @lSumAcRightDivide,AcLeftDB = @lSumAcLeftDivide where Id = @lAudiomentryId      
         
   update sExamination.tAudiometry set IsDoneLeft=case when (AudiometryAcResultLeftId>0 or AudiometryBcResultLeftId>0) then 1 else 0 end       
   where Id = @lAudiomentryId      
      
   update sExamination.tAudiometry set IsDoneRight=case when (AudiometryAcResultRightId>0 or AudiometryBcResultRightId>0) then 1 else 0 end       
   where Id = @lAudiomentryId      

   IF(@lAudiometryResultRemarkManualConf = 'True')
   BEGIN
	   update AUD set AudiometryAcResultLeftId = tmp.e_LeftAcResultId, AudiometryBcResultLeftId= tmp.e_LeftBcResultId, 
	   AudiometryAcResultRightId = tmp.e_RightAcResultId, AudiometryBcResultRightId = tmp.e_RightBcResultId, 
	   LeftManualRemark = tmp.e_LeftManualRemark, RightManualRemark = tmp.e_RightManualRemark
	   FROM sExamination.tAudiometry AUD
	   INNER JOIN #tbltmpExaminationN tmp on tmp.e_AudiometryId = AUD.Id
	   where AUD.Id = @lAudiomentryId
   END

   select @i = @i + 1      
  end      
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrAudiometry,10,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  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">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
 select distinct e_type, case       
    when e_type=0 then 'Error In XML Generation'      
    when e_type=1 then 'Error In Importing Examination Data'      
    when e_type=2 then 'Error In Importing Vital Data'      
    when e_type=3 then 'Error In Importing Diagnosis Data'      
    when e_type=4 then 'Error In Importing Habit Data'      
    when e_type=5 then 'Error In Importing Disease Data'      
    when e_type=6 then 'Error In Importing History Data'      
    when e_type=7 then 'Error In Importing Test Data'      
    when e_type=8 then 'Error In Importing General Data'      
    when e_type=9 then 'Error In Importing Pulmonary Data'      
    when e_type=10 then 'Error In Importing Audiometry Data'      
    else 'Error In Importing Data'      
    end as e_Message      
  from tbl_ImportExaminationErrorLog where e_UserId =@rUserId and (DATEDIFF(minute,e_CreatedDate,getdate())<=5)      
      
IF OBJECT_ID('tempdb..#tbltmpExamination') IS NOT NULL DROP TABLE #tbltmpExamination;  
IF OBJECT_ID('tempdb..#tbltmpExaminationNull') IS NOT NULL DROP TABLE #tbltmpExaminationNull;  
IF OBJECT_ID('tempdb..#tbltmpVitals') IS NOT NULL DROP TABLE #tbltmpVitals;  
IF OBJECT_ID('tempdb..#tbltmpDiagnosis') IS NOT NULL DROP TABLE #tbltmpDiagnosis;  
IF OBJECT_ID('tempdb..#tbltmpHabitsNull') IS NOT NULL DROP TABLE #tbltmpHabitsNull;  
IF OBJECT_ID('tempdb..#tbltmpHabitss') IS NOT NULL DROP TABLE #tbltmpHabitss;  
IF OBJECT_ID('tempdb..#tbltmpDisease') IS NOT NULL DROP TABLE #tbltmpDisease;  
IF OBJECT_ID('tempdb..#tbltmpDiseaseNull') IS NOT NULL DROP TABLE #tbltmpDiseaseNull;  
IF OBJECT_ID('tempdb..#tbltmpDiseaseDetailsNull') IS NOT NULL DROP TABLE #tbltmpDiseaseDetailsNull;  
IF OBJECT_ID('tempdb..#tbltmpTests') IS NOT NULL DROP TABLE #tbltmpTests;  
IF OBJECT_ID('tempdb..#tblGeneral') IS NOT NULL DROP TABLE #tblGeneral;  
IF OBJECT_ID('tempdb..#tblGeneralN') IS NOT NULL DROP TABLE #tblGeneralN;  
IF OBJECT_ID('tempdb..#tblExaminationGeneral') IS NOT NULL DROP TABLE #tblExaminationGeneral;  
IF OBJECT_ID('tempdb..#tblGeneralTests') IS NOT NULL DROP TABLE #tblGeneralTests;  
IF OBJECT_ID('tempdb..#tblPulmonary') IS NOT NULL DROP TABLE #tblPulmonary;  
IF OBJECT_ID('tempdb..#tbltmpAudiometry') IS NOT NULL DROP TABLE #tbltmpAudiometry;  
IF OBJECT_ID('tempdb..#tbltmpExaminationN') IS NOT NULL DROP TABLE #tbltmpExaminationN;  
IF OBJECT_ID('tempdb..#tbltmpAudiometryN') IS NOT NULL DROP TABLE #tbltmpAudiometryN;  
IF OBJECT_ID('tempdb..#tbltmpHabitDetailsNull') IS NOT NULL DROP TABLE #tbltmpHabitDetailsNull;  
IF OBJECT_ID('tempdb..#tbltmpDiseaseN') IS NOT NULL DROP TABLE #tbltmpDiseaseN;  
IF OBJECT_ID('tempdb..#tbltmpHistorySelf') IS NOT NULL DROP TABLE #tbltmpHistorySelf;  
IF OBJECT_ID('tempdb..#tbltmpHistoryMother') IS NOT NULL DROP TABLE #tbltmpHistoryMother;  
IF OBJECT_ID('tempdb..#tbltmpHistoryFather') IS NOT NULL DROP TABLE #tbltmpHistoryFather;  
IF OBJECT_ID('tempdb..#tbltmpHistoryBrother') IS NOT NULL DROP TABLE #tbltmpHistoryBrother;  
IF OBJECT_ID('tempdb..#tbltmpHistorySister') IS NOT NULL DROP TABLE #tbltmpHistorySister;  
IF OBJECT_ID('tempdb..#tbltmpHistorySelfN') IS NOT NULL DROP TABLE #tbltmpHistorySelfN;  
IF OBJECT_ID('tempdb..#tbltmpHistoryMotherN') IS NOT NULL DROP TABLE #tbltmpHistoryMotherN;  
IF OBJECT_ID('tempdb..#tbltmpHistoryFatherN') IS NOT NULL DROP TABLE #tbltmpHistoryFatherN;  
IF OBJECT_ID('tempdb..#tbltmpHistoryBrotherN') IS NOT NULL DROP TABLE #tbltmpHistoryBrotherN;  
IF OBJECT_ID('tempdb..#tbltmpHistorySisterN') IS NOT NULL DROP TABLE #tbltmpHistorySisterN;  
  
--Drop Table #tbltmpExamination  
--Drop Table #tbltmpExaminationNull      
--Drop Table #tbltmpVitals      
--Drop Table #tbltmpDiagnosis      
--Drop Table #tbltmpHabitsNull      
--Drop Table #tbltmpHabitss      
--Drop Table #tbltmpDisease      
--Drop Table #tbltmpDiseaseNull      
--Drop Table #tbltmpDiseaseDetailsNull      
--Drop Table #tbltmpTests      
----Drop table #tbltmpTestsN      
----Drop table #tbltmpRatioN      
----Drop table #tbltmpRatio      
--Drop table #tblGeneral      
--Drop table #tblGeneralN      
--Drop table #tblExaminationGeneral      
--Drop table #tblGeneralTests      
----Drop table #tblGeneralParameters      
--Drop table #tblPulmonary      
--Drop table #tbltmpAudiometry      
--Drop table #tbltmpExaminationN      
--Drop table #tbltmpAudiometryN      
--Drop table #tbltmpHabitDetailsNull      
--Drop table #tbltmpDiseaseN      
--Drop table #tbltmpHistorySelf      
--Drop table #tbltmpHistoryMother      
--Drop table #tbltmpHistoryFather      
--Drop table #tbltmpHistoryBrother      
--Drop table #tbltmpHistorySister      
--Drop table #tbltmpHistorySelfN      
--Drop table #tbltmpHistoryMotherN      
--Drop table #tbltmpHistoryFatherN      
--Drop table #tbltmpHistoryBrotherN      
--Drop table #tbltmpHistorySisterN      
end  

GO


CREATE OR ALTER PROCEDURE [sExamination].[pRegistrationGetDashboard]  
@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.AppointmentId,0) as AppointmentId,
  R.CompliantRemark, ISNULL(R.VisitTypeId, 0) AS VisitTypeId
 FROM sExamination.tRegistration 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 isnull(R.ExaminationId,0) = 0
 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


CREATE OR ALTER PROCEDURE [sIncident].[pRptInjuryReport]
@FromDate datetime = null,
@ToDate datetime = null,
@ReportTypeId bigint = 0,
@SubLocationId bigint = 0,
@EmployeeCode nvarchar(50) = null,
@DepartmentId bigint = 0,
@BodyPartId bigint = 0,      
@DesignationId bigint =0,
@EmployeeTypeId bigint = 0,     	
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='',   
@orgid int,
@Company int=0,
@EmployeeName nvarchar(50) = null,
@CodeLike nvarchar(300) = null,
@UserId BIGINT,
@VisitPurpose int = 0
AS
SET NOCOUNT ON
BEGIN
	
	
SELECT ExaminationId,ExaminationDate,EmployeeName,EmployeeCode,DepartmentName,IncidentTime,IncidentDate,ReportingTime,ReportingDate,age,Gender,DoctorName,DoctorSignature,DoctorCode,
[TM Name (CAPS)] AS TMNameCAPS,
    [TM No] AS TMNo,
    [TKM Experience] AS TKMExperience,
    [Process Experience] AS ProcessExperience,
    [Shift] AS Shift,
    [Process/Line name] AS ProcessLineName,
    [TM/Apprentice/Contractor/ GAT/DAT] AS TMType,
    [Contract name (CAPS)] AS ContractNameCAPS,
    [Supervisor Name (CAPS)] AS SupervisorNameCAPS,
    [Supervisor mobile no] AS SupervisorMobileNo,
    [Member mobile No] AS MemberMobileNo,
    [Shop Manager Name] AS ShopManagerName,
    [Shop DGM Name] AS ShopDGMName,
    [How Accident occurred?] AS HowAccidentOccurred,
    [Injury details] AS InjuryDetails,
    [Injured part (in words)] AS InjuredPart,
    [Treatment detail] AS TreatmentDetail,
    [Outside hospital referred. ?] AS OutsideHospitalReferred,
    [Reason?] AS Reason,
    [Outside hospital detail: (Hospital Name / Contact Number)] AS OutsideHospitalDetail,
    [Treatment/Other update details from outside hospital, If any:] AS OutsideTreatmentDetails,
    [Details regarding post-accident conditions of the member:] AS PostAccidentCondition
FROM
(
SELECT Distinct IA.Id,IA.ExaminationId,
convert(varchar(10),EAED.ExaminationDate,103) as ExaminationDate,
	--case isnull(IA.ParticipantSourceTypeId,95) when 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')
	--else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end AS EmployeeName,

	CASE EAED.ParticipantSourceTypeId WHEN 1009 THEN
	CASE WHEN isnull(O.OtherName,'')='' THEN
	isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') ELSE O.OtherName END
	WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END  AS EmployeeName,

	case isnull(EAED.ParticipantSourceTypeId,95) when 95 then EM.Id else CS.Id end AS EmployeeId,
	case isnull(EAED.ParticipantSourceTypeId,95) when 95 then isnull(EM.Code,'') else isnull(CS.Code,'') end AS EmployeeCode,	
	IA.IncidentTime,
	convert(varchar(10),IA.IncidentDate,103) as IncidentDate,
	IA.PlaceofIncident,
	ITM.Title AS IncidentType,IA.IncidentTypeId
	,IA.ReportingTime,
	convert(varchar(10),IA.ReportingDate,103) as ReportingDate,
	IA.IncidentRemark,IA.TreatmentRemark,	
    case isnull(EAED.ParticipantSourceTypeId,95) when 95 then 'Employee' else 'Other' end AS EmployeeType,
	CM.Title AS Cause,
	
	ISNULL(ODM.Title,'') As DepartmentName,
	--case when IA.BodySideId =4 then '' Else Isnull(BSM.Title,'') End + ' ' + eb.Title As BodyPart,	

	D.DoctorSignature AS DoctorSignature,
	(EM2.FirstName + ' ' + EM2.LastName) as DoctorName,
	EM2.Code as DoctorCode,

		case when EAED.ParticipantSourceTypeId = 1009 then    
 case when CS.DateOfBirth = '1900-01-01' then 0 else datediff(yy,CS.DateOfBirth,getdate()) end    
 when EAED.ParticipantSourceTypeId = 1001 then    
 case when EFD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EFD.DateOfBirth,getdate()) end else    
 case when EPD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EPD.DateOfBirth,getdate()) end end AS AGE,
	Gender = CASE EAED.ParticipantSourceTypeId
	WHEN 95 THEN GM1.Title
	WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
	WHEN 1009 THEN CASE WHEN isnull(O.GenderId,0) = 0 THEN GM2.Title ELSE (select Title from sCommon.tGenderMaster where Id = O.GenderId) END END,
	
	InS.FieldRemark,
        ALF.AccidentLogFieldResponse
	From sExamination.tAccidentLog IA
	LEFT JOIN sExamination.tExamination EAED ON EAED.Id=IA.ExaminationId 
	LEFT JOIN sSafety.tIncidentTypeMaster ITM ON ITM.Id=IA.IncidentTypeId
	LEFT JOIN sHrm.tEmployeeMaster EM ON EAED.ParticipantSourceId =EM.Id AND isnull(EAED.ParticipantSourceTypeId,95) = 95
	LEFT JOIN sHrm.tCsrBenefiterMaster CS ON EAED.ParticipantSourceId=CS.Id AND EAED.ParticipantSourceTypeId = 1009	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
	Inner join sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id=EJD.OrganizationDepartmentId
	
	LEFT Join sHrm.tEmployeeCompanyMaster ECM On ECM.id=EJD.EmployeeCompanyId
	LEFT Join sHrm.tEmployeeCompanyMaster ECM1 On ECM1.id=EAED.EmployeeCompanyId
	 LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EAED.ParticipantSourceId = EFD.Id and EAED.ParticipantSourceTypeId = 1001
	LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = CS.GenderId
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = EAED.CauseId
		LEFT JOIN sExamination.tOPD O ON O.ExaminationId = EAED.Id
	left JOIN sSecurity.tUser U ON U.Id = EAED.CreatedUserID		
	LEFT JOIN sCommon.tCompanyInformationDetail CID on EAED.OrgId = CID.orgid
	--LEFT join sSafety.tBodyPartMaster eb on eb.Id = IA.BodyPartId
	--left join sSafety.tBodySideMaster BSM On BSM.id=IA.BodySideId	
	left join sExamination.vExtEmployeeExaminationDetail EED ON EAED.Id = EED.ExaminationId
	--LEFT JOIN sExamination.tAccidentLog AL ON IA.SourceId=AL.Id	
	LEFT JOIN [sExamination].[tAccidentLogField] ALF ON ALF.ACCIDENTLOGID=IA.ID
	LEFT JOIN sSafety.tIncidentSetup InS ON  InS.Id= ALF.IncidentSetupId 
	LEFT JOIN sHrm.tEmployeeMaster EM2 ON EAED.DoctorEmployeeId=EM2.Id
    LEFT JOIN sCwb.tDoctorMaster D on d.EmployeeId = EM2.Id
   
	
		WHERE (EAED.StoreLocationId=@SubLocationId or (
			@SubLocationId = 0
			AND
			EAED.StoreLocationId IN (
				select LM.LocationId from sIp.tStoreLocationMaster LM 
				INNER JOIN [sSecurity].[tUserLocation] UL ON UL.StoreLocationId = LM.Id 
				where IsObsolete = 0 AND OrgId = @orgid AND UL.UserId = @UserId 
			)
		)
	)
	and isnull(EAED.iscancel,0) = 0
	and (EM.Code = @EmployeeCode or @EmployeeCode = '')
	and (EJD.OrganizationDepartmentId =@DepartmentId or @DepartmentId = 0)
	and (IA.BodyPartId =@BodyPartId or @BodyPartId = 0)
	and (EJD.EmployeeTypeId =@EmployeeTypeId or @EmployeeTypeId = 0)
	and ((IA.IncidentDate >= @FromDate) OR (ISNULL(@FromDate,'') = ''))
	and ((IA.IncidentDate <= @ToDate) OR (ISNULL(@ToDate,'') = ''))
	and (EJD.EmployeeDesignationId =@DesignationId or @DesignationId = 0)
	and (IA.EmployeeCompanyid= @Company or @Company=0)
	and ((EED.ParticipantName Like @EmployeeName +'%' ) or (ISNULL(@EmployeeName,'') = ''))
	and 
	(	
		exists (
			SELECT 1 FROM sCommon.fnsplit(@CodeLike, ',') AS SplitValues 
			WHERE LTRIM(RTRIM(ISNULL(SplitValues.item, ''))) <> '' 
			AND EM.Code = LTRIM(RTRIM(SplitValues.item))
		)
		or ISNULL(@CodeLike, '') = ''
	)
	and ((EAED.CauseId = @VisitPurpose) OR @VisitPurpose = 0)
	
	
	) AS src
PIVOT
(
    MAX(AccidentLogFieldResponse)
    FOR FieldRemark IN (
        [TM Name (CAPS)],
		[TM No],
		[TKM Experience],
		[Process Experience],
		[Shift],
		[Process/Line name],
		[TM/Apprentice/Contractor/ GAT/DAT],
		[Contract name (CAPS)],
		[Supervisor Name (CAPS)],
		[Supervisor mobile no],
		[Member mobile No],
		[Shop Manager Name],
		[Shop DGM Name],
		[How Accident occurred?],
		[Injury details],
		[Injured part (in words)],
		[Treatment detail],
		[Outside hospital referred. ?],
		[Reason?],
		[Outside hospital detail: (Hospital Name / Contact Number)],
		[Treatment/Other update details from outside hospital, If any:],
		[Details regarding post-accident conditions of the member:]
    )
) AS pvt

	--ORDER BY IA.IncidentDate DESC
END

GO


CREATE OR ALTER PROCEDURE [sExamination].[pRegistrationGetDashboard]  
@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.AppointmentId,0) as AppointmentId,
  R.CompliantRemark, ISNULL(R.VisitTypeId, 0) AS VisitTypeId
 FROM sExamination.tRegistration 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 isnull(R.ExaminationId,0) = 0
 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


CREATE OR ALTER PROCEDURE [sIncident].[pRptInjuryReport]
@FromDate datetime = null,
@ToDate datetime = null,
@ReportTypeId bigint = 0,
@SubLocationId bigint = 0,
@EmployeeCode nvarchar(50) = null,
@DepartmentId bigint = 0,
@BodyPartId bigint = 0,      
@DesignationId bigint =0,
@EmployeeTypeId bigint = 0,     	
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='',   
@orgid int,
@Company int=0,
@EmployeeName nvarchar(50) = null,
@CodeLike nvarchar(300) = null,
@UserId BIGINT,
@VisitPurpose int = 0
AS
SET NOCOUNT ON
BEGIN
	
	
SELECT ExaminationId,ExaminationDate,EmployeeName,EmployeeCode,DepartmentName,IncidentTime,IncidentDate,ReportingTime,ReportingDate,age,Gender,DoctorName,DoctorSignature,DoctorCode,
[TM Name (CAPS)] AS TMNameCAPS,
    [TM No] AS TMNo,
    [TKM Experience] AS TKMExperience,
    [Process Experience] AS ProcessExperience,
    [Shift] AS Shift,
    [Process/Line name] AS ProcessLineName,
    [TM/Apprentice/Contractor/ GAT/DAT] AS TMType,
    [Contract name (CAPS)] AS ContractNameCAPS,
    [Supervisor Name (CAPS)] AS SupervisorNameCAPS,
    [Supervisor mobile no] AS SupervisorMobileNo,
    [Member mobile No] AS MemberMobileNo,
    [Shop Manager Name] AS ShopManagerName,
    [Shop DGM Name] AS ShopDGMName,
    [How Accident occurred?] AS HowAccidentOccurred,
    [Injury details] AS InjuryDetails,
    [Injured part (in words)] AS InjuredPart,
    [Treatment detail] AS TreatmentDetail,
    [Outside hospital referred. ?] AS OutsideHospitalReferred,
    [Reason?] AS Reason,
    [Outside hospital detail: (Hospital Name / Contact Number)] AS OutsideHospitalDetail,
    [Treatment/Other update details from outside hospital, If any:] AS OutsideTreatmentDetails,
    [Details regarding post-accident conditions of the member:] AS PostAccidentCondition
FROM
(
SELECT Distinct IA.Id,IA.ExaminationId,
convert(varchar(10),EAED.ExaminationDate,103) as ExaminationDate,
	--case isnull(IA.ParticipantSourceTypeId,95) when 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')
	--else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end AS EmployeeName,

	CASE EAED.ParticipantSourceTypeId WHEN 1009 THEN
	CASE WHEN isnull(O.OtherName,'')='' THEN
	isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') ELSE O.OtherName END
	WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END  AS EmployeeName,

	case isnull(EAED.ParticipantSourceTypeId,95) when 95 then EM.Id else CS.Id end AS EmployeeId,
	case isnull(EAED.ParticipantSourceTypeId,95) when 95 then isnull(EM.Code,'') else isnull(CS.Code,'') end AS EmployeeCode,	
	IA.IncidentTime,
	convert(varchar(10),IA.IncidentDate,103) as IncidentDate,
	IA.PlaceofIncident,
	ITM.Title AS IncidentType,IA.IncidentTypeId
	,IA.ReportingTime,
	convert(varchar(10),IA.ReportingDate,103) as ReportingDate,
	IA.IncidentRemark,IA.TreatmentRemark,	
    case isnull(EAED.ParticipantSourceTypeId,95) when 95 then 'Employee' else 'Other' end AS EmployeeType,
	CM.Title AS Cause,
	
	ISNULL(ODM.Title,'') As DepartmentName,
	--case when IA.BodySideId =4 then '' Else Isnull(BSM.Title,'') End + ' ' + eb.Title As BodyPart,	

	D.DoctorSignature AS DoctorSignature,
	(EM2.FirstName + ' ' + EM2.LastName) as DoctorName,
	EM2.Code as DoctorCode,

		case when EAED.ParticipantSourceTypeId = 1009 then    
 case when CS.DateOfBirth = '1900-01-01' then 0 else datediff(yy,CS.DateOfBirth,getdate()) end    
 when EAED.ParticipantSourceTypeId = 1001 then    
 case when EFD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EFD.DateOfBirth,getdate()) end else    
 case when EPD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EPD.DateOfBirth,getdate()) end end AS AGE,
	Gender = CASE EAED.ParticipantSourceTypeId
	WHEN 95 THEN GM1.Title
	WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
	WHEN 1009 THEN CASE WHEN isnull(O.GenderId,0) = 0 THEN GM2.Title ELSE (select Title from sCommon.tGenderMaster where Id = O.GenderId) END END,
	
	InS.FieldRemark,
        ALF.AccidentLogFieldResponse
	From sExamination.tAccidentLog IA
	LEFT JOIN sExamination.tExamination EAED ON EAED.Id=IA.ExaminationId 
	LEFT JOIN sSafety.tIncidentTypeMaster ITM ON ITM.Id=IA.IncidentTypeId
	LEFT JOIN sHrm.tEmployeeMaster EM ON EAED.ParticipantSourceId =EM.Id AND isnull(EAED.ParticipantSourceTypeId,95) = 95
	LEFT JOIN sHrm.tCsrBenefiterMaster CS ON EAED.ParticipantSourceId=CS.Id AND EAED.ParticipantSourceTypeId = 1009	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
	Inner join sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id=EJD.OrganizationDepartmentId
	
	LEFT Join sHrm.tEmployeeCompanyMaster ECM On ECM.id=EJD.EmployeeCompanyId
	LEFT Join sHrm.tEmployeeCompanyMaster ECM1 On ECM1.id=EAED.EmployeeCompanyId
	 LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EAED.ParticipantSourceId = EFD.Id and EAED.ParticipantSourceTypeId = 1001
	LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = CS.GenderId
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = EAED.CauseId
		LEFT JOIN sExamination.tOPD O ON O.ExaminationId = EAED.Id
	left JOIN sSecurity.tUser U ON U.Id = EAED.CreatedUserID		
	LEFT JOIN sCommon.tCompanyInformationDetail CID on EAED.OrgId = CID.orgid
	--LEFT join sSafety.tBodyPartMaster eb on eb.Id = IA.BodyPartId
	--left join sSafety.tBodySideMaster BSM On BSM.id=IA.BodySideId	
	left join sExamination.vExtEmployeeExaminationDetail EED ON EAED.Id = EED.ExaminationId
	--LEFT JOIN sExamination.tAccidentLog AL ON IA.SourceId=AL.Id	
	LEFT JOIN [sExamination].[tAccidentLogField] ALF ON ALF.ACCIDENTLOGID=IA.ID
	LEFT JOIN sSafety.tIncidentSetup InS ON  InS.Id= ALF.IncidentSetupId 
	LEFT JOIN sHrm.tEmployeeMaster EM2 ON EAED.DoctorEmployeeId=EM2.Id
    LEFT JOIN sCwb.tDoctorMaster D on d.EmployeeId = EM2.Id
   
	
		WHERE (EAED.StoreLocationId=@SubLocationId or (
			@SubLocationId = 0
			AND
			EAED.StoreLocationId IN (
				select LM.LocationId from sIp.tStoreLocationMaster LM 
				INNER JOIN [sSecurity].[tUserLocation] UL ON UL.StoreLocationId = LM.Id 
				where IsObsolete = 0 AND OrgId = @orgid AND UL.UserId = @UserId 
			)
		)
	)
	and isnull(EAED.iscancel,0) = 0
	and (EM.Code = @EmployeeCode or @EmployeeCode = '')
	and (EJD.OrganizationDepartmentId =@DepartmentId or @DepartmentId = 0)
	and (IA.BodyPartId =@BodyPartId or @BodyPartId = 0)
	and (EJD.EmployeeTypeId =@EmployeeTypeId or @EmployeeTypeId = 0)
	and ((IA.IncidentDate >= @FromDate) OR (ISNULL(@FromDate,'') = ''))
	and ((IA.IncidentDate <= @ToDate) OR (ISNULL(@ToDate,'') = ''))
	and (EJD.EmployeeDesignationId =@DesignationId or @DesignationId = 0)
	and (IA.EmployeeCompanyid= @Company or @Company=0)
	and ((EED.ParticipantName Like @EmployeeName +'%' ) or (ISNULL(@EmployeeName,'') = ''))
	and 
	(	
		exists (
			SELECT 1 FROM sCommon.fnsplit(@CodeLike, ',') AS SplitValues 
			WHERE LTRIM(RTRIM(ISNULL(SplitValues.item, ''))) <> '' 
			AND EM.Code = LTRIM(RTRIM(SplitValues.item))
		)
		or ISNULL(@CodeLike, '') = ''
	)
	and ((EAED.CauseId = @VisitPurpose) OR @VisitPurpose = 0)
	
	
	) AS src
PIVOT
(
    MAX(AccidentLogFieldResponse)
    FOR FieldRemark IN (
        [TM Name (CAPS)],
		[TM No],
		[TKM Experience],
		[Process Experience],
		[Shift],
		[Process/Line name],
		[TM/Apprentice/Contractor/ GAT/DAT],
		[Contract name (CAPS)],
		[Supervisor Name (CAPS)],
		[Supervisor mobile no],
		[Member mobile No],
		[Shop Manager Name],
		[Shop DGM Name],
		[How Accident occurred?],
		[Injury details],
		[Injured part (in words)],
		[Treatment detail],
		[Outside hospital referred. ?],
		[Reason?],
		[Outside hospital detail: (Hospital Name / Contact Number)],
		[Treatment/Other update details from outside hospital, If any:],
		[Details regarding post-accident conditions of the member:]
    )
) AS pvt

	--ORDER BY IA.IncidentDate DESC
END

GO


CREATE OR ALTER PROCEDURE [sMro].[pExaminationGenerateReport]    
 @rId bigint = 0,    
 @rTitle nvarchar(50),    
 @rColumnName nvarchar(max) = '',    
 @rColumnIds nvarchar(max) = '',    
 @rOrgId int,    
 @rExaminationTypeId int = 0,    
 @rRoundGroupId int = 0,    
 @rRoundId int = 0,
 @rNationalId [nvarchar](max) = '',
 @rStoreLocationId int = 0,    
 @rEmployeeCode [nvarchar](20) = '',    
 @rCodeLike [nvarchar](max) = '',    
 @rEmployeeName [nvarchar](200) = '',		
 @rEmployeeId BigInt = 0,     
 @rFromDate Date = '0001-01-01',    
 @rToDate Date = '9999-12-31',    
 @rExaminationStatusId int = 0,    
 @rEmployeeTypeId int = 0,    
 @rDepartmentGroupIds [nvarchar](max) = '',    
 @rDepartmentIds [nvarchar](max) = '',    
 @rDesignationIds [nvarchar](max) = '',    
 @rTargetGroupIds [nvarchar](max) = '',    
 @rCompanyGroupIds [nvarchar](max) = '',    
 @rCompanyIds [nvarchar](max) = '',    
 @rCreatedUserId bigint    ,
 @rBusinessIds nvarchar(max) = '', -- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024
 @rSubBusinessIds nvarchar(max) = '',-- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024
 @rIsBusinessWise bit -- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024
WITH RECOMPILE  
AS    
BEGIN
SET NOCOUNT ON   SET NOCOUNT ON;
    SET XACT_ABORT ON;

    BEGIN TRY
        BEGIN TRANSACTION;

        IF (@rFromDate IS NULL) 
            SET @rFromDate = '0001-01-01';

        IF (@rToDate IS NULL)
            SET @rToDate = CONVERT(date, sCommon.fGetDate());

        -- Save preset
        IF (@rTitle <> N'' AND @rId = 0)
        BEGIN
            DECLARE @lNextNumber BIGINT;
            EXEC sCommon.pTableRowIdGet 
                @rOrgId, 
                'sHrm.tExaminationCustomSearch', 
                0, 1, 1, 
                @outNextNumber = @lNextNumber OUTPUT;

            INSERT INTO sHrm.tExaminationCustomSearch
            (
                Id, Title, ColumnName, OrgId, ExaminationTypeId, RoundGroupId, RoundId,
                StoreLocationId, EmployeeCode, CodeLike, EmployeeName, EmployeeId,
                FromDate, ToDate, ExaminationStatusId, EmployeeTypeId, DepartmentGroupIds,
                DepartmentIds, DesignationIds, TargetGroupIds, CompanyGroupIds, CompanyIds,
                CreatedUserId, CreatedDateTime, ColumnIds
            )
            VALUES
            (
                @lNextNumber, @rTitle, @rColumnName, @rOrgId, @rExaminationTypeId, @rRoundGroupId, @rRoundId,
                @rStoreLocationId, @rEmployeeCode, @rCodeLike, @rEmployeeName, @rEmployeeId,
                @rFromDate, @rToDate, @rExaminationStatusId, @rEmployeeTypeId, @rDepartmentGroupIds,
                @rDepartmentIds, @rDesignationIds, @rTargetGroupIds, @rCompanyGroupIds, @rCompanyIds,
                @rCreatedUserId, sCommon.fGetDate(), @rColumnIds
            );
        END

        -- Load preset
        IF (@rId > 0)
        BEGIN
            SELECT
                @rColumnName        = ColumnName,    
                @rOrgId             = OrgId,    
                @rExaminationTypeId = ExaminationTypeId,    
                @rRoundGroupId      = RoundGroupId,    
                @rRoundId           = RoundId,    
                @rStoreLocationId   = StoreLocationId,    
                @rEmployeeCode      = EmployeeCode,    
                @rCodeLike          = CodeLike,    
                @rEmployeeName      = EmployeeName,     
                @rEmployeeId        = EmployeeId,     
                @rFromDate          = FromDate,    
                @rToDate            = ToDate,    
                @rExaminationStatusId = ExaminationStatusId,    
                @rEmployeeTypeId    = EmployeeTypeId,    
                @rDepartmentGroupIds= DepartmentGroupIds,    
                @rDepartmentIds     = DepartmentIds,    
                @rDesignationIds    = DesignationIds,    
                @rTargetGroupIds    = TargetGroupIds,    
                @rCompanyGroupIds   = CompanyGroupIds,    
                @rCompanyIds        = CompanyIds        
            FROM sHrm.tExaminationCustomSearch
            WHERE Id = @rId;
        END

        ------------------------------------------------------------
        -- CLEAN TEMP OBJECTS (idempotent)
        ------------------------------------------------------------
        IF OBJECT_ID('tempdb..#ExaminationDetail') IS NOT NULL DROP TABLE #ExaminationDetail;    
        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..##tblMainTable') IS NOT NULL DROP TABLE ##tblMainTable;    
        IF OBJECT_ID('tempdb..#tblExaminationAudiometrys') IS NOT NULL DROP TABLE #tblExaminationAudiometrys;    
        IF OBJECT_ID('tempdb..#tblAudiometry') IS NOT NULL DROP TABLE #tblAudiometry;    
        IF OBJECT_ID('tempdb..#ColumnTable') IS NOT NULL DROP TABLE #ColumnTable;    
        IF OBJECT_ID('tempdb..#ColumnTable1') IS NOT NULL DROP TABLE #ColumnTable1;    

        ------------------------------------------------------------
        -- BASE DETAIL
        ------------------------------------------------------------
        CREATE TABLE #ExaminationDetail
        (
            ExaminationId            bigint        NOT NULL,
            ExaminationDate          varchar(100)  NULL,
            MainTypeName             varchar(100)  NULL,
            StoreLocationName        varchar(100)  NULL,
            RoundGroup               varchar(200)  NULL,
            Round                    varchar(100)  NULL,
            Doctor                   varchar(100)  NULL,
            EmployeeType             varchar(100)  NULL,
            Code                     varchar(100)  NULL,
            EmployeeName             varchar(200)  NULL,
            Gender                   varchar(100)  NULL,
            Department               varchar(100)  NULL,
            Company                  varchar(500)  NULL,
            Designation              varchar(100)  NULL,
            BloodGroup               varchar(100)  NULL,
            Age                      varchar(50)   NULL,
            Height                   varchar(100)  NULL,
            [Weight]                 varchar(100)  NULL,
            BMI                      varchar(100)  NULL,
            Temperature              varchar(100)  NULL,
            Pulse                    varchar(100)  NULL,
            BloodPressureSystolic    varchar(100)  NULL,
            BloodPressureDiastolic   varchar(100)  NULL,
            Respiration              varchar(100)  NULL,
            ElbowWidth               varchar(100)  NULL,
            AbdominalGirth           varchar(100)  NULL,
            Inhalation               varchar(100)  NULL,
            Exhalation               varchar(100)  NULL,
            ChestExpansion           varchar(100)  NULL,
            Waist                    varchar(100)  NULL,
            Hip                      varchar(100)  NULL,
            Disease                  varchar(max)  NULL,
            History                  varchar(max)  NULL,
            Allergy                  varchar(max)  NULL,
            Habit                    varchar(max)  NULL,
            DiagnosisRemark          varchar(max)  NULL,
            Recommendation           varchar(max)  NULL,
            Hospital                 varchar(100)  NULL,
            ReferDoctor              varchar(100)  NULL,
            TargetGroup              nvarchar(200) NULL,
            UIDNumber                nvarchar(50)  NULL,
            Nationality              nvarchar(100) NULL,
            Business                 nvarchar(max) NULL,
            SubBusiness              nvarchar(max) NULL,
            CompanyGroup             nvarchar(max) NULL,
            ProcessType              nvarchar(100) NULL,
			Contractor               varchar(500)  NULL,
        );

        INSERT INTO #ExaminationDetail
        SELECT 
            EED.ExaminationId,
            CONVERT(varchar(10), EED.ExaminationDate, 103),
            EED.MainTypeName,
            EED.StoreLocationName,
            SGM.Title,
            EED.SetupName,
            EED.DoctorName,
            EED.ParticipantType,
            EED.ParticipantCode,
            EED.ParticipantName,
            EED.Gender,
            EED.DepartmentName,
            CASE WHEN @rOrgId <> 3001 THEN ECM.Title ELSE ISNULL(EED.EmployeeLegalEntity, '') END,
            ISNULL(EDM.Title,''),
            ISNULL(BG.Title,''),
            DATEDIFF(yyyy, EED.DateOfBirth, sCommon.fGetDate()),
            V.Height,
            V.BodyWeight,
            V.BMI,
            V.Temperature,
            V.Pulse,
            V.BloodPressureSystolic,
            V.BloodPressureDiastolic,
            V.Respiration,
            V.ElbowWidth,
            V.AbdominalGirth,
            V.ChestExpansionInhalation,
            V.ChestExpansionExhalation,
            V.ChestExpansion,
            V.Waist,
            V.Hip,
            [sExamination].[fExistingDiseaseGet](EED.ExaminationId),
            [sExamination].[fHistoryGet](EED.EmployeeId),
            [sExamination].[fAllergyGet](EED.EmployeeId),
            [sExamination].[fHabitHygineGet](EED.ExaminationId),
            REPLACE(REPLACE(ISNULL(D.DiagnosisRemark, ''), CHAR(13), ' '), CHAR(10), ' '),
            REPLACE(REPLACE(ISNULL(D.RecommendationEnglish, ''), CHAR(13), ' '), CHAR(10), ' '),
            CL.Title,
            CL.DoctorName,
            EED.EmployeeTargetGroupName,
            EED.UIDNumber,
            NM.Title,
            SCT.Title,
            VTM.Title,
            CGM.Title,
            ISNULL(PTM.Title,''),
			ISNULL(CONV.Title,'')
        FROM sExamination.vExtEmployeeExaminationDetail AS EED
        INNER JOIN sExamination.tSetupMaster               AS SM   ON SM.Id = EED.SetupId
        LEFT  JOIN sHrm.tEmployeePersonalDetail            AS EPD  ON EED.EmployeeId = EPD.EmployeeId 
        LEFT  JOIN sHrm.tEmployeeJobDetail                 AS EJD  ON EJD.EmployeeId = EED.EmployeeId 
        LEFT  JOIN sHrm.tNationalityMaster                 AS NM   ON NM.Id = EPD.NationalityId
        LEFT  JOIN sExamination.tSetupGroupMaster          AS SGM  ON SGM.Id = SM.SetupGroupId    
        LEFT  JOIN sHrm.tEmployeeCompanyMaster             AS ECM  ON ECM.Id = (CASE WHEN @rIsBusinessWise = 0 THEN EED.EmployeeCompanyId ELSE EJD.EmployeeCompanyId END)
        LEFT  JOIN sCommon.tDepartmentGroupMaster          AS DGM  ON EED.DepartmentGroupId = DGM.Id AND DGM.IsObsolete = 0    
        LEFT  JOIN sCommon.tFunctionMaster                 AS FM   ON DGM.FunctionId = FM.Id AND FM.IsObsolete = 0    
        INNER JOIN sIp.tStoreLocationMaster                AS SLM  ON SLM.Id = EED.StoreLocationId    
        INNER JOIN sSecurity.tUserLocation                 AS UL   ON SLM.Id = UL.StoreLocationId    
        INNER JOIN sCommon.tLocationMaster                 AS LM   ON LM.Id = SLM.LocationId    
        LEFT  JOIN sHrm.tEmployeeDesignationMaster         AS EDM  ON EED.EmployeeDesignationId = EDM.Id    
        LEFT  JOIN sHrm.tGradeMaster                       AS GM   ON GM.Id = EED.GradeId AND GM.IsObsolete = 0    
        LEFT  JOIN sCommon.tBloodGroupMaster               AS BG   ON EED.BloodGroupId = BG.Id    
        LEFT  JOIN sExamination.tVital                     AS V    ON EED.ExaminationId = V.SourceId    
        LEFT  JOIN sExamination.tDiagnosis                 AS D    ON EED.ExaminationId = D.SourceId     
        LEFT  JOIN sExamination.tReferral                  AS R    ON R.SourceId = EED.ExaminationId    
        LEFT  JOIN sCommon.tClinicMaster                   AS CL   ON CL.Id = R.ReferToClinicId   
        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.tProcessTypeMaster              AS PTM  ON PTM.Id = EED.ProcessTypeId
		LEFT  JOIN sProcurement.tVendorMaster              AS CONV  ON CONV.Id = (CASE WHEN @rIsBusinessWise = 0 THEN EED.ExaminationContractorId ELSE EJD.ContractorId END)
        WHERE ((EED.StoreLocationId = @rStoreLocationId) OR @rStoreLocationId = 0)    
          AND ((EED.ParticipantCode IN (SELECT item FROM sCommon.fnsplit(@rEmployeeCode, ','))) OR @rEmployeeCode = N'')
          AND ((EED.ParticipantName LIKE @rEmployeeName + N'%') OR @rEmployeeName = N'')       
          AND ((EED.MainTypeId = @rExaminationTypeId) OR @rExaminationTypeId = 0)    
          AND (EED.MainTypeId <> 8)    
          AND ((EED.ExaminationDate >= @rFromDate) OR ISNULL(@rFromDate, '') = N'')    
          AND ((EED.ExaminationDate <= @rToDate)   OR ISNULL(@rToDate,   '') = N'')     
          AND (EED.OrgId = @rOrgId)     
          AND (UL.UserId = @rCreatedUserId)     
          AND (EED.StatusId = @rExaminationStatusId OR @rExaminationStatusId = 0)    
          AND (EED.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)    
          AND ((EED.SetupId = @rRoundId) OR ISNULL(@rRoundId, 0) IN (0, -1))
          AND ((ISNULL(EPD.NationalityId, 0) IN (SELECT item FROM sCommon.fnsplit(@rNationalId, ','))) OR ISNULL(@rNationalId, '') = N'')
          AND ((SM.SetupGroupId = @rRoundGroupId) OR ISNULL(@rRoundGroupId, 0) = 0)    
          AND ((EED.EmployeeCompanyId       IN (SELECT item FROM sCommon.fnsplit(@rCompanyIds, ',')))        OR ISNULL(@rCompanyIds, '') = N'')    
          AND ((EED.OrganizationDepartmentId IN (SELECT item FROM sCommon.fnsplit(@rDepartmentIds, ',')))    OR ISNULL(@rDepartmentIds, '') = N'')    
          AND ((EED.DepartmentGroupId        IN (SELECT item FROM sCommon.fnsplit(@rDepartmentGroupIds, ',')))OR ISNULL(@rDepartmentGroupIds, '') = N'')    
          AND ((EED.EmployeeDesignationId    IN (SELECT item FROM sCommon.fnsplit(@rDesignationIds, ',')))   OR ISNULL(@rDesignationIds, '') = N'')    
          AND (EED.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)    
          AND ((EED.EmployeeTargetGroupId    IN (SELECT item FROM sCommon.fnsplit(@rTargetGroupIds, ',')))   OR @rTargetGroupIds = N'')
          AND (ISNULL(@rCompanyGroupIds, '') = N'' OR ISNULL(ECM.CompanyGroupId, 0) IN (SELECT CAST(item AS int) FROM sCommon.fnsplit(@rCompanyGroupIds, ',')))
          AND ((VTM.SectorId  IN (SELECT item FROM sCommon.fnsplit(@rBusinessIds, ',')))     OR ISNULL(@rBusinessIds,    '') = N'')
          AND ((CGM.VerticalId IN (SELECT item FROM sCommon.fnsplit(@rSubBusinessIds, ','))) OR ISNULL(@rSubBusinessIds, '') = N'');

        -- Helpful index for joins that follow
        CREATE CLUSTERED INDEX IX_ExaminationDetail_ExaminationId ON #ExaminationDetail(ExaminationId);

        ------------------------------------------------------------
        -- GENERAL TEMPLATE -> PIVOT
        ------------------------------------------------------------
        CREATE TABLE #tblExaminationGeneralTemplates
        (
            tid int IDENTITY(1,1) PRIMARY KEY,
            g_ExaminationId bigint,
            g_Value varchar(500),
            g_Remark varchar(500),
            g_Title varchar(300)
        );

        INSERT INTO #tblExaminationGeneralTemplates(g_ExaminationId, g_Value, g_Remark, g_Title)
        SELECT ED.Id,
               GED.ParameterValue,
               GED.Remark,
               GP.Title
        FROM sExamination.tExamination                    AS ED
        INNER JOIN #ExaminationDetail                     AS EED ON ED.Id = EED.ExaminationId    
        INNER JOIN sExamination.tSetupMaster              AS SSM ON ED.SetupId = SSM.Id    
        INNER JOIN sHrm.tEmployeeMaster                   AS EM  ON ED.ParticipantSourceId = EM.Id    
        INNER JOIN sHrm.tEmployeeJobDetail                AS EJD ON EJD.EmployeeId = ED.ParticipantSourceId    
        LEFT  JOIN sExamination.tGeneralTemplateExamination      AS GE  ON ED.Id = GE.SourceId    
        LEFT  JOIN sExamination.tGeneralTemplateExaminationDetail AS GED ON GE.Id = GED.GeneralTemplateExaminationId    
        LEFT  JOIN sExamination.tGeneralTemplateParameter         AS GP  ON GP.Id = GED.GeneralTEmplateParameterId;

        DECLARE @GeneralCols  nvarchar(max) = N'';
        DECLARE @GeneralCols1 nvarchar(max) = N'';
        DECLARE @lQueryExisting nvarchar(max) = N'';

        SELECT @GeneralCols =
        STUFF((
            SELECT DISTINCT ',' + QUOTENAME(GTP.Title)
            FROM sExamination.tGeneralTemplateParameter GTP
            INNER JOIN sExamination.tGeneralTemplateMaster GTM ON GTM.Id = GTP.GeneralTemplateId
            WHERE GTM.GeneralTemplateGroupId <> 4 AND GTP.OrgId = @rOrgId AND GTP.IsObsolete = 0
            FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '');

        SELECT @GeneralCols1 =
        STUFF((
            SELECT DISTINCT ',' + QUOTENAME(GTP.Title) + ' varchar(300)'
            FROM sExamination.tGeneralTemplateParameter GTP
            INNER JOIN sExamination.tGeneralTemplateMaster GTM ON GTM.Id = GTP.GeneralTemplateId
            WHERE GTM.GeneralTemplateGroupId <> 4 AND GTP.OrgId = @rOrgId AND GTP.IsObsolete = 0
            FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '');
			
        -- Step 1: Create the base temp table
CREATE TABLE #tblGeneral (
    tid INT IDENTITY(1,1) PRIMARY KEY,
    d_ExamId BIGINT
);

-- Step 1: Add dynamic columns if any
IF (@GeneralCols1 <> '')
BEGIN
    -- Add columns dynamically
    SET @lQueryExisting = N'ALTER TABLE #tblGeneral ADD ' + @GeneralCols1;
    EXEC sp_executesql @lQueryExisting;

    -- Insert pivoted data
    SET @lQueryExisting = N'
        INSERT INTO #tblGeneral (d_ExamId, ' + @GeneralCols + ')
        SELECT g_ExaminationId,' + @GeneralCols + '
        FROM
        (
            SELECT g_ExaminationId, g_Value, g_Title
            FROM #tblExaminationGeneralTemplates
        ) src
        PIVOT
        (
            MAX(g_Value) FOR g_Title IN (' + @GeneralCols + ')
        ) piv;
    ';
    EXEC sp_executesql @lQueryExisting;
END

        CREATE NONCLUSTERED INDEX IX_tblGeneral_d_ExamId ON #tblGeneral(d_ExamId);
        ------------------------------------------------------------
        -- TESTS -> PIVOT
        ------------------------------------------------------------
        -- Narrow the TR set first
        CREATE TABLE #tmpTR (TestRequestId bigint, ExaminationId bigint);
        INSERT INTO #tmpTR(TestRequestId, ExaminationId)
        SELECT TR.Id, EED.ExaminationId
        FROM sExamination.tTestRequest AS TR
        INNER JOIN #ExaminationDetail AS EED ON EED.ExaminationId = TR.SourceId;

        CREATE TABLE #tblExaminationTests
        (
            tid int IDENTITY(1,1) PRIMARY KEY,
            g_ExaminationId bigint,
            g_Value varchar(max),
            g_Remark varchar(max),
            g_Title varchar(max)
        );

        INSERT INTO #tblExaminationTests(g_ExaminationId, g_Value, g_Remark, g_Title)
        SELECT GE.ExaminationId,
               GED.ServiceValue,
               GED.Remark,
               GP.Title
        FROM #tmpTR AS GE
        LEFT JOIN sExamination.tTestRequestDetail   AS GED ON GE.TestRequestId = GED.TestRequestId
        LEFT JOIN sOrderEntry.tTestDetail           AS TD  ON TD.Id = GED.TestDetailId
        LEFT JOIN sOrderEntry.tTestParameterMaster  AS GP  ON GP.Id = TD.TestParameterId;
		

        DECLARE @TestCols  nvarchar(max) = N'';
        DECLARE @TestCols1 nvarchar(max) = N'';

        SELECT @TestCols =
        STUFF((
            SELECT DISTINCT ',' + QUOTENAME(Title)
            FROM sOrderEntry.tTestParameterMaster
            WHERE OrgId = @rOrgId AND IsObsolete = 0
            FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '');

        SELECT @TestCols1 =
        STUFF((
            SELECT DISTINCT ',' + QUOTENAME(Title) + ' varchar(300)'
            FROM sOrderEntry.tTestParameterMaster
            WHERE OrgId = @rOrgId AND IsObsolete = 0
            FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '');

       -- Step 1: Create base temp table
CREATE TABLE #tblTests (
    tid INT IDENTITY(1,1) PRIMARY KEY,
    d_ExamId BIGINT
);

-- Step 2: Add dynamic columns if present
IF (@TestCols1 <> '')
BEGIN
    SET @lQueryExisting = N'ALTER TABLE #tblTests ADD ' + @TestCols1;
    EXEC sp_executesql @lQueryExisting;
END

        IF (@TestCols <> '')
        BEGIN
            SET @lQueryExisting = N'
                INSERT INTO #tblTests (d_ExamId,' + @TestCols + ')
                SELECT g_ExaminationId,' + @TestCols + '
                FROM (
                    SELECT g_ExaminationId, g_Value, g_Title
                    FROM #tblExaminationTests
                    GROUP BY g_ExaminationId, g_Value, g_Remark, g_Title
                ) AS src
                PIVOT (MAX(g_Value) FOR g_Title IN (' + @TestCols + ')) AS piv;';
            EXEC sp_executesql @lQueryExisting;
        END

        CREATE NONCLUSTERED INDEX IX_tblTests_d_ExamId ON #tblTests(d_ExamId);

        ------------------------------------------------------------
        -- FLAGS FOR SPECIAL BLOCKS (329=Audiometry, 330=Pulmonary)
        ------------------------------------------------------------
        DECLARE @isAudiometry bit = 0, @isPulmonary bit = 0;

        ;WITH SplitIds AS
        (
            SELECT TRY_CAST(item AS int) AS ColumnId
            FROM sCommon.fnsplit(@rColumnIds, ',')
        )
        SELECT
            @isAudiometry = CASE WHEN EXISTS(SELECT 1 FROM SplitIds WHERE ColumnId = 329) THEN 1 ELSE 0 END,
            @isPulmonary  = CASE WHEN EXISTS(SELECT 1 FROM SplitIds WHERE ColumnId = 330) THEN 1 ELSE 0 END;

        -- Remove 329/330 from @rColumnIds so they don't try to map to tExaminationCustomColumns
        IF (@isAudiometry = 1)
            SELECT @rColumnIds = REVERSE(STUFF(REVERSE(STUFF(REPLACE(',' + @rColumnIds + ',', ',329,', ','), 1, 1, '')), 1, 1, ''));
        IF (@isPulmonary = 1)
            SELECT @rColumnIds = REVERSE(STUFF(REVERSE(STUFF(REPLACE(',' + @rColumnIds + ',', ',330,', ','), 1, 1, '')), 1, 1, ''));

        ------------------------------------------------------------
        -- BUILD REPORT COLUMN LISTS FROM sHrm.tExaminationCustomColumns
        ------------------------------------------------------------
        CREATE TABLE #ColumnTable1(Id1 int IDENTITY(1,1) PRIMARY KEY, ColumnId1 int);
        CREATE TABLE #ColumnTable (Id int IDENTITY(1,1) PRIMARY KEY, ColumnId int);

        INSERT INTO #ColumnTable1(ColumnId1)
        SELECT item FROM sCommon.fnsplit(@rColumnIds, ',');

        INSERT INTO #ColumnTable(ColumnId)
        SELECT DISTINCT ColumnId1 FROM #ColumnTable1 ORDER BY ColumnId1 ASC;

        DECLARE @ColCount int = (SELECT COUNT(*) FROM #ColumnTable);
        DECLARE @ReportCols   nvarchar(max) = N'';
        DECLARE @ReportColVal nvarchar(max) = N'';

       IF (@ColCount > 0)
        BEGIN
       -- Build column definitions with datatype
       -- Build column definitions with datatype
-- Build column + datatype list
SELECT @ReportCols =
    STUFF((
        SELECT ',' + QUOTENAME(ECC.ColumnName) + ' ' + ECC.DataType
        FROM #ColumnTable CT
        INNER JOIN sHrm.tExaminationCustomColumns ECC 
            ON ECC.Id = CT.ColumnId
        WHERE 
            (
                -- Check in General Templates
                EXISTS (
                    SELECT 1 
                    FROM #tblExaminationGeneralTemplates T 
                    WHERE T.g_Title = ECC.ColumnName
                )
                OR
                -- Check in Examination Tests
                EXISTS (
                    SELECT 1 
                    FROM #tblExaminationTests TT 
                    WHERE TT.g_Title = ECC.ColumnName
                )
                OR
                -- Check in #ExaminationDetail temp table columns
                EXISTS (
                    SELECT 1
                    FROM tempdb.sys.columns sc
                    INNER JOIN tempdb.sys.objects so 
                        ON sc.object_id = so.object_id
                    WHERE so.name LIKE '#ExaminationDetail%' 
                      AND sc.name = ECC.ColumnName
                )
            )
        ORDER BY CT.ColumnId
        FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, ''
    );

-- Build only column list (no datatype)
SELECT @ReportColVal =
    STUFF((
        SELECT ',' + QUOTENAME(ECC.ColumnName)
        FROM #ColumnTable CT
        INNER JOIN sHrm.tExaminationCustomColumns ECC 
            ON ECC.Id = CT.ColumnId
        WHERE 
            (
                EXISTS (
                    SELECT 1 
                    FROM #tblExaminationGeneralTemplates T 
                    WHERE T.g_Title = ECC.ColumnName
                )
                OR
                EXISTS (
                    SELECT 1 
                    FROM #tblExaminationTests TT 
                    WHERE TT.g_Title = ECC.ColumnName
                )
                OR
                EXISTS (
                    SELECT 1
                    FROM tempdb.sys.columns sc
                    INNER JOIN tempdb.sys.objects so 
                        ON sc.object_id = so.object_id
                    WHERE so.name LIKE '#ExaminationDetail%' 
                      AND sc.name = ECC.ColumnName
                )
            )
        ORDER BY CT.ColumnId
        FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, ''
    );
end

        ------------------------------------------------------------
        -- AUDIO PIVOT (if requested)
        ------------------------------------------------------------
        IF (@isAudiometry = 1)
        BEGIN
            CREATE TABLE #tblExaminationAudiometrys
            (
                tid int IDENTITY(1,1) PRIMARY KEY,
                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),
                ED.Id,
                ISNULL(A.IsDoneLeft, 0),
                ISNULL(A.IsDoneRight, 0),
                ISNULL(AD.AcValueLeft, 0),
                ISNULL(AD.AcValueRight, 0),
                ISNULL(AD.FrequencyId, 0),
                ISNULL(A.AudiometryAcResultLeftId, 0),
                ISNULL(A.AudiometryAcResultRightId, 0),
                ISNULL(A.AudiometryResultRemarkLeftId, 0),
                ISNULL(A.AudiometryResultRemarkRightId, 0)
            FROM sExamination.tExamination         AS ED
            INNER JOIN #ExaminationDetail          AS EED ON ED.Id = EED.ExaminationId    
            INNER JOIN sExamination.tSetupMaster   AS SSM ON ED.SetupId = SSM.Id    
            INNER JOIN sHrm.tEmployeeMaster        AS EM  ON ED.ParticipantSourceId = EM.Id    
            INNER JOIN sHrm.tEmployeeJobDetail     AS EJD ON EJD.EmployeeId = ED.ParticipantSourceId    
            LEFT  JOIN sExamination.tAudiometry    AS A   ON A.SourceId = ED.Id    
            LEFT  JOIN sExamination.tAudiometryDetail AS AD ON AD.AudiomentryId = A.Id;

            CREATE NONCLUSTERED INDEX IX_tblExaminationAudiometrys_Exam ON #tblExaminationAudiometrys(ExaminationId);

            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)
);

            DECLARE @AudioInsert nvarchar(max) = N'
                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,
                    ISNULL(LeftPivot.AudiometryAcResultLeft, ''''),
                    ISNULL(LeftPivot.AudiometryResultRemarkLeft, ''''),
                    LeftPivot.[250],LeftPivot.[500],LeftPivot.[1000],LeftPivot.[2000],LeftPivot.[4000],LeftPivot.[6000],LeftPivot.[8000],
                    CASE WHEN RightPivot.IsDoneRight = 1 THEN ''TRUE'' ELSE ''FALSE'' END,
                    RightPivot.AudiometryAcResultRight,
                    RightPivot.AudiometryResultRemarkRight,
                    RightPivot.[250],RightPivot.[500],RightPivot.[1000],RightPivot.[2000],RightPivot.[4000],RightPivot.[6000],RightPivot.[8000]
                FROM
                (
                    SELECT pvt.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 AS 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
                ) AS LeftPivot
                INNER JOIN
                (
                    SELECT pvt.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 AS 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
                ) AS RightPivot
                ON LeftPivot.ExaminationId = RightPivot.ExaminationId;';
            EXEC sp_executesql @AudioInsert;

            CREATE NONCLUSTERED INDEX IX_tblAudiometry_aExamId ON #tblAudiometry(a_ExamId);
        END

        ------------------------------------------------------------
        -- MAIN RESULT TABLE (dynamic shape)
        ------------------------------------------------------------
-- Step 1: Create temp table with no (or minimal) columns
 DECLARE @lMainQuery NVARCHAR(MAX) = ''    

SELECT @lMainQuery = 
'CREATE TABLE ##tblMainTable ('+ @ReportCols 
+ CASE WHEN (@ReportCols <> '' AND @isAudiometry= 1) THEN ',' ELSE '' END 
+ CASE WHEN @isAudiometry = 1 THEN '    
 IsDoneLeft bit,AudiometryAcResultLeft varchar(200),AudiometryResultRemarkLeft varchar(200),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)'  
ELSE '' END 

+ CASE WHEN (@isAudiometry= 1 AND @isPulmonary = 1) THEN ',' 
       ELSE (CASE WHEN (@ReportCols <> '' AND @isPulmonary= 1) THEN ',' ELSE '' END) END 

+ CASE WHEN @isPulmonary = 1 THEN '    
 FVCPredicted varchar(200),FVCObserved varchar(200),PerOfPredictedFVC varchar(200),FEV1Predicted varchar(200),FEV1Observed varchar(200),    
 PerOfFEV1 varchar(200),PerOfFEV1ByFVC varchar(200),PulmonaryResult varchar(200))' 
ELSE ')' END    

EXEC(@lMainQuery);

 





        ------------------------------------------------------------
        -- INSERT MAIN DATA
        ------------------------------------------------------------
        ------------------------------------------------------------
-- Step 1: Create the temp table (base columns only)
------------------------------------------------------------


------------------------------------------------------------
-- Step 2: Add dynamic columns safely
------------------------------------------------------------
-- Step 1: Split and clean column names into a table
-- Step 1: Split @ReportColVal into individual column names

------------------------------------------------------------
-- Step 4: Build dynamic insert
------------------------------------------------------------
IF ISNULL(@ReportColVal,'') <> ''
BEGIN	
    DECLARE @InsertMain NVARCHAR(MAX) = N'
       insert into ##tblMainTable select ' + @ReportColVal +  (case when (@ReportColVal <> '' and @isAudiometry= 1) then ',' else '' end) + case when @isAudiometry = 1 then +    
 ' IsDoneLeft,AudiometryAcResultLeft,AudiometryResultRemarkLeft,L250,L500,    
 L1000,L2000,L4000,L6000,L8000,IsDoneRight,AudiometryAcResultRight,AudiometryResultRemarkRight,    
 R250,R500,R1000,R2000,R4000,R6000,R8000' Else ' ' END +  (case when (@isAudiometry= 1 and @isPulmonary = 1) then ',' else (case when (@ReportColVal <> '' and @isPulmonary= 1) then ',' else '' end) end) + case when @isPulmonary = 1 then +  ' FVCPredicted,
  
FVCObserved,PerOfPredictedFVC,FEV1Predicted,FEV1Observed,PerOfFEV1,PerOfFEV1ByFVC,    
 PulmonaryResult = P.PulmonaryResulIntensity + '' '' + P.PulmonaryResult ' else ' ' END +'     
     
 from #ExaminationDetail EA     
 left join #tblGeneral GE on EA.ExaminationId = GE.d_ExamId    
 left join #tblTests TE on EA.ExaminationId = TE.d_ExamId '     
 + case when @isAudiometry = 1 then +    
 ' left join #tblAudiometry AA on EA.ExaminationId = AA.a_ExamId '  Else ' ' END +'     
 left join sExamination.tPulmonary P on EA.ExaminationId = P.SourceId'
   
    EXEC sp_executesql @InsertMain;
END

----------------------------------------------------------
 --Step 5: Return results
----------------------------------------------------------
SELECT DISTINCT * 
FROM ##tblMainTable;


        ------------------------------------------------------------
        -- CLEANUP
        ------------------------------------------------------------
        DROP TABLE IF EXISTS #tmpTR;
        -- others dropped automatically at scope end; explicit not necessary but ok:
        -- DROP TABLE IF EXISTS #ExaminationDetail, #tblExaminationGeneralTemplates, #tblGeneral, #tblExaminationTests, #tblTests, #tblExaminationAudiometrys, #tblAudiometry, #ColumnTable, #ColumnTable1, #tblMainTable;

        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        --IF (XACT_STATE() <> 0) ROLLBACK TRANSACTION;
        ---- Optional: uncomment to debug
        --SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_LINE() AS ErrorLine, ERROR_PROCEDURE() AS ErrorProcedure;
        --SELECT 
        --ERROR_NUMBER() AS ErrorNumber,       -- The error number
        --ERROR_MESSAGE() AS ErrorMessage,     -- The detailed error message
        --ERROR_SEVERITY() AS ErrorSeverity,   -- The severity of the error
        --ERROR_STATE() AS ErrorState,         -- The state of the error
        --ERROR_LINE() AS ErrorLine,           -- The line where the error occurred
        --ERROR_PROCEDURE() AS ErrorProcedure  
		 SELECT -1 AS Result
    END CATCH
END

GO


CREATE OR ALTER PROCEDURE [sPharmacy].[pPharmacyQueueListingGetDashboard]	
   	@rOrgID [int] = 0,  
	@rLocationId int 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
	DECLARE @FromDate DATETIME = CAST(GETDATE() AS DATE);
DECLARE @ToDate   DATETIME = DATEADD(DAY, 1, @FromDate);
	SELECT 
	P.ID,
	Code = 
	CASE AED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code 
	WHEN 1009 THEN BM.Code END,
	PatientName = CASE AED.ParticipantSourceTypeId WHEN 95 THEN isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')
	WHEN 1001 THEN EFD.Name WHEN 1009 THEN 
	(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end) END ,
	case when isnull(U.DisplayTitle,'') <> '' then U.DisplayTitle
	else ISNULL(EM1.FirstName,'') + ' ' + ISNULL( EM1.LastName,'') end AS EmployeeName,
	CASE AED.ParticipantSourceTypeId WHEN 95 THEN 'SELF' WHEN 1001 THEN RM.Title WHEN 1009 THEN 'Other'	END As Relation,
	AED.ExaminationDate,
	AED.ExaminationNumber
	FROM sExamination.tPrescription P with(NOLOCK)
	INNER JOIN sSecurity.tUser U ON U.Id = P.CreatedUserId
	INNER JOIN sExamination.tExamination AED ON AED.Id = P.SourceId
	INNER JOIN sExamination.tSetupMaster SM on AED.SetupId = SM.Id
	INNER JOIN sExamination.tSubTypeMaster ST on SM.SubTypeId = ST.Id
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= AED.Id
	LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id=AED.DoctorEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EM on AED.ParticipantSourceId = EM.Id and AED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on AED.ParticipantSourceId = EFD.Id and AED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on AED.ParticipantSourceId = BM.Id and AED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=EFD.RelationshipId
	WHERE isnull(AED.IsCancel,0) = 0 
	AND AED.ExaminationDate >= @FromDate
    AND AED.ExaminationDate <  @ToDate
	AND P.IsDispensed = 0
	AND ST.MainTypeId = 8 AND AED.OrgId = P.OrgId
	AND AED.StoreLocationId = @rLocationId AND P.IsObsolete  = 0 AND IsDirect = 0
	AND P.OrgId = @rOrgID 
	AND isnull(IsOtherIssue,0) = 0 order by P.Id desc
END

GO


ALTER proc [sSupport].[pAHCCounsellingReferDoctor]
@rDoctorId bigint,
@rHealthIndicatorId int,
@rStatusId int, 
@rstrXML nvarchar(max),
@rCreatedUserId bigint,
@rOrgId int
as  
Begin
	BEGIN TRY
		 BEGIN TRANSACTION	
		 declare @lostrXML  xml
		 declare @empId bigint, @rDoctorName nvarchar(200) = '';

		 declare @lAssignDesignationConfigVal varchar(5);
            
		 select @lAssignDesignationConfigVal = sConfig.fConfigurationValueGet('Provider.AssignDesignationFreezeWiseOrEntityWise',@rOrgId,0,0,0)

		 Set @empId = (select SourceId  from sSecurity.tUser Where id = @rCreatedUserId And SourceTypeId = 95);

		IF (@rDoctorId > 0)
		BEGIN
			set @rDoctorName = (select ISNULL(FirstName, '') + ' ' + ISNULL(LastName, '') from sHrm.tEmployeeMaster where Id = @rDoctorId)
		END

		 set @lostrXML = cast(@rstrXML as xml)

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

			Create table #tbltmpAHCTeam
			(
				tid int identity(1,1),
				ProviderAppointmentId bigint,
				CSVNonPathoParameters nvarchar(max),
				HealthIndicatorCurrentStatus int
			)
			insert into #tbltmpAHCTeam
			select T.c.value('@ProviderAppointmentId','int') as ProviderAppointmentId,
			T.c.value('@CSVNonPathoParameters','nvarchar(max)') as CSVNonPathoParameters, 0
			from @lostrXML.nodes('/StatusChange/StatusData')T(c)

			update tmp set tmp.HealthIndicatorCurrentStatus = PA.HealthIndicatorId from #tbltmpAHCTeam tmp 
			INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = tmp.ProviderAppointmentId

			MERGE sSupport.tProviderAppointment AS TARGET
USING (SELECT * FROM #tbltmpAHCTeam) AS SOURCE
ON TARGET.Id = SOURCE.ProviderAppointmentId AND TARGET.OrgId = @rOrgId
WHEN MATCHED THEN
    UPDATE SET  
        HealthIndicatorId = @rHealthIndicatorId,
        AssignToDoctorId = @rDoctorId,
        UpdatedUserId = @rCreatedUserId,
        UpdatedDateTime = sCommon.fGetDate(),
		NonPathoParameters = CSVNonPathoParameters,
		AssignByDoctorId = @empId,
		AssignDate = sCommon.fGetDate(),
        StatusId = CASE 
                      WHEN @rHealthIndicatorId = 608 OR @rHealthIndicatorId = 611 OR @rHealthIndicatorId = 612 THEN @rStatusId 
					  WHEN @rHealthIndicatorId = 606 OR @rHealthIndicatorId = 607 THEN 609
                      ELSE TARGET.StatusId 
                   END;

			Insert into sSupport.tProviderAppointmentlog
			select AHCT.ProviderAppointmentId, CASE 
                      WHEN @rHealthIndicatorId = 608 OR @rHealthIndicatorId = 611 OR @rHealthIndicatorId = 612 THEN @rStatusId 
					  WHEN @rHealthIndicatorId = 606 OR @rHealthIndicatorId = 607 THEN 609
                      ELSE PA.StatusId END, 
					  @rCreatedUserId, sCommon.fGetDate(),'Refer to Doctor ' + @rDoctorName
			from #tbltmpAHCTeam AHCT
			INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId

			--Health Indicator Log
			Insert into sSupport.tProviderAppointmentHealthIndicatorLog
			select AHCT.ProviderAppointmentId, @rHealthIndicatorId, @rCreatedUserId, sCommon.fGetDate(),'Refer to Doctor ' + @rDoctorName
			from #tbltmpAHCTeam AHCT
			INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId

			if (@lAssignDesignationConfigVal = 'True' AND @rHealthIndicatorId = 606)
			BEGIN
				UPDATE tpa SET tpa.HealthIndicatorId = (CASE WHEN CAST(DetailsVital.BMI AS Float) >= 30 AND CAST(DetailsVital.BMI AS Float) <= 35 THEN 612
													WHEN CAST(DetailsVital.BloodPressureSystolic AS Float) >= 150 AND CAST(DetailsVital.BloodPressureSystolic AS Float) <= 160 THEN 612
													WHEN CAST(DetailsVital.BloodPressureDiastolic AS Float) >= 100 AND CAST(DetailsVital.BloodPressureDiastolic AS Float) <= 110 THEN 612
													WHEN CAST(Details.HB AS Float) >= 8 and CAST(Details.HB AS Float) < 10 THEN 612
													WHEN CAST(Details.HBA1C AS Float) >= 8 and CAST(Details.HBA1C AS Float) <= 10 THEN 612
													WHEN CAST(Details.[SERUM CREATININE] AS Float) >= 1.5 AND CAST(Details.[SERUM CREATININE] AS Float) <= 2 THEN 612
													WHEN CAST(Details.[SERUM URIC ACID] AS Float) >= 7.7 AND CAST(Details.[SERUM URIC ACID] AS Float) <= 9.4 THEN 612
													WHEN CAST(Details.[TRIGLYCERIDE] AS Float) >= 200 AND CAST(Details.[TRIGLYCERIDE] AS Float) <= 500 THEN 612
													WHEN CAST(Details.[LDL] AS Float) >= 150 AND CAST(Details.[LDL] AS Float) <= 200 THEN 612
													WHEN CAST(Details.[TSH] AS Float) >= 11 AND CAST(Details.[TSH] AS Float) <= 50 THEN 612
													WHEN CAST(Details.[PSA] AS Float) > 5 THEN 612
													--Mild
													WHEN CAST(DetailsVital.BMI AS Float) >= 26 AND CAST(DetailsVital.BMI AS Float) < 30 THEN 611
													WHEN CAST(DetailsVital.BloodPressureSystolic AS Float) >= 140 AND CAST(DetailsVital.BloodPressureSystolic AS Float) < 150 THEN 611
													WHEN CAST(DetailsVital.BloodPressureDiastolic AS Float) >= 90 AND CAST(DetailsVital.BloodPressureDiastolic AS Float) < 100 THEN 611
													WHEN CAST(Details.HB AS Float) >= 10 and CAST(Details.HB AS Float) < 12 THEN 611
													WHEN CAST(Details.HBA1C AS Float) >= 6.5 and CAST(Details.HBA1C AS Float) < 8 THEN 611
													WHEN CAST(Details.[SERUM CREATININE] AS Float) >= 1.3 AND CAST(Details.[SERUM CREATININE] AS Float) < 1.5 THEN 611
													WHEN CAST(Details.[SERUM URIC ACID] AS Float) >= 6.5 AND CAST(Details.[SERUM URIC ACID] AS Float) < 7.7 THEN 611
													WHEN CAST(Details.[TRIGLYCERIDE] AS Float) >= 150 AND CAST(Details.[TRIGLYCERIDE] AS Float) < 200 THEN 611
													WHEN CAST(Details.[LDL] AS Float) >= 101 AND CAST(Details.[LDL] AS Float) < 150 THEN 611
													WHEN CAST(Details.[TSH] AS Float) >= 5.6 AND CAST(Details.[TSH] AS Float) < 11 THEN 611
													Else 606 END),
							tpa.UpdatedDateTime = sCommon.fGetDate()
						FROM sSupport.tProviderAppointment AS tpa
						INNER JOIN #tbltmpAHCTeam AS ot ON ot.ProviderAppointmentId = tpa.Id
						INNER JOIN sExamination.tExamination AS EXM ON EXM.ParticipantSourceId = tpa.PatientSourceId AND EXM.SetupId = tpa.SetupId
						INNER JOIN sExamination.tSetupMaster AS STM ON STM.ID = EXM.SetupId
						INNER JOIN sExamination.tSubTypeMaster AS SSM ON SSM.Id = STM.SubTypeId
						INNER JOIN sIp.tStoreLocationMaster AS SLM ON SLM.Id = EXM.StoreLocationId
						LEFT JOIN  
						(
							SELECT ExaminationId, Details.[R.B.C. COUNT], Details.[MCV], Details.[F B S], Details.[CHOLESTEROL],  
								   Details.[TRIGLYCERIDE], Details.[LDL], Details.[HDL], Details.[SGPT],  
								   Details.[ECG], Details.[SONOGRAPHY], Details.[TMT], Details.[ECHO],  
								   Details.[HB], Details.[SERUM CREATININE], Details.[SERUM URIC ACID], [HBA1C], [R B S], [P P B S], 
								   Details.[Waist Circumference], Details.[TSH], Details.[PSA], Details.[XRAY]
							FROM sExamination.tExamination AS EXM
							LEFT JOIN
							(
								SELECT ExaminationId, [R.B.C. COUNT], [MCV], [F B S], [CHOLESTEROL], [TRIGLYCERIDE], [LDL], [HDL],  
									   [SGPT], [ECG], [SONOGRAPHY], [TMT], [ECHO], [HB], [SERUM CREATININE], [SERUM URIC ACID], [HBA1C], [R B S], [P P B S], 
									   [Waist Circumference], [TSH], [PSA], [XRAY]
								FROM  
								(
									SELECT SPM.Title, TR.SourceId [ExaminationId], TRD.ServiceValue  
									FROM sOrderEntry.tStaticTestParameterMaster AS SPM  
									INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id  
									INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id  
									INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id  
									INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId  
									WHERE SPM.Id in (3, 5, 19, 20, 21, 25, 31, 32, 33, 34, 38, 107, 104, 105, 109, 108, 2, 27, 49, 166, 54, 58)
								)
								d PIVOT
								(
									MIN(ServiceValue) FOR Title IN  
									(
										[R.B.C. COUNT], [MCV], [F B S], [CHOLESTEROL], [TRIGLYCERIDE], [LDL], [HDL], [SGPT],  
										[ECG], [SONOGRAPHY], [TMT], [ECHO], [HB], [SERUM CREATININE], [SERUM URIC ACID], [HBA1C], [R B S], [P P B S], 
										[Waist Circumference], [TSH], [PSA], [XRAY]
									)
								) piv
							) AS Details ON Details.ExaminationId = EXM.Id
						) AS Details ON Details.ExaminationId = EXM.Id
						LEFT JOIN 
						(
							SELECT TR.SourceId AS ExaminationId, TRD.Remark
							FROM sExamination.tTestRequestDetail TRD
							INNER JOIN sOrderEntry.tTestDetail TTD ON TTD.Id = TRD.TestDetailId
							INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TTD.TestParameterId
							INNER JOIN sOrderEntry.tStaticTestParameterMaster SPM ON SPM.Id = TPM.StaticTestParameterId
							INNER JOIN sExamination.tTestRequest TR ON TR.Id = TRD.TestRequestId
							WHERE SPM.Id = 108
						) AS ECHO_REMARKS ON ECHO_REMARKS.ExaminationId = EXM.Id
						LEFT JOIN 
						(
							SELECT TR.SourceId AS ExaminationId, TRD.Remark
							FROM sExamination.tTestRequestDetail TRD
							INNER JOIN sOrderEntry.tTestDetail TTD ON TTD.Id = TRD.TestDetailId
							INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TTD.TestParameterId
							INNER JOIN sOrderEntry.tStaticTestParameterMaster SPM ON SPM.Id = TPM.StaticTestParameterId
							INNER JOIN sExamination.tTestRequest TR ON TR.Id = TRD.TestRequestId
							WHERE SPM.Id = 107
						) AS ECG_REMARKS ON ECG_REMARKS.ExaminationId = EXM.Id
						LEFT JOIN
						 (
						  SELECT EXM.ID [ExaminationId],DetailsVital.[BMI],DetailsVital.[BloodPressureSystolic], DetailsVital.[BloodPressureDiastolic]
						  FROM sExamination.tExamination AS EXM  
						  LEFT JOIN
						  (
						   SELECT VTL.SourceId [ExaminationId],
						   ISNULL(BMI, 0) as BMI, 
						   ISNULL(BloodPressureSystolic, 0) as BloodPressureSystolic,
						   ISNULL(BloodPressureDiastolic, 0) as BloodPressureDiastolic
						   FROM sExamination.tVital AS VTL
						  ) AS DetailsVital ON DetailsVital.ExaminationId = EXM.Id
						 ) AS DetailsVital ON DetailsVital.ExaminationId = EXM.Id
						WHERE EXM.ParticipantSourceTypeId = 95 AND (ot.HealthIndicatorCurrentStatus = 607 OR ot.HealthIndicatorCurrentStatus = 608)
						AND EXM.OrgId = @rOrgId;

						UPDATE PA SET PA.AssignToDoctorId = SE.SiteDoctorId,
							   PA.HealthIndicatorId = (CASE WHEN SE.SiteDoctorId IS NULL THEN 606 ELSE PA.HealthIndicatorId END),
							   PA.AssignDate = sCommon.fGetDate()
						FROM sSupport.tProviderAppointment AS PA
						INNER JOIN #tbltmpAHCTeam AS ot ON ot.ProviderAppointmentId = PA.Id
						INNER JOIN sExamination.tExamination AS EXM ON EXM.ParticipantSourceId = PA.PatientSourceId AND EXM.SetupId = PA.SetupId
						INNER JOIN sExamination.tSetupEmployee AS SE ON SE.SetupId = EXM.SetupId AND SE.EmployeeId = EXM.ParticipantSourceId
						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 EM ON EM.Id = EXM.ParticipantSourceId
						WHERE EXM.ParticipantSourceTypeId = 95
						AND EXM.OrgId = @rOrgId AND (ot.HealthIndicatorCurrentStatus = 607 OR ot.HealthIndicatorCurrentStatus = 608)
						AND (PA.HealthIndicatorId = 611 OR PA.HealthIndicatorId = 612);

						UPDATE tpa SET tpa.StatusId=CASE WHEN HealthIndicatorId = 611 OR HealthIndicatorId = 612 THEN @rStatusId 
                                                         WHEN HealthIndicatorId = 606 THEN 609 ELSE TPA.StatusId END,
							tpa.UpdatedDateTime = sCommon.fGetDate()
						FROM sSupport.tProviderAppointment AS tpa
						INNER JOIN #tbltmpAHCTeam AS ot ON ot.ProviderAppointmentId = tpa.Id
						INNER JOIN sExamination.tExamination AS EXM ON EXM.ParticipantSourceId = tpa.PatientSourceId AND EXM.SetupId = tpa.SetupId
						WHERE EXM.ParticipantSourceTypeId = 95 AND (ot.HealthIndicatorCurrentStatus = 607 OR ot.HealthIndicatorCurrentStatus = 608)
						AND EXM.OrgId = @rOrgId;

						Insert into sSupport.tProviderAppointmentlog
						select AHCT.ProviderAppointmentId, PA.StatusId, @rCreatedUserId, sCommon.fGetDate(),
							   'Refer to Doctor ' + ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '')
						from #tbltmpAHCTeam AHCT
						INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId
						LEFT JOIN sHRM.tEmployeeMaster EM ON EM.Id = PA.AssignToDoctorId
						WHERE (AHCT.HealthIndicatorCurrentStatus = 607 OR AHCT.HealthIndicatorCurrentStatus = 608)

						--Health Indicator Log
						Insert into sSupport.tProviderAppointmentHealthIndicatorLog
						select AHCT.ProviderAppointmentId, PA.HealthIndicatorId, @rCreatedUserId, sCommon.fGetDate(),
							   'Refer to Doctor ' + ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '')
						from #tbltmpAHCTeam AHCT
						INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId
						LEFT JOIN sHRM.tEmployeeMaster EM ON EM.Id = PA.AssignToDoctorId
						WHERE (AHCT.HealthIndicatorCurrentStatus = 607 OR AHCT.HealthIndicatorCurrentStatus = 608)
			END

		
		COMMIT TRANSACTION
		SELECT 1 AS Result
	END TRY
	
	BEGIN CATCH 
		IF @@TRANCOUNT > 0
        ROLLBACK
		--SELECT -1 AS Result
		select ERROR_MESSAGE() 
	END CATCH	

end

GO


CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateMHIUpdationCategoryBulk]
( 
    @rUserId BIGINT,
    @rMHICategoryList [sWellness].[udt_MHIBulkCategoryImport] READONLY,
    @Result INT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ModifiedRows INT = 0;

    MERGE [sWellness].[tMHIScoreUpdation] AS T
    USING
    (
        SELECT 
            E.Id AS ParticipantSourceId,
            M.HBA1CCategory,
            M.LDLCategory,
            M.BMICategory,
            M.BPCategory,
            M.StressCategory,
            M.LifestyleCategory
        FROM @rMHICategoryList M
        INNER JOIN [sHrm].[tEmployeeMaster] E
            ON E.Code = M.EmployeeCode
    ) AS S
    ON T.ParticipantSourceId = S.ParticipantSourceId

    WHEN MATCHED THEN
        UPDATE SET
            T.HBA1CCategory = S.HBA1CCategory,
            T.BMICategory = S.BMICategory,
            T.LDLCategory = S.LDLCategory,
            T.BPCategory = S.BPCategory,
            T.StressCategory = S.StressCategory,
            T.LifestyleCategory = S.LifestyleCategory,
            T.InsertType = 2,
            T.UpdatedUserId = @rUserId,
            T.UpdatedDateTime = sCommon.fGetDate()

    WHEN NOT MATCHED THEN
        INSERT
        (
            ParticipantSourceTypeId,
            ParticipantSourceId,
			HBA1CCategory,
            BMICategory,
            LDLCategory,
			BPCategory,
            StressCategory,
            LifestyleCategory,
			InsertType,
            CreatedUserId,
            CreatedDateTime
        )
        VALUES
        (
            95,
            S.ParticipantSourceId,
            S.HBA1CCategory,
            S.BMICategory,
            S.LDLCategory,
            S.BPCategory,
            S.StressCategory,
            S.LifestyleCategory,
			2,
            @rUserId,
            sCommon.fGetDate()
        );

    SET @ModifiedRows = @@ROWCOUNT;
    SET @Result = @ModifiedRows;
END

GO


CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramMHICategory]
(
	@rOrgId SMALLINT,	
    @rEmployeeId BIGINT,
	@rEmployeeSourceTypeId INT,
    @rSubmitFrom SMALLINT,

    -- Raw values (kept for storage only)
    @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,

    -- NEW: Direct Scores
    @rBMIScore SMALLINT,
    @rHBA1CScore SMALLINT,
    @rLDLScore SMALLINT,
    @rBPScore SMALLINT,
    @rStressScore SMALLINT,
    @rLifestyleScore SMALLINT,

    @rUserId BIGINT
)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE @lNextNumber BIGINT = 0;

	BEGIN TRY
	BEGIN TRANSACTION

	-- =========================================
	-- Normalize Scores (0 → NULL)
	-- =========================================
	DECLARE 
		@BMIScore SMALLINT = CASE WHEN @rBMIScore IN (1,2,3) THEN @rBMIScore ELSE NULL END,
		@HBA1CScore SMALLINT = CASE WHEN @rHBA1CScore IN (1,2,3) THEN @rHBA1CScore ELSE NULL END,
		@LDLScore SMALLINT = CASE WHEN @rLDLScore IN (1,2,3) THEN @rLDLScore ELSE NULL END,
		@BPScore SMALLINT = CASE WHEN @rBPScore IN (1,2,3) THEN @rBPScore ELSE NULL END,
		@StressIndex SMALLINT = CASE WHEN @rStressScore IN (1,2,3) THEN @rStressScore ELSE NULL END,
		@LifestyleIndex SMALLINT = CASE WHEN @rLifestyleScore IN (1,2,3) THEN @rLifestyleScore ELSE NULL END,
		@AssignedMHIIndicatorId INT = 0;

	-- =========================================
	-- Category Mapping
	-- =========================================
	DECLARE 
		@BMICategory NVARCHAR(30),
		@HBA1CCategory NVARCHAR(30),
		@LDLCategory NVARCHAR(30),
		@BPCategory NVARCHAR(30),
		@StressCategory NVARCHAR(30),
		@LifeStyleCategory NVARCHAR(30);

	SET @BMICategory = CASE @BMIScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END;
	SET @HBA1CCategory = CASE @HBA1CScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END;
	SET @LDLCategory = CASE @LDLScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END;
	SET @BPCategory = CASE @BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END;
	SET @StressCategory = CASE @StressIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END;
	SET @LifeStyleCategory = CASE @LifestyleIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END;

	-- =========================================
	-- INSERT / UPDATE BASE DATA
	-- =========================================
	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,
			Stress,StressScore,StressCategory,
			Lifestyle,LifestyleScore,LifestyleCategory,
			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,
			@rStressScore,@StressIndex,@StressCategory,
			@rLifestyleScore,@LifestyleIndex,@LifeStyleCategory,
			@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,

			Stress=@rStressScore,
			StressScore=@StressIndex,
			StressCategory=@StressCategory,

			Lifestyle=@rLifestyleScore,
			LifestyleScore=@LifestyleIndex,
			LifestyleCategory=@LifeStyleCategory,

			UpdatedUserId=@rUserId,
			UpdatedDatetime=sCommon.fGetDate()
		WHERE EmployeeId=@rEmployeeId;

		SET @lNextNumber = @@ROWCOUNT;
	END

	-- =========================================
	-- BIOMETRICS CALCULATION (STRICT)
	-- =========================================
	DECLARE @BiometricScore DECIMAL(10,2)=NULL,
			@BiometricsCategory VARCHAR(30)=NULL,
			@TotalBiometrics INT=NULL;

	IF(@BMIScore IS NOT NULL AND @HBA1CScore IS NOT NULL AND @LDLScore IS NOT NULL AND @BPScore IS NOT NULL)
	BEGIN
		SET @TotalBiometrics = @BMIScore + @HBA1CScore + @LDLScore + @BPScore;
		SET @BiometricScore = (100.0 * @TotalBiometrics) / 4;

		SET @BiometricsCategory =
			CASE 
				WHEN @BiometricScore <= 100 THEN 'Optimal'
				WHEN @BiometricScore < 150 THEN 'SubOptimal'
				ELSE 'Alert'
			END
	END

	-- =========================================
	-- SURVEY CALCULATION (STRICT)
	-- =========================================
	DECLARE @SurveyCategory VARCHAR(30)=NULL;

	IF(@StressIndex IS NOT NULL AND @LifestyleIndex IS NOT NULL)
	BEGIN
		SET @SurveyCategory =
			CASE 
				WHEN @StressIndex = 3 OR @LifestyleIndex = 3 THEN 'Alert'
				WHEN @StressIndex = 2 OR @LifestyleIndex = 2 THEN 'SubOptimal'
				ELSE 'Optimal'
			END
	END

	-- =========================================
	-- MHI CALCULATION (STRICT)
	-- =========================================
	DECLARE @MHICategory VARCHAR(30)=NULL,
			@MHICategoryId SMALLINT=0,
			@AssignedProgramId INT=0;

	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='Optimal' THEN 1
				WHEN @MHICategory='SubOptimal' THEN 2
				WHEN @MHICategory='Alert' THEN 3
				ELSE 0
			END;
	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

	-- =========================================
	-- FINAL UPDATE
	-- =========================================
	UPDATE [sWellness].[tMHIScore]
	SET
		Biometrics=@BiometricScore,
		BiometricsCategory=@BiometricsCategory,
		SurveyCategory=@SurveyCategory,
		MHICategory=@MHICategory,
		MHICategoryId=@MHICategoryId,
		ProgramId = @AssignedProgramId,
		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 '1' AS Result

	END TRY
	BEGIN CATCH
		IF @@TRANCOUNT > 0 ROLLBACK
		SELECT '-1' AS Result, ERROR_MESSAGE()
	END CATCH
END


GO


CREATE OR ALTER PROCEDURE [sWellness].[pAssignMHIProgramCategoryBulk]
(
      @rOrgId SMALLINT,
      @rUserId BIGINT,
      @rMHIScoreList [sWellness].[udt_MHIBulkCategoryImport] READONLY,
      @InsertedCount INT OUTPUT,
      @UpdatedCount INT OUTPUT,
      @SkippedEmployeeCodeCount INT OUTPUT,
      @TotalProcessed INT OUTPUT
)
AS
BEGIN
SET NOCOUNT ON;

BEGIN TRY
BEGIN TRANSACTION;

DECLARE @MergeResult TABLE
(
    ActionType NVARCHAR(10),
    EmployeeId BIGINT
);

------------------------------------------------
-- NORMALIZATION (ALLOW 0)
------------------------------------------------
SELECT *
INTO #Calculated
FROM
(
    SELECT
          EM.EmployeeId,
          EM.GenderId,

          CA.HBA1C,
          CA.LDL,
          CA.BMI,
          CA.BP,
          CA.Stress,
          CA.Lifestyle,

          CA.BMI AS BMIScore,
          CA.HBA1C AS HBA1CScore,
          CA.LDL AS LDLScore,
          CA.BP AS BPScore,
          CA.Stress AS StressScore,
          CA.Lifestyle AS LifestyleScore

    FROM @rMHIScoreList S
    JOIN sHrm.vExtEmployeeMaster EM 
        ON EM.Code = S.EmployeeCode

    CROSS APPLY
    (
        SELECT
            CASE 
                WHEN LOWER(S.HBA1CCategory)='optimal' THEN 1
                WHEN LOWER(S.HBA1CCategory)='suboptimal' THEN 2
                WHEN LOWER(S.HBA1CCategory)='alert' THEN 3
                WHEN TRY_CAST(S.HBA1CCategory AS INT) IN (0,1,2,3) THEN TRY_CAST(S.HBA1CCategory AS INT)
            END,

            CASE 
                WHEN LOWER(S.LDLCategory)='optimal' THEN 1
                WHEN LOWER(S.LDLCategory)='suboptimal' THEN 2
                WHEN LOWER(S.LDLCategory)='alert' THEN 3
                WHEN TRY_CAST(S.LDLCategory AS INT) IN (0,1,2,3) THEN TRY_CAST(S.LDLCategory AS INT)
            END,

            CASE 
                WHEN LOWER(S.BMICategory)='optimal' THEN 1
                WHEN LOWER(S.BMICategory)='suboptimal' THEN 2
                WHEN LOWER(S.BMICategory)='alert' THEN 3
                WHEN TRY_CAST(S.BMICategory AS INT) IN (0,1,2,3) THEN TRY_CAST(S.BMICategory AS INT)
            END,

            CASE 
                WHEN LOWER(S.BPCategory)='optimal' THEN 1
                WHEN LOWER(S.BPCategory)='suboptimal' THEN 2
                WHEN LOWER(S.BPCategory)='alert' THEN 3
                WHEN TRY_CAST(S.BPCategory AS INT) IN (0,1,2,3) THEN TRY_CAST(S.BPCategory AS INT)
            END,

            CASE 
                WHEN LOWER(S.StressCategory)='optimal' THEN 1
                WHEN LOWER(S.StressCategory)='suboptimal' THEN 2
                WHEN LOWER(S.StressCategory)='alert' THEN 3
                WHEN TRY_CAST(S.StressCategory AS INT) IN (0,1,2,3) THEN TRY_CAST(S.StressCategory AS INT)
            END,

            CASE 
                WHEN LOWER(S.LifestyleCategory)='optimal' THEN 1
                WHEN LOWER(S.LifestyleCategory)='suboptimal' THEN 2
                WHEN LOWER(S.LifestyleCategory)='alert' THEN 3
                WHEN TRY_CAST(S.LifestyleCategory AS INT) IN (0,1,2,3) THEN TRY_CAST(S.LifestyleCategory AS INT)
            END
    ) CA (HBA1C, LDL, BMI, BP, Stress, Lifestyle)

    WHERE 
        CA.HBA1C IN (0,1,2,3) AND
        CA.LDL IN (0,1,2,3) AND
        CA.BMI IN (0,1,2,3) AND
        CA.BP IN (0,1,2,3) AND
        CA.Stress IN (0,1,2,3) AND
        CA.Lifestyle IN (0,1,2,3)

) X;

------------------------------------------------
-- CONVERT 0 → NULL (CRITICAL FIX)
------------------------------------------------
UPDATE #Calculated
SET 
    BMIScore = NULLIF(BMIScore,0),
    HBA1CScore = NULLIF(HBA1CScore,0),
    LDLScore = NULLIF(LDLScore,0),
    BPScore = NULLIF(BPScore,0),
    StressScore = NULLIF(StressScore,0),
    LifestyleScore = NULLIF(LifestyleScore,0);

------------------------------------------------
-- SKIPPED COUNT
------------------------------------------------
SELECT @SkippedEmployeeCodeCount =
(
    SELECT COUNT(*)
    FROM @rMHIScoreList S
    LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.Code = S.EmployeeCode
    WHERE EM.EmployeeId IS NULL
);

------------------------------------------------
-- DERIVED LOGIC
------------------------------------------------
ALTER TABLE #Calculated ADD 
Biometrics DECIMAL(10,2),
BiometricsCategory VARCHAR(30),
SurveyCategory VARCHAR(30),
MHICategory VARCHAR(30),
MHICategoryId SMALLINT,
ProgramId INT;

UPDATE #Calculated
SET Biometrics =
CASE 
    WHEN BMIScore IS NULL OR HBA1CScore IS NULL OR LDLScore IS NULL OR BPScore IS NULL THEN NULL
    ELSE (100.0 * (BMIScore + HBA1CScore + LDLScore + BPScore)) / 4
END;

UPDATE #Calculated
SET BiometricsCategory =
CASE 
    WHEN Biometrics IS NULL THEN NULL 
    WHEN Biometrics <= 100 THEN 'Optimal'
    WHEN Biometrics < 150 THEN 'SubOptimal'
    ELSE 'Alert'
END;

UPDATE #Calculated
SET SurveyCategory =
CASE
    WHEN StressScore IS NULL OR LifestyleScore IS NULL THEN NULL
    WHEN StressScore = 3 OR LifestyleScore = 3 THEN 'Alert'
    WHEN StressScore = 2 OR LifestyleScore = 2 THEN 'SubOptimal'
    WHEN StressScore = 1 AND LifestyleScore = 1 THEN 'Optimal'
END;

UPDATE #Calculated
SET MHICategory =
CASE
    WHEN BiometricsCategory IS NULL OR SurveyCategory IS NULL THEN 'NotApplicable'
    WHEN BiometricsCategory='Alert' OR SurveyCategory='Alert' THEN 'Alert'
    WHEN BiometricsCategory='SubOptimal' OR SurveyCategory='SubOptimal' THEN 'SubOptimal'
    WHEN BiometricsCategory='Optimal' AND SurveyCategory='Optimal' THEN 'Optimal'
    ELSE 'NotApplicable'
END;

UPDATE #Calculated
SET MHICategoryId =
CASE
    WHEN MHICategory='Optimal' THEN 1
    WHEN MHICategory='SubOptimal' THEN 2
    WHEN MHICategory='Alert' THEN 3
    ELSE 0
END;

UPDATE C 
SET ProgramId = ISNULL(PM.Id, 0)
FROM #Calculated C
LEFT JOIN sWellness.tStaticMHICategoryIndicator I ON I.Id = C.MHICategoryId
LEFT JOIN sWellness.tProgramMaster PM 
    ON PM.MHIIndicatorId = I.Id 
   AND PM.CategoryId = 1 
   AND PM.IsObsolete = 0;

------------------------------------------------
-- UPDATE
------------------------------------------------
UPDATE T
SET
BMIScore=C.BMIScore,
BMICategory=CASE WHEN C.BMIScore IS NULL THEN NULL WHEN C.BMIScore=1 THEN 'Optimal' WHEN C.BMIScore=2 THEN 'SubOptimal' ELSE 'Alert' END,

HBA1CScore=C.HBA1CScore,
HBA1CCategory=CASE WHEN C.HBA1CScore IS NULL THEN NULL WHEN C.HBA1CScore=1 THEN 'Optimal' WHEN C.HBA1CScore=2 THEN 'SubOptimal' ELSE 'Alert' END,

LDLScore=C.LDLScore,
LDLCategory=CASE WHEN C.LDLScore IS NULL THEN NULL WHEN C.LDLScore=1 THEN 'Optimal' WHEN C.LDLScore=2 THEN 'SubOptimal' ELSE 'Alert' END,

BPScore=C.BPScore,
BPCategory=CASE WHEN C.BPScore IS NULL THEN NULL WHEN C.BPScore=1 THEN 'Optimal' WHEN C.BPScore=2 THEN 'SubOptimal' ELSE 'Alert' END,

StressScore=C.StressScore,
StressCategory=CASE WHEN C.StressScore IS NULL THEN NULL WHEN C.StressScore=1 THEN 'Optimal' WHEN C.StressScore=2 THEN 'SubOptimal' ELSE 'Alert' END,

LifestyleScore=C.LifestyleScore,
LifestyleCategory=CASE WHEN C.LifestyleScore IS NULL THEN NULL WHEN C.LifestyleScore=1 THEN 'Optimal' WHEN C.LifestyleScore=2 THEN 'SubOptimal' ELSE 'Alert' END,

Biometrics=C.Biometrics,
BiometricsCategory=C.BiometricsCategory,
SurveyCategory=C.SurveyCategory,
MHICategory=C.MHICategory,
MHICategoryId=C.MHICategoryId,
ProgramId=C.ProgramId,

UpdatedUserId=@rUserId,
UpdatedDatetime=sCommon.fGetDate()

OUTPUT 'UPDATE',inserted.EmployeeId INTO @MergeResult
FROM sWellness.tMHIScore T
JOIN #Calculated C ON C.EmployeeId=T.EmployeeId;

------------------------------------------------
-- INSERT
------------------------------------------------
DECLARE @EmployeeId BIGINT,@NextId BIGINT;

DECLARE curInsert CURSOR FAST_FORWARD FOR
SELECT EmployeeId
FROM #Calculated C
WHERE NOT EXISTS
(
    SELECT 1 FROM sWellness.tMHIScore T WHERE T.EmployeeId=C.EmployeeId
);

OPEN curInsert;
FETCH NEXT FROM curInsert INTO @EmployeeId;

WHILE @@FETCH_STATUS=0
BEGIN

EXEC sCommon.pTableRowIdGet
@rOrgId,'sWellness.tMHIScore',0,1,1,@outNextNumber=@NextId OUTPUT;

INSERT INTO sWellness.tMHIScore
(
Id,OrgId,ProgramId,EmployeeId,EmployeeSourceTypeId,LastUpdateType,
BMIScore,BMICategory,
HBA1CScore,HBA1CCategory,
LDLScore,LDLCategory,
BPScore,BPCategory,
StressScore,StressCategory,
LifestyleScore,LifestyleCategory,
Biometrics,BiometricsCategory,
SurveyCategory,MHICategory,MHICategoryId,
CreatedUserId,CreatedDatetime
)
SELECT
@NextId,@rOrgId,C.ProgramId,C.EmployeeId,95,4,
C.BMIScore,CASE WHEN C.BMIScore IS NULL THEN NULL WHEN C.BMIScore=1 THEN 'Optimal' WHEN C.BMIScore=2 THEN 'SubOptimal' ELSE 'Alert' END,
C.HBA1CScore,CASE WHEN C.HBA1CScore IS NULL THEN NULL WHEN C.HBA1CScore=1 THEN 'Optimal' WHEN C.HBA1CScore=2 THEN 'SubOptimal' ELSE 'Alert' END,
C.LDLScore,CASE WHEN C.LDLScore IS NULL THEN NULL WHEN C.LDLScore=1 THEN 'Optimal' WHEN C.LDLScore=2 THEN 'SubOptimal' ELSE 'Alert' END,
C.BPScore,CASE WHEN C.BPScore IS NULL THEN NULL WHEN C.BPScore=1 THEN 'Optimal' WHEN C.BPScore=2 THEN 'SubOptimal' ELSE 'Alert' END,
C.StressScore,CASE WHEN C.StressScore IS NULL THEN NULL WHEN C.StressScore=1 THEN 'Optimal' WHEN C.StressScore=2 THEN 'SubOptimal' ELSE 'Alert' END,
C.LifestyleScore,CASE WHEN C.LifestyleScore IS NULL THEN NULL WHEN C.LifestyleScore=1 THEN 'Optimal' WHEN C.LifestyleScore=2 THEN 'SubOptimal' ELSE 'Alert' END,
C.Biometrics,C.BiometricsCategory,
C.SurveyCategory,C.MHICategory,C.MHICategoryId,
@rUserId,sCommon.fGetDate()
FROM #Calculated C
WHERE C.EmployeeId=@EmployeeId;

INSERT INTO @MergeResult VALUES('INSERT',@EmployeeId);

FETCH NEXT FROM curInsert INTO @EmployeeId;
END

CLOSE curInsert;
DEALLOCATE curInsert;

------------------------------------------------
-- HISTORY
------------------------------------------------
DECLARE @EmpId BIGINT;

DECLARE curHistory CURSOR FAST_FORWARD FOR
SELECT DISTINCT EmployeeId FROM @MergeResult;

OPEN curHistory;
FETCH NEXT FROM curHistory INTO @EmpId;

WHILE @@FETCH_STATUS=0
BEGIN
EXEC sWellness.pInsertMHIScoreHistoryIfChanged
@rEmployeeId=@EmpId,
@rUserId=@rUserId;

FETCH NEXT FROM curHistory INTO @EmpId;
END

CLOSE curHistory;
DEALLOCATE curHistory;

------------------------------------------------
-- COUNTS
------------------------------------------------
SELECT
@InsertedCount=ISNULL(SUM(CASE WHEN ActionType='INSERT' THEN 1 END),0),
@UpdatedCount=ISNULL(SUM(CASE WHEN ActionType='UPDATE' THEN 1 END),0)
FROM @MergeResult;

SET @TotalProcessed =
ISNULL(@InsertedCount,0)
+ISNULL(@UpdatedCount,0)
+ISNULL(@SkippedEmployeeCodeCount,0);

COMMIT TRANSACTION;

END TRY
BEGIN CATCH
IF @@TRANCOUNT>0 ROLLBACK;

SET @InsertedCount=-1;
SET @UpdatedCount=-1;
SET @SkippedEmployeeCodeCount=-1;
SET @TotalProcessed=-1;

SELECT ERROR_MESSAGE() ErrorMessage,ERROR_LINE() ErrorLine;
END CATCH

END

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,
			CASE WHEN MHI.BMICategory LIKE '[1-3]' THEN CAST(MHI.BMICategory AS SMALLINT) ELSE 0 END AS BMICategory,
			CASE WHEN MHI.HBA1CCategory LIKE '[1-3]' THEN CAST(MHI.HBA1CCategory AS SMALLINT) ELSE 0 END AS HBA1CCategory,
			CASE WHEN MHI.LDLCategory LIKE '[1-3]' THEN CAST(MHI.LDLCategory AS SMALLINT) ELSE 0 END AS LDLCategory,
			CASE WHEN MHI.BPCategory LIKE '[1-3]' THEN CAST(MHI.BPCategory AS SMALLINT) ELSE 0 END AS BPCategory,
			CASE WHEN MHI.StressCategory LIKE '[1-3]' THEN CAST(MHI.StressCategory AS SMALLINT) ELSE 0 END AS StressCategory,
			CASE WHEN MHI.LifestyleCategory LIKE '[1-3]' THEN CAST(MHI.LifestyleCategory AS SMALLINT) ELSE 0 END AS LifestyleCategory,
			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


CREATE OR ALTER PROCEDURE [sWellness].[pGetMHIScoreUpdationList]
(
	@rOrgId SMALLINT = 0,
	@rProgramId INT = 0,
	@rDepartmentId INT = 0,
	@rLocationId INT = 0,
	@rInsertType SMALLINT = 1,
	@rUserId BIGINT
)
AS
BEGIN	

	;WITH BaseData AS
	(
		SELECT DISTINCT
			MHI.Id,
			MHI.ParticipantSourceTypeId,
			MHI.ParticipantSourceId,

			MHI.BMI,
			MHI.HBA1C,
			MHI.LDL,
			MHI.BPSystolic,
			MHI.BPDiastolic,
			MHI.Stress,
			MHI.LifeStyle,

			MHI.HBA1CCategory,
			MHI.LDLCategory,
			MHI.BMICategory,
			MHI.BPCategory,
			MHI.StressCategory,
			MHI.LifestyleCategory,

			ED.Code AS EmployeeCode,
			ED.EmployeeName,
			MHI.InsertType

		FROM [sWellness].[tMHIScoreUpdation] MHI

		INNER JOIN [sHrm].[vEmployeeDetail] ED 
			ON MHI.ParticipantSourceId = ED.EmployeeId

		LEFT JOIN [sWellness].[tMHIScore] MHS
			ON MHS.EmployeeId = ED.EmployeeId

		INNER JOIN [sIp].[tStoreLocationMaster] SLM 
			ON SLM.LocationId = ED.EmployeeLocationId

		INNER JOIN [sSecurity].[tUserLocation] UL 
			ON UL.StoreLocationId = SLM.Id

		LEFT JOIN [sWellness].[tProgramMaster] PM	
			ON PM.Id = MHS.ProgramId

		WHERE
			(@rProgramId = 0 
			 OR (@rProgramId = 999 AND (MHS.ProgramId = 0 OR MHS.ProgramId IS NULL))
			 OR (@rProgramId <> 0 AND @rProgramId <> 999 AND MHS.ProgramId = @rProgramId))
		AND (@rDepartmentId = 0 OR ED.DepartmentId = @rDepartmentId)
		AND (@rLocationId = 0 OR ED.EmployeeLocationId = @rLocationId)
		AND ED.OrgId = @rOrgId
		AND UL.UserId = @rUserId
	)

	SELECT
		Id,
		ParticipantSourceTypeId,
		ParticipantSourceId,

		-- =========================
		-- SCORE MODE
		-- =========================
		CASE WHEN @rInsertType = 1 THEN BMI END AS BMI,
		CASE WHEN @rInsertType = 1 THEN HBA1C END AS HBA1C,
		CASE WHEN @rInsertType = 1 THEN LDL END AS LDL,
		CASE WHEN @rInsertType = 1 THEN BPSystolic END AS BPSystolic,
		CASE WHEN @rInsertType = 1 THEN BPDiastolic END AS BPDiastolic,
		CASE WHEN @rInsertType = 1 THEN Stress END AS Stress,
		CASE WHEN @rInsertType = 1 THEN LifeStyle END AS LifeStyle,

		-- =========================
		-- CATEGORY MODE (NUMERIC)
		-- =========================
		CASE WHEN @rInsertType = 2 AND HBA1CCategory LIKE '[1-3]' THEN CAST(HBA1CCategory AS SMALLINT) ELSE 0 END AS HBA1CCategory,
		CASE WHEN @rInsertType = 2 AND LDLCategory LIKE '[1-3]' THEN CAST(LDLCategory AS SMALLINT) ELSE 0 END AS LDLCategory,
		CASE WHEN @rInsertType = 2 AND BMICategory LIKE '[1-3]' THEN CAST(BMICategory AS SMALLINT) ELSE 0 END AS BMICategory,
		CASE WHEN @rInsertType = 2 AND BPCategory LIKE '[1-3]' THEN CAST(BPCategory AS SMALLINT) ELSE 0 END AS BPCategory,
		CASE WHEN @rInsertType = 2 AND StressCategory LIKE '[1-3]' THEN CAST(StressCategory AS SMALLINT) ELSE 0 END AS StressCategory,
		CASE WHEN @rInsertType = 2 AND LifestyleCategory LIKE '[1-3]' THEN CAST(LifestyleCategory AS SMALLINT) ELSE 0 END AS LifestyleCategory,

		-- =========================
		-- CATEGORY MODE (NAME)
		-- =========================
		CASE 
			WHEN @rInsertType = 2 AND HBA1CCategory = '1' THEN 'Optimal'
			WHEN @rInsertType = 2 AND HBA1CCategory = '2' THEN 'SubOptimal'
			WHEN @rInsertType = 2 AND HBA1CCategory = '3' THEN 'Alert'
			ELSE NULL
		END AS HBA1CCategoryName,

		CASE 
			WHEN @rInsertType = 2 AND LDLCategory = '1' THEN 'Optimal'
			WHEN @rInsertType = 2 AND LDLCategory = '2' THEN 'SubOptimal'
			WHEN @rInsertType = 2 AND LDLCategory = '3' THEN 'Alert'
			ELSE NULL
		END AS LDLCategoryName,

		CASE 
			WHEN @rInsertType = 2 AND BMICategory = '1' THEN 'Optimal'
			WHEN @rInsertType = 2 AND BMICategory = '2' THEN 'SubOptimal'
			WHEN @rInsertType = 2 AND BMICategory = '3' THEN 'Alert'
			ELSE NULL
		END AS BMICategoryName,

		CASE 
			WHEN @rInsertType = 2 AND BPCategory = '1' THEN 'Optimal'
			WHEN @rInsertType = 2 AND BPCategory = '2' THEN 'SubOptimal'
			WHEN @rInsertType = 2 AND BPCategory = '3' THEN 'Alert'
			ELSE NULL
		END AS BPCategoryName,

		CASE 
			WHEN @rInsertType = 2 AND StressCategory = '1' THEN 'Optimal'
			WHEN @rInsertType = 2 AND StressCategory = '2' THEN 'SubOptimal'
			WHEN @rInsertType = 2 AND StressCategory = '3' THEN 'Alert'
			ELSE NULL
		END AS StressCategoryName,

		CASE 
			WHEN @rInsertType = 2 AND LifestyleCategory = '1' THEN 'Optimal'
			WHEN @rInsertType = 2 AND LifestyleCategory = '2' THEN 'SubOptimal'
			WHEN @rInsertType = 2 AND LifestyleCategory = '3' THEN 'Alert'
			ELSE NULL
		END AS LifeStyleCategoryName,

		EmployeeCode,
		EmployeeName

	FROM BaseData
	WHERE InsertType = @rInsertType
	ORDER BY Id DESC

END


GO


CREATE OR ALTER PROCEDURE [sWellness].[pLastExaminationConsultationParameter]
@rParticipantSourceTypeId int,
@rParticipantSourceId bigint,
@rOrgId int
as
begin   
	 Declare @rHeight nvarchar(10), @rWeight nvarchar(10), @rBMI nvarchar(10), 
	 @rBPSys nvarchar(10), @rBPDia nvarchar(10), @rHBA1C nvarchar(10), @rLDL nvarchar(10);
	 
	 set @rHeight = (select Top 1 CAST(Isnull(GTCD.ParameterValue,'') AS NVARCHAR(10)) AS Height from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tGeneralTemplateConsultation GTC ON GTC.SourceId = WC.Id
	 INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	 INNER JOIN sExamination.tGeneralTemplateParameter GTM ON GTM.Id = GTCD.GeneralTemplateParameterId
	 WHERE WC.ParticipantSourceId = @rParticipantSourceId and WC.ParticipantSourceTypeId = @rParticipantSourceTypeId
	 and GTM.StaticGeneralTemplateParameterId = 502 and Isnull(CAST(GTCD.ParameterValue as float),0) > 0
	 order by WC.Id desc)

	 set @rWeight = (select Top 1 CAST(Isnull(GTCD.ParameterValue,'') AS NVARCHAR(10)) AS [Weight] from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tGeneralTemplateConsultation GTC ON GTC.SourceId = WC.Id
	 INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	 INNER JOIN sExamination.tGeneralTemplateParameter GTM ON GTM.Id = GTCD.GeneralTemplateParameterId
	 WHERE WC.ParticipantSourceId = @rParticipantSourceId and WC.ParticipantSourceTypeId = @rParticipantSourceTypeId
	 and GTM.StaticGeneralTemplateParameterId = 501 and Isnull(CAST(GTCD.ParameterValue as float),0) > 0
	 order by WC.Id desc)

	 set @rBMI = (select Top 1 CAST(Isnull(GTCD.ParameterValue,'') AS NVARCHAR(10)) AS BMI from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tGeneralTemplateConsultation GTC ON GTC.SourceId = WC.Id
	 INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	 INNER JOIN sExamination.tGeneralTemplateParameter GTM ON GTM.Id = GTCD.GeneralTemplateParameterId
	 WHERE WC.ParticipantSourceId = @rParticipantSourceId and WC.ParticipantSourceTypeId = @rParticipantSourceTypeId
	 and GTM.StaticGeneralTemplateParameterId = 503 and Isnull(CAST(GTCD.ParameterValue as float),0) > 0
	 order by WC.Id desc)

	 set @rBPSys = (select Top 1 CAST(Isnull(GTCD.ParameterValue,'') AS NVARCHAR(10)) AS BPSys from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tGeneralTemplateConsultation GTC ON GTC.SourceId = WC.Id
	 INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	 INNER JOIN sExamination.tGeneralTemplateParameter GTM ON GTM.Id = GTCD.GeneralTemplateParameterId
	 WHERE WC.ParticipantSourceId = @rParticipantSourceId and WC.ParticipantSourceTypeId = @rParticipantSourceTypeId
	 and GTM.StaticGeneralTemplateParameterId = 506 and Isnull(CAST(GTCD.ParameterValue as float),0) > 0
	 order by WC.Id desc)
	 
	 set @rBPDia = (select Top 1 CAST(Isnull(GTCD.ParameterValue,'') AS NVARCHAR(10)) AS BPDia from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tGeneralTemplateConsultation GTC ON GTC.SourceId = WC.Id
	 INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	 INNER JOIN sExamination.tGeneralTemplateParameter GTM ON GTM.Id = GTCD.GeneralTemplateParameterId
	 WHERE WC.ParticipantSourceId = @rParticipantSourceId and WC.ParticipantSourceTypeId = @rParticipantSourceTypeId
	 and GTM.StaticGeneralTemplateParameterId = 507 and Isnull(CAST(GTCD.ParameterValue as float),0) > 0
	 order by WC.Id desc)

	 set @rHBA1C = (select Top 1 CAST(Isnull(CTRD.ServiceValue,'') AS NVARCHAR(10)) AS HBA1C from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tConsultationTestRequest CTR ON CTR.SourceId = WC.Id
	 INNER JOIN sWellness.tConsultationTestRequestDetail CTRD ON CTRD.TestRequestId = CTR.Id
	 INNER JOIN sOrderEntry.tTestDetail TD ON TD.Id = CTRD.TestDetailId
	 INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
	 WHERE WC.ParticipantSourceId = @rParticipantSourceId and WC.ParticipantSourceTypeId = @rParticipantSourceTypeId
	 and TPM.StaticTestParameterId = 25 and Isnull(CAST(CTRD.ServiceValue as float),0) > 0
	 order by WC.Id desc)
	 
	 set @rLDL = (select Top 1 CAST(Isnull(CTRD.ServiceValue,'') AS NVARCHAR(10)) AS LDL from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tConsultationTestRequest CTR ON CTR.SourceId = WC.Id
	 INNER JOIN sWellness.tConsultationTestRequestDetail CTRD ON CTRD.TestRequestId = CTR.Id
	 INNER JOIN sOrderEntry.tTestDetail TD ON TD.Id = CTRD.TestDetailId
	 INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
	 WHERE WC.ParticipantSourceId = @rParticipantSourceId and WC.ParticipantSourceTypeId = @rParticipantSourceTypeId
	 and TPM.StaticTestParameterId = 34 and Isnull(CAST(CTRD.ServiceValue as float),0) > 0
	 order by WC.Id desc)

	 IF (ISNULL(@rHeight,'') = '' AND ISNULL(@rWeight,'') = '')
	 BEGIN
		 Select Top 1 @rHeight=CAST(ISNULL(V.Height,0) AS NVARCHAR(10)),
						@rWeight=CAST(ISNULL(V.BodyWeight,0) AS NVARCHAR(10)),
						@rBMI=CAST(ISNULL(V.BMI,0) AS NVARCHAR(10)) 
		 FROM sExamination.tExamination E 
		 LEFT JOIN sExamination.tVital V ON V.SourceId = E.Id
		 where E.ParticipantSourceId = @rParticipantSourceId and E.ParticipantSourceTypeId = @rParticipantSourceTypeId
		 and E.SetupId <> [sCommon].[fGetIntIdForOrg](8, @rOrgId) 
		 and Isnull(V.Height,0)>0 and Isnull(V.BodyWeight,0)>0 and Isnull(V.BMI,0)>0
		 order by E.id desc
	 END
	 IF (ISNULL(@rBPSys,'') = '' AND ISNULL(@rBPDia,'') = '')
	 BEGIN
		 Select Top 1 @rBPSys=CAST(ISNULL(BloodPressureSystolic,0) AS NVARCHAR(10)), 
					  @rBPDia=CAST(ISNULL(BloodPressureDiastolic,0) AS NVARCHAR(10)) 
		 FROM sExamination.tExamination E 
		 LEFT JOIN sExamination.tVital V ON V.SourceId = E.Id
		 where E.ParticipantSourceId = @rParticipantSourceId and E.ParticipantSourceTypeId = @rParticipantSourceTypeId
		 and E.SetupId <> [sCommon].[fGetIntIdForOrg](8, @rOrgId)
		 and ISNUMERIC(V.BloodPressureSystolic) = 1 and ISNUMERIC(V.BloodPressureDiastolic) = 1
		 and Isnull(V.BloodPressureSystolic,0)>0 and Isnull(V.BloodPressureDiastolic,0)>0
		 order by E.id desc
	 END
	 IF (ISNULL(@rHBA1C,'') = '')
	 BEGIN
		 set @rHBA1C = (select Top 1 CAST(Isnull(TRD.ServiceValue,'') AS NVARCHAR(10)) AS HBA1C 
		 from sExamination.tExamination E
		 INNER JOIN sExamination.tTestRequest TR ON TR.SourceId = E.Id
		 INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id
		 INNER JOIN sOrderEntry.tTestDetail TD ON TD.Id = TRD.TestDetailId
		 INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
		 WHERE E.ParticipantSourceId = @rParticipantSourceId and E.ParticipantSourceTypeId = @rParticipantSourceTypeId
		 and TPM.StaticTestParameterId = 25 and ISNUMERIC(TRD.ServiceValue) = 1
		 AND (CASE 
			  WHEN TRD.ServiceValue NOT LIKE '%[^0-9.]%' 
			  		AND TRD.ServiceValue <> ''
			  THEN CAST(TRD.ServiceValue AS FLOAT)
			  ELSE 0
		 END) > 0
		 order by E.Id desc)
	 END
	 IF (ISNULL(@rLDL,'') = '')
	 BEGIN
		 set @rLDL = (select Top 1 CAST(Isnull(TRD.ServiceValue,'') AS NVARCHAR(10)) AS LDL 
		 from sExamination.tExamination E
		 INNER JOIN sExamination.tTestRequest TR ON TR.SourceId = E.Id
		 INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id
		 INNER JOIN sOrderEntry.tTestDetail TD ON TD.Id = TRD.TestDetailId
		 INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
		 WHERE E.ParticipantSourceId = @rParticipantSourceId and E.ParticipantSourceTypeId = @rParticipantSourceTypeId
		 and TPM.StaticTestParameterId = 34 and ISNUMERIC(TRD.ServiceValue) = 1 
		 AND (CASE 
			  WHEN TRD.ServiceValue NOT LIKE '%[^0-9.]%' 
			  		AND TRD.ServiceValue <> ''
			  THEN CAST(TRD.ServiceValue AS FLOAT)
			  ELSE 0
		 END) > 0
		 order by E.Id desc)
	 END

	 select @rHeight as Height, @rWeight as [Weight], @rBMI as BMI, 
			@rBPSys as BPSys, @rBPDia as BPDia,
			@rHBA1C as HBA1C, @rLDL as LDL;
end


GO


CREATE OR ALTER PROCEDURE [sWellness].[pMHICategoryUpdationAddUpdate]
(
	@rId INT=0,
	@rParticipantSourceTypeId SMALLINT,
	@rParticipantSourceId BIGINT,
	@rHBA1CCategory SMALLINT,
	@rLDLCategory SMALLINT,
	@rBMICategory SMALLINT,
	@rBPCategory SMALLINT,
	@rStressCategory SMALLINT,
	@rLifestyleCategory SMALLINT,
	@rUserId BIGINT
)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRAN
			DECLARE @lNextNumber BIGINT 
			IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScoreUpdation] WHERE ParticipantSourceId = @rParticipantSourceId and ParticipantSourceTypeId = @rParticipantSourceTypeId)
			BEGIN
			INSERT INTO [sWellness].[tMHIScoreUpdation]
					(
						ParticipantSourceTypeId,
						ParticipantSourceId,
						InsertType,
						HBA1CCategory,
						LDLCategory,
						BMICategory,
						BPCategory,
						StressCategory,
						LifestyleCategory,
						CreatedUserId,
						CreatedDateTime
					)
					values
					(
						@rParticipantSourceTypeId,
						@rParticipantSourceId,
						2,
						@rHBA1CCategory,
						@rLDLCategory,
						@rBMICategory,
						@rBPCategory,
						@rStressCategory,
						@rLifestyleCategory,
						@rUserId,
						sCommon.fGetDate()
					)
	        SET @lNextNumber = SCOPE_IDENTITY();
			END
			ELSE
			BEGIN
				Update [sWellness].[tMHIScoreUpdation]
				SET 
					InsertType = 2,
					HBA1CCategory = @rHBA1CCategory,
					LDLCategory = @rLDLCategory,
					BMICategory = @rBMICategory,
					BPCategory = @rBPCategory,
					StressCategory = @rStressCategory,
					LifestyleCategory = @rLifestyleCategory,
					UpdatedUserId = @rUserId,
					UpdatedDateTime = sCommon.fGetDate()
				WHERE 
					ParticipantSourceId=@rParticipantSourceId 
				AND 
					ParticipantSourceTypeId = @rParticipantSourceTypeId

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

	BEGIN CATCH
		ROLLBACK TRAN
		Select -105 as Result
		select ERROR_MESSAGE()
	END CATCH		
END

GO


CREATE OR ALTER PROCEDURE [sExamination].[pHealthIndexParameterDetailAdd]
@rId int,
@rCount int, 
@rHealthIndexParameterId int,
@rFieldName nvarchar(50),
@rFromValue nvarchar(50),
@rToValue nvarchar(50),
@rPoints int,
@rGenderId tinyint,
@rIsDelete bit,
@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		--BEGIN TRY	
  -- BEGIN TRANSACTION
  
 Declare @lTypeId int
 SELECT @lTypeId= HealthIndexParameterTypeId from sExamination.tHealthIndexParameterMaster WHERE Id=@rHealthIndexParameterId AND OrgId = @rOrgId

IF(@rId = 0)
BEGIN

IF EXISTS (select 1 from sExamination.tHealthIndexParameterMaster HPM
INNER JOIN sExamination.tHealthIndexParameterDetail HPD ON HPD.HealthIndexParameterId=HPM.Id
WHERE HPM.HealthIndexParameterTypeId=@lTypeId AND HPM.OrgId = @rOrgId AND GenderId=@rGenderId AND HPD.FieldName like @rFieldName AND @lTypeId IN (4,5) AND @rCount=1) 
	BEGIN
			SELECT -200 AS Result
			RETURN
	END


 IF EXISTS (select 1 from sExamination.tHealthIndexParameterDetail where  FieldName = @rFieldName AND OrgId = @rOrgId AND GenderId=@rGenderId AND @rCount=1 AND @lTypeId IN (1,2,3,11,12))
	BEGIN
--Already Exists
		SELECT -200 AS Result
		RETURN
	END	  

	
	DECLARE @lNextNumber BIGINT     
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sExamination.tHealthIndexParameterDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	SELECT @lNextNumber = ISNULL(MAX(Id), 0) + 1
	FROM sExamination.tHealthIndexParameterDetail where OrgId = @rOrgId

	INSERT INTO sExamination.tHealthIndexParameterDetail
		(
			Id,
			HealthIndexParameterId,
			FieldName,
			FromValue,
			ToValue,
			Points,
			GenderId,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rHealthIndexParameterId,
			@rFieldName,
			@rFromValue,
			@rToValue,
			@rPoints,
			@rGenderId,
			@rOrgId
		)

	 EXEC sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sExamination.tHealthIndexParameterDetail', 
	 @rCurrentNumber = @lNextNumber

	END
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	 IF(@rIsDelete = 1)
		 BEGIN
	 DELETE FROM sExamination.tHealthIndexParameterDetail  WHERE Id = @rId 	
	 END
	
  END
  SELECT @lNextNumber AS Result
	 -- COMMIT TRANSACTION
  --       END TRY
         
  --      BEGIN CATCH
		--ROLLBACK TRANSACTION
		--SELECT -1 AS RESULT
	 --   END CATCH	
END


GO

CREATE OR ALTER PROCEDURE [sSupport].[pAHCCounsellingReferDoctor]
@rDoctorId bigint,
@rHealthIndicatorId int,
@rStatusId int, 
@rstrXML nvarchar(max),
@rCreatedUserId bigint,
@rOrgId int
as  
Begin
	BEGIN TRY
		 BEGIN TRANSACTION	
		 declare @lostrXML  xml
		 declare @empId bigint, @rDoctorName nvarchar(200) = '';

		 declare @lAssignDesignationConfigVal varchar(5);
            
		 select @lAssignDesignationConfigVal = sConfig.fConfigurationValueGet('Provider.AssignDesignationFreezeWiseOrEntityWise',@rOrgId,0,0,0)

		 Set @empId = (select SourceId  from sSecurity.tUser Where id = @rCreatedUserId And SourceTypeId = 95);

		IF (@rDoctorId > 0)
		BEGIN
			set @rDoctorName = (select ISNULL(FirstName, '') + ' ' + ISNULL(LastName, '') from sHrm.tEmployeeMaster where Id = @rDoctorId)
		END

		 set @lostrXML = cast(@rstrXML as xml)

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

			Create table #tbltmpAHCTeam
			(
				tid int identity(1,1),
				ProviderAppointmentId bigint,
				CSVNonPathoParameters nvarchar(max),
				HealthIndicatorCurrentStatus int
			)
			insert into #tbltmpAHCTeam
			select T.c.value('@ProviderAppointmentId','int') as ProviderAppointmentId,
			T.c.value('@CSVNonPathoParameters','nvarchar(max)') as CSVNonPathoParameters, 0
			from @lostrXML.nodes('/StatusChange/StatusData')T(c)

			update tmp set tmp.HealthIndicatorCurrentStatus = PA.HealthIndicatorId from #tbltmpAHCTeam tmp 
			INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = tmp.ProviderAppointmentId

			MERGE sSupport.tProviderAppointment AS TARGET
USING (SELECT * FROM #tbltmpAHCTeam) AS SOURCE
ON TARGET.Id = SOURCE.ProviderAppointmentId AND TARGET.OrgId = @rOrgId
WHEN MATCHED THEN
    UPDATE SET  
        HealthIndicatorId = @rHealthIndicatorId,
        AssignToDoctorId = @rDoctorId,
        UpdatedUserId = @rCreatedUserId,
        UpdatedDateTime = sCommon.fGetDate(),
		NonPathoParameters = CSVNonPathoParameters,
		AssignByDoctorId = @empId,
		AssignDate = sCommon.fGetDate(),
        StatusId = CASE 
                      WHEN @rHealthIndicatorId = 608 OR @rHealthIndicatorId = 611 OR @rHealthIndicatorId = 612 THEN @rStatusId 
					  WHEN @rHealthIndicatorId = 606 OR @rHealthIndicatorId = 607 THEN 609
                      ELSE TARGET.StatusId 
                   END;

			Insert into sSupport.tProviderAppointmentlog
			select AHCT.ProviderAppointmentId, CASE 
                      WHEN @rHealthIndicatorId = 608 OR @rHealthIndicatorId = 611 OR @rHealthIndicatorId = 612 THEN @rStatusId 
					  WHEN @rHealthIndicatorId = 606 OR @rHealthIndicatorId = 607 THEN 609
                      ELSE PA.StatusId END, 
					  @rCreatedUserId, sCommon.fGetDate(),'Refer to Doctor ' + @rDoctorName
			from #tbltmpAHCTeam AHCT
			INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId

			--Health Indicator Log
			Insert into sSupport.tProviderAppointmentHealthIndicatorLog
			select AHCT.ProviderAppointmentId, @rHealthIndicatorId, @rCreatedUserId, sCommon.fGetDate(),'Refer to Doctor ' + @rDoctorName
			from #tbltmpAHCTeam AHCT
			INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId

			if (@lAssignDesignationConfigVal = 'True' AND @rHealthIndicatorId = 606)
			BEGIN
				UPDATE tpa SET tpa.HealthIndicatorId = (CASE WHEN CAST(DetailsVital.BMI AS Float) >= 30 AND CAST(DetailsVital.BMI AS Float) <= 35 THEN 612
													WHEN CAST(DetailsVital.BloodPressureSystolic AS Float) >= 150 AND CAST(DetailsVital.BloodPressureSystolic AS Float) <= 160 THEN 612
													WHEN CAST(DetailsVital.BloodPressureDiastolic AS Float) >= 100 AND CAST(DetailsVital.BloodPressureDiastolic AS Float) <= 110 THEN 612
													WHEN CAST(Details.HB AS Float) >= 8 and CAST(Details.HB AS Float) < 10 THEN 612
													WHEN CAST(Details.HBA1C AS Float) >= 8 and CAST(Details.HBA1C AS Float) <= 10 THEN 612
													WHEN CAST(Details.[SERUM CREATININE] AS Float) >= 1.5 AND CAST(Details.[SERUM CREATININE] AS Float) <= 2 THEN 612
													WHEN CAST(Details.[SERUM URIC ACID] AS Float) >= 7.7 AND CAST(Details.[SERUM URIC ACID] AS Float) <= 9.4 THEN 612
													WHEN CAST(Details.[TRIGLYCERIDE] AS Float) >= 200 AND CAST(Details.[TRIGLYCERIDE] AS Float) <= 500 THEN 612
													WHEN CAST(Details.[LDL] AS Float) >= 150 AND CAST(Details.[LDL] AS Float) <= 200 THEN 612
													WHEN CAST(Details.[TSH] AS Float) >= 11 AND CAST(Details.[TSH] AS Float) <= 50 THEN 612
													WHEN CAST(Details.[PSA] AS Float) > 5 AND CAST(Details.[PSA] AS Float) <= 10 THEN 612
													--Mild
													WHEN CAST(DetailsVital.BMI AS Float) >= 26 AND CAST(DetailsVital.BMI AS Float) < 30 THEN 611
													WHEN CAST(DetailsVital.BloodPressureSystolic AS Float) >= 140 AND CAST(DetailsVital.BloodPressureSystolic AS Float) < 150 THEN 611
													WHEN CAST(DetailsVital.BloodPressureDiastolic AS Float) >= 90 AND CAST(DetailsVital.BloodPressureDiastolic AS Float) < 100 THEN 611
													WHEN CAST(Details.HB AS Float) >= 10 and CAST(Details.HB AS Float) < 12 THEN 611
													WHEN CAST(Details.HBA1C AS Float) >= 6.5 and CAST(Details.HBA1C AS Float) < 8 THEN 611
													WHEN CAST(Details.[SERUM CREATININE] AS Float) >= 1.3 AND CAST(Details.[SERUM CREATININE] AS Float) < 1.5 THEN 611
													WHEN CAST(Details.[SERUM URIC ACID] AS Float) >= 6.5 AND CAST(Details.[SERUM URIC ACID] AS Float) < 7.7 THEN 611
													WHEN CAST(Details.[TRIGLYCERIDE] AS Float) >= 150 AND CAST(Details.[TRIGLYCERIDE] AS Float) < 200 THEN 611
													WHEN CAST(Details.[LDL] AS Float) >= 101 AND CAST(Details.[LDL] AS Float) < 150 THEN 611
													WHEN CAST(Details.[TSH] AS Float) >= 5.6 AND CAST(Details.[TSH] AS Float) < 11 THEN 611
													Else 606 END),
							tpa.UpdatedDateTime = sCommon.fGetDate()
						FROM sSupport.tProviderAppointment AS tpa
						INNER JOIN #tbltmpAHCTeam AS ot ON ot.ProviderAppointmentId = tpa.Id
						INNER JOIN sExamination.tExamination AS EXM ON EXM.ParticipantSourceId = tpa.PatientSourceId AND EXM.SetupId = tpa.SetupId
						INNER JOIN sExamination.tSetupMaster AS STM ON STM.ID = EXM.SetupId
						INNER JOIN sExamination.tSubTypeMaster AS SSM ON SSM.Id = STM.SubTypeId
						INNER JOIN sIp.tStoreLocationMaster AS SLM ON SLM.Id = EXM.StoreLocationId
						LEFT JOIN  
						(
							SELECT ExaminationId, Details.[R.B.C. COUNT], Details.[MCV], Details.[F B S], Details.[CHOLESTEROL],  
								   Details.[TRIGLYCERIDE], Details.[LDL], Details.[HDL], Details.[SGPT],  
								   Details.[ECG], Details.[SONOGRAPHY], Details.[TMT], Details.[ECHO],  
								   Details.[HB], Details.[SERUM CREATININE], Details.[SERUM URIC ACID], [HBA1C], [R B S], [P P B S], 
								   Details.[Waist Circumference], Details.[TSH], Details.[PSA], Details.[XRAY]
							FROM sExamination.tExamination AS EXM
							LEFT JOIN
							(
								SELECT ExaminationId, [R.B.C. COUNT], [MCV], [F B S], [CHOLESTEROL], [TRIGLYCERIDE], [LDL], [HDL],  
									   [SGPT], [ECG], [SONOGRAPHY], [TMT], [ECHO], [HB], [SERUM CREATININE], [SERUM URIC ACID], [HBA1C], [R B S], [P P B S], 
									   [Waist Circumference], [TSH], [PSA], [XRAY]
								FROM  
								(
									SELECT SPM.Title, TR.SourceId [ExaminationId], TRD.ServiceValue  
									FROM sOrderEntry.tStaticTestParameterMaster AS SPM  
									INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id  
									INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id  
									INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id  
									INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId  
									WHERE SPM.Id in (3, 5, 19, 20, 21, 25, 31, 32, 33, 34, 38, 107, 104, 105, 109, 108, 2, 27, 49, 166, 54, 58)
								)
								d PIVOT
								(
									MIN(ServiceValue) FOR Title IN  
									(
										[R.B.C. COUNT], [MCV], [F B S], [CHOLESTEROL], [TRIGLYCERIDE], [LDL], [HDL], [SGPT],  
										[ECG], [SONOGRAPHY], [TMT], [ECHO], [HB], [SERUM CREATININE], [SERUM URIC ACID], [HBA1C], [R B S], [P P B S], 
										[Waist Circumference], [TSH], [PSA], [XRAY]
									)
								) piv
							) AS Details ON Details.ExaminationId = EXM.Id
						) AS Details ON Details.ExaminationId = EXM.Id
						LEFT JOIN 
						(
							SELECT TR.SourceId AS ExaminationId, TRD.Remark
							FROM sExamination.tTestRequestDetail TRD
							INNER JOIN sOrderEntry.tTestDetail TTD ON TTD.Id = TRD.TestDetailId
							INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TTD.TestParameterId
							INNER JOIN sOrderEntry.tStaticTestParameterMaster SPM ON SPM.Id = TPM.StaticTestParameterId
							INNER JOIN sExamination.tTestRequest TR ON TR.Id = TRD.TestRequestId
							WHERE SPM.Id = 108
						) AS ECHO_REMARKS ON ECHO_REMARKS.ExaminationId = EXM.Id
						LEFT JOIN 
						(
							SELECT TR.SourceId AS ExaminationId, TRD.Remark
							FROM sExamination.tTestRequestDetail TRD
							INNER JOIN sOrderEntry.tTestDetail TTD ON TTD.Id = TRD.TestDetailId
							INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TTD.TestParameterId
							INNER JOIN sOrderEntry.tStaticTestParameterMaster SPM ON SPM.Id = TPM.StaticTestParameterId
							INNER JOIN sExamination.tTestRequest TR ON TR.Id = TRD.TestRequestId
							WHERE SPM.Id = 107
						) AS ECG_REMARKS ON ECG_REMARKS.ExaminationId = EXM.Id
						LEFT JOIN
						 (
						  SELECT EXM.ID [ExaminationId],DetailsVital.[BMI],DetailsVital.[BloodPressureSystolic], DetailsVital.[BloodPressureDiastolic]
						  FROM sExamination.tExamination AS EXM  
						  LEFT JOIN
						  (
						   SELECT VTL.SourceId [ExaminationId],
						   ISNULL(BMI, 0) as BMI, 
						   ISNULL(BloodPressureSystolic, 0) as BloodPressureSystolic,
						   ISNULL(BloodPressureDiastolic, 0) as BloodPressureDiastolic
						   FROM sExamination.tVital AS VTL
						  ) AS DetailsVital ON DetailsVital.ExaminationId = EXM.Id
						 ) AS DetailsVital ON DetailsVital.ExaminationId = EXM.Id
						WHERE EXM.ParticipantSourceTypeId = 95 AND (ot.HealthIndicatorCurrentStatus = 607 OR ot.HealthIndicatorCurrentStatus = 608)
						AND EXM.OrgId = @rOrgId;

						UPDATE PA SET PA.AssignToDoctorId = SE.SiteDoctorId,
							   PA.HealthIndicatorId = (CASE WHEN SE.SiteDoctorId IS NULL THEN 606 ELSE PA.HealthIndicatorId END),
							   PA.AssignDate = sCommon.fGetDate()
						FROM sSupport.tProviderAppointment AS PA
						INNER JOIN #tbltmpAHCTeam AS ot ON ot.ProviderAppointmentId = PA.Id
						INNER JOIN sExamination.tExamination AS EXM ON EXM.ParticipantSourceId = PA.PatientSourceId AND EXM.SetupId = PA.SetupId
						INNER JOIN sExamination.tSetupEmployee AS SE ON SE.SetupId = EXM.SetupId AND SE.EmployeeId = EXM.ParticipantSourceId
						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 EM ON EM.Id = EXM.ParticipantSourceId
						WHERE EXM.ParticipantSourceTypeId = 95
						AND EXM.OrgId = @rOrgId AND (ot.HealthIndicatorCurrentStatus = 607 OR ot.HealthIndicatorCurrentStatus = 608)
						AND (PA.HealthIndicatorId = 611 OR PA.HealthIndicatorId = 612);

						UPDATE tpa SET tpa.StatusId=CASE WHEN HealthIndicatorId = 611 OR HealthIndicatorId = 612 THEN @rStatusId 
                                                         WHEN HealthIndicatorId = 606 THEN 609 ELSE TPA.StatusId END,
							tpa.UpdatedDateTime = sCommon.fGetDate()
						FROM sSupport.tProviderAppointment AS tpa
						INNER JOIN #tbltmpAHCTeam AS ot ON ot.ProviderAppointmentId = tpa.Id
						INNER JOIN sExamination.tExamination AS EXM ON EXM.ParticipantSourceId = tpa.PatientSourceId AND EXM.SetupId = tpa.SetupId
						WHERE EXM.ParticipantSourceTypeId = 95 AND (ot.HealthIndicatorCurrentStatus = 607 OR ot.HealthIndicatorCurrentStatus = 608)
						AND EXM.OrgId = @rOrgId;

						Insert into sSupport.tProviderAppointmentlog
						select AHCT.ProviderAppointmentId, PA.StatusId, @rCreatedUserId, sCommon.fGetDate(),
							   'Refer to Doctor ' + ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '')
						from #tbltmpAHCTeam AHCT
						INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId
						LEFT JOIN sHRM.tEmployeeMaster EM ON EM.Id = PA.AssignToDoctorId
						WHERE (AHCT.HealthIndicatorCurrentStatus = 607 OR AHCT.HealthIndicatorCurrentStatus = 608)

						--Health Indicator Log
						Insert into sSupport.tProviderAppointmentHealthIndicatorLog
						select AHCT.ProviderAppointmentId, PA.HealthIndicatorId, @rCreatedUserId, sCommon.fGetDate(),
							   'Refer to Doctor ' + ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '')
						from #tbltmpAHCTeam AHCT
						INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId
						LEFT JOIN sHRM.tEmployeeMaster EM ON EM.Id = PA.AssignToDoctorId
						WHERE (AHCT.HealthIndicatorCurrentStatus = 607 OR AHCT.HealthIndicatorCurrentStatus = 608)
			END

		
		COMMIT TRANSACTION
		SELECT 1 AS Result
	END TRY
	
	BEGIN CATCH 
		IF @@TRANCOUNT > 0
        ROLLBACK
		--SELECT -1 AS Result
		select ERROR_MESSAGE() 
	END CATCH	

end

GO


update sOrderEntry.tTestMaster set IsForOPD=1

GO




ALTER TABLE [sExamination].[tEmployeePrescription]
ADD DrugFrequencyPattern [nvarchar](200)

GO


CREATE TYPE [sWellness].[udt_MHIScoreUpdateThroughtSurveyBulk] AS TABLE(
	[EmployeeCode] [nvarchar](50) NOT NULL,
	[Stress] [numeric](10, 2) NULL,
	[LifeStyle] [numeric](10, 2) NULL
)

GO


CREATE OR ALTER PROCEDURE [sExamination].[pEmployeePrescriptionDetailGet]
@rPatientId bigint,
@rPatientSourceTypeId smallint
as
begin
	SELECT AutoId as Id,
	StockItemId,
	DrugInstruction AS InstructionName,
	SIM.Title AS StockItem,
	EPD.Remark,
	Dosage,
	Duration,
	ceiling(((Dosage * Duration * DF.DurgQuantity) / case when SIM.DrawSize = 0 then 1 else isnull(SIM.DrawSize,1) end)) * case when SIM.DrawSize = 0 then 1 else isnull(SIM.DrawSize,1) end AS Total,
	IsNotInStore,
	IsAllowDirectIssue AS IsDirectIssue,
	SIM.ItemSubGroupId AS SubGroupId,
	SIM.Reminder,
	sExamination.fMedicineTypeGet(SIM.ItemSubGroupId) as MedicineType,
	EPD.DurgDosageQty,
	EPD.DrugDosageFrequencyId,
	EPD.DrugDosageScheduleId,
	DF.DurgQuantity,
	DQ.Title,
	DF.Title as FreqText,
	DS.Title as SchedText,
	'' as ConsumeUOM,
	SIM.IsBatchWiseTracking, UOM.Title as UOM,
	ISNULL(EPD.DrugFrequencyPattern, '') as DrugFrequencyPattern
	FROM sExamination.tEmployeePrescription EPD	
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = EPD.stockItemId
	INNER JOIN sFinanceCommon.tStockUomMaster UOM ON UOM.Id = SIM.IssueStockUomId
	INNER JOIN sIp.tDrugDosageFrequencyMaster DF on EPD.DrugDosageFrequencyId = DF.Id
	INNER JOIN sIp.tDrugScheduleMaster DS on EPD.DrugDosageScheduleId = DS.Id
	INNER JOIN sIp.tDrugDosageQtyMaster DQ on EPD.DurgDosageQty = DQ.DosageQty
	where EPD.PatientSourceTypeId = @rPatientSourceTypeId and PatientSourceId = @rPatientId
end

GO


CREATE OR ALTER PROCEDURE [sExamination].[pGetAdditionalFieldConsultation]
@rSourceTypeId int = 3,
@rExaminationTypeId int = 17,
@rSourceId bigint = 0,
@rVisitPurposeId int = 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.VisitPurposeId, 0) = @rVisitPurposeId
		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 CAFM.Id from [sWellness].[tConsultationAdditionalFieldMaster] CAFM
				INNER JOIN [sWellness].[tWellnessConsultation] WC ON WC.Id = CAFM.ConsultationId
	           where ConsultationId = @rSourceId AND WC.CauseId = @rVisitPurposeId)
	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.VisitPurposeId, 0) = @rVisitPurposeId
			and (ISNULL(InS.ExaminationTypeId, 0) = @rExaminationTypeId OR @rExaminationTypeId = 0)
			AND (Isnull([AdditionalFieldId],0) = (Select Top 1 Id from [sWellness].[tConsultationAdditionalFieldMaster] where ConsultationId = @rSourceId))
			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.VisitPurposeId, 0) = @rVisitPurposeId
			and (ISNULL(InS.ExaminationTypeId, 0) = @rExaminationTypeId OR @rExaminationTypeId = 0)
			ORDER BY FieldOrder
	END
END
GO


CREATE OR ALTER PROCEDURE [sExamination].[pGetAppointmentRequestedMailDetail]
(
	@rAppointmentId BIGINT,	
	@rOrgId SMALLINT,
	@rEventId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;

	DECLARE 
		@DoctorId BIGINT,
		@PatientSourceTypeId SMALLINT,
		@PatientSourceId BIGINT,
		@DoctorName NVARCHAR(200)='',
		@EmployeeName NVARCHAR(200)= '',
		@AppointmentDate NVARCHAR(500),
		@Template NVARCHAR(MAX),
		@MailSubject NVARCHAR(MAX),
		@EmployeeEmailId NVARCHAR(200),
		@CoachEmailId NVARCHAR(200),
		@FromTime NVARCHAR(10),
		@ToTime NVARCHAR(10);

		SELECT 
			@DoctorId = APP.DoctorEmployeeId,
			@PatientSourceTypeId = APP.PatientSourceTypeId,
			@PatientSourceId = APP.PatientSourceId,
			@AppointmentDate = ISNULL(CONVERT(VARCHAR(20),APP.AppointmentDate,103),'-'),
			@FromTime = CASE WHEN TimeS.FromTime IS NOT NULL AND LTRIM(RTRIM(TimeS.FromTime)) <> '' THEN CONVERT(VARCHAR(5), CAST(TimeS.FromTime AS TIME), 108) ELSE NULL END,
			@ToTime = CASE WHEN TimeS.ToTime IS NOT NULL AND LTRIM(RTRIM(TimeS.ToTime)) <> '' THEN CONVERT(VARCHAR(5), CAST(TimeS.ToTime AS TIME), 108) ELSE NULL END
		FROM
			[sWellness].[tAppointment] APP
		LEFT JOIN
			[sAppointment].[tTimeSlotMaster] TimeS
		ON
			TimeS.Id = APP.TimeSlotId
		WHERE
			APP.Id = @rAppointmentId;

		IF (@FromTime IS NOT NULL OR @ToTime IS NOT NULL)
		BEGIN
			SET @AppointmentDate = @AppointmentDate + ' From '
				+ ISNULL(@FromTime, '')
				+ CASE WHEN @FromTime IS NOT NULL AND @ToTime IS NOT NULL THEN ' To ' ELSE '' END
				+ ISNULL(@ToTime, '');
		END

		

		SELECT 
			@DoctorName = Users.DisplayTitle 
		FROM 
			[sHRM].[tEmployeeMaster] EM 
		INNER JOIN
			[sSecurity].[tUser] Users
		ON
			Users.SourceId = EM.Id
		WHERE 
			EM.Id = @DoctorId


		SELECT @CoachEmailId = (
								 SELECT 
								 	EMPCOM.CompanyEmail 
								 FROM 
								 	[sHrm].[tEmployeeMaster] EMPMAS 
								 INNER JOIN 
								 	[sHrm].[tEmployeeCommunications] EMPCOM
								 ON
								 	EMPCOM.EmployeeId = EMPMAS.Id
								  WHERE 
								 	EMPMAS.Id = @DoctorId
							   )

		SELECT @Template = ET.Template, @MailSubject = ET.MailSubject FROM [sAlert].[tEventTemplate] ET WHERE EventId = @rEventId AND AlertModeId = 1

		IF(@PatientSourceTypeId = 95)
		BEGIN
			SELECT @EmployeeName = EMP.FirstName + ' ' + EMP.LastName FROM [sHrm].[tEmployeeMaster] EMP WHERE EMP.Id = @PatientSourceId
			SELECT @EmployeeEmailId = (
										SELECT 
											EMPCOM.CompanyEmail 
										FROM 
											[sHrm].[tEmployeeMaster] EMPMAS 
										INNER JOIN 
											[sHrm].[tEmployeeCommunications] EMPCOM
										ON
											EMPCOM.EmployeeId = EMPMAS.Id
										 WHERE 
											EMPMAS.Id = @PatientSourceId
									   ) 
		END
		ELSE IF(@PatientSourceTypeId = 1009)
		BEGIN
			SELECT 
				@EmployeeName = CSR.FirstName + ' ' + CSR.LastName,
				@EmployeeEmailId = EmailId
			FROM 
				[sHrm].[tCsrBenefiterMaster] CSR
			WHERE 
				CSR.Id = @PatientSourceId
		END

		SET @Template = REPLACE(@Template, '[CoachName]', @DoctorName);
		SET @Template = REPLACE(@Template, '[EmployeeName]', @EmployeeName); 
		SET @Template = REPLACE(@Template, '[AppointmentDateTime]', @AppointmentDate);


		IF(@rEventId = 115)
		BEGIN
			SELECT @MailSubject AS Subject , @Template AS MsgText, @CoachEmailId AS EmailId, @EmployeeEmailId AS strCC
		END
		ELSE IF(@rEventId = 116)
		BEGIN
			SELECT @MailSubject AS Subject , @Template AS MsgText, @EmployeeEmailId AS EmailId, @CoachEmailId AS strCC
		END
END
		
		GO
		
CREATE OR ALTER PROCEDURE [sExamination].[pGetEmployeeExaminationVisitDatasNg_New]
@rExaminationId bigint,
@rPageIndex int,
@rflg int,
@rPatientType int,
@rorg int,
@rexamID bigint
as
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
begin
	declare @header varchar(max)='',@res varchar(max)='',@lpaging varchar(max)='',@TotalRecords int,@PageSize int=500
	declare @rParticipantSourceTypeId int,@rEmployeeId bigint,@rOrgId int
	
	select @rParticipantSourceTypeId = @rPatientType,@rEmployeeId = @rExaminationId,@rOrgId = @rorg	
	
	declare @tbltmp table(tid int identity(1,1),exid bigint)
	create table #tbltmparchive (tid int identity(1,1),exid bigint)

	if @rflg = 1
	begin
		insert into @tbltmp
		select ED.Id from sExamination.tExamination ED
		left join sExamination.tDiagnosis D ON ED.Id=D.SourceId
		where ((ED.Id = @rexamID) or (@rexamID = 0))
		and OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
		and ParticipantSourceTypeId = @rParticipantSourceTypeId
		and ED.Id not in (select SourceId from sExamination.tPrescription Where IsDirect = 1)
		order by ED.Id desc
		OPTION (RECOMPILE)

		insert into #tbltmparchive
		select ED.Id from sExamination.tArchieveExamination ED
		left join sExamination.tArchieveDiagnosis D ON ED.Id=D.SourceId
		where ((ED.Id = @rexamID) or (@rexamID = 0))
		and OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
		and ParticipantSourceTypeId = @rParticipantSourceTypeId
		and ED.Id not in (select SourceId from sExamination.tArchievePrescription Where IsDirect = 1)
		order by ED.Id desc
		OPTION (RECOMPILE)
	end
	else
	begin
		insert into @tbltmp
		select ED.Id from sExamination.tExamination ED
		inner join sExamination.tSetupMaster SM on ED.SetupId = SM.Id
		inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
		left join sExamination.tDiagnosis D ON ED.Id=D.SourceId
		where ((ED.Id = @rexamID) or (@rexamID = 0))
		and ED.OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
		and ParticipantSourceTypeId = @rParticipantSourceTypeId and STM.MainTypeId = 8
		and ED.Id not in (select SourceId from sExamination.tPrescription Where IsDirect = 1)
		order by ED.Id desc
		OPTION (RECOMPILE)

		insert into #tbltmparchive
		select ED.Id from sExamination.tArchieveExamination ED
		inner join sExamination.tSetupMaster SM on ED.SetupId = SM.Id
		inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
		left join sExamination.tArchieveDiagnosis D ON ED.Id=D.SourceId
		where ((ED.Id = @rexamID) or (@rexamID = 0))
		and ED.OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
		and ParticipantSourceTypeId = @rParticipantSourceTypeId and STM.MainTypeId = 8
		and ED.Id not in (select SourceId from sExamination.tArchievePrescription Where IsDirect = 1)
		order by ED.Id desc
		OPTION (RECOMPILE)
	end
	
	select @TotalRecords = count(*)	from @tbltmp
	select @TotalRecords = @TotalRecords + count(*)	from #tbltmparchive
	select @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@rPageindex,@TotalRecords,@PageSize)

	--select * from @tbltmp
		
	select  isnull(Mt.Title,'') as MtTitle,
	 isnull(SL.Title,'') as SLTitle ,
	 convert(varchar(10),isnull(ED.ExaminationDate,''),103) as EDExamnationDate, 
	 isnull(SM.Title,'') as SMTitle,
    case when STM.MainTypeId = 8 then
	Convert(varchar(1000),isnull(sExamination.fDiseaseGet(ED.Id),'')) else Convert(varchar(1000),isnull(D.DiagnosisRemark,'')) end as DiagnosisRemark,
    case when STM.MainTypeId = 8 then '<b>Remark - </b>' + isnull(VIT.Remark, '') + CHAR(13) + CHAR(10) + '<b>FollowUp Remark - </b>' + isnull(APP.FollowupRemark, '')
	else convert(varchar(1000),isnull(D.RecommendationEnglish,'')) END as RecommendationEnglish, 
    convert(varchar,ED.Id) as EDId,
    convert(varchar,ED.ParticipantSourceId) as ParticipantSourceId,
    convert(varchar,ED.ParticipantSourceTypeId) as ParticipantSourceTypeId,
    case when ED.ParticipantSourceTypeId = 95 then convert(varchar,EP.GenderId)
    when ED.ParticipantSourceTypeId = 1001 then convert(varchar,EFD.GenderId) else
    convert(varchar,CS.GenderId) end  as GenderId,
    case when ED.ParticipantSourceTypeId = 95 then convert(varchar,isnull(datediff(yy,EP.DateOfBirth,getdate()),0))
    when ED.ParticipantSourceTypeId = 1001 then convert(varchar,isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)) else
    convert(varchar,isnull(datediff(yy,CS.DateOfBirth,getdate()),0)) end as Age,
    convert(varchar,STM.MainTypeId) as MainTypeId, convert(varchar,SM.Id) as SetupId,
	ParticipantCode = CASE ED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN CS.Code END,
	ParticipantName = CASE ED.ParticipantSourceTypeId WHEN 1009 THEN
	(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'')) end)
	WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END,
	ISNULL(ED.ExaminationNumber,'') AS ExaminationNumber
    from sExamination.tExamination ED
    inner join sIp.tStoreLocationMaster SL on ED.StoreLocationId = SL.Id
    inner join sExamination.tSetupMaster SM on ED.SetupId = SM.Id
	inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
	inner join sExamination.tMainTypeMaster Mt on STM.MainTypeId = Mt.Id
	left join sHrm.tEmployeeMaster EM on EM.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 95
	left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 1001
	left join sHrm.tCSRBenefiterMaster CS on CS.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	LEFT JOIN sExamination.tVital VIT ON VIT.SourceId = ED.Id
	LEFT JOIN sAppointment.tAppointment APP ON APP.ReferSourceId = ED.Id
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= ED.Id
	left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId
	left join sExamination.tDiagnosis D ON ED.Id=D.SourceId
	inner join @tbltmp tmp On tmp.exid = ED.Id
	where ((ED.Id = @rexamID) or (@rexamID = 0))
	and ED.OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
	and ParticipantSourceTypeId = @rParticipantSourceTypeId
	and ED.Id not in (select SourceId from sExamination.tPrescription Where IsDirect = 1)
	and tid	between ((@PageSize * (@rPageindex-1)) + 1) and (@PageSize * @rPageindex)
	and ISNULL(ED.IsCancel, 0) = 0
	order by ED.ExaminationDate desc
	OPTION (RECOMPILE)
	
	

	select 
	 isnull(Mt.Title,'') as MtTitle ,
	 isnull(SL.Title,'') as SLTitle,
	 convert(varchar(10),isnull(ED.ExaminationDate,''),103) as EDExamnationDate,
	 isnull(SM.Title,'') as SMTitle,
	 case when STM.MainTypeId = 8 then
	 Convert(varchar(1000),isnull(sExamination.fDiseaseGet(ED.Id),'')) else convert(varchar(1000),isnull(D.DiagnosisRemark,'')) end as DiagnosisRemark ,
	 case when STM.MainTypeId = 8 then '<b>Remark - </b>' + isnull(VIT.Remark, '') + CHAR(13) + CHAR(10) + '<b>FollowUp Remark - </b>' + isnull(APP.FollowupRemark, '')
	 else Convert(varchar(1000),isnull(D.RecommendationEnglish,'')) END as RecommendationEnglish,
	 convert(varchar,ED.Id)as EDId,
     convert(varchar,ED.ParticipantSourceId)as ParticipantSourceId,
     convert(varchar,ED.ParticipantSourceTypeId) as ParticipantSourceTypeId ,
     case when ED.ParticipantSourceTypeId = 95 then convert(varchar,EP.GenderId)
    when ED.ParticipantSourceTypeId = 1001 then convert(varchar,EFD.GenderId) else
    convert(varchar,CS.GenderId) end as GenderId,
    case when ED.ParticipantSourceTypeId = 95 then convert(varchar,isnull(datediff(yy,EP.DateOfBirth,getdate()),0))
    when ED.ParticipantSourceTypeId = 1001 then convert(varchar,isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)) else
    convert(varchar,isnull(datediff(yy,CS.DateOfBirth,getdate()),0)) end as Age,
    convert(varchar,STM.MainTypeId) as STMMainTypeId, convert(varchar,SM.Id) as SetupId,
	ParticipantCode = CASE ED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN CS.Code END,
	ParticipantName = CASE ED.ParticipantSourceTypeId WHEN 1009 THEN
	(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'')) end)
	WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END,
	ISNULL(ED.ExaminationNumber,'') AS ExaminationNumber
    from sExamination.tArchieveExamination ED
    inner join sIp.tStoreLocationMaster SL on ED.StoreLocationId = SL.Id
    inner join sExamination.tSetupMaster SM on ED.SetupId = SM.Id
	inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id	
	inner join sExamination.tMainTypeMaster Mt on STM.MainTypeId = Mt.Id
	left join sHrm.tEmployeeMaster EM on EM.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 95
	left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 1001
	left join sHrm.tCSRBenefiterMaster CS on CS.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	LEFT JOIN sExamination.tVital VIT ON VIT.SourceId = ED.Id
	LEFT JOIN sAppointment.tAppointment APP ON APP.ReferSourceId = ED.Id
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= ED.Id
	left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId
	left join sExamination.tArchieveDiagnosis D ON ED.Id=D.SourceId,#tbltmparchive 
	where exid = ED.Id and ((ED.Id = @rexamID) or (@rexamID = 0))
	and ED.OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
	and ParticipantSourceTypeId = @rParticipantSourceTypeId
	and ED.Id not in (select SourceId from sExamination.tArchievePrescription Where IsDirect = 1)
	and tid	between ((@PageSize * (@rPageindex-1)) + 1) and (@PageSize * @rPageindex)
	order by ED.ExaminationDate desc
	OPTION (RECOMPILE)
	
	select @res = isnull(@res,'')
	select @res as result,@lpaging as paging
	OPTION (RECOMPILE)
	Drop Table #tbltmparchive
	SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off
end

GO


CREATE OR ALTER PROCEDURE [sExamination].[pGetOPDReferToDoctorBasedOnDesignation]  
@rOrgId INT,  
@rDesignationId INT,  
@rEmployeeLocationId INT = 0,
@rEmployeeId bigint
AS  
BEGIN  
declare @lAssignDoctorFreezeWiseOrEntityWiseConfigVal varchar(5); 
            
 select @lAssignDoctorFreezeWiseOrEntityWiseConfigVal = sConfig.fConfigurationValueGet('Provider.AssignDoctorFreezeWiseOrEntityWise',@rOrgId,0,0,0);

 IF (@lAssignDoctorFreezeWiseOrEntityWiseConfigVal = 'TRUE')
 BEGIN
	 IF(@rDesignationId = 9)  
	 BEGIN  
		SELECT DISTINCT HeadEmployeeId as Id, ISNULL(
				CASE 
					WHEN EM.EmployeePrefix IS NULL OR EM.EmployeePrefix = '' 
					THEN EM.FirstName + ' ' + EM.LastName
					ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName
				END, 
			'') AS Title from sHrm.tEntityHead EH  
		  INNER JOIN sExamination.tSetupEmployee SE ON SE.SiteDoctorId = EH.HeadEmployeeId
		  INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.HeadEmployeeId
		  WHERE DesignationId = @rDesignationId and EM.OrgId = @rOrgId and SE.EmployeeId = @rEmployeeId
	 END  
	 ELSE IF(@rDesignationId = 10) 
	 BEGIN  
		  SELECT DISTINCT HeadEmployeeId as Id, ISNULL(
				CASE 
					WHEN EM.EmployeePrefix IS NULL OR EM.EmployeePrefix = '' 
					THEN EM.FirstName + ' ' + EM.LastName
					ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName
				END, 
			'') AS Title from sHrm.tEntityHead EH  
		  INNER JOIN sExamination.tSetupEmployee SE ON SE.CentralDoctorId = EH.HeadEmployeeId
		  INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.HeadEmployeeId
		  WHERE DesignationId = @rDesignationId and EM.OrgId = @rOrgId and SE.EmployeeId = @rEmployeeId
	 END
	 ELSE
	 BEGIN
		SELECT DISTINCT HeadEmployeeId as Id, ISNULL(
				CASE 
					WHEN EM.EmployeePrefix IS NULL OR EM.EmployeePrefix = '' 
					THEN EM.FirstName + ' ' + EM.LastName
					ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName
				END, 
			'') AS Title from sHrm.tEntityHead EH
			INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.HeadEmployeeId
			WHERE DesignationId = @rDesignationId
	 END
 END
 ELSE
 BEGIN
	 IF(@rDesignationId = 9)  
	 BEGIN  
		  SELECT DISTINCT HeadEmployeeId as Id, ISNULL(
				CASE 
					WHEN EM.EmployeePrefix IS NULL OR EM.EmployeePrefix = '' 
					THEN EM.FirstName + ' ' + EM.LastName
					ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName
				END, 
			'') AS Title from sHrm.tEntityHead EH  
		  INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.HeadEmployeeId  
		  WHERE DesignationId = @rDesignationId and OrgId = @rOrgId
		  and EntitySourceTypeId = 1014 and EntitySourceId IN (Select Id from sIp.tStoreLocationMaster where LocationId = @rEmployeeLocationId)
	 END  
	 ELSE IF(@rDesignationId = 10)
	 BEGIN  
		  SELECT DISTINCT HeadEmployeeId as Id,  ISNULL(
				CASE 
					WHEN EM.EmployeePrefix IS NULL OR EM.EmployeePrefix = '' 
					THEN EM.FirstName + ' ' + EM.LastName
					ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName
				END, 
			'') AS Title from sHrm.tEntityHead EH  
		  INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.HeadEmployeeId  
		  WHERE DesignationId = @rDesignationId and OrgId = @rOrgId  
	 END
	 ELSE
	 BEGIN
		SELECT DISTINCT HeadEmployeeId as Id, ISNULL(
				CASE 
					WHEN EM.EmployeePrefix IS NULL OR EM.EmployeePrefix = '' 
					THEN EM.FirstName + ' ' + EM.LastName
					ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName
				END, 
			'') AS Title from sHrm.tEntityHead EH
			INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.HeadEmployeeId
			WHERE DesignationId = @rDesignationId
	 END
 END
END

GO


CREATE OR ALTER PROCEDURE [sExamination].[pHealthIndexParameterDetailAdd]
@rId int,
@rCount int, 
@rHealthIndexParameterId int,
@rFieldName nvarchar(50),
@rFromValue nvarchar(50),
@rToValue nvarchar(50),
@rPoints int,
@rGenderId tinyint,
@rIsDelete bit,
@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		--BEGIN TRY	
  -- BEGIN TRANSACTION
  
 Declare @lTypeId int
 SELECT @lTypeId= HealthIndexParameterTypeId from sExamination.tHealthIndexParameterMaster WHERE Id=@rHealthIndexParameterId AND OrgId = @rOrgId

IF(@rId = 0)
BEGIN

IF EXISTS (select 1 from sExamination.tHealthIndexParameterMaster HPM
INNER JOIN sExamination.tHealthIndexParameterDetail HPD ON HPD.HealthIndexParameterId=HPM.Id
WHERE HPM.HealthIndexParameterTypeId=@lTypeId AND HPM.OrgId = @rOrgId AND GenderId=@rGenderId AND HPD.FieldName like @rFieldName AND @lTypeId IN (4,5) AND @rCount=1) 
	BEGIN
			SELECT -200 AS Result
			RETURN
	END


 IF EXISTS (select 1 from sExamination.tHealthIndexParameterDetail where  FieldName = @rFieldName AND OrgId = @rOrgId AND GenderId=@rGenderId AND @rCount=1 AND @lTypeId IN (1,2,3,11,12))
	BEGIN
--Already Exists
		SELECT -200 AS Result
		RETURN
	END	  

	
	DECLARE @lNextNumber BIGINT     
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sExamination.tHealthIndexParameterDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	SELECT @lNextNumber = ISNULL(MAX(Id), 0) + 1
	FROM sExamination.tHealthIndexParameterDetail where OrgId = @rOrgId

	INSERT INTO sExamination.tHealthIndexParameterDetail
		(
			Id,
			HealthIndexParameterId,
			FieldName,
			FromValue,
			ToValue,
			Points,
			GenderId,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rHealthIndexParameterId,
			@rFieldName,
			@rFromValue,
			@rToValue,
			@rPoints,
			@rGenderId,
			@rOrgId
		)

	 EXEC sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sExamination.tHealthIndexParameterDetail', 
	 @rCurrentNumber = @lNextNumber

	END
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	 IF(@rIsDelete = 1)
		 BEGIN
	 DELETE FROM sExamination.tHealthIndexParameterDetail  WHERE Id = @rId 	
	 END
	
  END
  SELECT @lNextNumber AS Result
	 -- COMMIT TRANSACTION
  --       END TRY
         
  --      BEGIN CATCH
		--ROLLBACK TRANSACTION
		--SELECT -1 AS RESULT
	 --   END CATCH	
END


GO


ALTER proc [sExamination].[pLSDDashboardGridGet]
@rOrgId int,
@rStoreLocationId int,
@rUserId bigint,
@rTypeId int,
@rtyp int,
@rsqlcondition varchar(50),
@rPageIndex int
as
begin
	declare @lResultHeader varchar(max) = '',@lResultGrid varchar(max) = '',@lResultPaging varchar(max)=''
	declare @lPageSize int = 100,@lCount int,@rFromDate varchar(100)='',@rToDate varchar(100)=''
	
	declare @SqlStatement nvarchar(max)='',@SqlSelect nvarchar(max)='',@SqlTables nvarchar(max)=''
	declare @SqlWheres nvarchar(max)='',@Sqlorders nvarchar(max)=''

	select @rToDate=convert(varchar,getdate(),102)
	if(@rTypeId=1)
	begin
		select @rFromDate = convert(varchar,dateadd(mm,-1,getdate()),102)
	end
	else if(@rTypeId=2)
	begin
		select @rFromDate = convert(varchar,dateadd(mm,-3,getdate()),102)
	end
	else if(@rTypeId=3)
	begin
		select @rFromDate = convert(varchar,dateadd(mm,-6,getdate()),102)
	end
	if(@rTypeId=4)
	begin
		select @rFromDate = convert(varchar,dateadd(mm,-12,getdate()),102)
	end
	
	if @rtyp = 0
	begin
		select @lResultHeader = @lResultHeader + '<tr><th align="left" scope="col">No</th>
		<th align="left" scope="col">Employee Code</th><th align="left" scope="col">Employee Name</th>
		<th align="left" scope="col">Department</th></tr>'
	end
	else if @rtyp = 1
	begin
		select @lResultHeader = @lResultHeader + '<tr><th align="left" scope="col">Department</th>
		<th align="left" scope="col">Employee Count</th></tr>'		
	end
	else
	begin
		select @lResultHeader = @lResultHeader + '<tr><th align="left" scope="col">Company</th><th align="left" scope="col">Employee Count</th></tr>'
	end
	IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL
		DROP TABLE #tbltmpEmployeeList

	CREATE TABLE #tbltmpEmployeeList
	(tid int identity(1,1),EmployeeCode varchar(300),EmployeeName varchar(300),DepartmentName varchar(300),
	CompanyName varchar(300),EmployeeId bigint)
	select @SqlSelect=@SqlSelect+'insert into #tbltmpEmployeeList
	select Distinct EMP.Code,isnull(EMP.FirstName,'''') + '' '' + isnull(EMP.LastName,''''),isnull(DPT.Title,''Not Assigned''),
	isnull(ECM.Title,''Not Assigned''),EMP.Id
	
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id = EXM.OrganizationDepartmentId
	LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM ON ECM.Id = EXM.EmployeeCompanyId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = ' + convert(varchar,@rOrgId) + '
	AND UL.UserId = ' + convert(varchar,@rUserId) + '
	AND (datediff(day,'''+@rFromDate+''',EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,'''+@rToDate+''')>=0 )
	AND '+ @rsqlcondition +''
	
	print @SqlSelect
	exec(@SqlSelect)

	declare @tbltmpEmployeeListDepartment table(tid int identity(1,1),EmployeeCnt varchar(300),DepartmentName varchar(300))
	insert into @tbltmpEmployeeListDepartment
	select count(EmployeeId),DepartmentName from #tbltmpEmployeeList group by DepartmentName
	
	declare @tbltmpEmployeeListCompany table(tid int identity(1,1),EmployeeCnt varchar(300),CompanyName varchar(300))
	insert into @tbltmpEmployeeListCompany
	select count(EmployeeId),CompanyName from #tbltmpEmployeeList group by CompanyName
	
	if @rtyp=0 -- Employee Wise List
	begin
		select @lCount = count(*) from #tbltmpEmployeeList
		select @lResultPaging = @lResultPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lCount,@lPageSize)
		
		select @lResultGrid = @lResultGrid + '<tr><td>' + convert(varchar,tid) + '</td>
		<td>' + isnull(EmployeeCode,'') + '</td><td>' + isnull(EmployeeName,'') + '</td>
		<td>' + isnull(DepartmentName,'') + '</td></tr>' from #tbltmpEmployeeList
		where tid between ((@lPageSize * (@rPageIndex-1)) + 1) and (@lPageSize * @rPageIndex)		
	end
	else if @rtyp =1 -- Department Wise List
	begin
		select @lCount = count(*) from @tbltmpEmployeeListDepartment
		select @lResultPaging = @lResultPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lCount,@lPageSize)
		
		select @lResultGrid = @lResultGrid + '<tr><td>' + isnull(DepartmentName,'') + '</td>
		<td>' + convert(varchar,EmployeeCnt) + '</td></tr>' from @tbltmpEmployeeListDepartment
		where tid between ((@lPageSize * (@rPageIndex-1)) + 1) and (@lPageSize * @rPageIndex)		
	end
	else -- Company Wise List
	begin
		select @lCount = count(*) from @tbltmpEmployeeListDepartment
		select @lResultPaging = @lResultPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lCount,@lPageSize)
		
		select @lResultGrid = @lResultGrid + '<tr><td>' + isnull(CompanyName,'') + '</td>
		<td>' + convert(varchar,EmployeeCnt) + '</td></tr>' from @tbltmpEmployeeListCompany
		where tid between ((@lPageSize * (@rPageIndex-1)) + 1) and (@lPageSize * @rPageIndex)		
	end
	
	select isnull(@lResultGrid,'') as result,isnull(@lResultHeader,'') as header,isnull(@lResultPaging,'') as Paging , isnull(@rtyp,0) AS ExportType
	select * from #tbltmpEmployeeList
end

GO

CREATE OR ALTER PROCEDURE [sExamination].[pPeriodicExaminationFreezeDataListGetforSurvey]
(
    @rSetupId INT = 0,
    @rOrgId INT = 0,
    @rDepartmentId NVARCHAR(MAX) = '',
    @rCode NVARCHAR(MAX) = '',
    @rName NVARCHAR(MAX) = '',
    @rDesignationId INT = 0,
    @rStatusId INT = 0,
    @rLocationId INT = 0,
    @rEmployeeStoreLocationId INT = 0,
    @rTargetGroupId INT = 0,
    @rDurationindays INT = 0,
    @rVerticalId INT = 0,
    @rSectorId INT = 0,
    @rCompanyId INT = 0,
    @GlobalSearch NVARCHAR(MAX) = ''
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @rAgeTo INT,
            @rAgeFrom INT;

    SELECT 
        @rAgeTo = AgeTo,
        @rAgeFrom = AgeFrom
    FROM sExamination.tSetupMaster 
    WHERE Id = @rSetupId;

    SELECT *
    FROM
    (
        SELECT DISTINCT
            SE.EmployeeId,
            EM.Code AS EmployeeCode,
            ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName
        FROM sExamination.tSetupEmployee SE
        INNER JOIN sExamination.tSetupMaster SEM ON SEM.Id = SE.SetupId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = SE.EmployeeId
        LEFT JOIN sHrm.tEmployeeJobDetail JD ON JD.EmployeeId = SE.EmployeeId
        LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = SE.EmployeeId
        LEFT JOIN sCommon.tOrganizationDepartmentMaster DM ON DM.Id = JD.OrganizationDepartmentId
        LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = JD.EmployeeDesignationId
        LEFT JOIN sExamination.tExamination E 
            ON E.ParticipantSourceId = SE.EmployeeId 
            AND E.SetupId = SE.SetupId
        LEFT JOIN sExamination.tStatusMaster SM ON SM.Id = E.StatusId
        LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = SE.EmployeeId
        LEFT JOIN sHrm.tEmployeeCompanyMaster ECM ON ECM.Id = JD.EmployeeCompanyId
        LEFT JOIN sHrm.tCompanyGroupMaster CGM ON CGM.Id = ECM.CompanyGroupId
        LEFT JOIN sHrm.tVerticalMaster VM ON VM.Id = CGM.VerticalId
        LEFT JOIN sHrm.tSectorMaster SCM ON SCM.Id = VM.SectorId
        LEFT JOIN sHrm.tEmployeeLegalEntitymaster ELEM ON ELEM.Id = JD.LegalEntityId

        LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id = SE.CentralDoctorId
        LEFT JOIN sHrm.tEmployeeMaster EM2 ON EM2.Id = SE.SiteDoctorId
        LEFT JOIN sHrm.tEmployeeMaster EM3 ON EM3.Id = SE.CentralSpocId
        LEFT JOIN sHrm.tEmployeeMaster EM4 ON EM4.Id = SE.SiteSpocId

        WHERE   
            SE.SetupId = @rSetupId  
            AND EM.OrgId = @rOrgId

            AND (
                EXISTS (
                    SELECT 1
                    FROM sCommon.fnsplit(@rCode, ',') s
                    WHERE 
                        (CHARINDEX(',', @rCode) = 0 AND EM.Code LIKE s.item + '%')
                        OR (CHARINDEX(',', @rCode) > 0 AND EM.Code = s.item)
                )
                OR ISNULL(@rCode,'') = '' 
                OR ISNULL(@rCode,'') = '*'
            )

            AND (
                EXISTS (
                    SELECT 1
                    FROM sCommon.fnsplit(@rName, ',') s
                    WHERE 
                        (CHARINDEX(',', @rName) = 0 AND EM.FirstName LIKE s.item + '%')
                        OR (CHARINDEX(',', @rName) > 0 AND EM.FirstName = s.item)
                )
                OR ISNULL(@rName,'') = '' 
                OR ISNULL(@rName,'') = '*'
            )

            AND (ISNULL(JD.OrganizationDepartmentId,0) IN 
                (SELECT item FROM sCommon.fnsplit(@rDepartmentId,',')) 
                OR ISNULL(@rDepartmentId,'')='')

           -- AND DATEDIFF(YY,EPD.DateOfBirth,sCommon.fGetDate()) BETWEEN @rAgeFrom AND @rAgeTo

            AND (JD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
            AND (SE.TargetGroupId = @rTargetGroupId OR @rTargetGroupId = 0)

            AND (
                (ISNULL(E.StatusId,0)=0 AND @rStatusId=101)
                OR (E.StatusId=@rStatusId AND @rStatusId<>0)
                OR (@rStatusId=0)
            )

            AND (
                (CASE 
                    WHEN SE.PlannedExaminationDate IS NULL 
                        THEN DATEDIFF(DD,[sExamination].[fGetLatExaminationDate](SE.EmployeeId),sCommon.fGetDate())
                    ELSE DATEDIFF(DD,sCommon.fGetDate(),SE.PlannedExaminationDate)
                END = @rDurationindays)
                OR @rDurationindays = 0
            )

            AND ISNULL(EM.IsObsolete,0)=0
            AND (VM.Id=@rVerticalId OR @rVerticalId=0)
            AND (SCM.Id=@rSectorId OR @rSectorId=0)
            AND (ECM.Id=@rCompanyId OR @rCompanyId=0)

    ) t
    WHERE 
        ISNULL(@GlobalSearch,'') = ''
        OR t.EmployeeCode LIKE '%' + @GlobalSearch + '%'
        OR t.EmployeeName LIKE '%' + @GlobalSearch + '%'
END

GO


CREATE OR ALTER PROCEDURE [sExamination].[pSaveAllExaminationDatas]     
@rVital varchar(max),                
@rAppointments varchar(max),                
@rDisese varchar(max),                
@rDiseaseDetails varchar(max),                
@rPrescription varchar(max),                
@rPrescriptionDetail varchar(max),                
@rComplaint varchar(max),                
@rTests varchar(max),                
@rReferrals varchar(max),                
@rOthers varchar(max),                
@rHabits varchar(max),                
@rLSDTests varchar(max),  
@rGroupItemPrescription varchar(max),
@rIsonSugarMedication bit=0,       
@rIsonBPMedication bit=0,             
@rIsNewLSD bit=0,
@rIsDataEntryTemplateModal bit=0
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 @lOrgId int,@lNextNumber bigint,@lFromNextNumber bigint,@lCount int,@rStoreLocationId int,@lExaminationId bigint,@lStorelocationId bigint                
 declare @lAppointmentid bigint,@rReferSourceId bigint,@i int,@tParticipantSourceId bigint,@lAppointmentType tinyint                
 declare @loNextNumber varchar(20),@lAppointmentDate varchar(50),@lAutoDispense varchar(50)                
                 
 declare @lxmlVital xml,@lxmlAppointment xml,@lxmlDisease xml,@lxmlDiseaseDetail xml,                
 @lxmlPrescription xml,@lxmlPrescriptionDetail xml,@lxmlCmplaint xml,@lxmlTests xml,                
 @lxmlReferral xml,@lxmlOthers xml,@lxmlGroupItemPrescription xml             
                 
 declare @exceptiondetail nvarchar(max),@rUserId bigint,@username nvarchar(200)                 
 BEGIN TRY                       
 set @lxmlVital = CAST(@rVital AS xml)                
 set @lxmlAppointment = CAST(@rAppointments AS xml)                
 set @lxmlDisease = CAST(@rDisese AS xml)                
 set @lxmlDiseaseDetail = CAST(@rDiseaseDetails AS xml)                
 set @lxmlPrescription = CAST(@rPrescription AS xml)                
 set @lxmlPrescriptionDetail = CAST(@rPrescriptionDetail AS xml)                
 set @lxmlCmplaint = CAST(@rComplaint AS xml)                
 set @lxmlTests = CAST(@rTests AS xml)                
 set @lxmlReferral = CAST(@rReferrals AS xml)                
 set @lxmlOthers = CAST(@rOthers AS xml)    
 set @lxmlGroupItemPrescription = CAST(@rGroupItemPrescription AS xml)
                  
 declare @tblVital table(tid int identity(1,1),v_ExamId bigint,v_OrgId int,v_TypeId int,v_Pulse varchar(50),v_Temp varchar(50),                
 v_BPSys varchar(50),v_BPDia varchar(50),v_Height varchar(50),v_BodyWeight varchar(50),v_Id bigint,v_CreatedUserId bigint,v_Remark varchar(max),            
 a_providerId int,v_Spo2 varchar(50))       
    
 insert into @tblVital                
 select T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@SourceTypeId','int') as SourceTypeId,                
 T.c.value('@Pulse','varchar(50)') as Pulse,                
 T.c.value('@Temprature','varchar(50)') as Temprature,                
 T.c.value('@BPSys','varchar(50)') as BPSys,                
 T.c.value('@BPDia','varchar(50)') as BPDia,                
 T.c.value('@Height','varchar(50)') as Height,                
 T.c.value('@BodyWaight','varchar(50)') as BodyWaight,null,                
 T.c.value('@CreatedUserId','bigint') as CreatedUserId,                
 T.c.value('@Remark','varchar(max)') as Remark,            
 T.c.value('@ProviderId','int') as ProviderId,    
 T.c.value('@SPO2','varchar(50)') as v_Spo2        
 from @lxmlVital.nodes('/Vitals/vital')T(c)                
      -- select * from @tblVital
              
 set @rUserId = (Select Top 1 v_CreatedUserId from @tblVital)                
 set @username =(select Top 1 ISNULL(LoginTitle,'') from sSecurity.tUser where id=ISNULL(@rUserId,0))  

 update w set w.v_Id = v.Id from @tblVital w inner join sExamination.tVital v on w.v_ExamId = v.SourceId 
 
 select @lOrgId = v_OrgId,@lExaminationId=v_ExamId from @tblVital           
 select @tParticipantSourceId =ParticipantSourceId,@lStorelocationId=isnull(storelocationid,0) from sExamination.tExamination where Id=@lExaminationId               
 
  Declare @rOPDNumber nvarchar(50)='';
  set @rOPDNumber = (select ExaminationNumber from sExamination.tExamination where Id = @lExaminationId);

  Declare @rProviderAppointmentId BIGINT = 0;
  set @rProviderAppointmentId = (select top 1 ISNULL(a_providerId, 0) from @tblVital);
  IF (@rProviderAppointmentId > 0)
  BEGIN
		update sSupport.tProviderAppointment set StatusId = 591 Where Id = @rProviderAppointmentId;
		
		Insert into sSupport.tProviderAppointmentlog
		select Id, 591, @rUserId, sCommon.fGetDate(),@rOPDNumber
		FROM [sSupport].[tProviderAppointment]
		Where Id = @rProviderAppointmentId
  END
 
 --Developer: Deval, Added Configuration for Dispence Qty.            
 declare @lEnableDispenseConfigVal varchar(5), @lAutoDispenseConfigVal varchar(5);            
            
 select @lEnableDispenseConfigVal = sConfig.fConfigurationValueGet('OPD.IsEnableDispenseInPrescription',@lOrgId,@lStoreLocationId,0,0)            
 select @lAutoDispenseConfigVal = sConfig.fConfigurationValueGet('Examination.IsAutoDispense',@lOrgId,@lStoreLocationId,0,0)            
 --Developer: Deval, Added Configuration for Dispence Qty.            
 BEGIN TRY                
 --begin transaction                
                 
 --BEGIN                
 --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tVital', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 --SET @lFromNextNumber = @lNextNumber - 1                
 --END                
                
 --select * from @tblVital                 
 --return                
                
 MERGE sExamination.tVital AS Target USING                 
 (                
  SELECT Id,v_Id,v_ExamId,v_OrgId,v_TypeId,v_Pulse,v_Temp,v_BPSys,                
  v_BPDia,v_Height,v_BodyWeight,v_CreatedUserId,v_Remark,tid ,v_Spo2               
  FROM @tblVital TT LEFT JOIN sExamination.tVital T with(nolock) ON TT.v_id = T.Id                
 ) AS Source ON Target.Id = Source.v_Id                
 WHEN MATCHED THEN                
  UPDATE SET Pulse = case when isnull(Source.v_pulse,'') <> '' then Source.v_pulse else null end,                
  BloodPressureSystolic = case when isnull(Source.v_BPSys,'') <> '' then Source.v_BPSys else null end,                
  BloodPressureDiastolic = case when isnull(Source.v_BPDia,'') <> '' then Source.v_BPDia else null end,         
  SPo2 = case when isnull(Source.v_Spo2,'') <> '' then Source.v_Spo2 else null end,        
  Temperature = case when isnull(Source.v_Temp,'') <> '' then Source.v_Temp else null end,                  
  Height = case when isnull(Source.v_Height,'') <> '' then Source.v_Height else null end,                
  BodyWeight = case when isnull(Source.v_BodyWeight,'') <> '' then Source.v_BodyWeight else null end,                
  BMI = case when isnull(Source.v_Height,'') <> '' and isnull(Source.v_BodyWeight,'') <> '' then                
  ROUND((CASE WHEN (Source.v_Height) = 0 THEN 0                
  ELSE CONVERT(DECIMAL(14, 6), ((Source.v_BodyWeight) / CAST(SQUARE((CASE WHEN (Source.v_Height) <= 0 THEN 1                
  ELSE CAST((Source.v_Height) AS DECIMAL(9, 6)) END)/ 100) AS DECIMAL(9, 6)))) END), 3) else BMI end,                  
  Remark = left([sSetup].[fPortalXMLTagsReplaceReverse](v_Remark),1000),                
  UpdatedDateTime=sCommon.fGetDate()                
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,SourceId,SourceTypeId,Pulse,Temperature,BloodPressureSystolic,BloodPressureDiastolic,Height,                
   BodyWeight,BMI,IsObsolete,CreatedUserId,CreatedDateTime,OrgId,Remark ,SPo2               
  )                
  VALUES                
  (                
   v_ExamId,v_ExamId,v_TypeId,                
   case when isnull(v_pulse,'') = '' then null else v_pulse end,                
   case when isnull(v_Temp,'')='' then null else v_Temp end,                
   case when isnull(v_BPSys,'')='' then null else v_BPSys end,                
   case when isnull(v_BPDia,'')='' then null else v_BPDia end,         
   case when isnull(v_Height,'')='' then null else v_Height end,                
   case when isnull(v_BodyWeight,'')='' then null else v_BodyWeight end,                
   case when isnull(v_Height,'') <> '' and isnull(v_BodyWeight,'') <> '' then           
   ROUND((CASE WHEN (v_height) = 0 THEN 0 ELSE CONVERT(DECIMAL(14, 6),((v_BodyWeight) / CAST(SQUARE((CASE WHEN (v_height) <= 0 THEN 1                 
   ELSE CAST((v_height) AS DECIMAL(9, 6)) END)/ 100) AS DECIMAL(9, 6)))) END), 3) else 0 end,                
   0,v_CreatedUserId,sCommon.fGetDate(),v_OrgId,  
   left([sSetup].[fPortalXMLTagsReplaceReverse](v_Remark),1000),  
   case when isnull(v_Spo2,'')='' then null else v_Spo2 end  
  );                
 --begin                
 --select @lCount = COUNT(1) FROM @tblVital                 
 --SET @lNextNumber  = @lCount + @lFromNextNumber                 
 --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tVital', @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 @lOrgId,'OPD_Vital_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 1              
 END CATCH                
 declare @tblAppointments 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, a_riskCategoryChecked int, o_VisitTypeId int)            
 insert into @tblAppointments                
 select T.c.value('@AppointmentId','bigint') as AppointmentId,                
 T.c.value('@ExaminationId','bigint') as ExaminationId,                
 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,   
 [sSetup].[fPortalXMLTagsReplaceReverse](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,            
 T.c.value('@RiskCategoryChecked','int') as RiskCategoryChecked,
 T.c.value('@VisitTypeId','int') as VisitTypeId
 from @lxmlAppointment.nodes('/Appointments/Appointment')T(c)            
                
--select * from @tblAppointments --m            
            
 update w set w.a_SubTypeId = s.SubTypeId from @tblAppointments w inner join sExamination.tSetupMaster s on s.Id = w.a_SetupId                
                  
 update @tblAppointments set a_AppointmentId = IsNull(Id,0) from sAppointment.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 @tblAppointments 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 @tblAppointments 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, @lRiskCategoryChecked bit;            
  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), @lRiskCategoryChecked = ISNULL(a_riskCategoryChecked, 0) from @tblAppointments            
            
  IF(@lRiskCategoryChecked = 1)            
  BEGIN            
   INSERT INTO [sExamination].[tLSDTrackerEmployee] (ParticipantSourceId, ParticipantSourceTypeId)              
  SELECT EXM.ParticipantSourceId, EXM.ParticipantSourceTypeId             
  FROM sExamination.tExamination EXM            
  WHERE EXM.Id = @lExamid            
  AND NOT EXISTS (            
   SELECT 1             
   FROM [sExamination].[tLSDTrackerEmployee] T            
   WHERE T.ParticipantSourceId = EXM.ParticipantSourceId            
   AND T.ParticipantSourceTypeId = EXM.ParticipantSourceTypeId            
  );            
    update [sExamination].[tLSDTrackerEmployee] set RiskCategoryId = 1            
    where ParticipantSourceId = @lEmpId and ParticipantSourceTypeId = 95            
            
    update [sExamination].[tExamination] set RiskCategoryId = 1 Where Id = @lExamid            
  END            
  ELSE            
  BEGIN            
         update [sExamination].[tLSDTrackerEmployee] set RiskCategoryId = 0           
    where ParticipantSourceId = @lEmpId and ParticipantSourceTypeId = 95         
   update [sExamination].[tExamination] set RiskCategoryId = 0 Where Id = @lExamid            
  END            
            
  if(ISNULL(@lAppointmentid,0)>0 and ISNULL(@lFollowUpRemark,'') != '')            
  BEGIN            
  update sAppointment.tAppointment set FollowupRemark = @lFollowUpRemark where Id = ISNULL(@lAppointmentid,0)            
  END            
                
  if(ISNULL(@lAppointmentid,0)>0)              
  begin               
  if exists (select 1 from  sAppointment.tAppointment where Id = ISNULL(@lAppointmentid,0) and ISNULL(@lAppointmentType,0) <> 1 and ISNULL(@lExamid,0) <> ReferSourceId)                 
  begin               
                
  update sAppointment.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 @tblAppointments 
 --where isnull(a_AppointmentId,0) = 0                
                  
 --if @lAppointmentid > 0      
 --begin                 
 -- update sAppointment.tAppointment set ReferSourceId = @rReferSourceId,IsRegister = 1 where Id = @lAppointmentid                
 --end                
 update E set E.VaccineDoseId=Isnull(t.a_VaccineId,0)                
 from sExamination.tExamination E                 
 inner join @tblAppointments t on t.a_ExamId=E.Id                
                
 if exists(Select 1 from @tblAppointments t inner join sExamination.tCauseMaster CM on CM.Id=t.a_CauseId where CM.CauseTypeId=4 and isnull(a_VaccineId,0)>0 and a_PatientSourceTypeId=95)                
  begin                
   Insert into [sSupport].[tVaccineLog](Orgid,SourceTypeId,SourceId,ParticipantSourceTypeId,ParticipantSourceId,VaccineDate,VaccineDoseId,StoreLocationId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime)                
   Select a_OrgId,1002,a_ExamId,a_PatientSourceTypeId,a_EmpId,E.ExaminationDate,a_VaccineId,a_StoreLocationId,0,a_CreatedUserId,sCommon.fGetDate(),a_CreatedUserId,sCommon.fGetDate()                
   From @tblAppointments t                
   inner join sExamination.tExamination E on E.id=t.a_ExamId                
   where a_ExamId not in (select SourceId from [sSupport].[tVaccineLog] where SourceTypeId=1002)              
                
   Declare @rVaccineId int=0                
    select @rVaccineId = Isnull(VM.Id,0)                
    From sSupport.tVaccineMaster VM                
    inner join sSupport.tVaccineDoseMaster VDM on VDM.VaccineId=VM.Id                
    where VDM.Id in (select Distinct a_VaccineId from @tblAppointments) and Isnull(VDM.IsCompleted,0)=1            
    print @rVaccineId                
    if(@rVaccineId>0)                
    begin                
    Insert into sHrm.tEmployeeVaccine (OrgId,EmployeeId,VaccineId,LastVaccineDate,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime)                
    Select a_OrgId,a_EmpId,@rVaccineId,E.ExaminationDate,0,a_CreatedUserId,sCommon.fGetDate(),a_CreatedUserId,sCommon.fGetDate()                
    From @tblAppointments t                
    inner join sExamination.tExamination E on E.id=t.a_ExamId                
    where t.a_EmpId not in (select EmployeeId From sHrm.tEmployeeVaccine where VaccineId=@rVaccineId)                 
                
    update EV set EV.LastVaccineDate=E.ExaminationDate,UpdatedUserId=a_CreatedUserId,UpdatedDateTime=sCommon.fGetDate()                
    From shrm.tEmployeeVaccine EV                
    inner join @tblAppointments t on t.a_EmpId=ev.EmployeeId      
    inner join sExamination.tExamination E on E.id=t.a_ExamId                
    where ev.VaccineId=@rVaccineId and t.a_EmpId in (select EmployeeId From sHrm.tEmployeeVaccine where VaccineId=@rVaccineId)                
              
 --Declare @rValidDateForNextDoseForSameVaccine datetime = '';              
 --  select @rValidDateForNextDoseForSameVaccine = dateadd(MM,Isnull(VTD.FrequencyDays,0),E.ExaminationDate)              
 --   from @tblAppointments VL               
 --   Inner join sSupport.tVaccineDoseMaster VDM on VDM.Id = VL.a_VaccineId              
 --   Inner join sSupport.tVaccineTypeDetail VTD on VTD.Id = VDM.VaccineTypeDetailId              
 --   inner join sSupport.tVaccineTypeMaster VTM on VTM.Id = VTD.VaccineTypeMasterId              
 --   inner join sSupport.tVaccineMaster VM on VM.Id = VTM.VaccineMasterId              
 --   inner join sExamination.tExamination E on E.id = VL.a_ExamId              
 --   where VL.a_OrgId=@lOrgId AND VL.a_EmpId = @tParticipantSourceId AND E.Id = @lExaminationId AND VM.Id = @rVaccineId              
              
 --update VL set VL.VaccineDueDate = @rValidDateForNextDoseForSameVaccine,UpdatedUserId=a_CreatedUserId,UpdatedDateTime=sCommon.fGetDate()                
 --   From [sSupport].[tVaccineLog] VL               
 --   inner join @tblAppointments t on t.a_EmpId = VL.ParticipantSourceId              
 --Where t.a_ExamId = @lExaminationId              
                
    end           
  end                
               
 if @lAppointmentDate <> ''                
 begin                
   IF NOT EXISTS (SELECT 1 FROM sAppointment.tAppointment WHERE ReferSourceId = @lExamid)
   BEGIN    
  exec sCommon.pPrefixSetupNextNumberGet @rOrgId = @lOrgId,@rPrefixFunctionalityId = 8,@rStoreLocationId = @rStoreLocationId,                
  @rNextNumber = @loNextNumber output                
                  
  update @tblAppointments set a_AppointNumber = @loNextNumber                
  begin try                
  --begin tran                
  begin                
                
  exec sCommon.pTableRowIdGet @lOrgId, 'sAppointment.tAppointment', 0, 1, 1,@outNextNumber = @lNextNumber output                 
  SET @lFromNextNumber = @lNextNumber - 1                
  end                
  --MERGE sAppointment.tAppointment AS Target USING                 
  --(                
  -- SELECT Id,a_AppointmentId,a_ExamId,a_doctorId,a_EmpId,a_obsolete,a_PatientSourceTypeId,                
  -- a_OrgId,a_AppointmentDate,a_StoreLocationId,a_FollowupRemark,a_SetupId,a_CauseId,                
  -- a_CreatedUserId,a_AppointNumber,a_OtherName,tid,Isnull(a_age,0) as a_age, Isnull(a_genderId, 0) as a_genderId            
  -- FROM @tblAppointments TT LEFT JOIN sAppointment.tAppointment T with(nolock) ON TT.a_AppointmentId = T.Id                
  --) AS Source ON Target.Id = Source.a_AppointmentId                 
  --WHEN NOT MATCHED THEN                
  -- INSERT                
  -- (                
  --  Id,PatientSourceId,PatientSourceTypeId,AppointmentDate,                
  --  AppointmentNumber,DoctorEmployeeId,FromTime,ToTime,IsRegister,                
  --  IsObsolete,OrgId,StatusId,ReferSourceId,ReferSourceTypeId,                
  --  StoreLocationId,SetupId,CauseId,OtherName,FollowupRemark,age,ApprovalStatusId, GenderId               
  -- )                
  -- VALUES                
  -- (                
  --  @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               
  -- );        

    DECLARE @AppointmentFlag VARCHAR(50);

    IF EXISTS(Select 1 from @tblAppointments t inner join sExamination.tCauseMaster CM on CM.Id=t.a_CauseId where CM.CauseTypeId=8)
	BEGIN
	     SET @AppointmentFlag = 'AHC Followup Appointment'; --AHC Consultation Follow-up Appointment
	END
	ELSE
	BEGIN
	     SET @AppointmentFlag = 'Followup Appointment'; --Normal Follow-up Appointment
	END
    INSERT INTO sAppointment.tAppointment               
   (                
    Id,PatientSourceId,PatientSourceTypeId,AppointmentDate,                
    AppointmentNumber,DoctorEmployeeId,FromTime,ToTime,IsRegister,                
    IsObsolete,OrgId,StatusId,ReferSourceId,ReferSourceTypeId,                
    StoreLocationId,SetupId,CauseId,VisitTypeId,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,o_VisitTypeId,                
    case when a_OtherName <> '' then a_OtherName else null end,left(a_FollowupRemark,1000),case when Isnull(a_age,0)=0 then null else a_age end,548, a_genderId,@AppointmentFlag            
   FROM @tblAppointments TT;     
  begin                
  select @lCount = COUNT(1) FROM @tblAppointments                 
  SET @lNextNumber  = @lCount + @lFromNextNumber                 
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sAppointment.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 @lOrgId,'OPD_tAppointment_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 2              
 END CATCH     
 END
 end                
 declare @tblDisease table(tid int identity(1,1),d_ExaminDiseaseId bigint,d_OrgId int,d_ExamId bigint,d_SourceTypeId int)                
 insert into @tblDisease                
 select T.c.value('@ExaminDiseaseId','bigint') as ExaminDiseaseId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@SourceTypeId','int') as SourceTypeId                
 from @lxmlDisease.nodes('/ExaminDisease/Disease')T(c)                
                 
 update w set w.d_ExaminDiseaseId = d.Id from @tblDisease w inner join sExamination.tExaminDisease d                
 on d.SourceId = w.d_ExamId                
 BEGIN TRY                 
 --begin tran                
 --begin                
 --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tExaminDisease', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 --SET @lFromNextNumber = @lNextNumber - 1                
 --end                
 MERGE sExamination.tExaminDisease AS Target USING                 
 (                
  SELECT Id,d_ExaminDiseaseId,d_OrgId,d_ExamId,d_SourceTypeId,tid                
  FROM @tblDisease TT LEFT JOIN sExamination.tExaminDisease T with(nolock) ON TT.d_ExaminDiseaseId = T.Id                
 ) AS Source ON Target.Id = Source.d_ExaminDiseaseId                 
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,SourceTypeId,SourceId,Remark,OrgId,IsObsolete                
  )                
  VALUES                
  (                
   d_ExamId,d_SourceTypeId,d_ExamId,'',d_OrgId,0                
  );                
 --begin                
 --select @lCount = COUNT(1) FROM @tblDisease                 
 --SET @lNextNumber  = @lCount + @lFromNextNumber                 
 --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tExaminDisease', @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 @lorgid,'OPD_ExaminDisease_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 3              
 END CATCH                
 update w set w.d_ExaminDiseaseId = d.Id from @tblDisease w inner join sExamination.tExaminDisease d                
 on d.SourceId = w.d_ExamId                
                  
 declare @tblDiseaseDetail table(tid int identity(1,1),dd_ExaminDiseaseId bigint,dd_OrgId int,dd_ExaminDiseaseDetailId bigint,                
 dd_DiseaseId int,dd_Remark varchar(max),dd_IsObsolete bit,dd_ExaminationId bigint)                
 insert into @tblDiseaseDetail                
 select T.c.value('@ExaminDiseaseId','bigint') as ExaminDiseaseId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@ExaminDiseaseDetailId','bigint') as ExaminDiseaseDetailId,                
 T.c.value('@DiseaseId','int') as DiseaseId,                
 T.c.value('@Remark','varchar(max)') as Remark,                
 T.c.value('@IsObsolete','bit') as IsObsolete,                
 T.c.value('@ExaminationId','bigint') as ExaminationId                
 from @lxmlDiseaseDetail.nodes('/ExaminDiseaseDetail/DiseaseDetail')T(c)                
                 
 update w set w.dd_ExaminDiseaseId = d.d_ExaminDiseaseId from @tblDiseaseDetail w inner join @tblDisease d                
 on w.dd_ExaminationId = d.d_ExamId                
                 
 update w set w.dd_ExaminDiseaseDetailId = d.Id from @tblDiseaseDetail w inner join sExamination.tExaminDiseaseDetail d                
 on w.dd_ExaminDiseaseId = d.ExaminDiseaseId and w.dd_DiseaseId = d.DiseaseId                
                
                 
                
 begin try                
 --begin tran                
                  
 --begin                 
 --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tExaminDiseaseDetail', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 --SET @lFromNextNumber = @lNextNumber - 1                
 --end                
 MERGE sExamination.tExaminDiseaseDetail AS Target USING                 
 (                
  SELECT Id,dd_ExaminDiseaseId,dd_OrgId,dd_ExaminDiseaseDetailId,dd_DiseaseId,                
  dd_Remark,dd_IsObsolete,dd_ExaminationId,tid                
  FROM @tblDiseaseDetail TT LEFT JOIN sExamination.tExaminDiseaseDetail T with(nolock) ON TT.dd_ExaminDiseaseDetailId = T.Id                
 ) AS Source ON Target.Id = Source.dd_ExaminDiseaseDetailId                 
 WHEN MATCHED THEN                
  UPDATE SET Remark = left([sSetup].[fPortalXMLTagsReplaceReverse](dd_Remark),600)                
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   ExaminDiseaseId,DiseaseId,Remark,OrgId,IsObsolete                
  )                
  VALUES                
  (                
   dd_ExaminDiseaseId,dd_DiseaseId,left([sSetup].[fPortalXMLTagsReplaceReverse](dd_Remark),600),dd_OrgId,dd_IsObsolete                
  );                
                 
 update w set w.IsObsolete = 1 from sExamination.tExaminDiseaseDetail w                
 inner join sExamination.tExaminDisease ED on w.ExaminDiseaseId = ED.Id                
 inner join @tblDiseaseDetail dd on ED.Id = dd.dd_ExaminDiseaseId                
 inner join @tblDisease d on ED.SourceId = d.d_ExamId                
 where w.Id not in                
 (                
  select dd_ExaminDiseaseDetailId from @tblDiseaseDetail                
 )                
 and DiseaseId not in                
 (                
  select dd_DiseaseId from @tblDiseaseDetail                
 )                
 --begin                
 --select @lCount = COUNT(1) FROM @tblDiseaseDetail                 
 --SET @lNextNumber  = @lCount + @lFromNextNumber                 
 --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tExaminDiseaseDetail', @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 @lorgid,'OPD_ExaminDiseaseDetail_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 4              
 END CATCH                
 declare @tblPrescription table(tid int identity(1,1),p_PrescriptionId bigint,p_OrgId int,p_DoctorId bigint,p_SourceTypeId int,                
 p_ExaminationId bigint,p_Remark varchar(max),p_CreatedUserId bigint,p_IsAutoDispense bit,p_IsDirect bit,p_IsDispense bit)                
 insert into @tblPrescription                
 select T.c.value('@PrescriptionId','bigint') as PrescriptionId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@DoctorId','bigint') as DoctorId,                
 T.c.value('@SourceTypeId','int') as SourceTypeId,                
 T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@Remark','varchar(max)') as IsObsolete,                
 T.c.value('@CreatedUserId','bigint') as CreatedUserId,                
 T.c.value('@IsAutoDispense','bit') as IsAutoDispense,                
 T.c.value('@IsDirect','bit') as IsDirect,                
 T.c.value('@IsDispense','bit') as IsDispense                
 from @lxmlPrescription.nodes('/ExaminPrescription/Prescription')T(c)                
                 
 update w set w.p_PrescriptionId = p.Id from @tblPrescription w inner join sExamination.tPrescription p on w.p_ExaminationId = p.SourceId                
 begin try                
 --begin tran                
                 
 --begin                
 --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tPrescription', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 --SET @lFromNextNumber = @lNextNumber - 1                
 --end                
 MERGE sExamination.tPrescription AS Target USING                 
 (                
  SELECT Id,p_PrescriptionId,p_OrgId,p_DoctorId,p_SourceTypeId,p_ExaminationId,                
  p_Remark,p_CreatedUserId,p_IsAutoDispense,p_IsDirect,tid                
  FROM @tblPrescription TT LEFT JOIN sExamination.tPrescription T with(nolock) ON TT.p_PrescriptionId = T.Id                
 ) AS Source ON Target.Id = Source.p_PrescriptionId                
 WHEN MATCHED THEN                
  UPDATE SET Remark = left([sSetup].[fPortalXMLTagsReplaceReverse](p_Remark),200),IsObsolete = 0,                
  CreatedUserId = p_CreatedUserId,UpdatedUserId=p_CreatedUserId                
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,SourceTypeId,SourceId,DoctorEmployeeId,Number,IsObsolete,CreatedUserId,CreatedDateTime,                
   IsDispensed,UpdatedDateTime,UpdatedUserId,Remark,OrgId,IsDirect                
  )                
  VALUES                
  (                
   p_ExaminationId,p_SourceTypeId,p_ExaminationId,p_CreatedUserId,p_ExaminationId,                
   0,p_CreatedUserId,sCommon.fGetDate(),0,sCommon.fGetDate(),p_CreatedUserId,left([sSetup].[fPortalXMLTagsReplaceReverse](p_Remark),200),                
   p_OrgId,p_IsDirect                
  );                
 --begin                
 --select @lCount = COUNT(1) FROM @tblPrescription                 
 --SET @lNextNumber  = @lCount + @lFromNextNumber                 
 --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tPrescription', @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 @lorgid,'OPD_Prescription_DBError',5000,@exceptiondetail,getdate()                
 -- Set @errorCount=-1                
 --END CATCH                
 update w set w.p_PrescriptionId = p.Id from @tblPrescription w inner join sExamination.tPrescription p on w.p_ExaminationId = p.SourceId                
               
 declare @tblPrescriptionDetail_temp table(tid int identity(1,1),pp_PrescriptionId bigint,pp_OrgId int,pp_PrescriptionDetailId bigint,                
 pp_StockItemId int,pp_DrugFrequencyId int,pp_DrugQuantity varchar(50),pp_Dosage varchar(50),pp_DrugFrequencyText varchar(200),                
 pp_DrugInstruction varchar(200),pp_DrugScheduleId int,pp_ExaminationId bigint,pp_StockRemark varchar(max),                
 pp_Duration varchar(50),pp_Total varchar(50),pp_IsAllowDirectIssue bit,pp_IsNotInStore bit,pp_IsDispensed bit,                
 pp_CreatedUserId bigint,pp_StoreLocationId int,pp_SourceTypeId int,pp_DispensedQty varchar(50),pp_QueueTypeId int,                
 pp_Isobsolete bit,pp_IsBatchWise bit,pp_StockBatchId int,pp_DispenseId bigint,pp_RemainQty decimal(12,2),                
 pp_AverageCost decimal(12,2),pp_InwardValue decimal(12,2),pp_DispenseBatchId bigint,pp_LocationId int,pp_ConsumeUOM varchar(100),pp_IsNew bit)                
              
 declare @tblPrescriptionDetail table(tid int identity(1,1),pp_PrescriptionId bigint,pp_OrgId int,pp_PrescriptionDetailId bigint,                
 pp_StockItemId int,pp_DrugFrequencyId int,pp_DrugQuantity varchar(50),pp_Dosage varchar(50),pp_DrugFrequencyText varchar(200),                
 pp_DrugFrequencyPattern varchar(200),pp_DrugInstruction varchar(200),pp_DrugScheduleId int,pp_ExaminationId bigint,pp_StockRemark varchar(max),                
 pp_Duration varchar(50),pp_Total varchar(50),pp_IsAllowDirectIssue bit,pp_IsNotInStore bit,pp_IsDispensed bit,                
 pp_CreatedUserId bigint,pp_StoreLocationId int,pp_SourceTypeId int,pp_DispensedQty varchar(50),pp_QueueTypeId int,                
 pp_Isobsolete bit,pp_IsBatchWise bit,pp_StockBatchId int,pp_DispenseId bigint,pp_RemainQty decimal(12,2),                
 pp_AverageCost decimal(12,2),pp_InwardValue decimal(12,2),pp_DispenseBatchId bigint,pp_LocationId int,pp_ConsumeUOM varchar(100),pp_IsNew bit)                
 insert into @tblPrescriptionDetail                
 select T.c.value('@PrescriptionId','bigint') as PrescriptionId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@PrescriptionDetailId','bigint') as PrescriptionDetailId,                
 T.c.value('@StockItemId','int') as StockItemId,                
 T.c.value('@DrugFrequencyId','int') as DrugFrequencyId,                
 T.c.value('@DrugQuantity','varchar(50)') as DrugQuantity,                
 T.c.value('@Dosage','varchar(50)') as Dosage,                
 T.c.value('@DrugFrequencyText','varchar(200)') as DrugFrequencyText,
 T.c.value('@DrugFrequencyPattern','varchar(200)') as DrugFrequencyPattern,
 T.c.value('@DrugInstruction','varchar(200)') as DrugInstruction,                
 T.c.value('@DrugScheduleId','int') as DrugScheduleId,                
 T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@StockRemark','varchar(max)') as StockRemark,                
 T.c.value('@Duration','varchar(50)') as Duration,                
 T.c.value('@Total','varchar(50)') as Total,                
 T.c.value('@IsAllowDirectIssue','bit') as IsAllowDirectIssue,                
 T.c.value('@IsNotInStore','bit') as IsNotInStore,                
 T.c.value('@IsDispensed','bit') as IsDispensed,                
 T.c.value('@CreatedUserId','bigint') as CreatedUserId,                
 T.c.value('@StoreLocationId','int') as StoreLocationId,                
 T.c.value('@SourceTypeId','int') as SourceTypeId,                
 T.c.value('@DispensedQty','varchar(50)') as DispensedQty,                
 T.c.value('@QueueTypeId','int') as QueueTypeId,                
 T.c.value('@Isobsolete','bit') as Isobsolete,null,                
 T.c.value('@StockItemId','int') as StockItemId,null,null,null,null,null,                
 T.c.value('@LocationId','int') as LocationId,                
 T.c.value('@ConsumeUOM','varchar(100)') as ConsumeUOM ,0               
 from @lxmlPrescriptionDetail.nodes('/ExaminPrescriptionDetail/Prescription')T(c)                
                 
 update w set w.pp_PrescriptionId = p.p_PrescriptionId from @tblPrescriptionDetail w inner join @tblPrescription p                
 on w.pp_ExaminationId = p.p_ExaminationId                
               
 update @tblPrescriptionDetail set pp_IsNew = 1 where pp_PrescriptionDetailId = 0              
              
--Developer: Deval, Added IF Codition For Visit Purpose Type Daycare            
 IF NOT EXISTS(Select 1 from @tblAppointments t inner join sExamination.tCauseMaster CM on CM.Id=t.a_CauseId where CM.CauseTypeId=6)            
 BEGIN            
  update w set w.pp_PrescriptionDetailId = p.Id from @tblPrescriptionDetail w inner join sExamination.tPrescriptionDetail p                
  on w.pp_PrescriptionId = p.PrescriptionId and w.pp_StockItemId = p.StockItemId                
 END            
--Developer: Deval, Added IF Codition For Visit Purpose Type Daycare            
            
 update w set w.pp_IsBatchWise = p.IsBatchWiseTracking from @tblPrescriptionDetail w inner join sIp.tStockItemMaster p                
 on w.pp_StockItemId = p.Id                
                 
 update w set w.pp_StockBatchId = p.Id from @tblPrescriptionDetail w inner join sProcurement.tStockBatch p                
 on w.pp_StockItemId = p.StockItemId and p.StoreLocationId = w.pp_StoreLocationId and p.OrgId = w.pp_OrgId                
 and isnull(p.Number,'') = ''                
                 
 update w set w.IsObsolete = 1 from sExamination.tPrescriptionDetail w inner join @tblPrescriptionDetail                
 on w.PrescriptionId = pp_PrescriptionId                
 where Id not in (select pp_PrescriptionDetailId from @tblPrescriptionDetail)                
 --begin try                 
 --begin tran                
                 
 begin                
            
 Declare @rBatchAvl int = 0, @rUpDateBatchAvl int = 0; --Developer: Deval            
            
 Set @rBatchAvl = (select count(*) from @tblPrescriptionDetail Where pp_IsBatchWise = 1) --Developer: Deval            
            
 exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tPrescriptionDetail', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 SET @lFromNextNumber = @lNextNumber - 1                
 end                
 MERGE sExamination.tPrescriptionDetail AS Target USING                 
 (                
  SELECT Id,pp_PrescriptionId,pp_OrgId,pp_PrescriptionDetailId,                
  pp_StockItemId,pp_DrugFrequencyId,pp_DrugQuantity,pp_Dosage,pp_DrugFrequencyText,pp_DrugFrequencyPattern,                
  pp_DrugInstruction,pp_DrugScheduleId,pp_ExaminationId,pp_StockRemark,                
  pp_Duration,pp_Total,pp_IsAllowDirectIssue,pp_IsNotInStore,pp_IsDispensed, pp_DispensedQty,            
  pp_CreatedUserId,pp_StoreLocationId,pp_SourceTypeId,pp_QueueTypeId,pp_Isobsolete,pp_ConsumeUOM,tid                
  FROM @tblPrescriptionDetail TT LEFT JOIN sExamination.tPrescriptionDetail T with(nolock) ON TT.pp_PrescriptionDetailId = T.Id                
 ) AS Source ON Target.Id = Source.pp_PrescriptionDetailId                 
 WHEN MATCHED THEN                
  UPDATE SET Remark = left([sSetup].[fPortalXMLTagsReplaceReverse](pp_StockRemark),400),IsObsolete = 0,Duration = pp_Duration,                
  PrescribedQuantity = pp_Total,CreatedUserId = pp_CreatedUserId,UpdatedUserId = pp_CreatedUserId,                
  IsDirectIssue = pp_IsAllowDirectIssue,IsNotInStore = pp_IsNotInStore,DrugInstruction = pp_DrugInstruction,                
  Dosage = pp_Dosage,DurgDosageQty = pp_Dosage,DrugDosageFrequencyId = pp_DrugFrequencyId,                
  DrugFrequencyPattern = pp_DrugFrequencyPattern,DrugDosageScheduleId = pp_DrugScheduleId,ConsumeUOM = pp_ConsumeUOM             
  --DispensedQuantity = (Case When (@rBatchAvl > 0 and ISNULL(@lAutoDispenseConfigVal,'False') = 'True' and ISNULL(pp_IsDispensed,0) = 0) Then 0 Else pp_DispensedQty END) --Developer: Deval, Added Case            
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,PrescriptionId,StockItemId,DrugInstruction,Duration,Remark,                
  PrescribedQuantity,IsDirectIssue,IsObsolete,CreateduserId,UpdatedUserId,                
   IsDispensed,UpdatedDateTime,OrgId,DispensedQuantity,IsNotInStore,Dosage,                
   DurgDosageQty,DrugDosageFrequencyId,DrugFrequencyPattern,DrugDosageScheduleId,ConsumeUOM                
  )                
  VALUES                
  (                
   @lFromNextNumber + tid,pp_PrescriptionId,pp_StockItemId,pp_DrugInstruction,pp_Duration,                
   left([sSetup].[fPortalXMLTagsReplaceReverse](pp_StockRemark),400),                
   pp_Total,pp_IsAllowDirectIssue,0,pp_CreatedUserId,pp_CreatedUserId,0,                
   sCommon.fGetDate(),pp_OrgId,pp_DispensedQty,pp_IsNotInStore,pp_Dosage,
   pp_Dosage,pp_DrugFrequencyId,pp_DrugFrequencyPattern,pp_DrugScheduleId,pp_ConsumeUOM                
  ); --Developer: Deval, Added Case Statement for @rBatchAvl            
 begin                
 select @lCount = COUNT(1) FROM @tblPrescriptionDetail                 
 SET @lNextNumber  = @lCount + @lFromNextNumber                 
 exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tPrescriptionDetail', @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 @lorgid,'OPD_PrescriptionDetail_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 5              
 END CATCH  
 
 BEGIN TRY
 BEGIN
	 declare @tblGroupItemPrescriptionData table(tid int identity(1,1),pp_PrescriptionDetailId bigint,pp_GroupItemId int,
	 pp_StockBatchId int,pp_Quantity varchar(50),pp_OrgId int,pp_CreatedUserId bigint)                
	 insert into @tblGroupItemPrescriptionData                
	 select              
	 T.c.value('@PrescriptionDetailId','bigint') as PrescriptionDetailId, 
	 T.c.value('@GroupItemId','int') as GroupItemId,
	 T.c.value('@StockBatchId','int') as StockBatchId,     
	 T.c.value('@Quantity','varchar(50)') as Quantity,
	 T.c.value('@OrgId','int') as OrgId,
	 T.c.value('@CreatedUserId','bigint') as CreatedUserId
	 from @lxmlGroupItemPrescription.nodes('/GroupItemPrescriptionData/GroupItem')T(c)  
	 
	 --Delete If Unchecked From Group Item Tray
	 DELETE OGIT from sExamination.tOPDGroupItemTrack OGIT
	INNER JOIN sExamination.tPrescriptionDetail T ON T.Id = OGIT.PrescriptionDetailId     
	INNER JOIN sExamination.tPrescription PRE ON PRE.Id = T.PrescriptionId
	Where PRE.SourceId = @lExaminationId
		  AND NOT EXISTS (
			SELECT 1
			FROM @tblGroupItemPrescriptionData TMP
			WHERE TMP.pp_StockBatchId = OGIT.StockBatchId
			  AND TMP.pp_GroupItemId = OGIT.GroupItemId
	  )

	exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tOPDGroupItemTrack', 0, 1, 1,@outNextNumber = @lNextNumber output                 
	 SET @lFromNextNumber = @lNextNumber - 1                
 END               
 MERGE sExamination.tOPDGroupItemTrack AS Target USING
 (                
  SELECT tid, T.Id as PrescriptionDetailId, pp_GroupItemId, pp_StockBatchId, pp_Quantity, pp_OrgId, pp_CreatedUserId 
  FROM @tblGroupItemPrescriptionData TT 
  LEFT JOIN sExamination.tPrescriptionDetail T with(nolock) ON T.StockItemId = TT.pp_GroupItemId      
  LEFT JOIN sExamination.tPrescription PRE ON PRE.Id = T.PrescriptionId
  WHERE PRE.SourceId = @lExaminationId
 ) AS Source ON Target.PrescriptionDetailId = Source.PrescriptionDetailId and Target.StockBatchId = Source.pp_StockBatchId          
 WHEN MATCHED THEN                
  UPDATE SET Target.Quantity=pp_Quantity, UpdatedUserId=pp_CreatedUserId, UpdatedDateTime=sCommon.fGetDate()
 WHEN NOT MATCHED THEN
  INSERT                
  (                
   Id,PrescriptionDetailId,GroupItemId,StockBatchId,Quantity,OrgId,IsObsolete,
   CreateduserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime           
  )                
  VALUES                
  (                
   @lFromNextNumber + tid,Source.PrescriptionDetailId,pp_GroupItemId,pp_StockBatchId,pp_Quantity,pp_OrgId,0,             
   pp_CreatedUserId, sCommon.fGetDate(), pp_CreatedUserId, sCommon.fGetDate()          
  );     
 begin                
 select @lCount = COUNT(1) FROM @tblGroupItemPrescriptionData          
 SET @lNextNumber  = @lCount + @lFromNextNumber
 exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tOPDGroupItemTrack', @rCurrentNumber = @lNextNumber
 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 @lorgid,'OPD_OPDGroupItemTrack_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 13           
 END CATCH
            
 --Developer: Deval, Added IF Codition For Visit Purpose Type Daycare            
 IF NOT EXISTS(Select 1 from @tblAppointments t inner join sExamination.tCauseMaster CM on CM.Id=t.a_CauseId where CM.CauseTypeId=6)            
 BEGIN            
  update w set w.pp_PrescriptionDetailId = p.Id from @tblPrescriptionDetail w inner join sExamination.tPrescriptionDetail p                
  on w.pp_PrescriptionId = p.PrescriptionId and w.pp_StockItemId = p.StockItemId                
 END            
 ELSE            
  BEGIN            
  update w set w.pp_PrescriptionDetailId = p.Id from @tblPrescriptionDetail w inner join sExamination.tPrescriptionDetail p                
  on w.pp_PrescriptionId = p.PrescriptionId and w.pp_StockItemId = p.StockItemId Where p.Id = @lFromNextNumber + tid            
 END            
 --Developer: Deval, Added IF Codition For Visit Purpose Type Daycare            
                 
 select top 1 @lAutoDispense = p_IsAutoDispense from @tblPrescription                
                
 IF @lAutoDispense <> '0' and (select count(*) from @tblPrescriptionDetail where pp_IsBatchWise = 0) > 0 and (select count(*) from @tblPrescriptionDetail where pp_IsBatchWise = 1 AND isnull(pp_IsNotInStore,0) = 1) > 0            
 BEGIN  --Developer: Deval, Date: 19/10/1023            
  UPDATE P SET P.IsDispensed = 1                
  FROM sExamination.tPrescription P with(ROWLOCK) inner join @tblPrescription w on P.Id = w.p_PrescriptionId            
 END            
            
 IF @lAutoDispense <> '0' and (select count(*) from @tblPrescriptionDetail where pp_IsBatchWise = 0) > 0 and (select count(*) from @tblPrescriptionDetail where pp_IsBatchWise = 1) = 0 -- 0019030; Nidhi Pandey; DT- 18/05/2022              
 begin               
              
 -- Delete from @tblPrescriptionDetail where pp_IsNew = 0              
              
   -- *** insert data into temp table for temporary to set proper tid value ***---              
                
 insert into @tblPrescriptionDetail_temp (pp_PrescriptionId ,pp_OrgId ,pp_PrescriptionDetailId , pp_StockItemId ,pp_DrugFrequencyId ,pp_DrugQuantity ,pp_Dosage ,              
 pp_DrugFrequencyText , pp_DrugInstruction ,pp_DrugScheduleId ,pp_ExaminationId ,pp_StockRemark , pp_Duration ,pp_Total ,pp_IsAllowDirectIssue ,pp_IsNotInStore ,              
 pp_IsDispensed , pp_CreatedUserId ,pp_StoreLocationId ,pp_SourceTypeId ,pp_DispensedQty,pp_QueueTypeId ,                
  pp_Isobsolete ,pp_IsBatchWise ,pp_StockBatchId ,pp_DispenseId ,pp_RemainQty,  pp_AverageCost ,pp_InwardValue ,pp_DispenseBatchId ,pp_LocationId ,pp_ConsumeUOM,pp_IsNew)              
   select pp_PrescriptionId , pp_OrgId ,pp_PrescriptionDetailId , pp_StockItemId ,pp_DrugFrequencyId ,pp_DrugQuantity ,pp_Dosage ,pp_DrugFrequencyText , pp_DrugInstruction ,pp_DrugScheduleId ,pp_ExaminationId ,pp_StockRemark , pp_Duration ,pp_Total ,    
  
    
      
        
          
pp_IsAllowDirectIssue ,pp_IsNotInStore ,pp_IsDispensed , pp_CreatedUserId ,pp_StoreLocationId ,pp_SourceTypeId ,pp_DispensedQty,pp_QueueTypeId ,                
  pp_Isobsolete ,pp_IsBatchWise ,pp_StockBatchId ,pp_DispenseId ,pp_RemainQty,  pp_AverageCost ,pp_InwardValue ,pp_DispenseBatchId ,pp_LocationId ,pp_ConsumeUOM,pp_IsNew from              
  @tblPrescriptionDetail where pp_IsNew = 1              
              
   -- *** insert data into temp table for temporary to set proper tid value ***---              
                
  UPDATE P SET P.IsDispensed = p_IsDispense                
  FROM sExamination.tPrescription P inner join @tblPrescription w on P.Id = w.p_PrescriptionId                
  inner join @tblPrescriptionDetail_temp wt ON wt.pp_PrescriptionId = w.p_PrescriptionId Where isnull(wt.pp_IsNotInStore,0) = 0 --Developer: Deval, Date: 19/10/1023            
                  
  UPDATE PD SET PD.DispensedQuantity = case when isnull(pp_IsNotInStore,0) = 0 then             
  (case When (@lAutoDispenseConfigVal = 'True' and @lEnableDispenseConfigVal = 'True') then PD.DispensedQuantity Else pp_Total END) --Developer: Deval            
  else 0 end            
  FROM sExamination.tPrescriptionDetail PD inner join @tblPrescriptionDetail_temp w ON PD.Id = w.pp_PrescriptionDetailId                
                  
  UPDATE P SET P.DirectIssuedCount = 1 + P.DirectIssuedCount                
  FROM sExamination.tPrescriptionDirect P INNER JOIN sExamination.tPrescriptionDirectDetail PD                
  ON P.Id = PD.PrescriptionDirectId inner join @tblPrescriptionDetail_temp w ON PD.Id = w.pp_PrescriptionDetailId                
  where pp_QueueTypeId = 2 and pp_Isobsolete = 1                
                  
  UPDATE e SET e.StatusId = 4 from sExamination.tExamination e inner join                
  @tblPrescription w on w.p_ExaminationId = e.Id                
                  
  update w set w.pp_DispenseId = p.Id from @tblPrescriptionDetail_temp w inner join sPharmacy.tDispense p                
  on w.pp_PrescriptionDetailId = p.PrescriptionDetailId                
  begin try                
  --begin tran                
                  
begin                
  exec sCommon.pTableRowIdGet @lOrgId, 'sPharmacy.tDispense', 0, 1, 1,@outNextNumber = @lNextNumber output                 
  SET @lFromNextNumber = @lNextNumber - 1               
  print @lNextNumber              
  end                
  MERGE sPharmacy.tDispense AS Target USING                 
  (                
   SELECT T.Id,pp_PrescriptionDetailId,pp_CreatedUserId,pp_OrgId,pp_IsNotInStore,tid                
   FROM @tblPrescriptionDetail_temp TT LEFT JOIN sPharmacy.tDispense T with(nolock) ON TT.pp_DispenseId = T.Id AND isnull(TT.pp_IsNotInStore,0) = 0                
  ) AS Source ON Target.Id = Source.Id AND isnull(Source.pp_IsNotInStore,0) = 0    --Developer: Deval, Date: 01/01/2024            
  WHEN MATCHED THEN            
   UPDATE SET PrescriptionDetailId = pp_PrescriptionDetailId            
  WHEN NOT MATCHED THEN                
   INSERT                
   (                
    Id,PrescriptionDetailId,CreatedUserId,CreatedDateTime,OrgId                
   )                
   VALUES                
   (                
    @lFromNextNumber + tid,pp_PrescriptionDetailId,pp_CreatedUserId,sCommon.fGetDate(),pp_OrgId                
   );                
  begin                 
  select @lCount = COUNT(1) FROM @tblPrescriptionDetail_temp                 
  SET @lNextNumber  = @lCount + @lFromNextNumber                 
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sPharmacy.tDispense', @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 @lorgid,'OPD_Dispense_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 6              
 END CATCH                
  update w set w.pp_DispenseId = p.Id from @tblPrescriptionDetail_temp w inner join sPharmacy.tDispense p                
  on w.pp_PrescriptionDetailId = p.PrescriptionDetailId                
                  
  update w set w.pp_RemainQty = case when isnull(pp_IsNotInStore,0) = 0 then                
  (isnull(p.PrescribedQuantity,0) - isnull(p.DispensedQuantity,0)) else 0 end                
  from @tblPrescriptionDetail_temp w inner join sExamination.tPrescriptionDetail p on w.pp_PrescriptionDetailId = p.Id                
                  
  update w set w.pp_AverageCost = case when isnull(pp_IsNotInStore,0) = 0 then WeightedAverageCost else 0 end from @tblPrescriptionDetail_temp w                
  inner join sIp.tStockItemPlanning p on w.pp_StockItemId = p.StockItemId and w.pp_StoreLocationId = p.StoreLocationId                
                  
  update @tblPrescriptionDetail_temp set pp_InwardValue = case when isnull(pp_IsNotInStore,0) = 0 then (pp_AverageCost * pp_RemainQty) else 0 end                
                  
  update w set w.pp_DispenseBatchId = p.Id from @tblPrescriptionDetail_temp w inner join sPharmacy.tDispenseBatch p                
  on w.pp_DispenseId = p.DispenseId                
  begin try                
  --begin tran                
                  
  begin                
  exec sCommon.pTableRowIdGet @lOrgId, 'sPharmacy.tDispenseBatch', 0, 1, 1,@outNextNumber = @lNextNumber output                 
  SET @lFromNextNumber = @lNextNumber - 1                
  end                
  MERGE sPharmacy.tDispenseBatch AS Target USING                 
  (                
   SELECT Id,pp_StockBatchId,pp_DispenseId,pp_RemainQty,pp_Total,pp_AverageCost,                
   pp_OrgId,pp_IsNotInStore,tid                
   FROM @tblPrescriptionDetail_temp TT  LEFT JOIN sPharmacy.tDispenseBatch T with (nolock) ON TT.pp_DispenseBatchId = T.Id and TT.pp_IsNotInStore = 0                 
  ) AS Source ON Target.Id = Source.Id and Source.pp_IsNotInStore = 0    --Developer: Deval, Date: 01/01/2024            
  WHEN MATCHED THEN                
   UPDATE SET DispenseId = pp_DispenseId                
  WHEN NOT MATCHED THEN                
   INSERT                
   (                
    Id,DispenseId,StockBatchId,Quantity,UnitCost,OrgId,ReturnQuantity                
   )                
   VALUES                
   (                
    @lFromNextNumber + tid,pp_DispenseId,pp_StockBatchId,              pp_Total,pp_AverageCost,pp_OrgId,0                
   );                
  begin                 
  select @lCount = COUNT(1),@i = 1 FROM @tblPrescriptionDetail_temp                 
  SET @lNextNumber  = @lCount + @lFromNextNumber                 
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sPharmacy.tDispenseBatch', @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 @lorgid,'OPD_DispenseBatch_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 7              
END CATCH                
  update w set w.pp_DispenseBatchId = p.Id from @tblPrescriptionDetail_temp w inner join sPharmacy.tDispenseBatch p                
  on w.pp_DispenseId = p.DispenseId                
           
               
      
  select @lCount = COUNT(1),@i = 1 FROM @tblPrescriptionDetail_temp                
                 
  while @i <= @lCount                
  begin                
   declare @rOrgId int,@rSourceTypeId int,@rSourceId bigint,@rItemSourceTypeId int,@rItemSourceId int,                
   @rQuantity decimal(12,2),@rValue decimal(12,2),@rCreatedUserId bigint,@rLocationId int,@rItemBatchId int,                
   @rIsNotInStore bit               
                 
                   
   select @rOrgId = pp_OrgId,@rSourceTypeId = 48,@rSourceId = pp_DispenseBatchId,@rItemSourceId = pp_StockItemId,@rItemSourceTypeId = 34,            
   @rQuantity = (case When (@lAutoDispenseConfigVal = 'True' and @lEnableDispenseConfigVal = 'True') then pp_DispensedQty Else pp_Total END),            
   @rValue = pp_InwardValue,@rCreatedUserId = pp_CreatedUserId,                
   @rStoreLocationId = pp_StoreLocationId,@rLocationId = pp_LocationId,@rItemBatchId = pp_StockBatchId,            
   @rIsNotInStore = isnull(pp_IsNotInStore,0)                
   from @tblPrescriptionDetail_temp where tid = @i                
                 
   if @rIsNotInStore = 0                
   begin               
 print 'DispenseBatchId -' + Cast(@rSourceId as varchar(200)) + '@rStoreLocationId -' + Cast(@rStoreLocationId as varchar(200)) + '@rItemSourceId -'+ Cast(@rItemSourceId as varchar(200))              
    Exec sIp.pWeightedAverageCostLogAdd_New @rOrgId =@rOrgId,@rSourceTypeId=@rSourceTypeId,@rSourceId=@rSourceId,                
    @rItemSourceTypeId = @rItemSourceTypeId,@rItemSourceId=@rItemSourceId,@rQuantity=@rQuantity ,@rValue=@rValue ,@rIsReceipt=0,                
    @rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rStoreLocationId ,@rLocationId=@rLocationId,@rItemBatchId = @rItemBatchId,                
    @rItemName =''                
   end                
   else                
   begin               
                 
    UPDATE P SET P.IsDispensed = 1                
    FROM sExamination.tPrescription P with(ROWLOCK) inner join @tblPrescription w on P.Id = w.p_PrescriptionId                
   end                
   select @i = @i + 1                
  end                
 end                 
               
 delete P from sExamination.tPrescription P with(ROWLOCK) inner join @tblPrescription t on P.Id = t.p_PrescriptionId                
 where P.Id not in (select PrescriptionId from sExamination.tPrescriptionDetail with(nolock))                
                 
 declare @tblComplaint table(tid int identity(1,1),c_ComplaintId bigint,c_OrgId int,c_ExaminationId bigint,c_SourceTypeId int,                
 c_Remark varchar(max))                
 insert into @tblComplaint                 
 select T.c.value('@ComplaintId','bigint') as ComplaintId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@SourceTypeId','int') as SourceTypeId,                
 T.c.value('@Remark','varchar(max)') as Remark                
 from @lxmlCmplaint.nodes('/ExaminComplaint/Complaint')T(c)                
                 
 update c set c.c_ComplaintId = cc.Id from @tblComplaint c inner join sExamination.tComplaint cc                
 on c.c_ExaminationId = cc.SourceId                
 begin try                
 --begin tran                
                 
 --begin                
 --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tComplaint', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 --SET @lFromNextNumber = @lNextNumber - 1                
 --end                
 MERGE sExamination.tComplaint AS Target USING                 
 (                
  SELECT Id,c_ComplaintId,c_OrgId,c_ExaminationId,c_SourceTypeId,c_Remark,tid                
  FROM @tblComplaint TT LEFT JOIN sExamination.tComplaint T with(NOLOCK) ON TT.c_ComplaintId = T.Id                
 ) AS Source ON Target.Id = Source.c_ComplaintId                 
 WHEN MATCHED THEN                
  UPDATE SET Remark = left([sSetup].[fPortalXMLTagsReplaceReverse](c_Remark),1000)                
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,SourceTypeId,SourceId,Remark,OrgId,IsObsolete                
  )                
  VALUES             
  (                
   c_ExaminationId,c_SourceTypeId,c_ExaminationId,left([sSetup].[fPortalXMLTagsReplaceReverse](c_Remark),1000),c_OrgId,0                
  );                
 --begin                
 --select @lCount = COUNT(1) FROM @tblComplaint                 
 --SET @lNextNumber  = @lCount + @lFromNextNumber                 
 --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tComplaint', @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 @lorgid,'OPD_Complaint_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 8              
 END CATCH                
                 
 declare @tblTests table(tid int identity(1,1),t_AreaId int,t_AreaTypeId int,t_ExaminationId 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('@ExaminationId','bigint') as ExaminationId,                 
 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 sExamination.tTestRequest p                
 on t.t_AreaId = p.TestId and t.t_ExaminationId = 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_ExaminationId bigint,tt_OrgId int,                
 tt_ParticipantAreaId bigint,tt_TestRequestId bigint,tt_IsPackageValue varchar(10))                
 insert into @tblTestsNew                
 select distinct t_AreaId,t_ExaminationId,t_OrgId,t_ParticipantAreaId,t_TestRequestId,t_IsPackageValue from @tblTests                
 BEGIN TRY                
 --begin tran                
                 
 begin                
 exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequest', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 SET @lFromNextNumber = @lNextNumber - 1                
 end                 
 MERGE sExamination.tTestRequest AS Target USING                 
 (                
  SELECT Id,tt_TestRequestId,tt_TestId,tt_OrgId,tt_ExaminationId,tid,tt_IsPackageValue                
  FROM @tblTestsNew TT LEFT JOIN sExamination.tTestRequest 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_ExaminationId,tt_TestId,1002,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 @lOrgId, @rTableTitle = 'sExamination.tTestRequest', @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 @lorgid,'OPD_TestRequest_DBError',5000,@exceptiondetail,getdate()                
 -- Set @errorCount=-1                
 --END CATCH                
                 
 update t set t.t_TestRequestId = p.Id from @tblTests t inner join sExamination.tTestRequest p                
 on t.t_AreaId = p.TestId and t.t_ExaminationId = p.SourceId                
                 
 update t set t.t_TestRequestDetailId = p.Id from @tblTests t inner join sExamination.tTestRequestDetail p                
 on t.t_TestDetailId = p.TestDetailId and t.t_TestRequestId = p.TestRequestId                
                 
--Developer: Deval, Mantis Id: 0025977              
 --delete w from sExamination.tTestRequestDetail w inner join @tblTests on w.TestRequestId = t_TestRequestId                
 --where Id not in (select t_TestRequestDetailId from @tblTests)                
              
 Declare @TestCount int, @TestDetailNewCount int, @TestDetailOldCount int, @TestDetailCount int;              
 set @TestCount = (select Count(*) from @tblTests);              
 set @TestDetailNewCount = (select Count(*) from @tblTests Where t_IsPackageValue = 'false')              
 set @TestDetailOldCount = (select Count(*) from @tblTests Where t_IsPackageValue = 'true')              
 set @TestDetailCount = (select Count(*) from sExamination.tTestRequestDetail w              
      inner join sExamination.tTestRequest TR on TR.Id = w.TestRequestId               
      Where TR.SourceId = @lExaminationId)              
 IF(@TestCount > 0)              
 BEGIN              
  IF(@TestDetailNewCount = 0)              
  BEGIN              
              
  delete w from sExamination.tTestRequestDetail w               
   inner join sExamination.tTestRequest TR on TR.Id = w.TestRequestId              
   where TR.SourceId = @lExaminationId AND w.Id not in (select t_TestRequestDetailId from @tblTests)              
              
     delete TR from sExamination.tTestRequest TR              
     Where TR.SourceId = @lExaminationId AND             
     TR.Id Not in               
 (select Distinct TRD.TestRequestId from sExamination.tTestRequestDetail TRD               
 inner join sExamination.tTestRequest TRE on TRE.Id = TRD.TestRequestId              
 Where TRE.SourceId = @lExaminationId)              
               
  END              
  ELSE IF(@TestDetailCount > @TestDetailOldCount and @TestDetailNewCount > 0)              
  BEGIN              
   delete w from sExamination.tTestRequestDetail w               
    inner join sExamination.tTestRequest TR on TR.Id = w.TestRequestId              
    where TR.SourceId = @lExaminationId AND            
 w.Id not in (select t_TestRequestDetailId from @tblTests Where t_IsPackageValue = 'true')                     
              
   delete TR from sExamination.tTestRequest TR              
   Where TR.SourceId = @lExaminationId AND            
   TR.Id not in (select Distinct TES.t_TestRequestId from @tblTests TES)              
               
  END              
 END              
 ELSE              
 BEGIN              
   exec [sExamination].[pSettingsForTestDetails] @lExaminationId              
 END              
 --Mantis Id: 0025977              
              
 --BEGIN TRY                
 --begin tran                
                  
 --begin                
 --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 --SET @lFromNextNumber = @lNextNumber - 1                
 --end                
                 
 declare @tblTestsM table(tid int identity(1,1),t_AreaId int,t_AreaTypeId int,t_ExaminationId 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_ExaminationId,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        
                
IF(@rIsDataEntryTemplateModal = 1)      
BEGIN      
 MERGE sExamination.tTestRequestDetail AS Target USING      
 (                
  SELECT Id,t_TestRequestId,t_TestDetailId,t_OrgId,t_ExaminationId,t_TestRequestDetailId,tid,t_ServiceValue,t_Remark      
  FROM @tblTestsM TT LEFT JOIN sExamination.tTestRequestDetail 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      
ELSE      
BEGIN      
 MERGE sExamination.tTestRequestDetail AS Target USING      
 (                
  SELECT Id,t_TestRequestId,t_TestDetailId,t_OrgId,t_ExaminationId,t_TestRequestDetailId,tid      
  FROM @tblTestsM TT LEFT JOIN sExamination.tTestRequestDetail 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        
  )                
  VALUES                
  (                
   t_TestRequestId,t_TestDetailId,t_OrgId      
  );      
END      
 --begin                
 --select @lCount = COUNT(1) FROM @tblTestsM                
 --SET @lNextNumber  = @lCount + @lFromNextNumber                 
 --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tTestRequestDetail', @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 @lOrgid,'OPD_TestRequestDetail_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 9              
 END CATCH                
 declare @tblReferral table(tid int identity(1,1),r_ReferralId bigint,r_OrgId int,r_ExaminationId bigint,                
 r_StoreLocationId int,r_ReferToClinicId int,r_ContactPerson varchar(200),r_CreatedUserId bigint)                
 insert into @tblReferral                
 select T.c.value('@ReferralId','bigint') as ReferralId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@StoreLocationId','int') as StoreLocationId,                
 T.c.value('@ReferToClinicId','int') as ReferToClinicId,                
 T.c.value('@ContactPerson','varchar(200)') as ContactPerson,                
 T.c.value('@CreatedUserId','bigint') as CreatedUserId                
 from @lxmlReferral.nodes('/ExaminReferral/Referral')T(c)                
                 
 update q set q.r_ReferralId = Id from @tblReferral q inner join sExamination.tReferral on q.r_ExaminationId = SourceId                
               
 begin try                
 --begin tran                
                 
 --begin                
 --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tReferral', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 --SET @lFromNextNumber = @lNextNumber - 1                
 --end                
 delete Ref from sExamination.tReferral Ref             
 inner join @tblReferral q on q.r_ReferralId = Ref.Id            
 Where q.r_ReferToClinicId <= 0 and q.r_ExaminationId = SourceId            
             
 delete from @tblReferral where r_ReferToClinicId <= 0                
                 
 MERGE sExamination.tReferral AS Target USING                 
 (                
  SELECT Id,r_ReferralId,r_OrgId,r_ExaminationId,r_StoreLocationId,r_ReferToClinicId,r_ContactPerson,                
  r_CreatedUserId,tid                
  FROM @tblReferral TT LEFT JOIN sExamination.tReferral T with(nolock) ON TT.r_ReferralId = T.Id and TT.r_ReferToClinicId > 0                
 ) AS Source ON Target.Id = Source.r_ReferralId and Source.r_ReferToClinicId > 0                
 WHEN MATCHED THEN                
  UPDATE SET ReferToClinicId = r_ReferToClinicId,ContactPerson = r_ContactPerson,                
  UpdatedUserId = r_CreatedUserId,UpdatedDateTime = sCommon.fGetDate()                
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,SourceId,ReferToClinicId,Remark,ContactPerson,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,                
   StoreLocationId,OrgId,HistoryOf,TreatmentDetail,Diagnosis                
  )                
  VALUES                
  (                
   r_ExaminationId,r_ExaminationId,r_ReferToClinicId,'',r_ContactPerson,r_CreatedUserId,sCommon.fGetDate(),                
   r_CreatedUserId,sCommon.fGetDate(),r_StoreLocationId,r_OrgId,'','',''                
  );                
                 
 delete from sExamination.tReferral where ReferToClinicId < 0                
 --begin                
 --select @lCount = COUNT(1) FROM @tblReferral                
 --SET @lNextNumber  = @lCount + @lFromNextNumber                 
 --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tReferral', @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 @lorgid,'OPD_Referral_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 10              
END CATCH                
 declare @tblOthers table(tid int identity(1,1),o_ExaminationId bigint,o_ReferenceEmployeeId bigint,o_IsWaive bit,                
 o_OutSideMedicine varchar(max),o_OutSideTest varchar(max),o_OtherName varchar(300),o_OtherAge varchar(20),                
 o_OtherAgeMonth varchar(20),o_OtherGenderId varchar(10),o_NursingRemark varchar(max),o_IsPediatric bit,                
 o_ParticipantSourceTypeId int,o_FurterActionId int,o_FurtherActionRemark varchar(1000),o_Time varchar(100),                
 o_OutTime varchar(100),o_IsFit int,o_FitnessStatus smallint,OutSidePrescriptionId bigint, o_OtherSubGroupId int,             
 o_ReferToDoctorId BIGINT, o_UnfitListingId BIGINT, o_UniqueIdType nvarchar(50), o_UniqueIdTypeOther nvarchar(100), o_UniqueId nvarchar(16),o_OtherEmail nvarchar(100),v_VendorCompanyName nvarchar(100),
 r_ReferenceOPDId bigint, o_VisitTypeId int, m_MobileNumber nvarchar(20))            
 insert into @tblOthers                
 select T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@ReferenceEmployeeId','bigint') as ReferenceEmployeeId,                
 T.c.value('@IsWaive','bit') as IsWaive,                
 T.c.value('@OutSideMedicine','varchar(max)') as OutSideMedicine,                
 T.c.value('@OutSideTest','varchar(max)') as OutSideTest,                
 T.c.value('@OtherName','varchar(300)') as OtherName,                
 T.c.value('@OtherAge','varchar(20)') as OtherAge,                
 T.c.value('@OtherAgeMonth','varchar(20)') as OtherAgeMonth,                
 case when T.c.value('@OtherGenderId','varchar(10)') = '-1' then null else T.c.value('@OtherGenderId','varchar(10)') end as OtherGenderId,                
 T.c.value('@NursingRemark','varchar(max)') as NursingRemark,                
 T.c.value('@IsPediatric','bit') as IsPediatric,null,                
 T.c.value('@FurtherActionId','int') as FurtherActionId,                
 left(T.c.value('@FurtherActionRemark','varchar(1000)'),1000) as FurtherActionRemark,                
 left(T.c.value('@OPDTime','varchar(100)'),100) as OPDTime,                
 left(T.c.value('@OPDOutTime','varchar(100)'),100) as OPDOutTime,                
 T.c.value('@IsFit','int') as IsFit,                
 T.c.value('@FitnessStatus','smallint') as FitnessStatus,                
 T.c.value('@OutSidePrescriptionId','bigint') as OutSidePrescriptionId,              
 T.c.value('@OtherSubGroupId','int') as OtherSubGroupId,            
 T.c.value('@ReferToDoctorId','bigint') as ReferToDoctorId,            
 T.c.value('@UnfitListingId','bigint') as UnfitListingId,      
 T.c.value('@UniqueIdType','nvarchar(50)') as UniqueIdType,      
 T.c.value('@UniqueIdTypeOther','nvarchar(100)') as UniqueIdTypeOther,      
 T.c.value('@UniqueId','nvarchar(16)') as UniqueId,      
 T.c.value('@OtherEmail','nvarchar(100)') as UniqueId,  
 T.c.value('@vendorCompanyName','nvarchar(100)') as VendorCompanyName,  
 T.c.value('@ReferenceOPDId','bigint') as ReferenceOPDId,
 T.c.value('@VisitTypeId','int') as VisitTypeId,
 T.c.value('@MobileNumber','nvarchar(20)') as MobileNumber  
 from @lxmlOthers.nodes('/ExaminOther/OhterDetail')T(c)      
                 
 update w set w.o_ParticipantSourceTypeId = E.ParticipantSourceTypeId from @tblOthers w inner join sExamination.tExamination E                
 on w.o_ExaminationId = E.Id                
                 
 update OSP set OSP.SourceId=w.o_ExaminationId ,UpdatedDateTime=sCommon.fGetDate(),UpdatedUserId=@rUserId from sExamination.tOutSidePrescription OSP                
 inner join @tblOthers w on w.OutSidePrescriptionId=OSP.id                
 where Isnull(w.OutSidePrescriptionId,0) >0                
          declare  @Fitnessstatus int , @ReferenceOPdId bigint, @ReferenceOPdIdNew bigint,@ExaminationId bigint      
  set @Fitnessstatus = (select o_FitnessStatus from  @tblOthers )    
  set @ReferenceOPdId = (select r_ReferenceOPDId from  @tblOthers )    
  set @ExaminationId = (select o_ExaminationId from  @tblOthers )    
  if (@Fitnessstatus != -1)
  begin
	  if(@ReferenceOPdId > 0)
	  set @ReferenceOPdIdNew = @ReferenceOPdId
	  else
	  set @ReferenceOPdIdNew = @ExaminationId
  end
 MERGE sExamination.tOPD AS Target USING
 (                
  SELECT ExaminationId,o_ExaminationId,o_ReferenceEmployeeId,o_IsWaive,o_OutSideMedicine,o_OutSideTest,o_OtherName,                
  o_OtherAge,o_NursingRemark,o_OtherAgeMonth,o_OtherGenderId,o_IsPediatric,o_ParticipantSourceTypeId,                
  o_FurterActionId,o_FurtherActionRemark,o_Time,o_OutTime,o_IsFit,o_FitnessStatus, o_OtherSubGroupId, o_ReferToDoctorId, tid,      
  o_UniqueIdType, o_UniqueIdTypeOther, o_UniqueId, o_OtherEmail,v_VendorCompanyName,r_ReferenceOPDId,o_VisitTypeId,m_MobileNumber      
  FROM @tblOthers TT LEFT JOIN sExamination.tOPD T with(nolock) ON TT.o_ExaminationId = T.ExaminationId                
 ) AS Source ON Target.ExaminationId = Source.o_ExaminationId                
 WHEN MATCHED THEN                
  UPDATE SET ReferenceEmployeeId = o_ReferenceEmployeeId,IsWaiveOff = o_IsWaive,                
  OutsideMedicine = left([sSetup].[fPortalXMLTagsReplaceReverse](o_OutSideMedicine),1000),                
  OutsideTest = left([sSetup].[fPortalXMLTagsReplaceReverse](o_OutSideTest),1000),                
  NursingRemark = left([sSetup].[fPortalXMLTagsReplaceReverse](o_NursingRemark),200),                
  Age = o_OtherAge,OtherName = o_OtherName,Months = o_OtherAgeMonth,                
  GenderId = case when o_OtherGenderId = '-1' then null else o_OtherGenderId end,                
  IsPediatric = case when o_ParticipantSourceTypeId in (1001,1009) then o_IsPediatric else null end,                
  FurtherActionId = o_FurterActionId,FurtherActionRemark = [sSetup].[fPortalXMLTagsReplaceReverse](o_FurtherActionRemark),                
  OPDTime = [sSetup].[fPortalXMLTagsReplaceReverse](o_Time),                
  OPDOutTime = [sSetup].[fPortalXMLTagsReplaceReverse](o_OutTime),                
  IsFit = case when o_IsFit = 1 then 1 else 0 end,                
  FitnessStatus = o_FitnessStatus,              
  OtherSubGroupId = o_OtherSubGroupId, ReferToDoctorId = o_ReferToDoctorId,       
  UniqueIdType = o_UniqueIdType, UniqueIdTypeOther = o_UniqueIdTypeOther, UniqueId = o_UniqueId ,
  OtherEmail = o_OtherEmail  ,VendorCompanyName = v_VendorCompanyName,
  ReferenceOPDId = r_ReferenceOPDId,VisitTypeId=o_VisitTypeId,MobileNumber = m_MobileNumber
 WHEN NOT MATCHED THEN
  INSERT                
  (
   ExaminationId,ReferenceEmployeeId,IsWaiveOff,OutsideMedicine,OutsideTest,OtherName,                
   NursingRemark,Age,Months,GenderId,IsPediatric,FurtherActionId,FurtherActionRemark,OPDTime,                
   OPDOutTime,IsFit,FitnessStatus,OtherSubGroupId,ReferToDoctorId, UniqueIdType, UniqueIdTypeOther, 
   UniqueId, OtherEmail, VendorCompanyName, ReferenceOPDId, VisitTypeId, MobileNumber  
  )
  VALUES                
  (                
   o_ExaminationId,o_ReferenceEmployeeId,o_IsWaive,left([sSetup].[fPortalXMLTagsReplaceReverse](o_OutSideMedicine),1000),                
   left([sSetup].[fPortalXMLTagsReplaceReverse](o_OutSideTest),1000),                
   o_OtherName,left([sSetup].[fPortalXMLTagsReplaceReverse](o_NursingRemark),200),                
   o_OtherAge,o_OtherAgeMonth,case when o_OtherGenderId = -1 then null else o_OtherGenderId end,                
   case when o_ParticipantSourceTypeId in (1001,1009) then o_IsPediatric else null end,o_FurterActionId,                
   [sSetup].[fPortalXMLTagsReplaceReverse](o_FurtherActionRemark),[sSetup].[fPortalXMLTagsReplaceReverse](o_Time),                
   [sSetup].[fPortalXMLTagsReplaceReverse](o_OutTime),case when o_IsFit = 1 then 1 else 0 end,o_FitnessStatus,o_OtherSubGroupId,o_ReferToDoctorId,      
   o_UniqueIdType, o_UniqueIdTypeOther,o_UniqueId,o_OtherEmail, 
   v_VendorCompanyName,@ReferenceOPdIdNew,o_VisitTypeId,m_MobileNumber  
  );
            
  Declare @rCauseId int = 0, @rIsTrackIncidentLog bit = 0, @rIsTrackForFitness bit = 0, 
  @rIsFit bit = 0, @rUnfitListingId bigint = 0, @rFitnessStatus int;            
  set @rCauseId = (select top 1 a_CauseId from @tblAppointments);            
  set @rIsTrackIncidentLog = (select IsTrackIncidentLog from sExamination.tCauseMaster where Id = @rCauseId);            
  set @rIsTrackForFitness = (select IsTrackForFitness from sExamination.tCauseMaster where Id = @rCauseId);            
  set @rIsFit = (select (case when o_IsFit = 1 then 1 else 0 end) from @tblOthers);            
  set @rUnfitListingId = (select ISNULL(o_UnfitListingId, 0) from @tblOthers);
  set @rFitnessStatus = (select ISNULL(o_FitnessStatus, 0) from @tblOthers);
            
  IF (@rFitnessStatus <= 5 AND ((ISNULL(@rIsTrackIncidentLog, 0) = 0 AND ISNULL(@rIsTrackForFitness, 0) = 1) OR @rUnfitListingId > 0))            
  BEGIN            
  IF(ISNULL(@rIsFit, 0) = 0 AND @rUnfitListingId = 0)            
  BEGIN            
    DECLARE @lNextNumberIsFit bigint;            
    EXEC sCommon.pTableRowIdGet @lOrgId, 'sExamination.tOPDUnfitListing', 0, 1, 1,@outNextNumber = @lNextNumberIsFit output            
            
    Insert Into [sExamination].[tOPDUnfitListing]            
    Values(@lNextNumberIsFit, @lExaminationId, 0, @rUserId, sCommon.fGetDate())            
  END            
  ELSE IF (ISNULL(@rIsFit, 0) = 1 AND @rUnfitListingId > 0)            
  BEGIN       
   Declare @runfitExaminationId BIGINT, @runfitEmployeeId BIGINT, @runfitSourceTypeId INT;
   set @runfitExaminationId = (select ExaminationId from [sExamination].[tOPDUnfitListing] Where Id = @rUnfitListingId);
   set @runfitEmployeeId = (select ParticipantSourceId from sExamination.tExamination Where Id = @runfitExaminationId);
   set @runfitSourceTypeId = (select ParticipantSourceTypeId from sExamination.tExamination Where Id = @runfitExaminationId);

   Update OUL set IsFit = 1 FROM [sExamination].[tOPDUnfitListing] OUL
   INNER JOIN sExamination.tExamination EXM ON EXM.Id = OUL.ExaminationId
   Where EXM.ParticipantSourceId = @runfitEmployeeId and EXM.ParticipantSourceTypeId = @runfitSourceTypeId;   
  END            
  END            
            
  update sExamination.tExamination set IsonSugarMedication=@rIsonSugarMedication,IsonBPMedication=@rIsonBPMedication,IsNewLSD=@rIsNewLSD                
  where Id=@lExaminationId                
              
  -- othername issue in importopd medicine by Nidhi Pandey              
 UPDATE [sExamination].[tExamination] SET OPDOtherName = ISNULL(c.OtherName,'')                
 FROM  [sExamination].[tExamination] t  INNER JOIN sExamination.tOPD c    ON t.Id = c.ExaminationId where t.Id=@lExaminationId                
   -- othername issue in importopd medicine by Nidhi Pandey               
  if(Len(@rHabits)>17)                
  begin                
   select @rHabits = Replace(Replace(Replace(@rHabits,'ExTobacco',''),'ExSmoker',''),'ExAlcohol','')                
   exec sExamination.pSaveHabitHygineDetailsN @lOrgId,@lExaminationId,@tParticipantSourceId,1002,@rHabits                
  end                
  if(Len(@rLSDTests)>15)                
  begin                
   exec [sExamination].[pCreateTestResultsByIdN] @lExaminationId,@lOrgId,@rLSDTests,1002                
   -- for genrating disnosis for test results                
   DECLARE @tbltmpTestDetail TABLE (tid int IDENTITY (1, 1),t_TestParameterId int,t_ServiceValue nvarchar(500),t_DateOfBirth date,t_GenderId int,t_ParameterValueTypeId int,t_ListValueTypeId int,t_TestType int,t_Age int,t_DetailId bigint,                
   t_ExaminationId bigint,t_StaticTestParameterId int)                
   DECLARE @tbltmpDiagnosis TABLE (tid int IDENTITY (1, 1),d_DiagnosisRemark varchar(max),d_Recommendation varchar(max),d_DetailId bigint,d_Type int,d_MainId bigint,d_ExaminationId bigint,d_StaticTestParameterId int)                
                
   INSERT INTO @tbltmpTestDetail                
    SELECT TPM.Id, TRD.ServiceValue, EP.DateOfBirth, EP.GenderId, TPM.ParameterValueTypeId, TPM.ListValueTypeId, 1,                
    DATEDIFF(yy, EP.DateOfBirth, GETDATE()), TRD.Id, ED.Id,TPM.StaticTestParameterId                
    FROM sExamination.tExamination ED                
    INNER JOIN sHrm.tEmployeePersonalDetail EP ON ED.ParticipantSourceId = EP.EmployeeId                
    INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId                
    INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId                
    INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id                
    INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id                
    WHERE ED.Id =@lExaminationId                
    AND TPM.ParameterValueTypeId IN (1, 2)                
    AND TPM.IsObsolete = 0                
    AND ISNULL(TRD.ServiceValue, '') <> ''                
    ORDER BY TPM.ParameterValueTypeId                
                
    INSERT INTO @tbltmpDiagnosis                
     SELECT ISNULL(TPD.Diagnosis, ''), ISNULL(TPD.Recommendation, ''), TPD.Id, t_TestType, t_DetailId, t_ExaminationId,t_StaticTestParameterId                
     FROM sOrderEntry.tTestParameterDetail TPD                
     INNER JOIN @tbltmpTestDetail TD ON TPD.TestParameterId = TD.t_TestParameterId                
     WHERE TPD.GenderId = TD.t_GenderId                
     AND t_Age BETWEEN TPD.AgeFrom AND TPD.AgeTo                
     AND ISNULL(TPD.IsNormal, 0) = 0                
     AND TD.t_ParameterValueTypeId = 1       
     AND t_TestType = 1                
     AND CONVERT(decimal(18, 9), t_ServiceValue) BETWEEN CAST(TPD.Minimum AS decimal(12, 4)) AND CAST(TPD.Maximum AS decimal(12, 4))                
     and ISNUMERIC(t_ServiceValue)=1                
     AND t_ServiceValue <>'+'                
     AND ISNULL(TPD.Diagnosis, '')<>''                 
    INSERT INTO @tbltmpDiagnosis                
     SELECT ISNULL(DiagnosisRemark, ''), ISNULL(RecommendationRemark, ''), TLS.Id, t_TestType, t_DetailId, t_ExaminationId,0                
     FROM sExamination.tTestListTypeSetup TLS                
     INNER JOIN @tbltmpTestDetail TD ON TLS.TestParameterId = TD.t_TestParameterId                
     INNER JOIN sOrderEntry.tListValueTypeMaster LVTM ON LVTM.Id = TD.t_ListValueTypeId                
     INNER JOIN sOrderEntry.tListValueMaster LV ON LV.ListValueTypeId = LVTM.Id AND LV.Id = TLS.ListValueId                
     WHERE TLS.IsNormal = 0                
     AND LV.Title LIKE TD.t_ServiceValue                
     AND TD.t_ParameterValueTypeId = 2                
     AND t_TestType = 1                
     AND ISNULL(DiagnosisRemark, '')<>''                
                
    UPDATE TRD SET TRD.Diagnosis = t.d_DiagnosisRemark,TRD.Recommendation = t.d_Recommendation,TRD.IsAbnormal = 1                
    FROM sExamination.tTestRequestDetail AS TRD                
    INNER JOIN @tbltmpDiagnosis AS t ON TRD.Id = d_MainId                
    WHERE t.d_Type = 1                
  end                
  declare @rSetupId int                 
  if(Len(@rHabits)>17 or Len(@rLSDTests)>15 or @rIsNewLSD='true')                
  begin                
   print 'Lsd started'                
   select @rSetupId=[sCommon].[fGetIntIdForOrg](8,@lOrgId)                   
   -- For Dianosis Tracker                
   EXEC [sExamination].[pDiagnosisTrackerEmployeeUpdateOPD] @lOrgId,@rSetupId,@lStorelocationId,@lExaminationId                
                
   update sExamination.tDiagnosisTrackerEmployee set IsonSugarMedication=@rIsonSugarMedication,IsonBPMedication=@rIsonBPMedication,                
   DiabeticExisting=case when Isnull(@rIsonSugarMedication,0)=1 then 'Diabetic Existing' else DiabeticExisting end,                
  HypertensionExisting = case when isnull(@rIsonBPMedication,1)=1 then 'Hypertension Existing' else HypertensionExisting end                
   where ExaminationId=@lExaminationId                   
                
   --For LSD Tracker                
   exec [sExamination].[pLSDTrackerEmployeeUpdateALL] @lOrgId,@rSetupId,@lStorelocationId,@lExaminationId,8,@rSetupId                
  end                
                
  if(@rIsNewLSD='true' and Len(@rHabits)<=17)                
  begin                
                   
   UPDATE DTE SET DTE.Tobacco = 0,                
   DTE.Smoker = 0,                
   DTE.Alcohol = 0,                
   DTE.ExTobacco=case when  Isnull(LTE.Tobacco,0)=1 then 1 else DTE.ExTobacco end,                
   DTE.ExSmoker=case when  Isnull(LTE.Smoker,0)=1 then 1 else DTE.ExSmoker end,                
   DTE.ExAlcohol=case when Isnull(LTE.Alcohol,0)=1 then 1 else DTE.ExAlcohol end                
   --DTE.AlcoholSocial = Details.[Alcohol-Social],                
   --DTE.Drug = Details.Drugs                
   FROM sExamination.tDiagnosisTrackerEmployee AS DTE                
   INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId                
   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 [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId                
   LEFT JOIN [sExamination].[tLSDTrackerEmployee] AS LTE ON EXM.ParticipantSourceId=LTE.ParticipantSourceId and EXM.ParticipantSourceTypeId=LTE.ParticipantSourceTypeId                
   WHERE EXM.ParticipantSourceTypeId=95                
   AND EXM.OrgId=@lOrgId                
   AND ((EXM.Id = @lExaminationId))                
   --AND SSM.MaINTypeId=@rMaINTypeId                
   --AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))                
   AND ((EXM.SetupId=@rSetupId))                
   AND ((EXM.StoreLocationId=@lStorelocationId))                
                
                
   UPDATE DTE SET DTE.Tobacco = 0,                
   DTE.Smoker = 0,                
   DTE.Alcohol = 0,                
   DTE.ExTobacco=case when Isnull(DTE.Tobacco,0)=1 then 1  else DTE.ExTobacco end,                
   DTE.ExSmoker=case when  Isnull(DTE.Smoker,0)=1 then 1 else DTE.ExSmoker end,                
   DTE.ExAlcohol=case when Isnull(DTE.Alcohol,0)=1 then 1 else DTE.ExAlcohol end                
   --DTE.AlcoholSocial = Details.[Alcohol-Social],                
   --DTE.Drug = Details.Drugs                
   FROM [sExamination].[tLSDTrackerEmployee] AS DTE                
   INNER JOIN sExamination.tExamination AS EXM ON EXM.ParticipantSourceId=DTE.ParticipantSourceId and EXM.ParticipantSourceTypeId=DTE.ParticipantSourceTypeId                
   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 [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId                
   WHERE EXM.ParticipantSourceTypeId=95                
   AND EXM.OrgId=@lOrgId                
   AND ((EXM.Id = @lExaminationId))                
   AND SSM.MaINTypeId=8                
   AND ((STM.SetupGroupId=@rSetupId))                
   AND ((EXM.SetupId=@rSetupId))                
   AND ((EXM.StoreLocationId=@lStorelocationId))                
                
  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,CreatedUserId)                
  Select @lOrgId,'OPD_DBError',5000,@exceptiondetail,getdate(),@rUserId                  
  Set @errorCount=-1                
  SET @errorLine = 11              
 END CATCH                  
 --print 'LifeStyleDisease Auto Insert start'                
 -- LifeStyleDisease Auto Insert start                
 declare @lConfValue varchar(100)                
 SELECT @lConfValue=ISNULL(cm.ItemValue,pm.ItemValue) FROM sConfig.tConfigurationMaster  AS PM                
 LEFt JOIN sConfig.tConfigurationSetup AS CM ON cm.ConfigurationId=Pm.Id AND SourceId=@lOrgId AND SourceTypeId=1016                 
 WHERE PM.Id=184                
 if(@lConfValue='True')                
 begin                
 begin try                
 --begin tran                
  declare @tblLifeStyleDisease table(tid int identity(1,1),dd_OrgId int,dd_DiseaseId int,dd_ExaminationId bigint,                
  dd_ParticipantSourceId bigint,dd_ParticipantSourceTypeId smallint,dd_RelationshipId smallint)                
                   
   insert into @tblLifeStyleDisease                
   select dd_OrgId,dd_DiseaseId,dd_ExaminationId,E.ParticipantSourceId,E.ParticipantSourceTypeId,case when EFD.id is null then 1 else EFD.RelationshipId End                
   from @tblDiseaseDetail as tDD                
   --inner join sExamination.tDiseaseMaster DM On DM.id=tDD.dd_DiseaseId and DM.StaticDiseaseId IN (7,11,13,20,25,159,190,328)                
   inner join sExamination.tDiseaseMaster DM On DM.id=tDD.dd_DiseaseId and DM.IsForOPD=1                
   inner join sExamination.tExamination E On E.id=tDD.dd_ExaminationId                
   left join sHrm.tEmployeeFamilyDetails EFD On EFD.id= E.ParticipantSourceid and E.ParticipantSourceTypeId=1001                
   --select * from @tblLifeStyleDisease                
   if((Select Count(*) from @tblLifeStyleDisease) > 0)                
   begin                
    declare @cnt int,@i1 int                
    select @cnt = count(*),@i1 = 1 from @tblLifeStyleDisease                
    while @i1 <= @cnt                
    begin                
    declare @lDiseasseid bigint,@lRelationshipid smallint                
    declare @lOrgId1 int,@lParticipantSourceId bigint,@lParticipantSourceTypeId smallint                
                
    select @lDiseasseid = dd_DiseaseId,@lRelationshipid=dd_RelationshipId,                
    @lOrgId1=dd_OrgId,@lParticipantSourceId=dd_ParticipantSourceId,@lParticipantSourceTypeId=dd_ParticipantSourceTypeId                
    from @tblLifeStyleDisease where tid=@i1                
                
    IF NOT EXISTS (select * from @tblLifeStyleDisease as tDD                
    inner join sExamination.tHistory H On H.ParticipantSourceId=tDD.dd_ParticipantSourceId and H.ParticipantSourceTypeId=tDD.dd_ParticipantSourceTypeId                
    inner join sExamination.tHistoryDetail HD On HD.HistoryId=H.Id and HD.DiseaseId= @lDiseasseid )                
    begin                
     print 'Not Exists'        
     declare @lNextNumber1 bigint                 
     
	 IF NOT EXISTS (select Id from sExamination.tHistory Where ParticipantSourceId = @lParticipantSourceId and ParticipantSourceTypeId = @lParticipantSourceTypeId)
	 BEGIN
		 exec sCommon.pTableRowIdGet @lOrgId1, 'sExamination.tHistory', 0, 1, 1,@outNextNumber = @lNextNumber1 output             
		 insert into sExamination.tHistory                
		 (                
		  Id,ParticipantSourceId,ParticipantSourceTypeId,Remark,OrgId,IsObsolete,IsSurgeryDone,SurgeryRemark                
		 )                
		 select @lNextNumber1,@lParticipantSourceId,@lParticipantSourceTypeId,'',@lOrgId1,0,0,''                
     END
	 ELSE
	 BEGIN
	    set @lNextNumber1 = (select Id from sExamination.tHistory Where ParticipantSourceId = @lParticipantSourceId and ParticipantSourceTypeId = @lParticipantSourceTypeId)
	 END
	 
     insert into sExamination.tHistoryDetail(HistoryId,DiseaseId,Remark,RelationshipId,OrgId,IsObsolete)                
     select @lNextNumber1,@lDiseasseid,'',@lRelationshipid,@lOrgId1,0                 
                
    end                
    else if not exists (select * from @tblLifeStyleDisease as tDD                
    inner join sExamination.tHistory H On H.ParticipantSourceId=tDD.dd_ParticipantSourceId and H.ParticipantSourceTypeId=tDD.dd_ParticipantSourceTypeId                
    inner join sExamination.tHistoryDetail HD On HD.HistoryId=H.Id and HD.DiseaseId= @lDiseasseid and HD.RelationshipId = @lRelationshipid)                
    begin                
     insert into sExamination.tHistoryDetail(HistoryId,DiseaseId,Remark,RelationshipId,OrgId,IsObsolete)                
     select Top 1 HD.HistoryId,tdd.dd_DiseaseId,'',@lRelationshipid,@lOrgId1,0 from @tblLifeStyleDisease as tDD                
    inner join sExamination.tHistory H On H.ParticipantSourceId=tDD.dd_ParticipantSourceId and H.ParticipantSourceTypeId=tDD.dd_ParticipantSourceTypeId                
    inner join sExamination.tHistoryDetail HD On HD.HistoryId=H.Id and HD.DiseaseId= @lDiseasseid                 
    end                
    select @i1 = @i1+ 1                
    end                
   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 @lorgid,'OPD_LifeStyleDisease_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 12              
 END CATCH                
 end                
 -- LifeStyleDisease Auto Insert end                
 --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


CREATE OR ALTER PROCEDURE [sExamination].[pSaveEmployeePrescription]
@rStrXML varchar(max)
as
begin
	declare @lxmlStr xml
	set @lxmlStr = CAST(@rStrXML AS xml)
	
	declare @tblPrescription table(tid int identity(1,1),p_StockItemId int,p_DrugFrequencyId int,p_DrugQuantity varchar(100),
	p_Dosage varchar(100),p_DrugInstruction varchar(200),p_DrugScheduleId int,p_StockRemark varchar(max),
	p_DrugFrequencyPattern varchar(200),p_Duration varchar(100),p_Total varchar(100),
	p_PatientSourceTypeId smallint,p_PatientSourceId bigint)
	insert into @tblPrescription
	select T.c.value('@StockItemId','int') as StockItemId,
	T.c.value('@DrugFrequencyId','int') as DrugFrequencyId,
	T.c.value('@DrugQuantity','varchar(100)') as DrugQuantity,
	T.c.value('@Dosage','varchar(100)') as Dosage,
	T.c.value('@DrugInstruction','varchar(200)') as DrugInstruction,
	T.c.value('@DrugScheduleId','int') as DrugScheduleId,
	T.c.value('@StockRemark','varchar(max)') as StockItemId,
	T.c.value('@DrugFrequencyPattern','varchar(200)') as DrugFrequencyPattern,
	T.c.value('@Duration','varchar(100)') as Duration,
	T.c.value('@Total','varchar(100)') as Total,
	T.c.value('@PatientSourceTypeId','smallint') as PatientSourceTypeId,
	T.c.value('@PatientSourceId','bigint') as PatientSourceId
	from @lxmlStr.nodes('/EmployeePrescription/Prescription')T(c)
	
	delete w from sExamination.tEmployeePrescription w
	inner join @tblPrescription p on w.PatientSourceTypeId = p.p_PatientSourceTypeId
	and w.PatientSourceId = p.p_PatientSourceId
	
	insert into sExamination.tEmployeePrescription
	(
		PatientSourceTypeId,PatientSourceId,StockItemId,DrugInstruction,Remark,
		Dosage,Duration,DurgDosageQty,DrugDosageFrequencyId,
		DrugDosageScheduleId,DrugFrequencyPattern
	)
	select p_PatientSourceTypeId,p_PatientSourceId,p_StockItemId,p_DrugInstruction,
	left(p_StockRemark,400),p_Dosage,p_Duration,p_DrugQuantity,p_DrugFrequencyId,
	p_DrugScheduleId,p_DrugFrequencyPattern from @tblPrescription
	
	select 1 as res
end

GO


CREATE OR ALTER PROCEDURE [sHrm].[pEmployeeMasterAdd]  
@rOrgId smallint,  
@rCode [nvarchar](100),  
@rFirstName [nvarchar](100),  
@rMiddleName [nvarchar](100),  
@rLastName [nvarchar](100),  
@rEmployeeTypeId int,  
@rDepartmentId int,  
@rLocationId int,  
@rDateOfBirth Date,  
@rDateOfJoining Date,  
@rGenderId int,  
@rStatusId [int],  
@rWorkLocationId [int],  
@rIsObsolete [bit],  
@rCreatedUserId [bigint],  
@rIsBirthDateUnknown bit,  
@OutEmployeeId bigint = null output,  
@rStoreLocationId int,  
@rContractorId int = null,   
@rEmployeeDesignationId INT,  
@rBloodGroupId INT = 0,  
@rEmployeeCompanyId INT = 0,  
@rProcessTypeId int,  
@rIsTemporary [bit] = 0,  
@rTemporaryCode [nvarchar](100)='',  
@rTargetGroupId int=0,  
@rDesignatedPositionId int=0,  
@rReferenceCode [nvarchar](100) = '',
@rEmployeePrefix [nvarchar](100) = '', 
@rNationalityId INT = 0  
  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
 DECLARE @lNextNumber BIGINT  
 DECLARE @loEmpNumber Nvarchar(100)  
 DECLARE @lEmpPrefixResult Int  
   
 IF(ISNULL(@rTemporaryCode,'') <> '') --15/03/2022 by Nidhi Pandey for Mantis : 0018096  
 BEGIN  
  IF EXISTS(SELECT Id FROM  sHrm.tEmployeeMaster where OrgID=@rOrgId AND TemporaryCode=@rTemporaryCode)  
  BEGIN     
   SELECT -2 AS RESULT  
   RETURN  
  END  
 END  
   
 if @rTemporaryCode = ''  
 begin  
  IF((@rCode = Null) OR (@rCode = ''))  
  BEGIN  
  IF EXISTS(SELECT Id FROM  sHrm.tEmployeeMaster where OrgID=@rOrgId AND Code=@rCode)  
   BEGIN     
    SELECT -2 AS RESULT  
    RETURN  
   END   
  END  
  IF((@rCode = Null) OR (@rCode = ''))  
  BEGIN  
   EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 94,@rStoreLocationId = 0, @rNextNumber = @loEmpNumber OUTPUT   
   SET @loEmpNumber = ISNULL(@loEmpNumber, '-300')  
   SET @lEmpPrefixResult = '-300'   
  END  
  ELSE  
  BEGIN  
   IF EXISTS(SELECT Id FROM sHrm.tEmployeeMaster where OrgID=@rOrgId AND Code=LTRIM(RTRIM(@rCode)))  
   BEGIN     
    SELECT -5 AS RESULT  
    RETURN  
   END
   ELSE  
   BEGIN  
   SET @loEmpNumber = @rCode  
   END  
  END  
 end  
  else  
 BEGIN  
  SET @loEmpNumber = 0  
 end  
   
 IF (@loEmpNumber <> '-300')  
 BEGIN  
  BEGIN TRY  
   BEGIN TRANSACTION  
   EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output  
  
   INSERT INTO sHrm.tEmployeeMaster  
   (  
    Id,Code,FirstName,MiddleName,LastName,StatusId,WorkLocationId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,  
    OrgId,IsTemporary,TemporaryCode,TargetGroupId,ReferenceCode ,EmployeePrefix 
   )  
   VALUES  
   (  
    @lNextNumber,case when isnull(@rTemporaryCode,'') <> '' then @rTemporaryCode else replace(@loEmpNumber,space(1),'') end,  
    @rFirstName,@rMiddleName,@rLastName,@rStatusId,isnull(@rWorkLocationId,0),@rIsObsolete,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,  
    sCommon.fGetDate(),@rOrgId,@rIsTemporary,case when isnull(@rTemporaryCode,'') <> '' then @rTemporaryCode else replace(@loEmpNumber,space(1),'') end,@rTargetGroupId,@rReferenceCode ,@rEmployeePrefix 
   )  
  
   SELECT Id AS RESULT, case when @rIsTemporary = 1 then @rTemporaryCode else @loEmpNumber end AS EmpCode FROM sHrm.tEmployeeMaster WHERE  Id = @lNextNumber  
   SET @OutEmployeeId = @lNextNumber -- added for import employee  
  
   BEGIN              
    
    Execute sHrm.pEmployeeJobDetailAdd @rOrgId,@lNextNumber,0,@rEmployeeDesignationId,@rLocationId,@rDepartmentId,  
    @rDateOfJoining,'','',0,0,@rCreatedUserId,@rEmployeeCompanyId,@rEmployeeTypeId,@rContractorId,@rProcessTypeId,null,null,0,@rStoreLocationId,0,null,'',@rDesignatedPositionId  
  
    Execute sHrm.pEmployeePersonalDetailAdd @rOrgId,@lNextNumber,'',@rDateOfBirth,@rGenderId,0,0,'','',@rBloodGroupId,0,'','','','','',  
    0,'',0,'',0,0,@rCreatedUserId,@rIsBirthDateUnknown,'',null,'',@rNationalityId  
      
      
   END   
   COMMIT TRANSACTION  
  END TRY  
  BEGIN CATCH    
  
 ROLLBACK TRANSACTION   
   RAISERROR   
   (  
    'Error saving employee Master', -- Message text.  
    16, -- Severity.  
    1 -- State.  
   );  
  END CATCH  
 END    
 ELSE  
 BEGIN  
  SELECT @loEmpNumber AS RESULT  
 END     
END  

GO


CREATE OR ALTER PROCEDURE [sSupport].[pAHCCounsellingReferDoctor]
@rDoctorId bigint,
@rHealthIndicatorId int,
@rStatusId int, 
@rstrXML nvarchar(max),
@rCreatedUserId bigint,
@rOrgId int
as  
Begin
	BEGIN TRY
		 BEGIN TRANSACTION	
		 declare @lostrXML  xml
		 declare @empId bigint, @rDoctorName nvarchar(200) = '';

		 declare @lAssignDesignationConfigVal varchar(5);
            
		 select @lAssignDesignationConfigVal = sConfig.fConfigurationValueGet('Provider.AssignDesignationFreezeWiseOrEntityWise',@rOrgId,0,0,0)

		 Set @empId = (select SourceId  from sSecurity.tUser Where id = @rCreatedUserId And SourceTypeId = 95);

		IF (@rDoctorId > 0)
		BEGIN
			set @rDoctorName = (select ISNULL(FirstName, '') + ' ' + ISNULL(LastName, '') from sHrm.tEmployeeMaster where Id = @rDoctorId)
		END

		 set @lostrXML = cast(@rstrXML as xml)

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

			Create table #tbltmpAHCTeam
			(
				tid int identity(1,1),
				ProviderAppointmentId bigint,
				CSVNonPathoParameters nvarchar(max),
				HealthIndicatorCurrentStatus int
			)
			insert into #tbltmpAHCTeam
			select T.c.value('@ProviderAppointmentId','int') as ProviderAppointmentId,
			T.c.value('@CSVNonPathoParameters','nvarchar(max)') as CSVNonPathoParameters, 0
			from @lostrXML.nodes('/StatusChange/StatusData')T(c)

			update tmp set tmp.HealthIndicatorCurrentStatus = PA.HealthIndicatorId from #tbltmpAHCTeam tmp 
			INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = tmp.ProviderAppointmentId

			MERGE sSupport.tProviderAppointment AS TARGET
USING (SELECT * FROM #tbltmpAHCTeam) AS SOURCE
ON TARGET.Id = SOURCE.ProviderAppointmentId AND TARGET.OrgId = @rOrgId
WHEN MATCHED THEN
    UPDATE SET  
        HealthIndicatorId = @rHealthIndicatorId,
        AssignToDoctorId = @rDoctorId,
        UpdatedUserId = @rCreatedUserId,
        UpdatedDateTime = sCommon.fGetDate(),
		NonPathoParameters = CSVNonPathoParameters,
		AssignByDoctorId = @empId,
		AssignDate = sCommon.fGetDate(),
        StatusId = CASE 
                      WHEN @rHealthIndicatorId = 608 OR @rHealthIndicatorId = 611 OR @rHealthIndicatorId = 612 THEN @rStatusId 
					  WHEN @rHealthIndicatorId = 606 OR @rHealthIndicatorId = 607 THEN 609
                      ELSE TARGET.StatusId 
                   END;

			Insert into sSupport.tProviderAppointmentlog
			select AHCT.ProviderAppointmentId, CASE 
                      WHEN @rHealthIndicatorId = 608 OR @rHealthIndicatorId = 611 OR @rHealthIndicatorId = 612 THEN @rStatusId 
					  WHEN @rHealthIndicatorId = 606 OR @rHealthIndicatorId = 607 THEN 609
                      ELSE PA.StatusId END, 
					  @rCreatedUserId, sCommon.fGetDate(),'Refer to Doctor ' + @rDoctorName
			from #tbltmpAHCTeam AHCT
			INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId

			--Health Indicator Log
			Insert into sSupport.tProviderAppointmentHealthIndicatorLog
			select AHCT.ProviderAppointmentId, @rHealthIndicatorId, @rCreatedUserId, sCommon.fGetDate(),'Refer to Doctor ' + @rDoctorName
			from #tbltmpAHCTeam AHCT
			INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId

			if (@lAssignDesignationConfigVal = 'True' AND @rHealthIndicatorId = 606)
			BEGIN
				UPDATE tpa SET tpa.HealthIndicatorId = (CASE WHEN CAST(DetailsVital.BMI AS Float) >= 30 AND CAST(DetailsVital.BMI AS Float) <= 35 THEN 612
													WHEN CAST(DetailsVital.BloodPressureSystolic AS Float) >= 150 AND CAST(DetailsVital.BloodPressureSystolic AS Float) <= 160 THEN 612
													WHEN CAST(DetailsVital.BloodPressureDiastolic AS Float) >= 100 AND CAST(DetailsVital.BloodPressureDiastolic AS Float) <= 110 THEN 612
													WHEN CAST(Details.HB AS Float) >= 8 and CAST(Details.HB AS Float) < 10 THEN 612
													WHEN CAST(Details.HBA1C AS Float) >= 8 and CAST(Details.HBA1C AS Float) <= 10 THEN 612
													WHEN CAST(Details.[SERUM CREATININE] AS Float) >= 1.5 AND CAST(Details.[SERUM CREATININE] AS Float) <= 2 THEN 612
													WHEN CAST(Details.[SERUM URIC ACID] AS Float) >= 7.7 AND CAST(Details.[SERUM URIC ACID] AS Float) <= 9.4 THEN 612
													WHEN CAST(Details.[TRIGLYCERIDE] AS Float) >= 200 AND CAST(Details.[TRIGLYCERIDE] AS Float) <= 500 THEN 612
													WHEN CAST(Details.[LDL] AS Float) >= 150 AND CAST(Details.[LDL] AS Float) <= 200 THEN 612
													WHEN CAST(Details.[TSH] AS Float) >= 11 AND CAST(Details.[TSH] AS Float) <= 50 THEN 612
													WHEN CAST(Details.[PSA] AS Float) > 5 AND CAST(Details.[PSA] AS Float) <= 10 THEN 612
													--Mild
													WHEN CAST(DetailsVital.BMI AS Float) >= 26 AND CAST(DetailsVital.BMI AS Float) < 30 THEN 611
													WHEN CAST(DetailsVital.BloodPressureSystolic AS Float) >= 140 AND CAST(DetailsVital.BloodPressureSystolic AS Float) < 150 THEN 611
													WHEN CAST(DetailsVital.BloodPressureDiastolic AS Float) >= 90 AND CAST(DetailsVital.BloodPressureDiastolic AS Float) < 100 THEN 611
													WHEN CAST(Details.HB AS Float) >= 10 and CAST(Details.HB AS Float) < 12 THEN 611
													WHEN CAST(Details.HBA1C AS Float) >= 6.5 and CAST(Details.HBA1C AS Float) < 8 THEN 611
													WHEN CAST(Details.[SERUM CREATININE] AS Float) >= 1.3 AND CAST(Details.[SERUM CREATININE] AS Float) < 1.5 THEN 611
													WHEN CAST(Details.[SERUM URIC ACID] AS Float) >= 6.5 AND CAST(Details.[SERUM URIC ACID] AS Float) < 7.7 THEN 611
													WHEN CAST(Details.[TRIGLYCERIDE] AS Float) >= 150 AND CAST(Details.[TRIGLYCERIDE] AS Float) < 200 THEN 611
													WHEN CAST(Details.[LDL] AS Float) >= 101 AND CAST(Details.[LDL] AS Float) < 150 THEN 611
													WHEN CAST(Details.[TSH] AS Float) >= 5.6 AND CAST(Details.[TSH] AS Float) < 11 THEN 611
													Else 606 END),
							tpa.UpdatedDateTime = sCommon.fGetDate()
						FROM sSupport.tProviderAppointment AS tpa
						INNER JOIN #tbltmpAHCTeam AS ot ON ot.ProviderAppointmentId = tpa.Id
						INNER JOIN sExamination.tExamination AS EXM ON EXM.ParticipantSourceId = tpa.PatientSourceId AND EXM.SetupId = tpa.SetupId
						INNER JOIN sExamination.tSetupMaster AS STM ON STM.ID = EXM.SetupId
						INNER JOIN sExamination.tSubTypeMaster AS SSM ON SSM.Id = STM.SubTypeId
						INNER JOIN sIp.tStoreLocationMaster AS SLM ON SLM.Id = EXM.StoreLocationId
						LEFT JOIN  
						(
							SELECT ExaminationId, Details.[R.B.C. COUNT], Details.[MCV], Details.[F B S], Details.[CHOLESTEROL],  
								   Details.[TRIGLYCERIDE], Details.[LDL], Details.[HDL], Details.[SGPT],  
								   Details.[ECG], Details.[SONOGRAPHY], Details.[TMT], Details.[ECHO],  
								   Details.[HB], Details.[SERUM CREATININE], Details.[SERUM URIC ACID], [HBA1C], [R B S], [P P B S], 
								   Details.[Waist Circumference], Details.[TSH], Details.[PSA], Details.[XRAY]
							FROM sExamination.tExamination AS EXM
							LEFT JOIN
							(
								SELECT ExaminationId, [R.B.C. COUNT], [MCV], [F B S], [CHOLESTEROL], [TRIGLYCERIDE], [LDL], [HDL],  
									   [SGPT], [ECG], [SONOGRAPHY], [TMT], [ECHO], [HB], [SERUM CREATININE], [SERUM URIC ACID], [HBA1C], [R B S], [P P B S], 
									   [Waist Circumference], [TSH], [PSA], [XRAY]
								FROM  
								(
									SELECT SPM.Title, TR.SourceId [ExaminationId], TRD.ServiceValue  
									FROM sOrderEntry.tStaticTestParameterMaster AS SPM  
									INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id  
									INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id  
									INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id  
									INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId  
									WHERE SPM.Id in (3, 5, 19, 20, 21, 25, 31, 32, 33, 34, 38, 107, 104, 105, 109, 108, 2, 27, 49, 166, 54, 58)
								)
								d PIVOT
								(
									MIN(ServiceValue) FOR Title IN  
									(
										[R.B.C. COUNT], [MCV], [F B S], [CHOLESTEROL], [TRIGLYCERIDE], [LDL], [HDL], [SGPT],  
										[ECG], [SONOGRAPHY], [TMT], [ECHO], [HB], [SERUM CREATININE], [SERUM URIC ACID], [HBA1C], [R B S], [P P B S], 
										[Waist Circumference], [TSH], [PSA], [XRAY]
									)
								) piv
							) AS Details ON Details.ExaminationId = EXM.Id
						) AS Details ON Details.ExaminationId = EXM.Id
						LEFT JOIN 
						(
							SELECT TR.SourceId AS ExaminationId, TRD.Remark
							FROM sExamination.tTestRequestDetail TRD
							INNER JOIN sOrderEntry.tTestDetail TTD ON TTD.Id = TRD.TestDetailId
							INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TTD.TestParameterId
							INNER JOIN sOrderEntry.tStaticTestParameterMaster SPM ON SPM.Id = TPM.StaticTestParameterId
							INNER JOIN sExamination.tTestRequest TR ON TR.Id = TRD.TestRequestId
							WHERE SPM.Id = 108
						) AS ECHO_REMARKS ON ECHO_REMARKS.ExaminationId = EXM.Id
						LEFT JOIN 
						(
							SELECT TR.SourceId AS ExaminationId, TRD.Remark
							FROM sExamination.tTestRequestDetail TRD
							INNER JOIN sOrderEntry.tTestDetail TTD ON TTD.Id = TRD.TestDetailId
							INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TTD.TestParameterId
							INNER JOIN sOrderEntry.tStaticTestParameterMaster SPM ON SPM.Id = TPM.StaticTestParameterId
							INNER JOIN sExamination.tTestRequest TR ON TR.Id = TRD.TestRequestId
							WHERE SPM.Id = 107
						) AS ECG_REMARKS ON ECG_REMARKS.ExaminationId = EXM.Id
						LEFT JOIN
						 (
						  SELECT EXM.ID [ExaminationId],DetailsVital.[BMI],DetailsVital.[BloodPressureSystolic], DetailsVital.[BloodPressureDiastolic]
						  FROM sExamination.tExamination AS EXM  
						  LEFT JOIN
						  (
						   SELECT VTL.SourceId [ExaminationId],
						   ISNULL(BMI, 0) as BMI, 
						   ISNULL(BloodPressureSystolic, 0) as BloodPressureSystolic,
						   ISNULL(BloodPressureDiastolic, 0) as BloodPressureDiastolic
						   FROM sExamination.tVital AS VTL
						  ) AS DetailsVital ON DetailsVital.ExaminationId = EXM.Id
						 ) AS DetailsVital ON DetailsVital.ExaminationId = EXM.Id
						WHERE EXM.ParticipantSourceTypeId = 95 AND (ot.HealthIndicatorCurrentStatus = 607 OR ot.HealthIndicatorCurrentStatus = 608)
						AND EXM.OrgId = @rOrgId;

						UPDATE PA SET PA.AssignToDoctorId = SE.SiteDoctorId,
							   PA.HealthIndicatorId = (CASE WHEN SE.SiteDoctorId IS NULL THEN 606 ELSE PA.HealthIndicatorId END),
							   PA.AssignDate = sCommon.fGetDate()
						FROM sSupport.tProviderAppointment AS PA
						INNER JOIN #tbltmpAHCTeam AS ot ON ot.ProviderAppointmentId = PA.Id
						INNER JOIN sExamination.tExamination AS EXM ON EXM.ParticipantSourceId = PA.PatientSourceId AND EXM.SetupId = PA.SetupId
						INNER JOIN sExamination.tSetupEmployee AS SE ON SE.SetupId = EXM.SetupId AND SE.EmployeeId = EXM.ParticipantSourceId
						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 EM ON EM.Id = EXM.ParticipantSourceId
						WHERE EXM.ParticipantSourceTypeId = 95
						AND EXM.OrgId = @rOrgId AND (ot.HealthIndicatorCurrentStatus = 607 OR ot.HealthIndicatorCurrentStatus = 608)
						AND (PA.HealthIndicatorId = 611 OR PA.HealthIndicatorId = 612);

						UPDATE tpa SET tpa.StatusId=CASE WHEN HealthIndicatorId = 611 OR HealthIndicatorId = 612 THEN @rStatusId 
                                                         WHEN HealthIndicatorId = 606 THEN 609 ELSE TPA.StatusId END,
							tpa.UpdatedDateTime = sCommon.fGetDate()
						FROM sSupport.tProviderAppointment AS tpa
						INNER JOIN #tbltmpAHCTeam AS ot ON ot.ProviderAppointmentId = tpa.Id
						INNER JOIN sExamination.tExamination AS EXM ON EXM.ParticipantSourceId = tpa.PatientSourceId AND EXM.SetupId = tpa.SetupId
						WHERE EXM.ParticipantSourceTypeId = 95 AND (ot.HealthIndicatorCurrentStatus = 607 OR ot.HealthIndicatorCurrentStatus = 608)
						AND EXM.OrgId = @rOrgId;

						Insert into sSupport.tProviderAppointmentlog
						select AHCT.ProviderAppointmentId, PA.StatusId, @rCreatedUserId, sCommon.fGetDate(),
							   'Refer to Doctor ' + ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '')
						from #tbltmpAHCTeam AHCT
						INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId
						LEFT JOIN sHRM.tEmployeeMaster EM ON EM.Id = PA.AssignToDoctorId
						WHERE (AHCT.HealthIndicatorCurrentStatus = 607 OR AHCT.HealthIndicatorCurrentStatus = 608)

						--Health Indicator Log
						Insert into sSupport.tProviderAppointmentHealthIndicatorLog
						select AHCT.ProviderAppointmentId, PA.HealthIndicatorId, @rCreatedUserId, sCommon.fGetDate(),
							   'Refer to Doctor ' + ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '')
						from #tbltmpAHCTeam AHCT
						INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId
						LEFT JOIN sHRM.tEmployeeMaster EM ON EM.Id = PA.AssignToDoctorId
						WHERE (AHCT.HealthIndicatorCurrentStatus = 607 OR AHCT.HealthIndicatorCurrentStatus = 608)
			END

		
		COMMIT TRANSACTION
		SELECT 1 AS Result
	END TRY
	
	BEGIN CATCH 
		IF @@TRANCOUNT > 0
        ROLLBACK
		--SELECT -1 AS Result
		select ERROR_MESSAGE() 
	END CATCH	

end

GO

CREATE OR ALTER PROCEDURE [sSupport].[pAssignEmployeeCustomSearchGet]
(
	@rOrgId smallint,
	@rAssignSurveyId int=0,
	@rCode [nvarchar](max) = '',
	@rDepartmentGroupId int = 0,	
	@rDepartmentId int = 0,	
	@rEmployeeTypeId int = 0,
	@rTargetGroupId int = 0,	
	@rBusinessId int = 0,	
	@rVerticalId int = 0,	
	@rCompanyGroupId int = 0,	
	@rCompanyId int = 0,	
	@rDesignationId int = 0,	
	@rGenderId int = 0,	
	@rProcessTypeId int = 0,
	@rLocationId int =0,
	@rIsShowExaminationEmployeeList bit,
    @rEmployeeId Bigint =0,
    @rSetupId int =0
 )
AS
SET NOCOUNT ON
BEGIN
if(@rIsShowExaminationEmployeeList = 'true')
begin
	SELECT EM.Id as EmployeeId,EM.Code AS EmployeeCode, ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS EmployeeName
	FROM sExamination.tExamination E
	inner join sExamination.tSetupMaster SM1	on E.SetupId = SM1.Id
		inner join sExamination.tSubTypeMaster STM on SM1.SubTypeId = STM.Id
		inner join sHrm.tEmployeeMaster EM on EM.Id = E.ParticipantSourceId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeJobTitleMaster EJTM ON EJTM.Id=EJD.EmployeeJobTitleId
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
		LEFT JOIN sHrm.tMedicalCoverageMaster MCM ON MCM.Id=EJD.MedicalCoverageId
		LEFT JOIN sCommon.tProcessTypeMaster PTM ON PTM.Id=EJD.ProcessTypeId
		LEFT JOIN sHrm.tSkillMaster SKM ON SKM.Id=EJD.SkillId
		INNER JOIN sCommon.tLocationMaster ELM ON ELM.Id = EJD.EmployeeLocationId 
		left JOIN sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
		INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=EPD.GenderId
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EPD.ReligionId
		LEFT JOIN sCommon.tMaritalStatusMaster MSM ON MSM.Id=EPD.MaritalStatusId
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=EPD.BloodGroupId
		LEFT JOIN sHrm.tNationalityMaster NM ON NM.Id=EPD.NationalityId
		LEFT JOIN sHrm.tQualificationMaster QM ON QM.Id=EPD.HigestQualificationId
		INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
		LEFT JOIN sHrm.tEmployeeCompanyMaster ECM ON ECM.Id = EJD.EmployeeCompanyId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4 
		LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id = EJD.ContractorId
		left join sHrm.tEmployeeCommunications ECO On ECO.EmployeeId=Em.id
		left join sHrm.tEmployeeLegalEntitymaster LEM On LEM.id=EJD.LegalEntityId
		left join sHrm.tCompanyGroupMaster CGM on CGM.Id=ECM.CompanyGroupId
		left join sHrm.tVerticalMaster VRM on VRM.Id=CGM.VerticalId
		left join sHrm.tSectorMaster S on S.Id=VRM.SectorId
 inner join sCommon.tDepartmentGroupMaster DGM on DGM.Id=ODM.DepartmentGroupId
 where EM.IsObsolete=0
    AND EM.OrgId = @rOrgId 
	AND (EM.Code in (SELECT a.Item FROM dbo.fSplitStr(@rCode,',') AS a where a.Item!='') or ISNULL(@rCode,'')='')
	AND (DGM.Id = @rDepartmentGroupId or isnull(@rDepartmentGroupId,0) = 0)
	AND (EJD.OrganizationDepartmentId = @rDepartmentId or isnull(@rDepartmentId,0) = 0)
	AND (EJD.EmployeeTypeId = @rEmployeeTypeId or isnull(@rEmployeeTypeId,0) = 0)
	AND (EM.TargetGroupId = @rTargetGroupId or isnull(@rTargetGroupId,0) = 0)
	AND (S.Id = @rBusinessId or isnull(@rBusinessId,0) = 0)
	AND (VRM.Id = @rVerticalId or isnull(@rVerticalId,0) = 0)
	AND (CGM.Id = @rCompanyGroupId or isnull(@rCompanyGroupId,0) = 0)
	AND (EJD.EmployeeCompanyId = @rCompanyId or isnull(@rCompanyId,0) = 0)
	AND (EJD.EmployeeDesignationId = @rDesignationId or isnull(@rDesignationId,0) = 0)
	AND (EPD.GenderId = @rGenderId or isnull(@rGenderId,0) = 0)
	AND (EJD.ProcessTypeId = @rProcessTypeId or isnull(@rProcessTypeId,0) = 0)	
	AND (EM.Id = @rEmployeeId OR ISNULL(@rEmployeeId, 0) = 0)
	AND EM.Id not in(select distinct ASD.SourceId from sSupport.tAssignSurveyMaster ASM inner join sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId where ASM.Id=@rAssignSurveyId and ASM.OrgId=@rOrgId)
	and E.SetupId = @rSetupId
end
	ELSE
BEGIN
	SELECT DISTINCT
		SE.EmployeeId,
        EM.Code AS EmployeeCode,
        ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName
	FROM sExamination.tSetupEmployee SE
    INNER JOIN sExamination.tSetupMaster SEM ON SEM.Id = SE.SetupId
	INNER JOIN sHrm.tEmployeeMaster EM ON SE.EmployeeId = EM.Id
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON DGM.Id = ODM.DepartmentGroupId
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
	LEFT JOIN sHrm.tEmployeeCompanyMaster ECM ON ECM.Id = EJD.EmployeeCompanyId
	LEFT JOIN sHrm.tCompanyGroupMaster CGM ON CGM.Id = ECM.CompanyGroupId
	LEFT JOIN sHrm.tVerticalMaster VRM ON VRM.Id = CGM.VerticalId
	LEFT JOIN sHrm.tSectorMaster S ON S.Id = VRM.SectorId
	LEFT JOIN sCommon.tLocationMaster LM ON LM.Id = EJD.EmployeeLocationId

	WHERE 
		EM.IsObsolete = 0
		AND EM.OrgId = @rOrgId
		AND SE.SetupId = @rSetupId  
		-- Code filter (supports single, CSV, LIKE)
		AND (
				EXISTS (
					SELECT 1
					FROM dbo.fSplitStr(@rCode, ',') s
					WHERE 
						(CHARINDEX(',', @rCode) = 0 AND EM.Code LIKE s.Item + '%')
						OR (CHARINDEX(',', @rCode) > 0 AND EM.Code = s.Item)
				)
				OR ISNULL(@rCode,'') = '' 
				OR ISNULL(@rCode,'') = '*'
			)

		-- Department Group
		AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)

		-- Department (support CSV)
		AND (
				EJD.OrganizationDepartmentId IN (
					SELECT Item FROM dbo.fSplitStr(@rDepartmentId, ',')
				)
				OR ISNULL(@rDepartmentId,'') = ''
			)

		-- Employee Type
		AND (EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)

		-- Target Group
		AND (EM.TargetGroupId = @rTargetGroupId OR @rTargetGroupId = 0)

		-- Business / Sector
		AND (S.Id = @rBusinessId OR @rBusinessId = 0)

		-- Vertical
		AND (VRM.Id = @rVerticalId OR @rVerticalId = 0)

		-- Company Group
		AND (CGM.Id = @rCompanyGroupId OR @rCompanyGroupId = 0)

		-- Company
		AND (EJD.EmployeeCompanyId = @rCompanyId OR @rCompanyId = 0)

		-- Designation
		AND (EJD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)

		-- Gender
		AND (EPD.GenderId = @rGenderId OR @rGenderId = 0)

		-- Process Type
		AND (EJD.ProcessTypeId = @rProcessTypeId OR @rProcessTypeId = 0)

		-- Location
		--AND (EJD.EmployeeLocationId = @rLocationId OR @rLocationId = 0)

		-- Employee filter
		AND (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND ISNULL(EM.IsObsolete,0)=0
		-- Exclude already assigned employees
		AND EM.Id NOT IN (
			SELECT ASD.SourceId
			FROM sSupport.tAssignSurveyMaster ASM
			INNER JOIN sSupport.tAssignSurveyDetail ASD 
				ON ASM.Id = ASD.AssignSurveyId
			WHERE ASM.Id = @rAssignSurveyId
			AND ASM.OrgId = @rOrgId
		)
END
END


GO


CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateMHIUpdationSurveyBulk]
( 
    @rUserId BIGINT,
    @rEmployeeMHISurveyBulkList [sWellness].[udt_MHIScoreUpdateThroughtSurveyBulk] READONLY,
    @Result INT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ModifiedRows INT = 0;

    MERGE [sWellness].[tMHIScoreUpdation] AS T
    USING
    (
        SELECT 
            E.Id AS ParticipantSourceId,
            M.Stress,
            M.LifeStyle
        FROM @rEmployeeMHISurveyBulkList M
        INNER JOIN [sHrm].[tEmployeeMaster] E
            ON E.Code = M.EmployeeCode
    ) AS S
    ON T.ParticipantSourceId = S.ParticipantSourceId

    WHEN MATCHED THEN
        UPDATE SET
            T.Stress = S.Stress,
            T.LifeStyle = S.LifeStyle,
            T.UpdatedUserId = @rUserId,
            T.UpdatedDateTime = sCommon.fGetDate()

    WHEN NOT MATCHED THEN
        INSERT
        (
            ParticipantSourceTypeId,
            ParticipantSourceId,
            Stress,
            LifeStyle,
            CreatedUserId,
            CreatedDateTime
        )
        VALUES
        (
            95,
            S.ParticipantSourceId,
            S.Stress,
            S.LifeStyle,
            @rUserId,
            sCommon.fGetDate()
        );

    SET @ModifiedRows = @@ROWCOUNT;
    SET @Result = @ModifiedRows;
END


GO


CREATE OR ALTER PROCEDURE [sWellness].[pAssignMHIProgramCategoryThroughSurveyBulk]
(
      @rOrgId SMALLINT
    , @rUserId BIGINT
    , @rEmployeeMHISurveyBulkList [sWellness].[udt_MHIScoreUpdateThroughtSurveyBulk] READONLY
    , @InsertedCount INT OUTPUT
    , @UpdatedCount INT OUTPUT
    , @SkippedEmployeeCodeCount INT OUTPUT
    , @TotalProcessed INT OUTPUT
)
AS
BEGIN

	SET NOCOUNT ON;

		BEGIN TRY
		BEGIN TRANSACTION;

			DECLARE @MergeResult TABLE( ActionType NVARCHAR(10), EmployeeId BIGINT );

			SELECT
				  EM.EmployeeId, S.Stress, S.LifeStyle
			INTO 
				#InputData
			FROM 
				@rEmployeeMHISurveyBulkList S
			JOIN 
				[sHrm].[vExtEmployeeMaster] EM
			ON 
				EM.Code = S.EmployeeCode;

			SELECT @SkippedEmployeeCodeCount =
			(
				SELECT 
					COUNT(*)
				FROM
					@rEmployeeMHISurveyBulkList S
				LEFT JOIN 
					sHrm.vExtEmployeeMaster EM ON EM.Code = S.EmployeeCode
				WHERE 
					EM.EmployeeId IS NULL
			);


			SELECT
				  I.EmployeeId
				, I.Stress
				, I.LifeStyle
				, CASE WHEN I.Stress IS NULL THEN NULL WHEN I.Stress <= 13 THEN 1 WHEN I.Stress <= 26 THEN 2 ELSE 3 END AS StressScore
				, CASE WHEN I.LifeStyle IS NULL THEN NULL WHEN I.LifeStyle <= 49 THEN 3 WHEN I.LifeStyle <= 70 THEN 2 ELSE 1 END AS LifestyleScore
			INTO 
				#Calculated
			FROM
				#InputData I;


			ALTER TABLE 
				#Calculated
			ADD 
				SurveyCategory VARCHAR(30), BiometricsCategory VARCHAR(30), MHICategory VARCHAR(30), MHICategoryId SMALLINT, ProgramId INT;


			UPDATE 
				#Calculated
			SET 
				SurveyCategory =
			CASE
				WHEN StressScore IS NULL OR LifestyleScore IS NULL THEN NULL
				WHEN StressScore = 3 OR LifestyleScore = 3 THEN 'Alert'
				WHEN StressScore = 2 OR LifestyleScore = 2 THEN 'SubOptimal'
				WHEN StressScore = 1 AND LifestyleScore = 1 THEN 'Optimal'
			END;


			UPDATE C
			SET 
				BiometricsCategory = T.BiometricsCategory
			FROM
				#Calculated C
			LEFT JOIN
				sWellness.tMHIScore T ON T.EmployeeId = C.EmployeeId;


			UPDATE 
				#Calculated
			SET 
				MHICategory =
			CASE
				WHEN BiometricsCategory IS NULL OR SurveyCategory IS NULL THEN 'NotApplicable'
				WHEN BiometricsCategory = 'Alert' OR SurveyCategory = 'Alert' THEN 'Alert'
				WHEN BiometricsCategory = 'SubOptimal' OR SurveyCategory = 'SubOptimal' THEN 'SubOptimal'
				WHEN BiometricsCategory = 'Optimal' AND SurveyCategory = 'Optimal' THEN 'Optimal'
				ELSE 'NotApplicable'
			END;


			UPDATE 
				#Calculated
			SET 
				MHICategoryId = CASE WHEN MHICategory = 'Optimal' THEN 1 WHEN MHICategory = 'SubOptimal' THEN 2 WHEN MHICategory = 'Alert' THEN 3 ELSE 0
			END;

			UPDATE C
			SET 
				ProgramId = ISNULL(PM.Id, 0)
			FROM 
				#Calculated C
			LEFT JOIN 
				[sWellness].[tStaticMHICategoryIndicator] I ON I.Id = C.MHICategoryId
			LEFT JOIN 
				[sWellness].[tProgramMaster] PM ON PM.MHIIndicatorId = I.Id
			AND 
				PM.CategoryId = 1
			AND 
				PM.IsObsolete = 0;


			UPDATE T
			SET
				Stress = C.Stress,
				StressScore = C.StressScore,
				StressCategory = CASE WHEN C.StressScore = 1 THEN 'Optimal' WHEN C.StressScore = 2 THEN 'SubOptimal' WHEN C.StressScore = 3 THEN 'Alert' END,
				Lifestyle = C.LifeStyle,
				LifestyleScore = C.LifestyleScore,
				LifestyleCategory = CASE WHEN C.LifestyleScore = 1 THEN 'Optimal' WHEN C.LifestyleScore = 2 THEN 'SubOptimal' WHEN C.LifestyleScore = 3 THEN 'Alert' END,
				SurveyCategory = C.SurveyCategory,
				MHICategory = C.MHICategory,
				MHICategoryId = C.MHICategoryId,
				ProgramId = C.ProgramId,
				UpdatedUserId = @rUserId,
				UpdatedDatetime = sCommon.fGetDate()

			OUTPUT 
				'UPDATE', inserted.EmployeeId INTO @MergeResult
			FROM 
				sWellness.tMHIScore T
			JOIN 
				#Calculated C
			ON 
				C.EmployeeId = T.EmployeeId;


			DECLARE @EmployeeId BIGINT, @NextId BIGINT;

			DECLARE curInsert CURSOR FAST_FORWARD FOR
			SELECT EmployeeId
			FROM #Calculated C
			WHERE NOT EXISTS
			(
				SELECT 1 FROM [sWellness].[tMHIScore] T WHERE T.EmployeeId = C.EmployeeId
			);

			OPEN curInsert;
				FETCH NEXT FROM curInsert INTO @EmployeeId;

				WHILE @@FETCH_STATUS = 0
				BEGIN

					EXEC sCommon.pTableRowIdGet @rOrgId,'sWellness.tMHIScore',0,1,1, @outNextNumber = @NextId OUTPUT;

					INSERT INTO sWellness.tMHIScore
					(
						Id, OrgId, EmployeeId,
						Stress, StressScore, StressCategory,
						Lifestyle, LifestyleScore, LifestyleCategory,
						SurveyCategory, MHICategory, MHICategoryId,
						ProgramId,
						CreatedUserId, CreatedDatetime
					)
					SELECT
						@NextId, @rOrgId, C.EmployeeId,
						C.Stress, C.StressScore, CASE WHEN C.StressScore = 1 THEN 'Optimal' WHEN C.StressScore = 2 THEN 'SubOptimal' WHEN C.StressScore = 3 THEN 'Alert' END,
						C.LifeStyle, C.LifestyleScore, CASE WHEN C.LifestyleScore = 1 THEN 'Optimal' WHEN C.LifestyleScore = 2 THEN 'SubOptimal' WHEN C.LifestyleScore = 3 THEN 'Alert' END,
						C.SurveyCategory, C.MHICategory, C.MHICategoryId,
						C.ProgramId,
						@rUserId, sCommon.fGetDate()
					FROM 
						#Calculated C
					WHERE
						C.EmployeeId = @EmployeeId;

					INSERT INTO @MergeResult VALUES ('INSERT', @EmployeeId);

					FETCH NEXT FROM curInsert INTO @EmployeeId;
				END

			CLOSE curInsert;
			DEALLOCATE curInsert;

			DECLARE @EmpId BIGINT;

			DECLARE curHistory CURSOR FAST_FORWARD FOR
			SELECT DISTINCT EmployeeId FROM @MergeResult;

			OPEN curHistory;
			FETCH NEXT FROM curHistory INTO @EmpId;

			WHILE @@FETCH_STATUS = 0
			BEGIN
				EXEC sWellness.pInsertMHIScoreHistoryIfChanged
					@rEmployeeId = @EmpId,
					@rUserId = @rUserId;

				FETCH NEXT FROM curHistory INTO @EmpId;
			END

			CLOSE curHistory;
			DEALLOCATE curHistory;


			SELECT
				@InsertedCount = ISNULL(SUM(CASE WHEN ActionType='INSERT' THEN 1 END),0),
				@UpdatedCount = ISNULL(SUM(CASE WHEN ActionType='UPDATE' THEN 1 END),0)
			FROM @MergeResult;

			SET @TotalProcessed = ISNULL(@InsertedCount,0) + ISNULL(@UpdatedCount,0) + ISNULL(@SkippedEmployeeCodeCount,0);

		COMMIT TRANSACTION;
		END TRY
		BEGIN CATCH

		IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;

		SET @InsertedCount = -1;
		SET @UpdatedCount = -1;
		SET @SkippedEmployeeCodeCount = -1;
		SET @TotalProcessed = -1;

		SELECT ERROR_MESSAGE() AS ErrorMessage, ERROR_LINE() AS ErrorLine;

		END CATCH
END

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,   
 [sSetup].[fPortalXMLTagsReplaceReverse](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 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

CREATE OR ALTER PROCEDURE [sExamination].[pGetAnnualHealthCheckupTicketAssignedAllDoctor]          
(
    @rOrgId INT,          
    @rTemplate NVARCHAR(MAX),          
    @rMailSubject NVARCHAR(MAX),          
    @rProviderAppointmentIds NVARCHAR(MAX) = '',          
    @rEventId INT        
)          
AS        
BEGIN          
    SET NOCOUNT ON;        

    -- ================= DOCTOR SUMMARY =================
    SELECT          
        EM.Id,        
        ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS EmployeeName,        
        EC.CompanyEmail AS ToDoctor,        
        STUFF((
            SELECT DISTINCT ',' + EC2.CompanyEmail        
            FROM sSupport.tProviderAppointment A2        
            INNER JOIN sHrm.tEmployeeCommunications EC_A2         
                ON EC_A2.EmployeeId = A2.AssignToDoctorId        
            LEFT JOIN sExamination.tSetupEmployee SE2         
                ON SE2.SetupId = A2.SetupId         
                AND SE2.EmployeeId = A2.PatientSourceId         
                AND SE2.SiteDoctorId = A2.AssignToDoctorId        
            LEFT JOIN sHrm.tEmployeeCommunications EC2         
                ON EC2.EmployeeId = SE2.CentralDoctorId        
            WHERE EC_A2.CompanyEmail = EC.CompanyEmail        
              AND SE2.EmployeeId IS NOT NULL        
              AND EC2.CompanyEmail IS NOT NULL        
            FOR XML PATH(''), TYPE        
        ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS CCDoctor        
    INTO #DoctorAssignmentSummary        
    FROM sSupport.tProviderAppointment A        
    INNER JOIN sHrm.tEmployeeMaster EM        
        ON EM.Id = A.AssignToDoctorId        
    INNER JOIN sHrm.tEmployeeCommunications EC         
        ON EC.EmployeeId = A.AssignToDoctorId        
    WHERE A.StatusId <> 591        
      AND ISNULL(A.AssignToDoctorId, 0) <> 0        
      AND (
            ISNULL(A.Id,0) IN (
                SELECT CAST(item AS INT) 
                FROM sCommon.fnsplit(ISNULL(@rProviderAppointmentIds,''),',')
            ) 
            OR ISNULL(@rProviderAppointmentIds,'')=''
          )        
    GROUP BY EM.Id, EM.FirstName, EM.LastName, EC.CompanyEmail;        


    -- ================= COUNT DATA =================
    SELECT          
        D.Id,        
        D.ToDoctor,        
        D.CCDoctor,        
        D.EmployeeName,        
        SUM(CASE WHEN A.AssignDate >= DATEADD(HOUR, -48, GETDATE()) THEN 1 ELSE 0 END) AS NewAssigned,        
        SUM(CASE WHEN A.AssignDate < DATEADD(HOUR, -48, GETDATE()) THEN 1 ELSE 0 END) AS LongOpen,  
        SUM(CASE WHEN A.HealthIndicatorId = 608 THEN 1 ELSE 0 END) AS HighRisk,  
        SUM(CASE WHEN A.HealthIndicatorId = 607 THEN 1 ELSE 0 END) AS Pending,  
        SUM(CASE WHEN A.HealthIndicatorId = 611 THEN 1 ELSE 0 END) AS Mild,  
        SUM(CASE WHEN A.HealthIndicatorId = 612 THEN 1 ELSE 0 END) AS Moderate  
    INTO #CountDoctorAssign        
    FROM sSupport.tProviderAppointment A        
    INNER JOIN #DoctorAssignmentSummary D 
        ON D.Id = A.AssignToDoctorId        
    WHERE A.StatusId <> 591  
    GROUP BY D.Id, D.ToDoctor, D.CCDoctor, D.EmployeeName;        


    -- ================= FINAL OUTPUT =================
    SELECT          
        C.Id,        
        C.ToDoctor AS EmailId,        
        C.CCDoctor AS strCC,        
        C.NewAssigned,   
        C.LongOpen,       
        C.Pending,        
        C.HighRisk,     
        C.Mild,        
        C.Moderate,     
        @rMailSubject AS Subject,

        CA1.MsgText
    FROM #CountDoctorAssign C       

    -- ================= TEMPLATE BUILD =================
    CROSS APPLY (
        SELECT 
            REPLACE(
            REPLACE(
                @rTemplate,
                '[AssignedDoctor]', C.EmployeeName
            ),
            '[dynamicfield]',

            CONCAT(

                 CASE WHEN C.NewAssigned > 0 
                    THEN 'New Assigned: ' + CAST(C.NewAssigned AS NVARCHAR(20)) + ' <br/> '
                    ELSE '' END,

                CASE WHEN C.LongOpen > 0 
                    THEN 'Long Open: ' + CAST(C.LongOpen AS NVARCHAR(20)) + ' <br/> '
                    ELSE '' END,

                CASE WHEN C.Pending > 0 
                    THEN 'Pending: ' + CAST(C.Pending AS NVARCHAR(20)) + ' <br/> '
                    ELSE '' END,

                CASE WHEN C.HighRisk > 0 
                    THEN 'High Risk: ' + CAST(C.HighRisk AS NVARCHAR(20)) + ' <br/> '
                    ELSE '' END,

                CASE WHEN C.Mild > 0 
                    THEN 'Mild: ' + CAST(C.Mild AS NVARCHAR(20)) + ' <br/> '
                    ELSE '' END,

                CASE WHEN C.Moderate > 0 
                    THEN 'Moderate: ' + CAST(C.Moderate AS NVARCHAR(20)) 
                    ELSE '' END

            )
        )
    ) CA1(MsgText)


    -- ================= CLEANUP =================
    IF OBJECT_ID('tempdb..#DoctorAssignmentSummary') IS NOT NULL              
        DROP TABLE #DoctorAssignmentSummary;        

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

END;

GO


CREATE OR ALTER PROCEDURE [sSupport].[pAHCCounsellingListGet]    
 @rOrgId smallint,          
 @rProviderId bigint = 0,          
 @rRoundGroupId bigint = 0,          
 @rHealthIndicatorId bigint = 0,          
 @rEmployeeCode nvarchar(100) = '',          
 @rEmployeeName nvarchar(100) = '',          
 @rStatusId int = 0,          
 @rSectorId varchar(100) = '',            
 @rVerticalId varchar(100) = '',            
 @rCompanyGroupId varchar(100) = '',            
 @rEmployeeCompanyId varchar(100) = '',            
 @rLocationMainGroupId varchar(100) = '',            
 @rLocationSubGroupId varchar(100) = '',            
 @rLocationId varchar(100) = '',            
 @rFunctionId varchar(100) = '',            
 @rDepartmentGroupId varchar(100) = '',            
 @rDepartmentId varchar(100) = '',            
 @rEmployeeTypeId varchar(100) = '',            
 @rGradeId varchar(100) = '',          
 @rTargetGroupId varchar(100) = '',          
 @rEmployeeDesignationId varchar(100) = '',          
 @rSectorIdEntity nvarchar(max)= '',          
 @rVerticalIdEntity nvarchar(max)= '',          
 @rCompanyGroupIdEntity nvarchar(max)= '',          
 @rCompanyIdEntity nvarchar(max)= '',           
 @rGradeIdEntity nvarchar(max)= '',          
 @rFunctionIdEntity nvarchar(max)= '',          
 @rStoreLocationIdEntity nvarchar(max)= '',          
 @rEmployeeTypeGroupId int = 0,          
 @rDoctorId bigint = 0,        
 @rCode NVARCHAR(MAX) = ''         
AS          
SET NOCOUNT ON          
BEGIN    
 declare @lAbnormalFindingsOrHealthIndicatorConfigVal varchar(5);     
                
 select @lAbnormalFindingsOrHealthIndicatorConfigVal = sConfig.fConfigurationValueGet('Provider.AbnormalFindingsOrHealthIndicatorParam',@rOrgId,0,0,0);    
     
 ---------------------------------------------------              
    -- Cache EventTemplate (IMPORTANT)              
    ---------------------------------------------------              
    DECLARE              
        @MailSubject NVARCHAR(MAX),              
        @MailTemplate NVARCHAR(MAX);              
              
    SELECT TOP 1              
        @MailSubject = MailSubject,              
        @MailTemplate = Template              
    FROM sAlert.tEventTemplate              
    WHERE OrgId = @rOrgId              
      AND EventId = 87              
      AND IsAutoSend = 1;              
      
    
  WITH LatestAlertLog AS     (               
   SELECT ProviderAppointmentId, CreatedDateTime as CreatedDate, ROW_NUMBER() OVER (PARTITION BY ProviderAppointmentId       
   ORDER BY CreatedDateTime DESC) AS RowNum               
   FROM sAlert.tAlertLog           
 )      
 SELECT PA.Id,EM.Id as EmployeeId,EM.Code as EmployeeCode,SCT.Id as BusinessSectorId,          
 ISNull(EM.FirstName, '') + ' ' + ISNull(EM.MiddleName, '') + ' ' + ISNull(EM.LastName, '') as EmployeeName,          
 MobileNumber = ISNULL(ECD.MobileNumber, ''),Department = ISNULL(ODM.Title, ''), CompanyEmail = ISNULL(ECD.CompanyEmail,''), EXM.ExaminationDate,        
 PA.AppointmentNumber, PA.AppointmentDate, PA.ProviderId, PM.Title as ProviderName,          
 PA.StatusId, SM.Title as Status, PA.RejectReason, AD.name as FileName, AD.configid as configId, ISNULL(PA.IsExcelUploaded, 0) as IsExcelUploaded,          
 Details.[SONOGRAPHY] as Sonography, Details.[XRAY] as Xray, Details.[ECG] as ECG, Details.[ECHO] as Echo, Details.[TMT] as TMT,          
 CASE WHEN @lAbnormalFindingsOrHealthIndicatorConfigVal = 'True' THEN AF.AbnormalFindingHtml    
      ELSE [dbo].[fGetDiagnosisDetailsofExamination](EXM.Id) END AS AbnormalFindings,     
 SCT.Title as Business, LM.Id as LocationId, LM.Title as [Location], SLM.Title as [ExaminationStoreLocation],         
 PA.CounsellingRemark as CounsellingRemark, PA.CounsellingRemarkId as CounsellingRemarkId, PA.CounsellingDate as CounsellingDate,PA.NonPathoParameters as CSVNonPathoParameters,          
 ISNULL(EMM.FirstName, '') + ' ' + ISNULL(EMM.LastName, '') AS AssignByDoctorName,PA.AssignDate, EJD.EmployeeStoreLocationId, ISNULL(PA.DocumentReuploadRemark, '') as DocumentReuploadRemark,        
 PA.PatientSourceId,PA.SetupId,MT.Title as ExaminationType,AL.CreatedDate,ISNULL(EMM1.FirstName, '') + ' ' + ISNULL(EMM1.LastName, '') AS AssignToDoctorName ,ISNULL(EMM1.FirstName, '') + ' ' + ISNULL(EMM1.LastName, '') AS AssignedDoctor    
 ,ISNULL(ECD1.ExtensionNo,'') as DoctorExtensionNo    
 ,sm1.title as HealthIndicator,    
 @MailSubject AS MailSubject,    
 @MailTemplate AS MailTemplate,    
 ISNULL(ECD1.CompanyEmail, '') + CASE WHEN ECD1.CompanyEmail IS NOT NULL AND ECD2.CompanyEmail IS NOT NULL 
    THEN ', ' ELSE '' END + ISNULL(ECD2.CompanyEmail, '') as Reportingmanagermail  
 ,VECD1.Gender
 FROM [sSupport].[tProviderAppointment] PA WITH (NOLOCK)          
 INNER JOIN [sExamination].[tExamination] EXM WITH (NOLOCK) ON EXM.ParticipantSourceId = PA.PatientSourceId AND EXM.SetupId = PA.SetupId          
 INNER JOIN sIp.tStoreLocationMaster SLM WITH (NOLOCK) ON SLM.Id = EXM.StoreLocationId        
 LEFT JOIN [sExamination].[tDiagnosis] DIA WITH (NOLOCK) ON DIA.SourceId = EXM.Id          
 INNER JOIN [sHrm].[tEmployeeMaster] EM WITH (NOLOCK) ON EM.Id = PA.PatientSourceId        
 INNER JOIN [sExamination].[tSetupMaster] SEM WITH (NOLOCK) ON SEM.Id = PA.SetupId        
 INNER JOIN sExamination.tSetupEmployee SE ON SE.EmployeeId = PA.PatientSourceId and SE.SetupId = PA.SetupId        
 LEFT JOIN sExamination.tSubTypeMaster ST on SEM.SubTypeId = ST.Id  LEFT JOIN sExamination.tMainTypeMaster MT on ST.MainTypeId = MT.Id        
 LEFT JOIN [sHrm].[tEmployeeMaster] EMM WITH (NOLOCK) ON EMM.Id = PA.AssignByDoctorId          
 LEFT JOIN [sHrm].[tEmployeeMaster] EMM1 WITH (NOLOCK) ON EMM1.Id = PA.AssignToDoctorId          
 LEFT JOIN [sSupport].[tProviderAppointmentDocument] AD WITH (NOLOCK) ON AD.ProviderAppointmentId = PA.Id          
 INNER JOIN [sSupport].[tProviderMaster] PM WITH (NOLOCK) ON PM.Id = PA.ProviderId          
 INNER JOIN sHrm.tEmployeeJobDetail EJD WITH (NOLOCK) ON EM.Id = EJD.EmployeeId          
 INNER JOIN [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id = EJD.EmployeeTypeId           
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id = EJD.EmployeeCompanyId          
 INNER JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id = ECM.CompanyGroupId          
 INNER JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID = CGM.VerticalId          
 INNER JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id = VTM.SectorId          
 INNER JOIN sCommon.tLocationMaster LM WITH (NOLOCK) ON LM.Id = EJD.EmployeeLocationId          
 LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LM.LocationSubGroupId              
 LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId          
 LEFT JOIN sCommon.tStatusMaster SM WITH (NOLOCK) ON SM.Id = PA.StatusId    
 LEFT JOIN sCommon.tStatusMaster SM1 WITH (NOLOCK) ON SM1.Id = PA.HealthIndicatorId      
 LEFT JOIN sHrm.tEmployeeCommunications AS ECD WITH (NOLOCK) ON ECD.EmployeeId = EM.Id          
 LEFT JOIN sHrm.tEmployeeCommunications AS ECD1 WITH (NOLOCK) ON ECD1.EmployeeId = EMM1.Id 
 LEFT JOIN sHrm.tEmployeeCommunications AS ECD2 WITH (NOLOCK) ON ECD2.EmployeeId = EJD.ReportingMangerEmployeeId
 LEFT JOIN sCommon.tOrganizationDepartmentMaster AS ODM WITH (NOLOCK) ON ODM.Id = EJD.OrganizationDepartmentId        
 LEFT JOIN sHrm.vEmployeeCustomSearch AS VECD1 WITH (NOLOCK) ON VECD1.EmployeeId =  ECD.EmployeeId     
 LEFT JOIN sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id          
 LEFT JOIN LatestAlertLog AL ON AL.ProviderAppointmentId = PA.Id AND AL.RowNum = 1
 OUTER APPLY [dbo].[fAbnormalFindingsHealthIndicator](EXM.Id) AF 
 LEFT JOIN          
 (          
  SELECT ExaminationId, [R.B.C. COUNT], [MCV], [F B S], [CHOLESTEROL], [TRIGLYCERIDE], [LDL], [HDL],            
    [SGPT], [ECG], [SONOGRAPHY], [TMT], [ECHO], [HB], [SERUM CREATININE], [SERUM URIC ACID], [HBA1C], [R B S], [P P B S],           
    [Waist Circumference], [TSH], [PSA], [XRAY]          
  FROM          
  (          
   SELECT SPM.Title, TR.SourceId [ExaminationId], LTRIM(RTRIM(TRD.Remark)) as Remark    
   FROM sOrderEntry.tStaticTestParameterMaster AS SPM            
   INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id            
   INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id            
   INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id            
   INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId            
   WHERE SPM.Id in (3, 5, 19, 20, 21, 25, 31, 32, 33, 34, 38, 107, 104, 105, 109, 108, 2, 27, 49, 166, 54, 58)          
  )          
  d PIVOT          
  (          
   MIN(Remark) FOR Title IN             (          
    [R.B.C. COUNT], [MCV], [F B S], [CHOLESTEROL], [TRIGLYCERIDE], [LDL], [HDL], [SGPT],            
    [ECG], [SONOGRAPHY], [TMT], [ECHO], [HB], [SERUM CREATININE], [SERUM URIC ACID], [HBA1C], [R B S], [P P B S],           
    [Waist Circumference], [TSH], [PSA], [XRAY]          
   )          
  ) piv          
 ) AS Details ON Details.ExaminationId = EXM.Id          
 WHERE PA.OrgId = @rOrgId           
 AND (PA.StatusId = @rStatusId OR ISNULL(@rStatusId, 0) = 0)          
 AND (PA.ProviderId = @rProviderId OR ISNULL(@rProviderId, 0) = 0)          
 AND (PA.AssignToDoctorId = @rDoctorId OR ISNULL(@rDoctorId, 0) = 0)          
 AND (SEM.SetUpGroupId = @rRoundGroupId OR ISNULL(@rRoundGroupId, 0) = 0)          
 AND (PA.HealthIndicatorId = @rHealthIndicatorId OR ISNULL(@rHealthIndicatorId, 0) = 0)          
 AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')          
 AND ((ISNull(EM.FirstName, '') + ' ' + ISNull(EM.MiddleName, '') + ' ' + ISNull(EM.LastName, '')) like '%' + @rEmployeeName + '%'          
 OR ISNULL(@rEmployeeName,'') = '')          
          
 AND ((VTM.SectorId  IN(SELECT item FROM sCommon.fnsplit(@rSectorId,','))) OR (ISNULL(@rSectorId,'') = ''))            
 AND ((LMG.Id  IN(SELECT item FROM sCommon.fnsplit(@rLocationMainGroupId,','))) OR (ISNULL(@rLocationMainGroupId,'') = ''))            
 AND ((CGM.VerticalId  IN(SELECT item FROM sCommon.fnsplit(@rVerticalId,','))) OR (ISNULL(@rVerticalId,'') = ''))            
 AND ((ECM.CompanyGroupId  IN(SELECT item FROM sCommon.fnsplit(@rCompanyGroupId,','))) OR (ISNULL(@rCompanyGroupId,'') = ''))            
 AND ((EJD.EmployeeCompanyId  IN(SELECT item FROM sCommon.fnsplit(@rEmployeeCompanyId,','))) OR (ISNULL(@rEmployeeCompanyId,'') = ''))            
 AND ((LSG.Id  IN(SELECT item FROM sCommon.fnsplit(@rLocationSubGroupId,','))) OR (ISNULL(@rLocationSubGroupId,'') = ''))            
 AND ((LM.Id  IN(SELECT item FROM sCommon.fnsplit(@rLocationId,','))) OR (ISNULL(@rLocationId,'') = ''))            
 AND ((DGM.FunctionId  IN(SELECT item FROM sCommon.fnsplit(@rFunctionId,','))) OR (ISNULL(@rFunctionId,'') = ''))            
 AND ((ODM.DepartmentGroupId  IN(SELECT item FROM sCommon.fnsplit(@rDepartmentGroupId,','))) OR (ISNULL(@rDepartmentGroupId,'') = ''))            
 AND ((EJD.OrganizationDepartmentId  IN(SELECT item FROM sCommon.fnsplit(@rDepartmentId,','))) OR (ISNULL(@rDepartmentId,'') = ''))            
 AND ((EJD.EmployeeTypeId  IN(SELECT item FROM sCommon.fnsplit(@rEmployeeTypeId,','))) OR (ISNULL(@rEmployeeTypeId,'') = ''))            
 AND ((EJD.GradeId  IN(SELECT item FROM sCommon.fnsplit(@rGradeId,','))) OR (ISNULL(@rGradeId,'') = ''))            
 AND ((EJD.EmployeeDesignationId  IN(SELECT item FROM sCommon.fnsplit(@rEmployeeDesignationId,','))) OR (ISNULL(@rEmployeeDesignationId,'') = ''))            
 AND ((EXM.TargetGroupId  IN(SELECT item FROM sCommon.fnsplit(@rTargetGroupId,','))) OR (ISNULL(@rTargetGroupId,'') = ''))          
          
 AND (ISNULL(SCT.Id,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rSectorIdEntity,''),','))OR ISNULL(@rSectorIdEntity,'')='')          
 AND (ISNULL(VTM.Id,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalIdEntity,''),','))OR ISNULL(@rVerticalIdEntity,'')='')          
 AND (ISNULL(ECM.CompanyGroupId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyGroupIdEntity,''),','))OR ISNULL(@rCompanyGroupIdEntity,'')='')          
 AND (ISNULL(EJD.EmployeeCompanyId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyIdEntity,''),','))OR ISNULL(@rCompanyIdEntity,'')='')          
 AND (ISNULL(EJD.GradeId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rGradeIdEntity,''),','))OR ISNULL(@rGradeIdEntity,'')='')          
 AND (ISNULL(DGM.FunctionId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rFunctionIdEntity,''),','))OR ISNULL(@rFunctionIdEntity,'')='')          
 AND (ISNULL(EXM.StoreLocationId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rStoreLocationIdEntity,''),','))OR ISNULL(@rStoreLocationIdEntity,'')='')         
 AND (ETM.EmployeeTypeGroupId = @rEmployeeTypeGroupId OR @rEmployeeTypeGroupId = 0)     
   AND EM.Code like @rEmployeeCode + '%'       
 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 ISNULL(@rCode, '') = ''  )    
 Order by EXM.ExaminationDate ASC    
END

GO


CREATE OR ALTER PROCEDURE [sExamination].[pGetEmployeeTestParameter] 
(
	@rOrgId SMALLINT,
	@rEmployeeCode NVARCHAR(100)
)
AS
SET NOCOUNT ON;
BEGIN

	DECLARE @EmployeeId BIGINT =
	(
		SELECT Id 
		FROM [sHrm].[tEmployeeMaster] 
		WHERE Code = @rEmployeeCode
	)
	

	IF(@EmployeeId IS NULL OR @EmployeeId = 0)
	BEGIN
		RETURN;
	END

	CREATE TABLE #EmployeeExamination
	(
		EId BIGINT PRIMARY KEY,
		ExaminationDate DATE,
		Round NVARCHAR(1000),
		RoundGroup NVARCHAR(1000)
	)

	INSERT INTO #EmployeeExamination
	SELECT 
		Exam.Id,
		Exam.ExaminationDate,
		SM.Title,
		SGM.Title
	FROM [sExamination].[tExamination] Exam
	INNER JOIN
		[sExamination].[tSetupMaster] SM 
	ON 
		SM.Id = Exam.SetupId
	INNER JOIN
		[sExamination].[tSetupGroupMaster] SGM 
	ON 
		SGM.Id = SM.SetupGroupId
	WHERE 
		Exam.ParticipantSourceId = @EmployeeId
	AND
		SM.[Id] <> [sCommon].[fGetIntIdForOrg](8,@rOrgId)


	---------------------------------------------------
	-- 2. Centralized Test Data
	---------------------------------------------------
	CREATE TABLE #TestData
	(
		EId BIGINT,
		ExaminationDate DATE,
		StaticTestParameterId INT,
		ServiceValue NVARCHAR(100)
	)

	INSERT INTO #TestData
	SELECT 
		E.Id,
		E.ExaminationDate,
		TP.StaticTestParameterId,
		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
	INNER JOIN sExamination.tSetupMaster SM ON SM.Id = E.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM ON STM.Id = SM.SubTypeId
	WHERE 
		E.ParticipantSourceId = @EmployeeId
		AND E.ParticipantSourceTypeId = 95
		AND ISNULL(TRD.ServiceValue,'') <> ''		
		AND TP.StaticTestParameterId IN (2,19,20,21,25,27,31,32,33,34,38,49,54,126,127)

	CREATE NONCLUSTERED INDEX IX_TestData 
	ON #TestData (StaticTestParameterId, ExaminationDate DESC)

	SELECT 
		EE.ExaminationDate,
		EE.Round,
		EE.RoundGroup,
		ISNULL(CONVERT(DECIMAL(10,2), ROUND(D.HealthIndex,2)),0) AS HealthIndex,
		ISNULL(Vtl.BMI,0) AS BMI,
		ISNULL(Vtl.BloodPressureSystolic,0) AS BPSystolic,
		ISNULL(Vtl.BloodPressureDiastolic,0) AS BPDiastolic,
		ISNULL(HBData.HB,0) AS HB,
		ISNULL(HBA1CData.HBA1C,0) AS HBA1C,
		ISNULL(Vtl.BodyWeight,0) AS Weight,
		ISNULL(CholData.Cholesterol,0) AS Cholesterol,
		ISNULL(FBSData.FBS,0) AS FBS,
		ISNULL(HDLData.HDL,0) AS HDL,
		ISNULL(LDLData.LDL,0) AS LDL,
		ISNULL(PPBSData.PPBS,0) AS PPBS,
		ISNULL(RBSData.RBS,0) AS RBS,
		ISNULL(CreatinineData.SerumCreatinine,0) AS SerumCreatinine,
		ISNULL(UricAcidData.UricAcid,0) AS SerumUricAcid,
		ISNULL(SGPTData.SGPT,0) AS SGPT,
		ISNULL(TriglycerideData.Triglyceride,0) AS Triglyceride,
		ISNULL(TSHData.TSH,0) AS TSH,
		ISNULL(B12Data.VitaminB12,0) AS VitaminB12,
		ISNULL(D3Data.VitaminD3,0) AS VitaminD3
	FROM 
		#EmployeeExamination EE
	LEFT JOIN 
		[sExamination].[tVital] Vtl ON Vtl.SourceId = EE.EId
	LEFT JOIN 
		[sExamination].[tExamination] E ON E.Id = EE.EId AND E.ParticipantSourceTypeId = 95
	LEFT JOIN 
		[sExamination].[tDiagnosis] D ON D.SourceId = E.Id AND ISNULL(D.HealthIndex,0) > 0
	LEFT JOIN 
		[sExamination].[tSetupMaster] SM  ON SM.Id = E.SetupId
	LEFT JOIN 
		[sExamination].[tSubTypeMaster] STM ON STM.Id = SM.SubTypeId AND STM.MainTypeId = 1
	OUTER APPLY	-- FBS (19)
	(
		SELECT TOP 1 TD.ServiceValue AS FBS
		FROM #TestData TD WHERE TD.StaticTestParameterId = 19 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) FBSData

	OUTER APPLY -- HBA1C (25)
	(
		SELECT TOP 1 TD.ServiceValue AS HBA1C
		FROM #TestData TD WHERE TD.StaticTestParameterId = 25 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) HBA1CData

	OUTER APPLY -- LDL (34)
	(
		SELECT TOP 1 TD.ServiceValue AS LDL
		FROM #TestData TD WHERE TD.StaticTestParameterId = 34 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) LDLData

	OUTER APPLY -- Cholesterol (31)
	(
		SELECT TOP 1 TD.ServiceValue AS Cholesterol
		FROM #TestData TD WHERE TD.StaticTestParameterId = 31 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) CholData

	OUTER APPLY -- RBS (21)
	(
		SELECT TOP 1 TD.ServiceValue AS RBS
		FROM #TestData TD WHERE TD.StaticTestParameterId = 21 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) RBSData

	OUTER APPLY -- HB (2)
	(
		SELECT TOP 1 TD.ServiceValue AS HB
		FROM #TestData TD WHERE TD.StaticTestParameterId = 2 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) HBData

	OUTER APPLY -- HDL (2)
	(
		SELECT TOP 1 TD.ServiceValue AS HDL
		FROM #TestData TD WHERE TD.StaticTestParameterId = 33 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) HDLData

	OUTER APPLY -- PPBS (20)
	(
		SELECT TOP 1 TD.ServiceValue AS PPBS
		FROM #TestData TD WHERE TD.StaticTestParameterId = 20 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) PPBSData

	OUTER APPLY -- SERUM CREATININE (27)
	(
		SELECT TOP 1 TD.ServiceValue AS SerumCreatinine
		FROM #TestData TD WHERE TD.StaticTestParameterId = 27 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) CreatinineData

	OUTER APPLY -- SERUM URIC ACID (49)
	(
		SELECT TOP 1 TD.ServiceValue AS UricAcid
		FROM #TestData TD WHERE TD.StaticTestParameterId = 49 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) UricAcidData

	OUTER APPLY -- SGPT (38)
	(
		SELECT TOP 1 TD.ServiceValue AS SGPT
		FROM #TestData TD WHERE TD.StaticTestParameterId = 38 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) SGPTData

	OUTER APPLY -- Triglyceride (32)
	(
		SELECT TOP 1 TD.ServiceValue AS Triglyceride
		FROM #TestData TD WHERE TD.StaticTestParameterId = 32 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) TriglycerideData

	OUTER APPLY -- TSH (54)
	(
		SELECT TOP 1 TD.ServiceValue AS TSH
		FROM #TestData TD WHERE TD.StaticTestParameterId = 54 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) TSHData
	
	OUTER APPLY -- Vitamin B12 (126)
	(
		SELECT TOP 1 TD.ServiceValue AS VitaminB12
		FROM #TestData TD WHERE TD.StaticTestParameterId = 126 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) B12Data
	
	OUTER APPLY -- Vitamin D3 (127)
	(
		SELECT TOP 1 TD.ServiceValue AS VitaminD3
		FROM #TestData TD WHERE TD.StaticTestParameterId = 127 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) D3Data

	ORDER BY EE.ExaminationDate DESC
	
	DROP TABLE #EmployeeExamination
	DROP TABLE #TestData

END

GO



