
IF NOT EXISTS (SELECT * FROM [sCommon].[tDepends] WHERE Id = 20325)
BEGIN
    INSERT INTO [sCommon].[tDepends] 
    (Id, ParentTable, DependentTable, FunctionalityType, ScreenId, TableId)
    VALUES 
    (20325, 'sWellness.tWellnessSessionSubTypeMaster', 'sWellness.tWellnessSessionActivityDetail.WellnessSessionSubTypeMasterId', 1, 20943, 29214);
END
ELSE
BEGIN
    SELECT 'Id 20325 Already Exists'
END
IF NOT EXISTS (SELECT * FROM [sCommon].[tDepends] WHERE Id = 20326)
BEGIN
    INSERT INTO [sCommon].[tDepends] 
    (Id, ParentTable, DependentTable, FunctionalityType, ScreenId, TableId)
    VALUES 
    (20326, 'sWellness.tWellnessSessionTypeMaster', 'sWellness.tWellnessSessionActivityDetail.WellnessSessionTypeMasterId', 1, 20943, 29214);
END
ELSE
BEGIN
    SELECT 'Id 20326 Already Exists'
END

GO


DECLARE @OrgId smallint = (select ID from sCommon.tCompanyInformation Where id > 100);

IF NOT EXISTS (SELECT 1 FROM sCommon.tTableRowId WHERE TableTitle ='sWellness.tWellnessSessionTypeMaster')
BEGIN
Insert into sCommon.tTableRowId(OrgId,	TableTitle,	CurrentNumber,	Seed,	Increment,	DataType,	UpdatedDateTime)
Values (@OrgId,	'sWellness.tWellnessSessionTypeMaster', [sCommon].[fGetIntIdForOrg](0, @OrgId),	1,	1,	NULL,	sCommon.fGetDate())
 END
ELSE
BEGIN
    SELECT 'sWellness.tWellnessSessionTypeMaster  Already Exists';
END;

GO

IF NOT EXISTS (SELECT 1 FROM sSecurity.tScreen WHERE Id = 20939)
BEGIN
    INSERT INTO sSecurity.tScreen 
	(Id, Title, TitleResourceKeyId, TaskId, Page, IsObsolete, ScreenGroupId, OrderIndex, ScreenTypeId, IconPath, IsHideInScreenGroup, HelpPath, PHIAccessLevel)
    VALUES 
	(20939, 'Wellness Session Type', NULL, 21005, '~/Pages/Wellness/WellnessSessionType/Index', 0, 216, 18, NULL, '', 0, NULL, 0
    );
END
ELSE
BEGIN
    SELECT '20939 Already Exists' AS Message;
END;


IF NOT EXISTS (SELECT 1 FROM sSecurity.tScreen WHERE Id = 20940)
BEGIN
    INSERT INTO sSecurity.tScreen 
	(Id, Title, TitleResourceKeyId, TaskId, Page, IsObsolete, ScreenGroupId, OrderIndex, ScreenTypeId, IconPath, IsHideInScreenGroup, HelpPath, PHIAccessLevel)
    VALUES 
	(20940, 'Wellness Session Sub Type', NULL, 21005, '~/Pages/Wellness/WellnessSessionSubType/Index', 0, 216, 19, NULL, '', 0, NULL, 0
    );
END
ELSE
BEGIN
    SELECT '20940 Already Exists' AS Message;
END;

GO

IF NOT EXISTS (SELECT 1 FROM sSecurity.tScreen WHERE Id = 21091)

BEGIN

    INSERT INTO sSecurity.tScreen 

	(Id, Title, TitleResourceKeyId, TaskId, Page, IsObsolete, ScreenGroupId, OrderIndex, ScreenTypeId, IconPath, IsHideInScreenGroup, HelpPath, PHIAccessLevel)

    VALUES 

	(21091, 'Wellness Session Type', NULL, 21031, '~/main/timemanagement/ImportShiftRoasterData', 0, 215, 3, NULL, '', 0, NULL, 0 );

END

ELSE

BEGIN

    SELECT '21091 Already Exists' AS Message;

END;
IF NOT EXISTS (SELECT 1 FROM sSecurity.tScreen WHERE Id = 21092)

BEGIN

    INSERT INTO sSecurity.tScreen 

	(Id, Title, TitleResourceKeyId, TaskId, Page, IsObsolete, ScreenGroupId, OrderIndex, ScreenTypeId, IconPath, IsHideInScreenGroup, HelpPath, PHIAccessLevel)

    VALUES 

	(21092, 'Wellness Sub Session Type', NULL, 21031, '~/main/timemanagement/ImportShiftRoasterData', 0, 215, 3, NULL, '', 0, NULL, 0 );

END

ELSE

BEGIN

    SELECT '21092 Already Exists' AS Message;

END;
IF NOT EXISTS (SELECT * FROM [sSecurity].[tTask] WHERE Id = 21091)
BEGIN
    INSERT INTO [sSecurity].[tTask] (
        Id, Title, TitleResourceKeyId, IsObsolete, ModuleId, 
        AvailablePermission, OrderIndex, ResourceTypeId, IsClientSpecific
    ) VALUES
    (21091, 'Wellness Session Type', 0, 0, 198, 31, 19, 2, 1)
END
ELSE
BEGIN
    SELECT '21091 Already Exists';
END
IF NOT EXISTS (SELECT * FROM [sSecurity].[tTask] WHERE Id = 21092)
BEGIN
    INSERT INTO [sSecurity].[tTask] (
        Id, Title, TitleResourceKeyId, IsObsolete, ModuleId, 
        AvailablePermission, OrderIndex, ResourceTypeId, IsClientSpecific
    ) VALUES
    (21092, 'Wellness Session Sub Type', 0, 0, 198, 31, 20, 2, 1)
END
ELSE
BEGIN
    SELECT '21092 Already Exists';
END

GO


CREATE TABLE [sWellness].[tWellnessSessionActivityDetail](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](250) NOT NULL,
	[ActivityDate] [datetime] NULL,
	[Description] [nvarchar](max) NULL,
	[WellnessSessionTypeMasterId] [int] NULL,
	[WellnessSessionSubTypeMasterId] [int] NULL,
	[IsObsolete] [bit] NOT NULL,
	[OrgId] [int] NOT NULL,
	[CreatedUserId] [bigint] NOT NULL,
	[CreatedDatetime] [datetime] NOT NULL,
	[UpdatedUserId] [bigint] NULL,
	[UpdatedDatetime] [datetime] NULL,
	[EmployeeCount] [nvarchar](50) NULL,
	[StoreLocationId] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [sWellness].[tWellnessSessionActivityDetail] ADD  DEFAULT ((0)) FOR [IsObsolete]
GO

ALTER TABLE [sWellness].[tWellnessSessionActivityDetail] ADD  DEFAULT (getdate()) FOR [CreatedDatetime]
GO





CREATE TABLE [sWellness].[tWellnessSessionActivityDocument](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[WellnessSessionActivityId] [int] NOT NULL,
	[OrgId] [int] NOT NULL,
	[FileName] [nvarchar](500) NULL,
	[FilePath] [nvarchar](max) NULL,
	[SessionTempFolderName] [nvarchar](500) NULL,
	[ConfigId] [int] NULL,
	[ConfigurationTypeId] [int] NULL,
	[IsObsolete] [bit] NOT NULL,
	[CreatedUserId] [bigint] NOT NULL,
	[CreatedDatetime] [datetime] NOT NULL,
	[FileSize] [nvarchar](100) NULL,
PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [sWellness].[tWellnessSessionActivityDocument] ADD  DEFAULT ((0)) FOR [IsObsolete]
GO

ALTER TABLE [sWellness].[tWellnessSessionActivityDocument] ADD  DEFAULT (getdate()) FOR [CreatedDatetime]
GO





ALTER TABLE [sWellness].[tWellnessConsultation]
ADD OPDId BIGINT

ALTER TABLE sExamination.tArchieveOPD
ADD [MobileNumber] [nvarchar](50) NULL,
	[VisitTypeId] [int] NULL, 
	[WellnessConsultationId] BIGINT
	
ALTER TABLE sExamination.tOPD
ADD WellnessConsultationId BIGINT

GO


Declare @rOrgId int = (select ID from sCommon.tCompanyInformation Where id > 100);

update sCommon.tTableRowId set CurrentNumber = [sCommon].[fGetBigIntIdForOrg](0,@rOrgId) where TableTitle = 'sWellness.tAppointment'
update sCommon.tTableRowId set CurrentNumber = [sCommon].[fGetBigIntIdForOrg](0,@rOrgId) where TableTitle = 'sWellness.tConsultationAdditionalFieldMaster'
update sCommon.tTableRowId set CurrentNumber = [sCommon].[fGetBigIntIdForOrg](0,@rOrgId) where TableTitle = 'sWellness.tConsultationTestRequest'
update sCommon.tTableRowId set CurrentNumber = [sCommon].[fGetBigIntIdForOrg](0,@rOrgId) where TableTitle = 'sWellness.tGeneralTemplateConsultation'
update sCommon.tTableRowId set CurrentNumber = [sCommon].[fGetBigIntIdForOrg](0,@rOrgId) where TableTitle = 'sWellness.tWellnessRegistration'
update sCommon.tTableRowId set CurrentNumber = [sCommon].[fGetBigIntIdForOrg](0,@rOrgId) where TableTitle = 'sExamination.tAdditionalFieldMaster'

GO


CREATE OR ALTER PROCEDURE[sAppointment].[pAppointmentListGet]
    @rOrgId INT,      
    @rId BIGINT = 0,      
    @rFromDate DATETIME,      
    @rToDate DATETIME,      
    @rEmployeeCode NVARCHAR(20) = '',      
    @rPatientName NVARCHAR(500) = '',      
    @rStoreLocationId INT = 0,      
    @rLocationId INT = 0,      
    @rSetupId INT = 0,      
    @rDoctorEmployeeId BIGINT = 0,      
    @rEmployeeStoreLocationId INT = 0      
AS      
BEGIN    
    SET @rEmployeeCode = CASE     
        WHEN CHARINDEX('*', @rEmployeeCode) > 0    
            THEN REPLACE(@rEmployeeCode, '*', '%')    
        ELSE '%' + @rEmployeeCode + '%'    
    END;
    
    SELECT     
        A.Id,    
        A.AppointmentNumber,    
        A.PatientSourceTypeId,    
        A.PatientSourceId,    
        A.PatientName,    
        A.AppointmentDate,    
        ISNULL(A.FromTime, CONVERT(DATETIME, A.AppointmentDate)) AS FromTime,    
        ISNULL(A.ToTime, CONVERT(DATETIME, A.AppointmentDate)) AS ToTime,    
        ISNULL(A.DoctorEmployeeId, 0) AS DoctorEmployeeId,    
        A.EmployeeCode,    
        A.EmployeeId,    
        REPLACE(A.Relation, 'Ohter', 'Other') AS Relation,    
        --A.Gender,    
		case when A.PatientSourceTypeId = 95 then isnull((SELECT Title FROM sCommon.tGenderMaster WHERE Id=ED.GenderId),'')
	     when A.PatientSourceTypeId = 1009 then isnull((SELECT Title FROM sCommon.tGenderMaster WHERE Id=CBM.GenderId),'') end as Gender,
        A.DoctorName,    
        A.OrgId,    
        A.IsRegister,    
        A.IsObsolete,    
        A.StatusName,    
        A.DepartmentName,    
        ISNULL(A.DepartmentId, 0) AS DepartmentId,    
        A.DependentId,    
        A.StoreLocationId,    
        A.SetupId,    
        A.ExaminationTypeId,    
        A.MainType,    
        A.Setup,    
        A.ReferSourceId,    
        A.LocationId,    
        ISNULL(A.CauseId, -1) AS CauseId,    
        A.StoreLocation,    
        ISNULL(A.OtherName, '') AS OtherName,    
        ISNULL(A.FollowupRemark, '') AS FollowupRemark,    
	    ISNULL(A.CompliantRemark, '') AS CompliantRemark,   
        A.Age,    
        A.Months,    
        A.GenderId,    
        A.ExaminationId,    
        A.Timeslot, 
		(CASE WHEN A.PatientSourceTypeId = 95 THEN sExamination.fGetLatestHeight(A.PatientSourceId) ELSE 0 END) as Height,
		CASE  
		    WHEN A.PatientSourceTypeId=95 THEN ISNULL(ED.CompanyEmail,'') 
			WHEN A.PatientSourceTypeId=1009 THEN ISNULL(CBM.EmailId,'')  
			ELSE '' 
		END AS EmailId,
        CASE  
		    WHEN A.PatientSourceTypeId=95 THEN ISNULL(ED.MobileNumber,'') 
			WHEN A.PatientSourceTypeId=1009 THEN ISNULL(CBM.MobileNo,'') 
			ELSE '' 
		END AS MobileNumber
    FROM     
        sAppointment.vExtPatientAppointmentDetail A    
    LEFT JOIN     
        sExamination.tExamination E ON A.ExaminationId = E.Id    
        OR A.ReferSourceId = E.Id
	LEFT JOIN
	    sHrm.tEmployeeMaster EM ON EM.Id = A.EmployeeId AND A.PatientSourceTypeId=95
	LEFT JOIN 
	    sHrm.vEmployeeDetail ED ON ED.Id = A.EmployeeId AND A.PatientSourceTypeId=95
    LEFT JOIN 
	    sHrm.tCsrBenefiterMaster CBM ON CBM.Id = A.EmployeeId AND A.PatientSourceTypeId=1009
    WHERE     
        A.ApprovalStatusId = 548    
        AND A.AppointmentDate BETWEEN ISNULL(@rFromDate, sCommon.fGetDate()) AND ISNULL(@rToDate, sCommon.fGetDate())    
        AND (A.Id = @rId OR @rId = 0)    
        AND A.OrgId = @rOrgId    
        AND (A.PatientName LIKE @rPatientName + '%' OR A.OtherName LIKE @rPatientName + '%' OR ISNULL(@rPatientName, '') = '')    
        AND (A.EmployeeCode LIKE @rEmployeeCode OR ISNULL(@rEmployeeCode, '') = '')
		AND (
    A.PatientSourceTypeId <> 95
    OR
    (
        A.PatientSourceTypeId = 95
        AND (
            ((EM.StatusId = 9 OR EM.IsObsolete = 1) AND A.ExaminationId > 0)
            OR
            (EM.StatusId <> 9 AND EM.IsObsolete <> 1)
        )
    )
)
        --AND (A.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)
		AND (
             (
               @rStoreLocationId = 0
               AND EXISTS (
                    SELECT 1
                    FROM sCwb.tDoctorStoreLocation DSL
                    WHERE DSL.EmployeeId = @rDoctorEmployeeId
                      AND DSL.SubLocationId = A.StoreLocationId
               )
             )
             OR (
                 @rStoreLocationId <> 0
                 AND A.StoreLocationId = @rStoreLocationId
                 AND EXISTS (
                      SELECT 1
                      FROM sCwb.tDoctorStoreLocation DSL
                      WHERE DSL.EmployeeId = @rDoctorEmployeeId
                        AND DSL.SubLocationId = @rStoreLocationId
                 )
                )
            )
        AND (A.LocationId = @rLocationId OR @rLocationId = 0)    
        AND (A.SetupId = @rSetupId OR @rSetupId = 0)    
        --AND (A.DoctorEmployeeId = @rDoctorEmployeeId OR @rDoctorEmployeeId = 0 OR A.DoctorEmployeeId = 0) 
		AND (
             (
               -- Case 1: @rDoctorEmployeeId = 0 → A.DoctorEmployeeId must exist in DoctorMaster
               @rDoctorEmployeeId = 0
               AND EXISTS (
                   SELECT 1
                   FROM sCwb.tDoctorMaster DM
                   WHERE DM.EmployeeId = A.DoctorEmployeeId
               )
             )
             OR
             (
               -- Case 2: @rDoctorEmployeeId <> 0 → A.DoctorEmployeeId = @rDoctorEmployeeId OR 0
               @rDoctorEmployeeId <> 0
               AND (
                    A.DoctorEmployeeId = @rDoctorEmployeeId
                    OR A.DoctorEmployeeId = 0
               )
               AND EXISTS (
                   SELECT 1
                   FROM sCwb.tDoctorMaster DM
                   WHERE DM.EmployeeId = @rDoctorEmployeeId
               )
             )
            )
        AND ISNULL(A.ExaminationId, 0) = 0    
        AND ISNULL(E.IsCancel, 0) = 0    
        AND A.Id NOT IN (SELECT IsNull(AppointmentId,0) FROM sExamination.tRegistration WHERE OrgId =@rOrgId)
    UNION ALL    
    SELECT     
        ER.Id,    
        NULL AS AppointmentNumber,    
        ER.ParticipantSourceTypeId AS PatientSourceTypeId,    
        ER.ParticipantSourceId AS PatientSourceId,    
        ISNULL(E.FirstName + ' ', '') + ISNULL(E.MiddleName + ' ', '') + ISNULL(E.LastName, '') AS PatientName,    
        ER.RequestedDate AS AppointmentDate,    
         ISNULL(ER.RequestedDate, CONVERT(DATETIME, ER.RequestedDate)) FromTime,    
     ISNULL(ER.RequestedDate, CONVERT(DATETIME, ER.RequestedDate)) AS ToTime,   
        ISNULL(ER.DoctorEmployeeId, 0) AS DoctorEmployeeId,    
        NULL AS EmployeeCode,    
        NULL AS EmployeeId,    
        NULL AS Relation,    
        NULL AS Gender,    
        NULL AS DoctorName,    
        ER.OrgId,    
        NULL AS IsRegister,    
        NULL AS IsObsolete,    
        NULL AS StatusName,    
        NULL AS DepartmentName,    
        NULL AS DepartmentId,    
        NULL AS DependentId,    
        ER.StoreLocationId,    
        ER.SetupId,    
        NULL AS ExaminationTypeId,    
        ST.Title AS MainType,    
  NULL AS Setup,    
        NULL AS ReferSourceId,    
        NULL AS LocationId,    
        NULL AS CauseId,    
        NULL AS StoreLocation,    
        NULL AS OtherName,    
        ER.Reason AS FollowupRemark,    
        NULL AS Age,    
        NULL AS Months,    
        NULL AS GenderId,    
        ER.ExaminationId,    
        NULL AS Timeslot,
		null AS CompliantRemark, 0 as Height,
		'' AS EmailId,
		'' AS MobileNumber
    FROM     
        sExamination.tExaminationRequest ER    
    LEFT JOIN     
        sHrm.tEmployeeMaster E ON E.Id = ER.DoctorEmployeeId    
    inner JOIN     
        (    
            SELECT     
                ST1.MainTypeId,     
                ST1.Title,    
                ROW_NUMBER() OVER (PARTITION BY ST1.MainTypeId ORDER BY ST1.Title) AS RowNum    
            FROM     
                sExamination.tSubTypeMaster ST1    
            WHERE     
                ST1.MainTypeId IS NOT NULL and ST1.MainTypeId=2    
        ) ST ON ST.MainTypeId = ER.SubTypeId AND ST.RowNum = 1     
    WHERE     
        ER.OrgId = @rOrgId    
        AND ER.StatusId = 101    
        AND ER.RequestedDate BETWEEN ISNULL(@rFromDate, sCommon.fGetDate()) AND ISNULL(@rToDate, sCommon.fGetDate())    
        AND (ER.Id = @rId OR @rId = 0)    
        AND (ER.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)    
        AND (ER.SetupId = @rSetupId OR @rSetupId = 0)    
        AND (ER.DoctorEmployeeId = @rDoctorEmployeeId OR @rDoctorEmployeeId = 0)    
    
    ORDER BY     
        Id DESC;    
END   

GO


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

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


GO


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


Go


CREATE OR ALTER PROCEDURE[sExamination].[pBulkOperationDiagnosisGenerateAll]         
(        
 @rOrgId [int] = 0,           
 @rSetupGroupId [int] = 0,
 @rSetupId [int] = 0       
)        
AS        
BEGIN
  DECLARE @NewLineChar AS char(2) = CHAR(13) + CHAR(10)  
            
 DECLARE @lConfValue varchar(20)        
 SELECT TOP 1 @lConfValue = ISNULL(CS.ItemValue,CM.ItemValue)        
 FROM sConfig.tConfigurationMaster as CM        
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id        
 WHERE CM.ItemKey = 'Examination.IsStatusCompleteRestrict'   

  DECLARE @lConfValueDiagnosis varchar(20)        
  
  SELECT TOP 1 @lConfValueDiagnosis = ISNULL(CS.ItemValue,CM.ItemValue)        
  FROM sConfig.tConfigurationMaster as CM        
  LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id        
  WHERE CM.ItemKey = 'Examiation.AllowAutoUpdateDiagnosis' AND SourceId = @rOrgId
  AND SourceTypeId = 1016   
	      
 --select @lConfValueDiagnosis = sConfig.fConfigurationValueGet('Examiation.AllowAutoUpdateDiagnosis',@rOrgId,0,0,0)      
 --select @lConfValueDiagnosis

 DECLARE @BPConfig varchar(50)
 SELECT @BPConfig = ISNULL(cm.ItemValue,pm.ItemValue)
 FROM sConfig.tConfigurationMaster PM
 LEFT JOIN sConfig.tConfigurationSetup CM ON CM.ConfigurationId = PM.Id
    AND SourceId = @rOrgId AND SourceTypeId = 1016
 WHERE PM.Id = 170

 DECLARE @HabitDiseaseSourceId INT;
 SET @HabitDiseaseSourceId = sCommon.fGetIntIdForOrg(13,@rOrgId)

 CREATE TABLE #DiagnosisTable        
 (        
  tId int IDENTITY(1,1),rowid int,ExaminationId bigint,ParticipantCode nvarchar(50),        
  ParticipantName nvarchar(100),SetupId int,StatusId int,OrganizationDepartmentId int,        
  DiagnosisId bigint,DiagnosisRemark nvarchar(max),RecommendationEnglish nvarchar(max),        
  FitUnfitId int,StatusName nvarchar(100),IsPublish int,IsNewDiabetic bit,IsNewHyperTension bit,        
  IsDoneAudio bit,IsDonePulmo bit,Age varchar(10)        
 )
 INSERT INTO #DiagnosisTable        
 SELECT * FROM        
 (        
  SELECT ROW_NUMBER() OVER (ORDER BY Exm.Id asc) AS rowid,        
  ExaminationId = Exm.Id,ParticipantCode = EM.Code,        
  ParticipantName = EM.FirstName + ' ' + EM.LastName,        
  SetupId = Exm.SetupId,Exm.StatusId,Exm.OrganizationDepartmentId,        
  ISNULL(D.Id, 0) AS DiagnosisId,D.DiagnosisRemark,D.RecommendationEnglish,        
  ISNULL(D.FitUnfitId, 0) AS FitUnfitId,        
  ST.Title + '<br/>' + case when @lConfValue='True' then case when Isnull(TGET.AutoId,0)>0 then case when (Isnull(A.IsDoneLeft,0) =1 or Isnull(A.IsDoneRight,0) =1) then 'A-Done' Else 'A-NotDone' End Else 'A-Done' End         
  + '<br/>' + case when Isnull(TGET1.AutoId,0)>0 then case when Isnull(P.IsDone,0) =1 then 'P-Done' Else 'P-NotDone' End Else 'P-Done' End Else '' END AS StatusName,        
  isnull(Exm.IsPublish,0) as IsPublish,isnull(IsNewDiabatic,0) as IsNewDiabatic,        
  isnull(IsNewHyperTension,0) as IsNewHyperTension,        
  case when Isnull(TGET.AutoId,0)>0 then case when (Isnull(A.IsDoneLeft,0) =1 or Isnull(A.IsDoneRight,0) =1) then 'True' Else 'False' End Else 'True' End as IsDoneAudio,        
  case when Isnull(TGET1.AutoId,0)>0 then case when Isnull(P.IsDone,0) =1 then 'True' Else 'False' End Else 'True' End as IsDonePulmo,        
  CONVERT(varchar,ISNULL(datediff(yy,DateOfBirth,getdate()), '')) Age        
  FROM sExamination.tExamination Exm        
  INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = Exm.ParticipantSourceId        
  LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId        
  LEFT JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.Id        
  INNER JOIN sExamination.tSetupMaster SM ON SM.Id = Exm.SetupId        
  LEFT JOIN sExamination.tDiagnosis D ON D.SourceId = Exm.Id        
  INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = Exm.StoreLocationId        
  LEFT JOIN sExamination.tStatusMaster ST ON Exm.StatusId = ST.Id        
  left join sExamination.tAudiometry A on A.SourceId=Exm.id and A.SourceTypeId=1002        
  left join sExamination.tPulmonary P on P.SourceId=Exm.Id and P.SourceTypeId=1002        
  left join sExamination.tTargetGroupExaminationTemplate TGET on TGET.TargetGroupId=Exm.TargetGroupId and TGET.MainTypeId=Exm.SetupId and TGET.SourceTemplateId=10162        
  left join sExamination.tTargetGroupExaminationTemplate TGET1 on TGET1.TargetGroupId=Exm.TargetGroupId and TGET1.MainTypeId=Exm.SetupId and TGET1.SourceTemplateId=10163         
  WHERE Exm.OrgId = @rOrgId             
  AND Exm.ParticipantSourceTypeId = 95          
  AND ((Exm.SetupId = @rSetupId) OR (@rSetupId = 0)) 
  AND ((SM.SetupGroupId = @rSetupGroupId) OR (@rSetupGroupId = 0))
 ) AS t ORDER BY t.ExaminationId DESC        
         
 SELECT DISTINCT ExaminationId INTO #ExamIds FROM #DiagnosisTable

 CREATE TABLE #tbltmpTestDetail        
 (        
  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        
 )
 CREATE CLUSTERED INDEX IX_tbltmpTestDetail ON #tbltmpTestDetail(t_TestParameterId, t_ExaminationId, t_TestType, t_ParameterValueTypeId)

 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 IN (SELECT ExaminationId FROM #ExamIds)        
 AND TPM.ParameterValueTypeId IN (1, 2) AND TPM.IsObsolete = 0        
 AND ISNULL(TRD.ServiceValue, '') <> ''        
         
 INSERT INTO #tbltmpTestDetail        
 SELECT GP.Id,GED.ParameterValue,EP.DateOfBirth,EP.GenderId,GP.ParameterValueTypeId,0,2,        
 DATEDIFF(yy,EP.DateOfBirth,GETDATE()),GED.Id,ED.Id,0        
 FROM sExamination.tExamination ED        
 INNER JOIN sHrm.tEmployeePersonalDetail EP ON ED.ParticipantSourceId = EP.EmployeeId        
 INNER JOIN sExamination.tGeneralTemplateExamination GE ON ED.Id = GE.SourceId        
 INNER JOIN sExamination.tGeneralTemplateExaminationDetail GED ON GE.Id = GED.GeneralTemplateExaminationId        
 INNER JOIN sExamination.tGeneralTemplateParameter GP ON GED.GeneralTemplateParameterId = GP.Id        
 WHERE ED.Id IN (SELECT ExaminationId FROM #ExamIds)        
 AND GP.ParameterValueTypeId IN (1, 2) AND GP.IsObsolete = 0        
 AND ISNULL(GED.ParameterValue, '') <> ''      
         
 CREATE TABLE #tbltmpDiagnosis        
 (        
  tid int IDENTITY(1,1),d_DiagnosisRemark nvarchar(max),d_Recommendation nvarchar(max),        
  d_DetailId bigint,d_Type int,d_MainId bigint,d_ExaminationId bigint,d_StaticTestParameterId int        
 )  
 CREATE CLUSTERED INDEX IX_tbltmpDiagnosis ON #tbltmpDiagnosis(d_ExaminationId, d_StaticTestParameterId)

 INSERT INTO #tbltmpDiagnosis        
 SELECT a.BMI,case when a.BMI='Overweight' OR a.BMI='Obese' then 'Reduce weight' else '' end,
 0,0,0,a.ExaminationId,0        
 FROM        
 (        
  SELECT VTL.SourceId [ExaminationId], BR.Title AS [BMI]        
  FROM sExamination.tVital AS VTL
  LEFT JOIN sExamination.tBMIRangeMaster BR ON VTL.BMI BETWEEN BR.FromRange AND BR.ToRange AND BR.IsObsolete = 0
  WHERE VTL.SourceId IN (SELECT ExaminationId FROM #ExamIds)       
 ) AS a WHERE ISNULL(a.BMI, '') <> 'Normal' AND a.BMI IS NOT NULL AND ISNULL(a.BMI, '') <> ''        
         
 UNION ALL        
         
 SELECT BP.BloodPressure,ISNULL(DHS.RecommendationRemark, ''),0,0,0,BP.ExaminationId,0        
 FROM
(
    SELECT  
        VTL.SourceId AS ExaminationId,
        CASE 
            WHEN @BPConfig = 'Diastolic'
            THEN
            (
                SELECT TOP 1 BRM.Title
                FROM sExamination.tBloodPressureRangeMaster BRM
                WHERE VTL.BloodPressureDiastolic BETWEEN BRM.FromRange AND BRM.ToRange
                AND BRM.IsObsolete = 0
            )

            WHEN @BPConfig = 'AHA'
            THEN
                CASE
                    WHEN VTL.BloodPressureSystolic >= 180 
                         OR VTL.BloodPressureDiastolic >= 110
                        THEN 'Hypertension Crisis'
                    WHEN VTL.BloodPressureSystolic >= 140 
                         OR VTL.BloodPressureDiastolic >= 90
                        THEN 'Hypertension'
                    WHEN (VTL.BloodPressureSystolic BETWEEN 121 AND 139)
                         OR (VTL.BloodPressureDiastolic BETWEEN 81 AND 89)
                        THEN 'PreHypertension'
                    WHEN VTL.BloodPressureSystolic <= 90
                         OR VTL.BloodPressureDiastolic <= 60
                        THEN 'Hypotension'
                    WHEN (VTL.BloodPressureSystolic BETWEEN 91 AND 120)
                         AND (VTL.BloodPressureDiastolic BETWEEN 61 AND 80)
                        THEN 'Normal'
                END
            ELSE
                CASE
                    WHEN VTL.BloodPressureDiastolic >= 110
                         OR VTL.BloodPressureSystolic >= 180
                        THEN 'Stage III HTN'
                    WHEN (VTL.BloodPressureDiastolic BETWEEN 100 AND 109)
                         OR (VTL.BloodPressureSystolic BETWEEN 160 AND 179)
                        THEN 'Stage II HTN'
                    WHEN (VTL.BloodPressureDiastolic BETWEEN 90 AND 99)
                         OR (VTL.BloodPressureSystolic BETWEEN 140 AND 159)
                        THEN 'Stage I HTN'
                    WHEN (VTL.BloodPressureDiastolic BETWEEN 85 AND 89)
                         OR (VTL.BloodPressureSystolic BETWEEN 130 AND 139)
                        THEN 'High Normal'
                    WHEN (VTL.BloodPressureDiastolic BETWEEN 80 AND 84)
                         OR (VTL.BloodPressureSystolic BETWEEN 120 AND 129)
                        THEN 'Normal'
                    WHEN VTL.BloodPressureDiastolic < 80
                         AND VTL.BloodPressureSystolic < 120
                        THEN 'Optimal'
                END
        END AS BloodPressure
    FROM sExamination.tVital VTL
    WHERE VTL.SourceId IN (SELECT ExaminationId FROM #ExamIds)
) BP
LEFT JOIN sExamination.tDiseaseHabitSetup DHS ON DHS.SourceId = @HabitDiseaseSourceId 
    AND DHS.SourceTypeId = 3004 AND BP.BloodPressure = 'Hypertension'
WHERE ISNULL(BP.BloodPressure, '') NOT IN ('', 'Normal', 'Optimal')
         
 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 LTRIM(RTRIM(t_ServiceValue)) <> '+' AND t_ServiceValue NOT LIKE '%e%' AND t_ServiceValue NOT LIKE '%E%'
 AND ISNUMERIC(t_ServiceValue) = 1 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, '') <> ''        
         
 INSERT INTO #tbltmpDiagnosis        
 SELECT ISNULL(Diagnosis, ''),ISNULL(Recommendation, ''),GETS.Id,t_TestType,t_DetailId,        
 t_ExaminationId,0        
 FROM sExamination.tGeneralTemplateParameterRange GETS        
 INNER JOIN #tbltmpTestDetail TD ON GETS.GeneralTemplateParameterId = TD.t_TestParameterId        
 WHERE GETS.GenderId = TD.t_GenderId AND TD.t_Age BETWEEN GETS.AgeFrom AND GETS.AgeTo        
 AND TD.t_ParameterValueTypeId = 1 AND t_TestType = 2        
 AND CONVERT(decimal(18, 9), t_ServiceValue) BETWEEN CAST(GETS.Minimum AS decimal(12, 4)) AND CAST(GETS.Maximum AS decimal(12, 4))        
 AND ISNUMERIC(t_ServiceValue) = 1 AND ISNULL(Diagnosis, '') <> ''        
         
 INSERT INTO #tbltmpDiagnosis        
 SELECT ISNULL(Diagnosis, ''),ISNULL(Recommendation, ''),GPL.Id,t_TestType,t_DetailId,        
 t_ExaminationId,0        
 FROM sExamination.tGeneralTemplateParameterList GPL        
 INNER JOIN #tbltmpTestDetail TD ON TD.t_TestParameterId = GPL.GeneralTemplateParameterId        
 WHERE GPL.IsNormal = 0 AND GPL.Title LIKE t_ServiceValue AND TD.t_ParameterValueTypeId = 2        
 AND t_TestType = 2 AND ISNULL(Diagnosis, '') <> ''        
         
 CREATE TABLE #tbltmpHabitDiseaseDetail        
 (        
  tid int IDENTITY(1,1),hd_DetailId bigint,hd_SourceId int,hd_SourceTypeId int,hd_ExaminationId bigint        
 )        
 INSERT INTO #tbltmpHabitDiseaseDetail        
 SELECT HHD.Id,HHD.HabitId,239,E.Id        
 FROM sExamination.tExamination E        
 INNER JOIN sExamination.tHabitHygine HH ON E.Id = HH.SourceId        
 INNER JOIN sExamination.tHabitHygineDetail HHD ON HH.Id = HHD.HabitHygineId        
 WHERE E.Id IN (SELECT ExaminationId FROM #ExamIds)       
         
 UNION ALL        
         
 SELECT EDD.Id,EDD.DiseaseId,3004,E.Id        
 FROM sExamination.tExamination E        
 INNER JOIN sExamination.tExistingDisease ED ON E.Id = ED.SourceId        
 INNER JOIN sExamination.tExistingDiseaseDetail EDD ON ED.Id = EDD.ExistingDiseaseId        
 WHERE E.Id IN (SELECT ExaminationId FROM #ExamIds)      
         
 INSERT INTO #tbltmpDiagnosis        
 SELECT ISNULL(DiagnosisRemark, ''),ISNULL(RecommendationRemark, ''),t.hd_DetailId,3,        
 t.hd_DetailId,hd_ExaminationId,0        
 FROM sExamination.tDiseaseHabitSetup DHS        
 INNER JOIN #tbltmpHabitDiseaseDetail t ON DHS.SourceId = t.hd_SourceId        
 AND DHS.SourceTypeId = t.hd_SourceTypeId WHERE ISNULL(DiagnosisRemark, '') <> ''        
         
 INSERT INTO #tbltmpDiagnosis        
 SELECT AM.Title,'',0,5,0,A.SourceId,0        
 FROM sExamination.tAudiometry A        
 INNER JOIN sExamination.tAudiometryResultMaster AM ON A.AudiometryAcResultLeftId = AM.Id        
 WHERE A.SourceId IN (SELECT ExaminationId FROM #ExamIds)
 AND AM.Id <> 1 AND AM.Title <> ''       
         
 UNION        
         
 SELECT AM.Title,'',0,5,0,A.SourceId,0        
 FROM sExamination.tAudiometry A        
 INNER JOIN sExamination.tAudiometryResultMaster AM ON A.AudiometryAcResultRightId = AM.Id        
 WHERE A.SourceId IN (SELECT ExaminationId FROM #ExamIds)
 AND AM.Id <> 1 AND AM.Title <> ''        
         
 INSERT INTO #tbltmpDiagnosis        
 SELECT ISNULL(PulmonaryResulIntensity, '') + ' ' + ISNULL(PulmonaryResult, ''),'',0,6,0,        
 SourceId,0        
 FROM sExamination.tPulmonary WHERE SourceId IN (SELECT ExaminationId FROM #ExamIds) 
 AND PerOfPredictedFVC IS NOT NULL         
 --AND ISNULL(PulmonaryResulIntensity, '') <> ''        
 AND UPPER(ISNULL(PulmonaryResult, '')) <> 'NORMAL'        
         
 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        
         
 UPDATE GED SET GED.Diagnosis = t.d_DiagnosisRemark,GED.Recommendation = t.d_Recommendation,        
 GED.IsAbnormal = 1 FROM sExamination.tGeneralTemplateExaminationDetail GED        
 INNER JOIN #tbltmpDiagnosis AS t ON GED.Id = d_MainId WHERE t.d_Type = 2        
         
 CREATE TABLE #tblMain        
 (        
  tid int IDENTITY(1,1),m_ExaminationId bigint,m_Diagnosis nvarchar(max),m_Recommendation nvarchar(max)        
 )        
 CREATE CLUSTERED INDEX IX_tblMain ON #tblMain(m_ExaminationId)
 
 INSERT INTO #tblMain        
 SELECT DISTINCT d_ExaminationId,'','' FROM #tbltmpDiagnosis        
        
 declare @configval varchar(50)='Independent'        
 select @configval=ISNULL(CS.ItemValue,CM.ItemValue)         
 FROM sConfig.tConfigurationMaster CM        
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id         
 where CM.id=190

IF(@configval = 'Priority')
BEGIN

    DELETE TD
    FROM #tbltmpDiagnosis TD
    INNER JOIN
    (
        SELECT DISTINCT d_ExaminationId
        FROM #tbltmpDiagnosis
        WHERE d_StaticTestParameterId = 25
        AND d_DiagnosisRemark IS NOT NULL
        AND d_DiagnosisRemark <> ''
    ) X ON TD.d_ExaminationId = X.d_ExaminationId
    WHERE TD.d_StaticTestParameterId IN (19,20,21)

    DELETE TD
    FROM #tbltmpDiagnosis TD
    INNER JOIN
    (
        SELECT DISTINCT d_ExaminationId
        FROM #tbltmpDiagnosis
        WHERE d_StaticTestParameterId = 19
        AND d_DiagnosisRemark IS NOT NULL
        AND d_DiagnosisRemark <> ''
    ) X ON TD.d_ExaminationId = X.d_ExaminationId
    WHERE TD.d_StaticTestParameterId IN (20,21)

    DELETE TD
    FROM #tbltmpDiagnosis TD
    INNER JOIN
    (
        SELECT DISTINCT d_ExaminationId
        FROM #tbltmpDiagnosis
        WHERE d_StaticTestParameterId = 20
        AND d_DiagnosisRemark IS NOT NULL
        AND d_DiagnosisRemark <> ''
    ) X ON TD.d_ExaminationId = X.d_ExaminationId
    WHERE TD.d_StaticTestParameterId IN (21)

    DELETE TD
    FROM #tbltmpDiagnosis TD
    INNER JOIN
    (
        SELECT DISTINCT ED.Id AS ExaminationId
        FROM sExamination.tExamination ED
        INNER JOIN sExamination.tTestRequest TR 
            ON ED.Id = TR.SourceId
        INNER JOIN sExamination.tTestRequestDetail TRD 
            ON TR.Id = TRD.TestRequestId
        INNER JOIN sOrderEntry.tTestDetail TDT 
            ON TRD.TestDetailId = TDT.Id
        INNER JOIN sOrderEntry.tTestParameterMaster TPM 
            ON TDT.TestParameterId = TPM.Id
        WHERE TPM.StaticTestParameterId = 25
        AND TRD.IsAbnormal = 0
        AND ISNULL(TRD.ServiceValue,'') <> ''
    ) X ON TD.d_ExaminationId = X.ExaminationId
    WHERE TD.d_StaticTestParameterId IN (19,20,21)

    DELETE TD
    FROM #tbltmpDiagnosis TD
    INNER JOIN
    (
        SELECT DISTINCT ED.Id AS ExaminationId
        FROM sExamination.tExamination ED
        INNER JOIN sExamination.tTestRequest TR 
            ON ED.Id = TR.SourceId
        INNER JOIN sExamination.tTestRequestDetail TRD 
            ON TR.Id = TRD.TestRequestId
        INNER JOIN sOrderEntry.tTestDetail TDT 
            ON TRD.TestDetailId = TDT.Id
        INNER JOIN sOrderEntry.tTestParameterMaster TPM 
            ON TDT.TestParameterId = TPM.Id
        WHERE TPM.StaticTestParameterId = 19
        AND TRD.IsAbnormal = 0
        AND ISNULL(TRD.ServiceValue,'') <> ''
    ) X ON TD.d_ExaminationId = X.ExaminationId
    WHERE TD.d_StaticTestParameterId IN (20,21)

    DELETE TD
    FROM #tbltmpDiagnosis TD
    INNER JOIN
    (
        SELECT DISTINCT ED.Id AS ExaminationId
        FROM sExamination.tExamination ED
        INNER JOIN sExamination.tTestRequest TR 
            ON ED.Id = TR.SourceId
        INNER JOIN sExamination.tTestRequestDetail TRD 
            ON TR.Id = TRD.TestRequestId
        INNER JOIN sOrderEntry.tTestDetail TDT 
            ON TRD.TestDetailId = TDT.Id
        INNER JOIN sOrderEntry.tTestParameterMaster TPM 
            ON TDT.TestParameterId = TPM.Id
        WHERE TPM.StaticTestParameterId = 20
        AND TRD.IsAbnormal = 0
        AND ISNULL(TRD.ServiceValue,'') <> ''
    ) X ON TD.d_ExaminationId = X.ExaminationId
    WHERE TD.d_StaticTestParameterId IN (21)

END
ELSE IF(@configval = 'Priority Abnormal')
BEGIN

    DELETE TD
    FROM #tbltmpDiagnosis TD
    INNER JOIN
    (
        SELECT DISTINCT d_ExaminationId
        FROM #tbltmpDiagnosis
        WHERE d_StaticTestParameterId = 25
        AND d_DiagnosisRemark <> 'Pre Diabetic'
    ) X ON TD.d_ExaminationId = X.d_ExaminationId
    WHERE TD.d_StaticTestParameterId IN (19,20,21)

    DELETE TD
    FROM #tbltmpDiagnosis TD
    INNER JOIN
    (
        SELECT DISTINCT d_ExaminationId
        FROM #tbltmpDiagnosis
        WHERE d_StaticTestParameterId = 19
        AND d_DiagnosisRemark <> 'Pre Diabetic'
    ) X ON TD.d_ExaminationId = X.d_ExaminationId
    WHERE TD.d_StaticTestParameterId IN (20,21,25)

    DELETE TD
    FROM #tbltmpDiagnosis TD
    INNER JOIN
    (
        SELECT DISTINCT d_ExaminationId
        FROM #tbltmpDiagnosis
        WHERE d_StaticTestParameterId = 20
        AND d_DiagnosisRemark <> 'Pre Diabetic'
    ) X ON TD.d_ExaminationId = X.d_ExaminationId
    WHERE TD.d_StaticTestParameterId IN (19,21,25)

    DELETE TD
    FROM #tbltmpDiagnosis TD
    INNER JOIN
    (
        SELECT DISTINCT d_ExaminationId
        FROM #tbltmpDiagnosis
        WHERE d_StaticTestParameterId = 21
        AND d_DiagnosisRemark <> 'Pre Diabetic'
    ) X ON TD.d_ExaminationId = X.d_ExaminationId
    WHERE TD.d_StaticTestParameterId IN (19,20,25)

    DELETE TD
    FROM #tbltmpDiagnosis TD
    INNER JOIN
    (
        SELECT DISTINCT d_ExaminationId
        FROM #tbltmpDiagnosis
        WHERE d_StaticTestParameterId = 25
        AND d_DiagnosisRemark <> 'Diabetic'
    ) X ON TD.d_ExaminationId = X.d_ExaminationId
    WHERE TD.d_StaticTestParameterId IN (19,20,21)

    DELETE TD
    FROM #tbltmpDiagnosis TD
    INNER JOIN
    (
        SELECT DISTINCT d_ExaminationId
        FROM #tbltmpDiagnosis
        WHERE d_StaticTestParameterId = 19
        AND d_DiagnosisRemark <> 'Diabetic'
    ) X ON TD.d_ExaminationId = X.d_ExaminationId
    WHERE TD.d_StaticTestParameterId IN (20,21,25)

    DELETE TD
    FROM #tbltmpDiagnosis TD
    INNER JOIN
    (
        SELECT DISTINCT d_ExaminationId
        FROM #tbltmpDiagnosis
        WHERE d_StaticTestParameterId = 20
        AND d_DiagnosisRemark <> 'Diabetic'
    ) X ON TD.d_ExaminationId = X.d_ExaminationId
    WHERE TD.d_StaticTestParameterId IN (19,21,25)

    DELETE TD
    FROM #tbltmpDiagnosis TD
    INNER JOIN
    (
        SELECT DISTINCT d_ExaminationId
        FROM #tbltmpDiagnosis
        WHERE d_StaticTestParameterId = 21
        AND d_DiagnosisRemark <> 'Diabetic'
    ) X ON TD.d_ExaminationId = X.d_ExaminationId
    WHERE TD.d_StaticTestParameterId IN (19,20,25)

END

 DECLARE @cnt int, @i int        
         
 SELECT @i=1,@cnt=COUNT(*) FROM #tblMain        
         
 WHILE @i <= @cnt        
 BEGIN        
  DECLARE @lExaminationId bigint;       
          
  SELECT @lExaminationId = m_ExaminationId FROM #tblMain WHERE tid = @i        
          
 -- if(@configval='Priority')        
 --  begin        
 --   -- For adani We have changes the priority MS 2019-04-09 (Abhi)        
 --   if exists(select 1 From #tbltmpDiagnosis where d_StaticTestParameterId=25 and Isnull(d_DiagnosisRemark,'')<>'' and d_ExaminationId = @lExaminationId)        
 --    begin        
 --     Delete from #tbltmpDiagnosis where d_StaticTestParameterId in (19,20,21) and d_ExaminationId = @lExaminationId        
 --    end        
 --   else if exists(select 1 From #tbltmpDiagnosis where d_StaticTestParameterId=19 and Isnull(d_DiagnosisRemark,'')<>'' and d_ExaminationId = @lExaminationId)        
 --    begin        
 --     Delete from #tbltmpDiagnosis where d_StaticTestParameterId in (20,21) and d_ExaminationId = @lExaminationId        
 --    end        
 --   else if exists(select 1 From #tbltmpDiagnosis where d_StaticTestParameterId=20 and Isnull(d_DiagnosisRemark,'')<>'' and d_ExaminationId = @lExaminationId)        
 --    begin        
 --     Delete from #tbltmpDiagnosis where d_StaticTestParameterId in (21) and d_ExaminationId = @lExaminationId        
 --    end        
        
 --   if exists        
 --    (select 1 FROM sExamination.tExamination ED                
 --    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 and StaticTestParameterId=25        
 --    WHERE ED.Id IN (@lExaminationId)        
 --    and TRD.IsAbnormal = 0 and (Isnull(TRD.ServiceValue,'')<>'')        
 --    )        
 --     begin        
 --     Delete from #tbltmpDiagnosis where d_StaticTestParameterId in (19,20,21) and d_ExaminationId = @lExaminationId        
 --     end        
 --   else if exists        
 --    (        
 --    select 1 FROM sExamination.tExamination ED                
 --    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 and StaticTestParameterId=19        
 --    WHERE ED.Id IN (@lExaminationId)        
 --    and TRD.IsAbnormal = 0 and (Isnull(TRD.ServiceValue,'')<>'')        
 --    )        
 --     begin        
 --      Delete from #tbltmpDiagnosis where d_StaticTestParameterId in (20,21) and d_ExaminationId = @lExaminationId        
 --     end        
 --   else if exists        
 --    (        
 --    select 1 FROM sExamination.tExamination ED                
 --    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 and StaticTestParameterId=20        
 --    WHERE ED.Id IN (@lExaminationId)        
 --    and TRD.IsAbnormal = 0 and (Isnull(TRD.ServiceValue,'')<>'')        
 --    )        
 --     begin        
 --      Delete from #tbltmpDiagnosis where d_StaticTestParameterId in (21) and d_ExaminationId = @lExaminationId        
 --     end        
        
 --  end        
 -- else if(@configval='Priority Abnormal')        
 --  begin        
 --   if exists(select 1 From #tbltmpDiagnosis where d_StaticTestParameterId=25 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic' and d_ExaminationId = @lExaminationId)        
 --   begin        
 --    print 5        
 --    Delete from #tbltmpDiagnosis where d_StaticTestParameterId in (19,20,21) and d_ExaminationId = @lExaminationId        
 --   end        
 --   else if exists(select 1 From #tbltmpDiagnosis where d_StaticTestParameterId=19 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic' and d_ExaminationId = @lExaminationId)        
 --   begin        
 --    print 6        
 --    Delete from #tbltmpDiagnosis where d_StaticTestParameterId in (20,21,25) and d_ExaminationId = @lExaminationId        
 --   end        
 --   else if exists(select 1 From #tbltmpDiagnosis where d_StaticTestParameterId=20 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic' and d_ExaminationId = @lExaminationId)        
 --   begin        
 --    print 7        
 --    Delete from #tbltmpDiagnosis where d_StaticTestParameterId in (19,21,25) and d_ExaminationId = @lExaminationId        
 --   end 
	--else if exists(select 1 From #tbltmpDiagnosis where d_StaticTestParameterId=21 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic' and d_ExaminationId = @lExaminationId)        
 --   begin        
 --    print 8        
 --    Delete from #tbltmpDiagnosis where d_StaticTestParameterId in (19,20,25) and d_ExaminationId = @lExaminationId        
 --   end        
 --   else if exists(select 1 From #tbltmpDiagnosis where d_StaticTestParameterId=25 and Isnull(d_DiagnosisRemark,'')<>'Diabetic' and d_ExaminationId = @lExaminationId)        
 --   begin        
 --    print 1        
 --    Delete from #tbltmpDiagnosis where d_StaticTestParameterId in (19,21,20) and d_ExaminationId = @lExaminationId        
 --   end        
 --   else if exists(select 1 From #tbltmpDiagnosis where d_StaticTestParameterId=19 and Isnull(d_DiagnosisRemark,'')<>'Diabetic' and d_ExaminationId = @lExaminationId)        
 --   begin        
 --    print 2        
 --    Delete from #tbltmpDiagnosis where d_StaticTestParameterId in (20,21,25) and d_ExaminationId = @lExaminationId        
 --   end        
 --   else if exists(select 1 From #tbltmpDiagnosis where d_StaticTestParameterId=20 and Isnull(d_DiagnosisRemark,'')<>'Diabetic' and d_ExaminationId = @lExaminationId)        
 --   begin        
 --    print 3        
 --    Delete from #tbltmpDiagnosis where d_StaticTestParameterId in (19,21,25) and d_ExaminationId = @lExaminationId        
 --   end 
	--else if exists(select 1 From #tbltmpDiagnosis where d_StaticTestParameterId=21 and Isnull(d_DiagnosisRemark,'')<>'Diabetic' and d_ExaminationId = @lExaminationId)        
 --   begin        
 --    print 4        
 --    Delete from #tbltmpDiagnosis where d_StaticTestParameterId in (19,20,25) and d_ExaminationId = @lExaminationId        
 --   end         
 --  end        

   DECLARE @rIsDiabetic bit = 0, @rIsDiabeticExisting bit = 0, @rIsHypertension bit = 0 , @rIsHypertensionExisting bit = 0;
	 set @rIsDiabetic = (select top 1 1 from #tbltmpDiagnosis where d_DiagnosisRemark = 'Diabetic' and d_ExaminationId = @lExaminationId)
	 --set @rIsDiabeticExisting = (select top 1 1 from #tbltmpDiagnosis where d_DiagnosisRemark = 'Diabetic ( Existing )' and d_ExaminationId = @lExaminationId)
	 set @rIsDiabeticExisting = (select top 1 1 from sExamination.tExistingDisease ED
										INNER JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId = ED.Id
										INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = EDD.DiseaseId
										Where DM.StaticDiseaseId = 7 AND ED.SourceId = @lExaminationId)
	 set @rIsHypertension = (select top 1 1 from #tbltmpDiagnosis where (d_DiagnosisRemark = 'Hypertension' or d_DiagnosisRemark = 'Stage I HTN' or d_DiagnosisRemark = 'Stage II HTN' 
																		or d_DiagnosisRemark = 'Stage III HTN' or d_DiagnosisRemark = 'Hypertension Crisis') and d_ExaminationId = @lExaminationId)
	 --set @rIsHypertensionExisting = (select top 1 1 from #tbltmpDiagnosis where d_DiagnosisRemark = 'Hypertension ( Existing )' and d_ExaminationId = @lExaminationId)
	 set @rIsHypertensionExisting = (select top 1 1 from sExamination.tExistingDisease ED
										INNER JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId = ED.Id
										INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = EDD.DiseaseId
										Where DM.StaticDiseaseId = 13 AND ED.SourceId = @lExaminationId)

	 IF(@rIsDiabetic = 1 and ISNULL(@rIsDiabeticExisting, 0) <> 1)
	 BEGIN
			update sExamination.tDiagnosis set IsNewDiabatic = 1 where SourceId = @lExaminationId
			--set @rIsNewDiabatic = 1;
  	 END
	 ELSE
	 BEGIN
			update sExamination.tDiagnosis set IsNewDiabatic = 0 where SourceId = @lExaminationId
  	 END

	 IF(@rIsHypertension = 1 and ISNULL(@rIsHypertensionExisting, 0) <> 1)
	 BEGIN
			update sExamination.tDiagnosis set IsNewHyperTension = 1 where SourceId = @lExaminationId
			--set @rIsNewHyperTension = 1;
  	 END
	 ELSE
	 BEGIN
			update sExamination.tDiagnosis set IsNewHyperTension = 0 where SourceId = @lExaminationId
  	 END

	-- -- Dummy table to capture and discard result set
	--CREATE TABLE #dummy (reulst int, ResultStrin nvarchar(50));  -- Adjust column type to match actual output

	---- Discard the result
	--INSERT INTO #dummy
	--EXEC [sExamination].[pUpdateDiagnosis] @lExaminationId, @rIsNewDiabatic, @rIsNewHyperTension;

	--DROP TABLE #dummy;
        
  --SELECT @lDiagnosis = @lDiagnosis + d_DiagnosisRemark + @NewLineChar        
  --FROM #tbltmpDiagnosis WHERE d_ExaminationId = @lExaminationId        
          
  --SELECT @lRecommendation = @lRecommendation + d_Recommendation + @NewLineChar        
  --FROM (SELECT DISTINCT d_Recommendation FROM #tbltmpDiagnosis WHERE d_ExaminationId = @lExaminationId AND d_Recommendation <> ''  ) AS a        
          
  --UPDATE #tblMain SET m_Diagnosis = @lDiagnosis, m_Recommendation = @lRecommendation        
  --WHERE m_ExaminationId = @lExaminationId 
      
  SELECT @i = @i + 1        
 END 
 
 UPDATE TM
  SET
    m_Diagnosis =
    STUFF(
    (
        SELECT CHAR(13)+CHAR(10)+ISNULL(TD.d_DiagnosisRemark,'')
        FROM #tbltmpDiagnosis TD
        WHERE TD.d_ExaminationId = TM.m_ExaminationId
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
    ,1,2,''),
    m_Recommendation =
    STUFF(
    (
        SELECT DISTINCT CHAR(13)+CHAR(10)+ISNULL(TD.d_Recommendation,'')
        FROM #tbltmpDiagnosis TD
        WHERE TD.d_ExaminationId = TM.m_ExaminationId
        AND ISNULL(TD.d_Recommendation,'') <> ''
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
    ,1,2,'')
  FROM #tblMain TM
         
 --select * from #tbltmpDiagnosis order by d_ExaminationId     
 IF (@lConfValueDiagnosis = 'true')
BEGIN
    UPDATE D
	 SET DiagnosisRemarkNew = m_Diagnosis,
        RecommendationEnglishNew = m_Recommendation
    FROM sExamination.tDiagnosis D
    INNER JOIN #tblMain t ON t.m_ExaminationId = D.SourceId
	INNER JOIN sExamination.tExamination E ON E.Id = D.SourceId
	where E.StatusId = 1
END
ELSE
BEGIN
    UPDATE D
       SET DiagnosisRemark = m_Diagnosis,
        RecommendationEnglish = m_Recommendation
    FROM sExamination.tDiagnosis D
    INNER JOIN #tblMain t ON t.m_ExaminationId = D.SourceId
	INNER JOIN sExamination.tExamination E ON E.Id = D.SourceId
	where E.StatusId = 1
END
Select 1 as tId 

DROP TABLE #DiagnosisTable
DROP TABLE #tbltmpTestDetail
DROP TABLE #tbltmpDiagnosis
DROP TABLE #tbltmpHabitDiseaseDetail
DROP TABLE #tblMain
DROP TABLE #ExamIds
 --SELECT dt.tId,dt.rowid,CauseId=dt.rowid,ParentExaminationId=dt.ExaminationId,        
 --dt.ParticipantCode,dt.ParticipantName,dt.SetupId,dt.StatusId,dt.OrganizationDepartmentId,        
 --Id=dt.DiagnosisId,Diagnosis=tm.m_Diagnosis,Recommendation=tm.m_Recommendation,        
 --dt.FitUnfitId,Status=dt.StatusName,DepartmentId=0,dt.IsPublish,dt.IsNewDiabetic as NewDiabatic,        
 --dt.IsNewHyperTension as NewHyperTension,dt.IsDoneAudio,dt.IsDonePulmo,dt.Age        
 --FROM #DiagnosisTable AS dt LEFT JOIN #tblMain tm ON dt.ExaminationId = tm.m_ExaminationId        
 --order by ParentExaminationId asc        
        
 END 

 GO

 
ALTER proc [sExamination].[pGetAllExaminationDetails] 
@rExaminationId bigint,    
@rOrgId int,    
@rStoreLocationId int    
as    
SET NOCOUNT ON    
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED    
begin    
 declare @rParticipantId bigint,@rParticipantSourceTypeId int,@lothermedicines nvarchar(1000)    
 select @rParticipantId = ParticipantSourceId,@rParticipantSourceTypeId = ParticipantSourceTypeId    
 from sExamination.tExamination where Id = @rExaminationId    
     
 Select  @lothermedicines = COALESCE(@lothermedicines,'') + Isnull(OSPD.StockItemName,'') + '-' + Isnull(OSPD.DrugInstruction,'')    
  + '-' + Isnull(DFM.Title,'') + '-' + Isnull(DSM.Title,'') + '-' + Isnull(OSPD.Duration,'') + '-' + Isnull(OSPD.PrescribedQuantity,'') + ','    
 From sExamination.tExamination E    
 left join sExamination.tOutSidePrescription OSP on OSP.Sourceid=E.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    
 where E.Id = @rExaminationId    
    
 print @lothermedicines    
 SET @lothermedicines = Replace(LEFT(@lothermedicines, LEN(@lothermedicines) - 1),',','/r/n')    
    
 select EE.Id as ExaminationId,    
 ParticipantName = case when EE.ParticipantSourceTypeId = 1009 then CS.FirstName + ' ' + CS.LastName    
 when EE.ParticipantSourceTypeId = 1001 then EFD.Name else EM.FirstName + ' ' + EM.LastName end,    
 ParticipantCode = case when EE.ParticipantSourceTypeId = 1009 then CS.Code    
 when EE.ParticipantSourceTypeId = 1001 then EM3.Code else EM.Code end,    
 EE.ParticipantSourceTypeId,    
 EE.ParticipantSourceId,    
 EE.ProcessTypeId,    
 EE.OrganizationDepartmentId,    
 EE.ExaminationDate,    
 EE.SetupId,    
 EE.DoctorEmployeeId,    
 isnull(C.Id,0) as CauseId,     
 isnull(C.CauseTypeId,0) as CauseTypeId, --Developer: Deval, Added CauseTypeId, Date: 19/09/2023    
 EE.CriteiraGroupId,    
 BloodGroupId = case when EE.ParticipantSourceTypeId = 1001 then EF.BloodGroupId when EE.ParticipantSourceTypeId = 95 then PD.BloodGroupId    
 else 0 end,    
 (CASE WHEN C.IsCustomLog = 1 THEN '' ELSE isnull(convert(varchar,A.FollowupDate,103),'') END) as FollowupDate,     
 (CASE WHEN C.IsCustomLog = 1 THEN isnull(CI.IsFit,0) ELSE isnull(A.IsFit,0) END) as IsFit,    
 isnull(O.FitnessStatus,0) as FitnessStatus,    
 (CASE WHEN C.IsCustomLog = 1 THEN isnull(CI.Id,0) ELSE isnull(A.Id,0) END) as AccidentId,    
 isnull(IsTrackIncidentLog,0) as IsTrackIncidentLog,    
 isnull(IsTrackForFitness,0) as IsTrackForFitness,    
 isnull(R.ReferToClinicId,-1) as ReferToClinicId,    
 isnull(R.ContactPerson,'') as ContactPersion,    
 isnull(EM.StatusId,0) as EmployeeStatusId,    
 isnull(convert(varchar,EE.ExaminationDate,103),'') as ExDate,    
 isnull(v.Id,0) as VitalId,    
 isnull(NatureOfWorkId,0) as NatureOfWorkId,    
 isnull(Pulse,0) as Pulse,    
 isnull(Temperature,0) as Temperature,    
 isnull(BloodPressureSystolic,0) as BPSys,    
 isnull(BloodPressureDiastolic,0) as BPDia,    
 isnull(Respiration,0) as Respiration,    
 isnull(V.Height,0) as Height,    
 isnull(BodyWeight,0) as BodyWeight,    
 isnull(BMI,0) as BMI,    
 isnull(V.Remark,'') as VitalRemark,    
 isnull(O.OtherName,'') as OtherName,    
 isnull(EM2.Code,'') as ReferenceCode,    
 isnull(EM2.FirstName,'') + ' ' + isnull(EM2.LastName,'') as ReferenceName,    
 isnull(O.NursingRemark,'') as NursingRemark,    
 isnull(EM2.Id,0) as ReferenceEmployeeId,    
 isnull(O.IsWaiveOff,0) as IsWaiveOff,    
 isnull(O.Age,0) as OtherAge,    
 isnull(O.Months,0) as OtherMonth,    
 isnull(O.GenderId,0) as OtherGenderId,    
 isnull(O.OutsideMedicine,'') as OutsideMedicine,    
 isnull(O.OutsideTest,'') as OutsideTest,    
 isnull(p.Id,0) as PrescriptionId,    
 isnull(p.Remark,'') as PrescriptionRemark,    
 isnull(p.IsDispensed,0) as IsDispensed,    
 isnull(ED.Id,0) as ExaminDiseaseId,    
 isnull(ED.Remark,'') as DiseaseRemark,    
 isnull(COM.Id,0) as ComplaintId,    
 isnull(COM.Remark,'') as ComplaintRemark,    
 isnull(O.IsPediatric,0) as IsPediatric, 
 isnull(CASE 
	WHEN EE.ParticipantSourceTypeId = 1009 then G2.Title
	WHEN EE.ParticipantSourceTypeId = 1001 then ''
	ELSE G.Title
 End,'') AS Gender,
 Age = case when EE.ParticipantSourceTypeId = 1009 then    
 case when CS.DateOfBirth = '1900-01-01' then 0 else datediff(yy,CS.DateOfBirth,getdate()) end    
 when EE.ParticipantSourceTypeId = 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,    
 isnull(EE.ExaminationNumber,'') as ExaminationNumber,    
 isnull(SA.Id,'') as AppointmentId,    
 isnull(convert(varchar,SA.AppointmentDate,103),'') as AppointmentDate,    
 isnull(SA.FollowupRemark,'') as FollowupRemark,
  isnull(SA.CompliantRemark,'') as CompliantRemark,  
 case when EM5.StatusId <> 10 then     
 EM5.FirstName + ' ' + isnull(EM5.LastName,'')     
     
 else '' end as DoctorName, --[Neha - OPD Screen - DoctorName lable Issue]    
 isnull(O.FurtherActionId,0) as FurtherActionId,    
 isnull(O.FurtherActionRemark,'') as FurtherActionRemark,    
 FAM.Code as FurtherActionCode,    
 isnull(O.OPDTime,'') as OPDTime,    
 isnull(O.OPDOutTime,'') as OPDOutTime,    
 isnull(O.IsFit,0) as IsOPDFit,    
 Isnull(OSP.Id,0) as OutsideMedicineId,    
 Isnull(@lothermedicines,'') as OutsideMedicineList,    
 Isnull(EE.VaccineDoseId,0)VaccineDoseId,    
 ISNULL(O.OtherSubGroupId,0)OtherSubGroupId,    
 ISNULL(IsonSugarMedication, 0) IsonSugarMedication,    
 ISNULL(IsonBPMedication, 0) IsonBPMedication,    
 ISNULL(ReferToDoctorId, 0) ReferToDoctorId,
 ISNULL(O.VisitTypeId, 1) VisitTypeId,
 ISNULL(O.WellnessConsultationId, 0) WellnessConsultationId,
 ISNULL(OUL.Id, 0) UnfitListingId,    
 (Case When ISNULL(EE.RiskCategoryId, 0) = 1 Then 1 Else 0 END) RiskCategoryChecked, ISNULL(EE.DataEntryTemplateId, 0) as DataEntryTemplateId,    
 ISNULL(O.UniqueIdType, 0) as UniqueIdType, ISNULL(O.UniqueIdTypeOther, 0) as UniqueIdTypeOther, ISNULL(O.UniqueId, 0) as UniqueId  ,  
  isnull(V.SPo2,0) as SPO2 ,isnull(O.OtherEmail,'') as OtherEmail,isnull(O.VendorCompanyName,'') as VendorCompanyName,
  case when EE.ParticipantSourceTypeId = 1009 then CS.LocationId else EJD.EmployeeLocationId end as EmployeeLocationId,
   CASE 
    WHEN EE.ParticipantSourceTypeId = 1009 
        THEN ISNULL(o.MobileNumber,CS.MobileNO) when EE.ParticipantSourceTypeId = 1001 
        THEN ISNULL(o.MobileNumber,CS.MobileNO) 
    ELSE 
        ISNULL(o.MobileNumber, EC.MobileNumber)
END AS MobileNumber --Developer: Yogesh Banwe, Added MobileNumber, Date: 12/01/2026, Mantis : 0049519
 from sExamination.tExamination EE    
 left join sHrm.tEmployeeMaster EM on EE.ParticipantSourceId = EM.Id and EE.ParticipantSourceTypeId = 95
 left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId
 left join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId = EM.Id
 left join sHrm.tEmployeePersonalDetail EP on EE.ParticipantSourceId = EP.EmployeeId and EE.ParticipantSourceTypeId = 95    
 left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = EE.ParticipantSourceId and EE.ParticipantSourceTypeId = 1001    
 left join sHrm.tEmployeeMaster EM3 on EFD.EmployeeId = EM3.Id    
 left join sHrm.tCsrBenefiterMaster CS on EE.ParticipantSourceId = CS.Id and EE.ParticipantSourceTypeId = 1009    
 left join sExamination.tAccidentLog A on EE.Id = A.ExaminationId    
 left join sExamination.tCustomIncident CI on EE.Id = CI.ExaminationId    
 left join sExamination.tOPDUnfitListing OUL on OUL.ExaminationId = EE.Id    
 left join sExamination.tCauseMaster C on C.Id = EE.CauseId    
 left join sExamination.tReferral R on EE.Id = R.SourceId    
 left join sExamination.tVital V on EE.Id = V.SourceId    
 left join sExamination.tOPD O on EE.Id = O.ExaminationId    
 left join sSafety.tFurtherActionMaster FAM ON FAM.Id = O.FurtherActionId    
 left join sHrm.tEmployeeMaster EM2 on EE.ParticipantSourceTypeId = 1009 AND O.ReferenceEmployeeId = EM2.Id    
 left join sHrm.tEmployeePersonalDetail PD on EE.ParticipantSourceId = PD.EmployeeId and EE.ParticipantSourceTypeId = 95    
 left join sHrm.tEmployeeFamilyDetails EF on EE.ParticipantSourceId = EF.Id and EE.ParticipantSourceTypeId = 1001    
 left join sExamination.tPrescription P on EE.Id = P.SourceId    
 left join sExamination.tExaminDisease ED on EE.Id = ED.SourceId    
 left join sExamination.tComplaint COM on COM.SourceId = EE.Id    
 left join sAppointment.tAppointment SA on EE.Id = SA.ReferSourceId     
 left join sHrm.tEmployeeMaster EM5 on EM5.Id = EE.DoctorEmployeeId    
 --Left join sCwb.tDoctorMaster CDM on CDM.EmployeeId = EM5.Id    
 --Left join sCwb.tDoctorStoreLocation DSL on CDM.EmployeeId = DSL.EmployeeId and DSL.SubLocationId = @rStoreLocationId    
 left join sExamination.tOutSidePrescription OSP on OSP.Sourceid=EE.id    
 --left join sSupport.tVaccineDoseMaster VDM on VDM.Id=EE.VaccineDoseId 
 left join [sCommon].[tGenderMaster] G ON EP.GenderId = G.Id   
 left join [sCommon].[tGenderMaster] G2 ON CS.GenderId = G2.Id   
 where EE.Id = @rExaminationId    
 OPTION (RECOMPILE)    
    
 select ED.Id,EED.Id as DetailId,    
 isnull(ED.Remark,'') as Remark,    
 EED.DiseaseId as DiseaseId,    
 isnull(EED.Remark,'') as DieseaseRemark,    
 CTM.Title as DiseaseType,    
 EED.IsObsolete    
 from sExamination.tExaminDiseaseDetail EED    
 inner join sExamination.tExaminDisease ED on EED.ExaminDiseaseId = ED.Id    
 inner join sExamination.tDiseaseMaster CTM on EED.DiseaseId = CTM.Id    
 where ED.SourceId = @rExaminationId and EED.IsObsolete = 0    
 OPTION (RECOMPILE)    
    
 SELECT PR.Id As PrescriptionId,    
 PR.IsDispensed,    
 PRED.Id AS PrescriptiondetailId,    
 PRED.StockItemId,    
 PRED.DrugInstruction,    
 PRED.Duration,    
 CONVERT(int,ROUND(ISNULL(PRED.DispensedQuantity,0),0)) AS DispensedQuantity,    
 SIM.Title AS StockItemName,    
 PRED.Remark AS StockItemremark,    
 PRED.PrescribedQuantity as Total,    
 PRED.IsDirectIssue AS IsAllowDirectIssue,    
 PRED.IsNotInStore,    
 PRED.Dosage,    
 SIM.ItemSubGroupId as SubGroupId,    
 isnull((select Title from sIp.tItemSubGroupMaster where Id = SIM.ItemSubGroupId),'') as MedicineType,    
 PRED.DurgDosageQty as DrugFreqQty,    
 PRED.DrugDosageScheduleId as DrugScheduleId,    
 PRED.DrugDosageFrequencyId as DrugFreqId,    
 DF.DurgQuantity as DrugQty,    
 DQ.Title as DrugQtyText,    
 DF.Title as DrugFrequencyText, isnull(PRED.DrugFrequencyPattern,'') AS DrugFrequencyPattern,   
 DS.Title as DrugScheduleText,0 as IsDelete,    
 isnull(PRED.ConsumeUOM,'') as Unit,    
 PRED.UpdatedDateTime, UOM.Title as UOM, ISNULL(SIM.IsGroupItem, 0) as IsGroupItem   
 FROM sExamination.tPrescriptionDetail PRED    
 INNER JOIN sExamination.tPrescription PR ON PR.Id = PRED.PrescriptionId    
 INNER JOIN sIp.tStockItemMaster SIM ON PRED.StockItemId = SIM.ID    
 INNER JOIN sFinanceCommon.tStockUomMaster UOM ON UOM.Id = SIM.IssueStockUomId    
 INNER JOIN sIp.tDrugDosageFrequencyMaster DF on PRED.DrugDosageFrequencyId = DF.Id    
 INNER JOIN sIp.tDrugScheduleMaster DS on PRED.DrugDosageScheduleId = DS.Id    
 INNER JOIN sIp.tDrugDosageQtyMaster DQ on PRED.DurgDosageQty = DQ.DosageQty    
 WHERE PR.SourceId= @rExaminationId AND PRED.IsObsolete = 0 AND PR.IsObsolete = 0    
 AND SIM.IsDrug = 1 AND SIM.IsBlockedForIssue = 0 AND SIM.IsObsolete = 0 order by PRED.IsNotInStore    
 OPTION (RECOMPILE)      
 SELECT TM.Id,    
 AM.Id,    
 TR.Id AS TestRequestId,    
 1 AS Id,    
 1 AS RId,    
 --AM.Id AS RespectiveTestId,    
 TM.Id AS RespectiveTestId,   -- Developer: Deval, Date: 02/10/2023    
 TPM.Id as TestAreaId,    
 AM.Title AS Test1Name,    
 TPM.Title as TestName,    
 isnull(TRd.Remark,'') AS Remark,    
 ISNULL(TR.IsReferred,0) As IsReferred,    
 ISNULL(TR.ReferredClinicId,0) AS ClinicalId,    
 ISNULL(CM.Title,'') AS Clinical,AM.AreaTypeId,    
 TM.ServiceSubGroupId as SubgroupId,    
 SSM.ServiceMainGroupId as MainGroupId,    
 ISNULL(SSM.Title,'') AS SubType,    
 ISNULL(SMG.Title,'') AS MainType,    
 CASE WHEN ISNULL(TR.IsResultDone,0)=0 THEN 'Not Done' ELSE 'Done' END AS StatusName,    
 0 as TestParameterFlag,    
 case when Isnull(TR.IsPackage,0) = 0 then 'Y' else 'N' end IsPackageValue    
 FROM [sExamination].[tAreaMaster] AM    
 INNER JOIN sExamination.tAreaTypeMaster AT ON AM.AreaTypeId = AT.Id    
 INNER JOIN sExamination.tTestRequest TR ON TR.TestId = AM.Id    
 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    
 LEFT JOIN sCommon.tClinicMaster CM ON  TR.ReferredClinicId = CM.Id     
 INNER JOIN sOrderEntry.tTestMaster TM ON TM.Id = TR.TestId AND TM.OrgId = @rOrgId    
 INNER JOIN sOrderEntry.tServiceSubGroupMaster SSM ON SSM.Id = TM.ServiceSubGroupId    
 INNER JOIN sOrderEntry.tServiceMainGroupMaster SMG ON SMG.Id = SSM.ServiceMainGroupId    
 WHERE TR.SourceId = @rExaminationId AND AM.OrgId = @rOrgId    
 AND AM.AreaTypeId IN (1,2) AND TR.IsObsolete = 0    
 order by AM.Title,TD.OrderIndex    
 OPTION (RECOMPILE)    
 SELECT ISNULL(ADT.AllergyId,0) AS AllergyId,    
 ISNULL(ADT.AllegyDetailId,0) AS AllergyDetailId,         
 ISNULL(ATM.Id,0) AS AllergyTypeId,    
 ISNULL(AllergyDetailRemark,'') AS AllergyDetailRemark,    
 ATM.Title AS AllergyType,    
 ISNULL(ADT.Duration,'') AS Number,    
 ISNULL(ADT.DurationUnitId,0) AS DurationUnitId,    
 ISNULL(ADT.IsObsolete,0) AS IsObsolete,    
 ISNull(DUM.Title,'') AS Unit,    
 CASE WHEN ADT.AllergyTypeId IS NOT NULL THEN 1 ELSE 0 END AS IsSelected    
 FROM sExamination.tAllergyTypeMaster ATM    
 LEFT JOIN                   
 (    
  SELECT AD.IsObsolete,    
  AD.Id AS AllegyDetailId,    
  AD.AllergyTypeId,A.Id AS AllergyId,    
  AD.Remark AS AllergyDetailRemark,    
  AD.Duration,    
  AD.DurationUnitId    
  FROM sExamination.tAllergyDetail AD    
  INNER JOIN sExamination.tAllergy A ON A.Id = AD.AllergyId    
  AND A.IsObsolete = 0 AND AD.IsObsolete = 0    
  AND A.ParticipantId = @rParticipantId    
  AND A.ParticipantSourceTypeId = @rParticipantSourceTypeId    
  AND A.OrgId = @rOrgId    
 ) ADT ON ADT.AllergyTypeId = ATM.Id AND ATM.IsObsolete = 0    
 LEFT JOIN sCommon.tDurationUnitMaster DUM ON ADT.DurationUnitId=DUM.ID    
 WHERE ATM.OrgId = @rOrgId    
 OPTION (RECOMPILE)     
 SELECT R.Id,    
 R.SourceId AS EmployeeId,    
 isnull(R.ReferToClinicId,-1) as ReferToClinicId,    
 CM.Title AS ClinicName,    
 R.Remark,isnull(R.ContactPerson,'') as ContactPerson,    
 ISNULL(RT.Remark,'') AS TestRemark,    
 ISNULL(TM.Id,0) AS TestId,    
 ISNULL(RT.Id,0) AS ReferralTestId,    
 ISNULL(TM.Title,'') AS Test,    
 ISNULL(TM.ServiceSubGroupId,0) AS ServiceSubGroupId,    
 ISNULL(SSM.ServiceMainGroupId,0) AS ServiceMainGroupId,    
 ISNULL(SSM.Title,'') AS ServiceSubGroup,    
 ISNULL(SMG.Title,'') AS ServiceMainGroup    
 FROM sExamination.tReferral R    
 INNER JOIN sCommon.tClinicMaster CM ON CM.Id=R.ReferToClinicId    
 LEFT JOIN sExamination.tReferralTest RT ON RT.ReferralId=R.Id    
 LEFT JOIN sOrderEntry.tTestMaster TM ON TM.Id=RT.TestId    
 LEFT JOIN sOrderEntry.tServiceSubGroupMaster SSM ON SSM.Id = TM.ServiceSubGroupId    
 LEfT JOIN sOrderEntry.tServiceMainGroupMaster SMG ON SMG.Id = SSM.ServiceMainGroupId    
 where R.SourceId = @rExaminationId AND R.StoreLocationId=@rStoreLocationId AND R.OrgId = @rOrgId    
 OPTION (RECOMPILE) 
 
 ;WITH ValidOGIT AS (
	SELECT O.*
	FROM sExamination.tOPDGroupItemTrack O
	LEFT JOIN sExamination.tPrescriptionDetail PD ON PD.Id = O.PrescriptionDetailId
	LEFT JOIN sExamination.tPrescription PRE ON PRE.Id = PD.PrescriptionId
	WHERE 
		O.PrescriptionDetailId IS NULL 
		OR PRE.SourceId = @rExaminationId
)
 select GII.Id, 
	GII.StockItemId, STM.Code as StockItemCode, STM.Title as StockItemName, 
	GII.GroupItemId,
	CASE WHEN OGIT.Quantity > 0 THEN OGIT.Quantity ELSE GII.DefaultQty END AS Quantity,
	GII.DefaultUOM, OSB.StockBatchId, ISNULL(OGIT.PrescriptionDetailId, 0) AS PrescriptionDetailId,
	CASE WHEN OGIT.Id > 0 THEN 1 ELSE 0 END AS IsChecked
	from sProcurement.tGroupItemIssue GII
	INNER JOIN sIp.tStockItemMaster STM ON STM.Id = GII.StockItemId
	INNER JOIN sProcurement.tStockBatch SB ON SB.Id = GII.StockBatchId
	INNER JOIN sProcurement.tOtherStockBatch OSB ON OSB.StockBatchId = SB.Id and OSB.OtherLocationSourceId = GII.GroupItemId
	LEFT JOIN ValidOGIT OGIT ON OGIT.GroupItemId = GII.GroupItemId AND OGIT.StockBatchId = OSB.StockBatchId
	where OSB.OtherLocationSourceTypeId = 10170
	AND GII.OrgId = @rOrgId AND GII.IsObsolete = 0
	AND GII.StoreLocationId = @rStoreLocationId
OPTION (RECOMPILE)

 SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off    
end 

GO


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

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

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

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

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

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

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


	select
	 isnull(col1,'') as col1,
	 isnull(col2,'') as col2		
	 from @tbltmpview
	OPTION (RECOMPILE)

	select @lVitalRes = @lVitalHead + @lVitalRes
	OPTION (RECOMPILE)

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


	select 
	isnull(col1,'') as col1
	from @tbltmpComplaint
	OPTION (RECOMPILE)

	select @lComplaintRes = @lComplaintHead + @lComplaintRes
	OPTION (RECOMPILE)

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

	

	select 
	 isnull(col1,'') as col1,	
	 isnull(col2,'') as col2,
	 isnull(col3,'') as col3	
	 from @tbltmpReferral
	OPTION (RECOMPILE)

	select @lReferralRes = @lReferralHead + @lReferralRes
	OPTION (RECOMPILE)

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

	select
	 isnull(col1,'') as col1,
	 isnull(col2,'') as col2,
	 isnull(col3,'') as col3			
	 from @tbltmpdisese
	OPTION (RECOMPILE)

	select @lDiagnosisRes = @lDiagnosisHead + @lDiagnosisRes
	OPTION (RECOMPILE)

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

	select 
	 isnull(col1,'') as col1,	
	 isnull(col2,'') as col2,
	 isnull(col3,'') as col3
	 from @tbltmptest
	OPTION (RECOMPILE)

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


	select 
	isnull(col1,'') as col1,
	isnull(col2,'') as col2,		
	isnull(col3,'') as col3	,	
	isnull(col4,'') as col4,		
	isnull(col5,'') as col5	,	
	isnull(col6,'') as col6		
	 from @tbltmpPres
	OPTION (RECOMPILE)

	select @lPrescriptionRes = @lPrescriptionHead + @lPrescriptionRes
	OPTION (RECOMPILE)

	-- select isnull(@lVitalRes,'') as Vital,isnull(@lDiagnosisRes,'') as Diagnos,isnull(@lTestRes,'') as Test,
	-- isnull(@lPrescriptionRes,'') as Pres,isnull(@lComplaintRes,'') as Comp,isnull(@lReferralRes,'') as Ref
	--OPTION (RECOMPILE)
	SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off
end

GO


ALTER PROC [sExamination].[pPatientListGetNg]
@rMainTypeId int,
@rOrgId int,
@rPageindex int,
@rCode varchar(200),
@rName varchar(200),
@rDoctor bigint,
@rfdate varchar(20),
@rtdate varchar(20),
@rStoreLocationId int
AS 
BEGIN 

set @rCode = replace(@rCode,'\\','\')
	select @rfdate = case when @rfdate <> '' then CONVERT(VARCHAR(10), CONVERT(date, @rfdate, 105), 23) else '' end
	select @rtdate = case when @rtdate <> '' then CONVERT(VARCHAR(10), CONVERT(date, @rtdate, 105), 23) else '' end
	
	declare @rSetupId int,@result varchar(max)='',@lpaging varchar(max)='',@TotalRecords int,@PageSize int=10
	select @rSetupId = case when len(@rMainTypeId) > 4 then @rMainTypeId else sCommon.fGetIntIdForOrg(@rMainTypeId,@rOrgId) end
	
	declare @tblpatient table(tid int identity(1,1),pid bigint)
	insert into @tblpatient
	select R.Id
	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
	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 
	where R.OrgId = @rOrgId and
	isnull(R.ExaminationId,0) = 0
	and (datediff(day,@rfdate,R.registrationDate)>=0 or @rfdate='') 
	and (datediff(day,R.registrationDate,@rtdate)>=0 or @rtdate='')
	and ((R.SetupId = @rSetupId) or (@rSetupId = 0))
	and ((R.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
	and ((R.DoctorEmployeeId = @rDoctor) or (@rDoctor = 0))
	and ((EM.Code like @rCode + '%') or (CSB.Code like @rCode + + '%') or (EM2.Code like @rCode + '%') or (isnull(@rCode,'') = ''))
	and (EM.FirstName like @rName + '%' or CSB.FirstName like @rName + '%' or EFD.Name like @rName + '%' or isnull(R.OtherName,'') like @rName + '%' or isnull(@rName,'')= '')
	order by R.Id desc
	
	select @TotalRecords = count(*)	from @tblpatient
	select @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@rPageindex,@TotalRecords,@PageSize)
	

	select isnull(R.Id,0) as Id,
	case when R.ParticipantSourceTypeId = 95 then	isnull(EM.Code,'')
	when R.ParticipantSourceTypeId = 1009 then isnull(CSB.Code,'') else isnull(EM2.Code,'') end as Code,
	isnull(R.OtherName,'') as OtherName,
	isnull(R.RegistrationNumber,'') as RegistrationNumber,
	case when R.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')
	when R.ParticipantSourceTypeId = 1009 then isnull(CSB.Code,'') else isnull(EM2.Code,'') end as PatientCode,
	case when R.ParticipantSourceTypeId = 95 then
	(isnull(EM.FirstName,'') + isnull(' ' + EM.MiddleName,'') + ' ' + isnull(EM.LastName,''))
	when R.ParticipantSourceTypeId = 1009 then case when isnull(R.OtherName,'') <> '' then isnull(R.OtherName,'') else
	(isnull(CSB.FirstName,'') + isnull(' ' + CSB.MiddleName, '') + ' ' + isnull(CSB.LastName,'')) end
	else isnull(EFD.Name,'') end as PatientName,
	isnull(EM1.FirstName,'') + isnull(' ' + EM1.MiddleName,'') + ' ' + isnull(EM1.LastName,'') as DoctorName,
	isnull(convert(varchar,R.RegistrationDate,103),'') as RegistrationDate,
    isnull(R.ParticipantSourceTypeId,0) as ParticipantSourceTypeId,
    case when R.ParticipantSourceTypeId = 95 then convert(varchar,isnull(EM.Id,0)) 
    when R.ParticipantSourceTypeId = 1009 THEN convert(varchar,isnull(CSB.Id,0)) ELSE convert(varchar,EFD.Id) end as EmployeeId,
    isnull(R.Id,0) as RegistrationId,
	isnull(R.ExaminationId,0) as ExaminationId,
    case when R.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')
	when R.ParticipantSourceTypeId = 1009 then isnull(CSB.Code,'') else isnull(EM2.Code,'') end as EmployeeCode,
    case when R.ParticipantSourceTypeId = 95 then
	(isnull(EM.FirstName,'') + isnull(' ' + EM.MiddleName,'') + ' ' + isnull(EM.LastName,'') )
	when R.ParticipantSourceTypeId = 1009 then (isnull(CSB.FirstName,'') + isnull(' ' + CSB.MiddleName, '') + ' ' + isnull(CSB.LastName,'')) 
	else EFD.Name end as aName,
    --isnull(EP.GenderId,0)as GenderId,
	 case when R.ParticipantSourceTypeId = 95 then isnull(EP.GenderId,0)
	when R.ParticipantSourceTypeId = 1009 then isnull(CSB.GenderId,0) end as GenderId,
    case when R.ParticipantSourceTypeId = 95 then isnull((SELECT Title FROM sCommon.tGenderMaster WHERE Id=EP.GenderId),'')
	when R.ParticipantSourceTypeId = 1009 then isnull((SELECT Title FROM sCommon.tGenderMaster WHERE Id=CSB.GenderId),'') end as Gender,
    isnull(EP.DateOfBirth,'') as DOB,
    isnull(datediff(yy,EP.DateOfBirth,getdate()),0)as DateofDOB,
    isnull(EJD.OrganizationDepartmentId,0) as OrganizationDepartmentId,
    isnull(EJD.EmployeeDesignationId,0) as EmployeeDesignationId,
    isnull(R.DoctorEmployeeId,0) as DoctorEmployeeId,
    isnull((select Title from sHrm.tEmployeeDesignationMaster where Id = EJD.EmployeeDesignationId),'') as Title,
     isnull(EJD.ProcessTypeId,0)as ProcessTypeId,
     isnull(R.Age,0)as OtherAge,
     isnull(R.Months,0)as OtherMonths,
     isnull(R.GenderId,0)as OtherGenderId,
	 isnull(R.RegistrationDate,'')as RegistrationDate,
	 isnull(R.CompliantRemark,'')as CompliantRemark,
	 CASE  
        WHEN R.ParticipantSourceTypeId=95 THEN ISNULL(ED.CompanyEmail,'') 
        WHEN R.ParticipantSourceTypeId=1009 THEN ISNULL(CSB.EmailId,'')  
        ELSE '' 
     END AS EmailId,
     CASE  
        WHEN R.ParticipantSourceTypeId=95 THEN ISNULL(ED.MobileNumber,'') 
        WHEN R.ParticipantSourceTypeId=1009 THEN ISNULL(CSB.MobileNo,'') 
        ELSE '' 
     END AS MobileNumber
    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.vEmployeeDetail ED ON ED.Id = R.ParticipantSourceId AND R.ParticipantSourceTypeId=95
	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
	left join sHrm.tEmployeePersonalDetail EP on R.ParticipantSourceId = EP.EmployeeId	
	inner join sExamination.vExtSetupMaster as VSM on VSM.Id = R.SetupId,
	@tblpatient t
	where t.pid = R.Id AND t.tid between ((@PageSize * (@rPageindex-1)) + 1) and (@PageSize * @rPageindex)
	order by t.tid
	
	select @TotalRecords AS TotalRecords,@rfdate,@rtdate
	select * from @tblpatient

END	    

GO


CREATE OR ALTER PROCEDURE[sExamination].[pReferredOpdSearch]
@rDoctorEmployeeId BIGINT,
@rEmployeeCode nvarchar(50),
@rEmployeeName nvarchar(200),
@rOrgId smallint,
@rStoreLocationId int
AS
BEGIN
	select EXM.Id, EXM.ExaminationNumber as OPDNumber, EXM.ParticipantSourceId AS EmployeeId,
	CASE WHEN EXM.ParticipantSourceTypeId = 1009 THEN ISNULL(CBM.Code,'') 
		 WHEN EXM.ParticipantSourceTypeId = 95 THEN ISNULL(EM.Code,'') END AS EmployeeCode,
	CASE WHEN EXM.ParticipantSourceTypeId = 1009 THEN ISNULL(CBM.FirstName,'') + ' ' + ISNULL(CBM.LastName,'')
		 WHEN EXM.ParticipantSourceTypeId = 95 THEN ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') 
		 END AS EmployeeName, 
	CASE WHEN EXM.ParticipantSourceTypeId = 1009 THEN 'Other'
		 WHEN EXM.ParticipantSourceTypeId = 95 THEN 'Employee' END AS Relation,
	ISNULL(DM.FirstName,'') + ' ' + ISNULL(DM.LastName,'') as DoctorName,
	EXM.ParticipantSourceTypeId, ISNULL(OP.OtherName, '') as OtherName,
	CASE WHEN EXM.ParticipantSourceTypeId = 1009 THEN 
	  (CASE WHEN CBM.DateOfBirth <> '1900-01-01' and ISNULL(CBM.DateOfBirth, '') <> ''
			     THEN ISNULL(DATEDIFF(yy,CBM.DateOfBirth,sCommon.fGetDate()),0) ELSE 0 END)
    WHEN EXM.ParticipantSourceTypeId = 95 THEN
	  (CASE WHEN EPD.DateOfBirth <> '1900-01-01' and ISNULL(EPD.DateOfBirth, '') <> ''
			     THEN ISNULL(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) ELSE 0 END)
	END AS Age,
	CASE WHEN EXM.ParticipantSourceTypeId = 1009 THEN GCBM.Title
	     WHEN EXM.ParticipantSourceTypeId = 95 THEN GEM.Title END AS Gender,
    CASE WHEN EXM.ParticipantSourceTypeId = 1009 THEN OP.Age ELSE 0 END AS OtherAge,
	CASE WHEN EXM.ParticipantSourceTypeId = 1009 THEN OP.Months ELSE 0 END AS OtherMonth,
	CASE WHEN EXM.ParticipantSourceTypeId = 1009 THEN OP.GenderId ELSE 0 END AS OtherGenderId,
	ISNULL(OP.OtherEmail,'') as EmailAddress, ISNULL(OP.MobileNumber,'') as MobileNumber,
    VIT.Height, VIT.BodyWeight as Weight, VIT.BMI, 
	VIT.BloodPressureSystolic as BPSys, VIT.BloodPressureDiastolic as BPDia, Hba1cTest.HBA1C, LDLTest.LDL
	from sExamination.tExamination EXM
	LEFT JOIN sWellness.tWellnessConsultation WC ON WC.OPDId = EXM.Id
	LEFT JOIN sExamination.tOPD OP ON OP.ExaminationId = EXM.Id
	LEFT JOIN sSafety.tFurtherActionMaster FAM ON FAM.Id = OP.FurtherActionId
	LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = EXM.ParticipantSourceId AND EXM.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeePersonalDetail AS EPD ON EM.Id = EPD.EmployeeId
	LEFT JOIN sCommon.tGenderMaster GEM ON EPD.GenderId = GEM.Id
	LEFT JOIN sHrm.tCsrBenefiterMaster CBM ON CBM.Id = EXM.ParticipantSourceId AND EXM.ParticipantSourceTypeId = 1009
	LEFT JOIN sCommon.tGenderMaster GCBM ON CBM.GenderId = GCBM.Id
	INNER JOIN sHrm.tEmployeeMaster DM ON DM.Id = EXM.DoctorEmployeeId
	LEFT JOIN sExamination.tVital VIT ON VIT.SourceId = EXM.Id
	OUTER APPLY (select TOP 1 ParticipantSourceTypeId,ParticipantSourceId,
	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 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
		 AND E.ParticipantSourceId = EXM.ParticipantSourceId
		AND E.ParticipantSourceTypeId = EXM.ParticipantSourceTypeId
		 order by E.ExaminationDate desc) Hba1cTest
	OUTER APPLY (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 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
		 AND E.ParticipantSourceId = EXM.ParticipantSourceId
		 AND E.ParticipantSourceTypeId = EXM.ParticipantSourceTypeId
		 order by E.ExaminationDate desc) LDLTest
	WHERE OP.ReferToDoctorId = @rDoctorEmployeeId AND FAM.Code = '201' AND EXM.OrgId = @rOrgId
	AND EXM.SetupId = [sCommon].[fGetIntIdForOrg](8, @rOrgId)
	AND EXM.StoreLocationId = @rStoreLocationId AND WC.OPDId IS NULL
	AND (EM.Code Like @rEmployeeCode or CBM.Code Like @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '' OR ISNULL(@rEmployeeCode,'') = '*')
	AND (EM.FirstName Like @rEmployeeName  + '%' or CBM.FirstName like @rEmployeeName  + '%' OR ISNULL(@rEmployeeName,'') = '' OR ISNULL(@rEmployeeName,'') = '*')
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,
  CASE  
        WHEN R.ParticipantSourceTypeId=95 THEN ISNULL(ED.CompanyEmail,'') 
        WHEN R.ParticipantSourceTypeId=1009 THEN ISNULL(CSB.EmailId,'')  
        ELSE '' 
     END AS EmailId,
     CASE  
        WHEN R.ParticipantSourceTypeId=95 THEN ISNULL(ED.MobileNumber,'') 
        WHEN R.ParticipantSourceTypeId=1009 THEN ISNULL(CSB.MobileNo,'') 
        ELSE '' 
     END AS MobileNumber,
  case when R.ParticipantSourceTypeId = 95 then isnull((SELECT Title FROM sCommon.tGenderMaster WHERE Id=ED.GenderId),'')
	when R.ParticipantSourceTypeId = 1009 then isnull((SELECT Title FROM sCommon.tGenderMaster WHERE Id=CSB.GenderId),'') end as Gender
 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.vEmployeeDetail ED ON ED.Id = R.ParticipantSourceId AND R.ParticipantSourceTypeId=95
 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[sExamination].[pRestrictLipidAutocalculationByRoundGet]
    @rOrgId INT,
    @rStoreLocationId INT,
    @rSetupId INT,
    @rCode NVARCHAR(500) = '',
    @PageNumber BIGINT = 1,
    @PageSize INT = 50,
    @FromValue BIGINT = 0,
    @ToValue BIGINT = 0
AS
BEGIN
    SET NOCOUNT ON;

    ;WITH PageNumbers AS (
        SELECT
            ROW_NUMBER() OVER (ORDER BY E.Id ASC) AS srno,
            E.Id,
            EM.Code AS ParticipantCode,
            EM.FirstName + ' ' + EM.LastName AS ParticipantName,
            ODM.Title AS Department,
            CASE WHEN RLA.id IS NULL THEN 'false' ELSE 'true' END AS chk
        FROM 
            sExamination.tExamination E
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = E.ParticipantSourceId
            LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM ON E.OrganizationDepartmentId = ODM.Id
            LEFT JOIN [sExamination].[tRestrictLipidAutocalculation] RLA ON RLA.ExaminationId = E.id
        WHERE 
            E.SetupId = @rSetupId
            AND E.StoreLocationId = @rStoreLocationId
            AND E.OrgId = @rOrgId
            AND (ISNULL(EM.Code, '') IN (SELECT item FROM sCommon.fnsplit(@rCode, ',')) OR @rCode = '')
    ),
    TotalCountCTE AS (
        SELECT COUNT(*) AS TotalCount FROM PageNumbers
    )
   SELECT 
    PN.*, 
    TC.TotalCount
	FROM 
    PageNumbers PN
    CROSS JOIN TotalCountCTE TC
	WHERE 
PN.srno BETWEEN
CASE
    -- only ToValue passed
    WHEN @FromValue = 0 AND @ToValue > 0 
        THEN 1

    -- FromValue passed
    WHEN @FromValue > 0 
        THEN @FromValue

    -- Normal pagination
    ELSE ((@PageNumber - 1) * @PageSize + 1)
END
AND
CASE
    -- both FromValue and ToValue passed
    WHEN @FromValue > 0 AND @ToValue > 0 
        THEN @ToValue

    -- only FromValue passed
    WHEN @FromValue > 0 AND @ToValue = 0 
        THEN (@FromValue + @PageSize - 1)

    -- only ToValue passed
    WHEN @FromValue = 0 AND @ToValue > 0 
        THEN @ToValue

    -- Normal pagination
    ELSE (@PageNumber * @PageSize)
END
	ORDER BY 
		PN.srno;
END;

GO


CREATE OR ALTER PROCEDURE[sExamination].[pRptPulmonaryResult]
@rExaminationId bigint
as 
begin
	SET NOCOUNT ON;   
	SELECT  P.*,isnull(PNM.Title,'') As ReversibilityTest,
	ISNULL(P.PulmonaryResulIntensity + ' ','') + P.PulmonaryResult AS Result
	FROM sExamination.tPulmonary P
	LEFT JOIN sExamination.tPositiveNegativeMaster PNM
	ON P.ReversibilityTestId = PNM.Id
	WHERE P.SourceId = @rExaminationId
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), o_WellnessConsultationId bigint)            
 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,
 T.c.value('@WellnessConsultationId','bigint') as WellnessConsultationId
 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, o_WellnessConsultationId     
  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, WellnessConsultationId = o_WellnessConsultationId
 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, WellnessConsultationId  
  )
  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,o_WellnessConsultationId
  );
            
  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[sOrderEntry].[pDiagnosisTrackerTipsGet]   
    @rDiagnosisTrackerId bigint,  
    @rLanguage nvarchar(100),  
    @rOrgid int   
WITH EXECUTE AS CALLER  
AS  
BEGIN  
    DECLARE @ResultString nvarchar(max) = '',
            @Resstr nvarchar(max) = ''

    SELECT @ResultString = @ResultString + 
        '<tr>  
            <td>
                <div class="dropdown">
                   
					 
    <span class="text-info">
    Options <i class="fa fa-caret-down" style="font-size:18px;"></i>
</span>
                    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                        <a class="dropdown-item" onclick="GetCanteenDataById(' + CONVERT(varchar, Dt.id) + ');">
                            <i class="fa fa-pencil"></i>Edit
                        </a>
                        <a class="dropdown-item" onclick="GetCanteenDataByIdView(' + CONVERT(varchar, Dt.id) + ');">
                            <i class="fa fa-eye"></i>View
                        </a>
                    </div>
                </div>
            </td>  
            <td>' + CONVERT(varchar, ROW_NUMBER() OVER (ORDER BY DTM.id)) + '</td>  
            <td>' + DTM.Title + '</td>  
            <td>' + CASE  
                        WHEN ISNULL(Dt.IsObsolete, 1) = 1 THEN 'N'  
                        ELSE 'Y'  
                    END + '</td>  
            <td>' + ISNULL(Dt.Language, 'english') + '</td>  
        </tr>'
    FROM sExamination.tDiagnosisTrackerTips Dt  
    INNER JOIN sExamination.tDiagnosisTrackerMaster DTM 
        ON DTM.Id = Dt.DiagnosisTrackerId  
    WHERE ((Dt.DiagnosisTrackerId = @rDiagnosisTrackerId) OR (ISNULL(@rDiagnosisTrackerId, 0) = 0))  
      AND (@rLanguage = '0' OR Dt.Language = @rLanguage)  
      AND Dt.OrgId = @rOrgid  
      AND DTM.IsObsolete = 0  
    ORDER BY DTM.id

    SELECT @Resstr = @Resstr + 
        '<tr>
            <td>' + DTM.Title + '</td>  
            <td>' + Dt.Remark + '</td>
        </tr>'  
    FROM sExamination.tDiagnosisTrackerTips Dt  
    INNER JOIN sExamination.tDiagnosisTrackerMaster DTM 
        ON DTM.Id = Dt.DiagnosisTrackerId  
    WHERE ((Dt.DiagnosisTrackerId = @rDiagnosisTrackerId) OR (ISNULL(@rDiagnosisTrackerId, 0) = 0))  
      AND Dt.OrgId = @rOrgid  
      AND DTM.IsObsolete = 0  
    ORDER BY DTM.id

    SELECT 1  

    SELECT @ResultString AS [ResultString], LEN(@ResultString) AS [LEN], @Resstr AS [RESStr]
END


GO


CREATE OR ALTER PROCEDURE[sWellness].[pAddOrUpdateWellnessSession]    
(    
    @rId INT,    
    @rTitle NVARCHAR(250),    
    @rActivityDate NVARCHAR(50),    
    @rDescription NVARCHAR(MAX) = '',    
    @rEmployeeCount NVARCHAR(50) = '0',   
    @rWellnessSessionTypeMasterId INT,    
    @rWellnessSessionSubTypeMasterId INT,    
    @rIsObsolete BIT,    
    @rOrgId INT,
	@rStoreLocationId INT, 
    @rCreatedUserId BIGINT,    
    @rUpdatedUserId BIGINT    
)    
AS    
BEGIN    
    SET NOCOUNT ON;    
    
    DECLARE @ActivityDate DATETIME;    
    
    -- Convert dd/MM/yyyy HH:mm:ss format    
    SET @ActivityDate =    
        CONVERT(DATETIME, @rActivityDate, 103);    
    
    -- Duplicate Check    
    IF EXISTS    
    (    
        SELECT 1    
        FROM [sWellness].[tWellnessSessionActivityDetail]    
        WHERE OrgId = @rOrgId    
          AND Id <> ISNULL(@rId, 0)    
          AND Title = @rTitle    
--          AND CONVERT(DATE, ActivityDate) = CONVERT(DATE, @ActivityDate)    
          AND ISNULL(IsObsolete, 0) = 0    
    )    
    BEGIN    
        SELECT 11;    
        RETURN;    
    END    
    
    -- Insert    
    IF ISNULL(@rId, 0) = 0    
    BEGIN    
        INSERT INTO [sWellness].[tWellnessSessionActivityDetail]    
        (    
            Title,    
            ActivityDate,    
            Description,    
            WellnessSessionTypeMasterId,    
            WellnessSessionSubTypeMasterId,    
            IsObsolete,    
            OrgId,    
            CreatedUserId,    
            CreatedDatetime  ,  
            EmployeeCount,
			StoreLocationId
        )    
        VALUES    
        (    
            @rTitle,    
            @ActivityDate,    
            @rDescription,    
            @rWellnessSessionTypeMasterId,    
            @rWellnessSessionSubTypeMasterId,    
            @rIsObsolete,    
            @rOrgId,    
            @rCreatedUserId,    
            GETDATE()  ,  
            @rEmployeeCount,
			@rStoreLocationId
        );    
    
        SELECT CONVERT(INT, SCOPE_IDENTITY());    
        RETURN;    
    END    
    
    -- Update    
    UPDATE [sWellness].[tWellnessSessionActivityDetail]    
    SET Title = @rTitle,    
        ActivityDate = @ActivityDate,    
        Description = @rDescription,    
        WellnessSessionTypeMasterId = @rWellnessSessionTypeMasterId,    
        WellnessSessionSubTypeMasterId = @rWellnessSessionSubTypeMasterId,    
        IsObsolete = @rIsObsolete,    
        UpdatedUserId = @rUpdatedUserId,    
        UpdatedDatetime = GETDATE()  ,  
   EmployeeCount = @rEmployeeCount,  
   StoreLocationId = @rStoreLocationId
    WHERE Id = @rId    
      AND OrgId = @rOrgId;    
    
    SELECT @rId;    
END 

GO


CREATE OR ALTER PROCEDURE[sWellness].[pAddOrUpdateWellnessSessionSybType]    
(          
 @rId INT = 0,      
 @rWellnessSessionTypeId INT,      
 @rTitle NVARCHAR(100),      
 @rCode NVARCHAR(100),      
 @rIsObsolete BIT,      
 @rOrgId SMALLINT,      
 @rCreatedUserId BIGINT,      
 @rUpdatedUserId BIGINT      
)       
AS      
SET NOCOUNT ON      
BEGIN      
 BEGIN TRY      
 DECLARE @lNextNumber BIGINT      
  IF(@rId = 0)       
  BEGIN      
   IF  EXISTS(SELECT Id FROM [sWellness].[tWellnessSessionSubTypeMaster] WHERE Code=@rCode AND WellnessSessionTypeId = @rWellnessSessionTypeId AND Id <> @rId)      
   BEGIN      
    SELECT -103 AS Result -- Code Already Exists      
    RETURN      
   END      
   IF  EXISTS(SELECT Id FROM  [sWellness].[tWellnessSessionSubTypeMaster] WHERE Title=@rTitle AND WellnessSessionTypeId = @rWellnessSessionTypeId AND Id <> @rId)      
   BEGIN      
    SELECT -102 AS Result -- Title Already Exists      
    RETURN      
   END      
      
         
      
   INSERT INTO [sWellness].[tWellnessSessionSubTypeMaster] (WellnessSessionTypeId, Title, Code, IsObsolete, OrgId, CreatedUserId,CreatedDateTime)      
   Values (@rWellnessSessionTypeId, @rTitle,@rCode,@rIsObsolete,@rOrgId,@rCreatedUserId,sCommon.fGetDate())      
   SET @lNextNumber = SCOPE_IDENTITY();      
   SELECT @lNextNumber AS Result      
   RETURN          
  END        
  ELSE      
  BEGIN          
   IF  EXISTS(SELECT Id FROM [sWellness].[tWellnessSessionSubTypeMaster] WHERE Code=@rCode AND WellnessSessionTypeId = @rWellnessSessionTypeId AND Id <> @rId)      
   BEGIN      
    SELECT -103 AS Result -- Code Already Exists      
    RETURN      
   END      
   IF  EXISTS(SELECT Id FROM [sWellness].[tWellnessSessionSubTypeMaster] WHERE Title=@rTitle AND WellnessSessionTypeId = @rWellnessSessionTypeId AND Id <> @rId)      
   BEGIN      
    SELECT -102 AS Result -- Title Already Exists      
    RETURN      
   END      
      
   --IF(@rIsObsolete = 1)      --- as disscussed with rushi child will not have this logic
   --BEGIN      
   -- IF EXISTS(SELECT Id FROM [sWellness].[tWellnessSessionSubTypeMaster] WHERE WellnessSessionTypeId = @rId AND IsObsolete = 0)      
   -- BEGIN      
   --  SELECT -104 AS Result -- Cannot inactive parent type without making inactive sub type      
   --  RETURN      
   -- END      
   --END      
      
   UPDATE       
    [sWellness].[tWellnessSessionSubTypeMaster]      
   SET       
    WellnessSessionTypeId = @rWellnessSessionTypeId,      
    Title=@rTitle,      
    Code=@rCode,         
    IsObsolete=@rIsObsolete,       
    UpdatedUserId=@rUpdatedUserId,      
    UpdatedDateTime=sCommon.fGetDate()      
   WHERE       
    Id = @rId      
      
   SELECT @rId AS Result      
   RETURN @rId      
   END           
 END TRY      
 BEGIN CATCH       
   SELECT -101 AS Result      
 END CATCH      
END 

GO

  
CREATE OR ALTER PROCEDURE[sWellness].[pAddOrUpdateWellnessSessionType] 
(      
 @rId INT = 0,  
 @rTitle NVARCHAR(100),  
 @rCode NVARCHAR(100),  
 @rIsObsolete BIT,  
 @rOrgId SMALLINT,  
 @rCreatedUserId BIGINT,  
 @rUpdatedUserId BIGINT  
)   
AS  
SET NOCOUNT ON  
BEGIN  
 BEGIN TRY  
 DECLARE @lNextNumber BIGINT  
  IF(@rId = 0)   
  BEGIN     
   IF  EXISTS(SELECT Id FROM [sWellness].[tWellnessSessionTypeMaster] WHERE Code=@rCode AND Id <> @rId)  
   BEGIN  
    SELECT -103 AS Result -- Code Already Exists  
    RETURN  
   END  
   IF  EXISTS(SELECT Id FROM  [sWellness].[tWellnessSessionTypeMaster] WHERE Title=@rTitle AND Id <> @rId)  
   BEGIN  
    SELECT -102 AS Result -- Title Already Exists  
    RETURN  
   END  
  
   INSERT INTO [sWellness].[tWellnessSessionTypeMaster] (Title,Code,IsObsolete,OrgId, CreatedUserId,CreatedDateTime)  
   Values (@rTitle,@rCode,@rIsObsolete,@rOrgId,@rCreatedUserId,sCommon.fGetDate())  
   SET @lNextNumber = SCOPE_IDENTITY();  
   SELECT @lNextNumber AS Result  
   RETURN      
  END    
  ELSE  
  BEGIN    
   IF  EXISTS(SELECT Id FROM [sWellness].[tWellnessSessionTypeMaster] WHERE Code=@rCode AND Id <> @rId)  
   BEGIN  
    SELECT -103 AS Result -- Code Already Exists  
    RETURN  
   END  
   IF  EXISTS(SELECT Id FROM [sWellness].[tWellnessSessionTypeMaster] WHERE Title=@rTitle AND Id <> @rId)  
   BEGIN  
    SELECT -102 AS Result -- Title Already Exists  
    RETURN  
   END     
   IF(@rIsObsolete = 1)  
   BEGIN  
    IF EXISTS(SELECT Id FROM [sWellness].[tWellnessSessionSubTypeMaster] WHERE WellnessSessionTypeId = @rId AND IsObsolete = 0)  
    BEGIN  
     SELECT -104 AS Result -- Cannot inactive parent type without making inactive sub type  
     RETURN  
    END  
   END  
  
   UPDATE   
    [sWellness].[tWellnessSessionTypeMaster]  
   SET     
    Title=@rTitle,  
    Code=@rCode,     
    IsObsolete=@rIsObsolete,   
    UpdatedUserId=@rUpdatedUserId,  
    UpdatedDateTime=sCommon.fGetDate()  
   WHERE   
    Id = @rId  
  
   SELECT @rId AS Result  
   RETURN @rId  
   END       
 END TRY  
 BEGIN CATCH   
   SELECT -101 AS Result  
 END CATCH  
END  

GO


CREATE OR ALTER PROCEDURE[sWellness].[pConsultationAdd]  
@rId bigint,  
@rOrgId smallint,  
@rParticipantSourceTypeId smallint,  
@rParticipantSourceId bigint,  
@rSetupId bigint,  
@rMainTypeId int,  
@rConsultationDate date,  
@rDoctorFlag int = null,  
@rDoctorEmployeeId bigint  = NULL,  
@rStatusId int,  
@rStoreLocationId bigint,  
@rCauseId int = null,  
@rConsultationNotes nvarchar(2000) = '',  
@rConsultationRemarks nvarchar(2000) = '',  
@rReferredToOHCDoctorId bigint = NULL,
@rOPDId bigint = NULL,
@rConsultationTime nvarchar(50) = '',  
@rConsultationOutTime nvarchar(50) = '',  
@rOtherName nvarchar(250) = '',  
@rOtherAge tinyint,  
@rOtherMonth tinyint,  
@rOtherGenderId tinyint,  
@rEmailAddress nvarchar(100) = '',  
@rMobileNumber nvarchar(100) = null,  
@rCreatedUserId bigint,  
@rUpdatedUserId bigint = 0  
AS  
SET NOCOUNT ON  
BEGIN  
declare @trancount int;  
  
  
 BEGIN TRY    
        begin transaction  
 set @trancount = @@trancount;          
  
  declare @exceptiondetail nvarchar(max)  
  if @rCreatedUserId = 0  
  begin  
   SELECT -101 AS RESULT  
   return  
  end  
  if @rParticipantSourceId = 0  
  begin  
   SELECT -102 AS RESULT  
   return  
  end  
  if @rParticipantSourceTypeId = 0  
  begin  
   SELECT -103 AS RESULT  
   return  
  end     
      
  IF(@rDoctorEmployeeId <= 0)  
   SET @rDoctorEmployeeId = NULL  
     
  DECLARE @lNextNumber bigint,@lEmployeeDesignationId int  
  
  IF (@rId = 0)  
  BEGIN  
   INSERT INTO [sWellness].[tWellnessConsultation]   
   (  
    OrgId,ParticipantSourceTypeId,ParticipantSourceId,ConsultationDate,  
    DoctorEmployeeId,SetupId,CauseId,StatusId,StoreLocationId,ConsultationNotes,ConsultationRemarks,  
    ConsultationTime,ConsultationOutTime,CreatedUserId,CreatedDateTime,  
    UpdatedUserId,UpdatedDateTime,OtherName,Age,Months,GenderId,EmailAddress,
	MobileNumber,ReferredToOHCDoctorId,OPDId
   )  
   VALUES  
   (  
    @rOrgId,@rParticipantSourceTypeId,@rParticipantSourceId,@rConsultationDate,  
    @rDoctorEmployeeId,@rSetupId,@rCauseId,1,@rStoreLocationId,@rConsultationNotes,@rConsultationRemarks,  
    @rConsultationTime,@rConsultationOutTime,@rCreatedUserId,sCommon.fGetDate(),  
    @rUpdatedUserId,sCommon.fGetDate(),@rOtherName,@rOtherAge,@rOtherMonth,@rOtherGenderId,@rEmailAddress,
	@rMobileNumber,@rReferredToOHCDoctorId,@rOPDId
   )
     
   select @lNextNumber = SCOPE_IDENTITY()  
  
   declare @cnt bigint = 0,@prefix varchar(100),@Title varchar(100),@cn varchar(300)  
  
   select @Title = Title from sExamination.tSetupMaster where Id = @rSetupId  
  
   select @cnt = Max(Right(ISNULL(ConsultationNumber,00000),13)) from [sWellness].[tWellnessConsultation] where isnull(ConsultationNumber,'') <> ''  
   and DATEDIFF(day,CONVERT(date, CreatedDateTime, 105),CONVERT(date, sCommon.fGetDate(), 105))>=0 and SetupId = @rSetupId  
   and StoreLocationId = @rStoreLocationId  
  
   if len(@cnt)=12  
   begin  
   select @cnt = Right(isnull(@cnt,00000),4)  
   end  
   else if(len(@cnt)=13)  
   begin  
   select @cnt = Right(isnull(@cnt,00000),5)  
   end  
   else  
   begin  
   select @cnt = Right(isnull(@cnt,00000),4)  
   end  
     
   if(@cnt=9999)  
   begin  
    select @cnt = @cnt + 1 +(select count(*) from [sWellness].[tWellnessConsultation]   
    where isnull(ConsultationNumber,'') <> '' and   
    DATEDIFF(day,CONVERT(date, CreatedDateTime, 105),CONVERT(date, sCommon.fGetDate(), 105))>=0   
    and SetupId = @rSetupId and StoreLocationId = @rStoreLocationId)  
   end  
   else  
   begin  
   select @cnt = @cnt + 1  
   end  
  
   select @prefix = case when sCommon.fGetIntIdForOrg(17,@rOrgId) = @rSetupId then  
   'WC-' + sCommon.fGetFormattedDate()  + RIGHT(100000 + (@cnt) ,5) else '' end  
  
   update [sWellness].[tWellnessConsultation] set ConsultationNumber = @prefix where Id = @lNextNumber  
  END  
  ELSE  
  BEGIN  
   SET @lNextNumber = @rId  
   UPDATE [sWellness].[tWellnessConsultation] SET OrgId = @rOrgId,ParticipantSourceTypeId  = @rParticipantSourceTypeId,  
   ParticipantSourceId  = @rParticipantSourceId, ConsultationDate = @rConsultationDate,  
   DoctorEmployeeId = case when isnull(@rDoctorFlag,0) = 1 then DoctorEmployeeId else @rDoctorEmployeeId end,  
   CauseId = @rCauseId,ConsultationNotes=@rConsultationNotes,ConsultationRemarks=@rConsultationRemarks,  
   ConsultationTime=@rConsultationTime,ConsultationOutTime=@rConsultationOutTime,  
   UpdatedUserId =  case when @rUpdatedUserId>0 then @rUpdatedUserId else @rCreatedUserId end,  
   UpdatedDateTime = sCommon.fGetDate(),  
   OtherName=@rOtherName,Age=@rOtherAge,Months=@rOtherMonth,GenderId=@rOtherGenderId,  
   EmailAddress=@rEmailAddress,MobileNumber=@rMobileNumber,ReferredToOHCDoctorId=@rReferredToOHCDoctorId,
   OPDId=@rOPDId
   WHERE Id = @rId  
  END  
  SELECT @lNextNumber AS Result    
    
      commit tran;  
 END TRY  
 BEGIN CATCH  
 declare @error int, @message varchar(4000), @xstate int,@username nvarchar(200);  
  select @error = ERROR_NUMBER(),  
               @message = ERROR_MESSAGE(),   
               @xstate = XACT_STATE();  
  set @username =(select Top 1 ISNULL(LoginTitle,'') from sSecurity.tUser where id=ISNULL(CreatedUserId,0))  
  --if @xstate = -1  
  --          rollback;  
  --      if @xstate = 1 and @trancount = 0  
  --          rollback  
  --      if @xstate = 1 and @trancount > 0  
            rollback transaction;  
  
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >  
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>  
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>  
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>  
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>  
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>  
  </Table>'  
  
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)  
  Select @rOrgId,'Consultation_Main_DBError',5000,@exceptiondetail,sCommon.fGetDate(),@rCreatedUserId   
  SELECT -1 AS RESULT  
  return  
 END CATCH   
   
END  
  

  GO

  
CREATE OR ALTER PROCEDURE[sWellness].[pConsultationDashboard]
	@rStoreLocationId int,
	@rFromDate datetime = null,
	@rToDate datetime = null,
	@rCauseId int,
	@rDepartmentId int,
	@rEmployeeCode nvarchar(50)='',
	@rProgramId int = -1,
	@rDoctorId bigint,
	@rGenderId smallint,
	@rStatusId smallint,
	@rOrgId int,
	@rUserId bigint	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
	CREATE TABLE #TempTable
	(
		ConsultationId bigint,DepartmentName nvarchar(200),OrganizationDepartmentId int,
		ParticipantCode nvarchar(50),ParticipantName nvarchar(300),GenderId tinyint,
		Gender nvarchar(20),CauseId int,CauseName nvarchar(100),ParticipantType nvarchar(100),
		ParticipantSourceTypeId smallint,EMPType nvarchar(100),LoginTitle nvarchar(100),
		UserId bigint,LocationId int, DoctorId bigint, DoctorName nvarchar(300),
		ProgramId int, ProgramName nvarchar(100)
	)

	INSERT INTO #TempTable
	(
		ConsultationId,DepartmentName,OrganizationDepartmentId,ParticipantCode,ParticipantName,
		GenderId,Gender,CauseId,CauseName,ParticipantType,ParticipantSourceTypeId,EMPType,
		LoginTitle,UserId,LocationId, DoctorId, DoctorName, ProgramId, ProgramName
	)
	SELECT ED.Id as ConsultationId,
	isnull(OD.Title,'-') AS DepartmentName,
	EJD.OrganizationDepartmentId,
	CASE
	    WHEN ED.ParticipantSourceTypeId = 95 THEN EM.Code
		ELSE BM.Code
	END AS ParticipantCode,
	CASE
	    WHEN ED.ParticipantSourceTypeId = 95 THEN EM.FirstName + ' ' + isnull(EM.LastName,'')
		ELSE BM.FirstName + ' ' + isnull(BM.LastName,'')
	END AS ParticipantName,
	--ParticipantCode = EM.Code,
	--ParticipantName = EM.FirstName + ' ' + isnull(EM.LastName,''),
	--GenderId = PD.GenderId,
	--Gender = ISNULL(GM.Title,'Not Known'),
	CASE 
		WHEN ED.ParticipantSourceTypeId = 95 THEN PD.GenderId
		ELSE BM.GenderId
	END AS GenderId,
	CASE 
		WHEN ED.ParticipantSourceTypeId = 95 THEN ISNULL(GM.Title,'Not Known')
		ELSE (CASE WHEN ED.GenderId > 0 THEN (select ISNULL(Title,'Not Known') from sCommon.tGenderMaster where Id = ED.GenderId) ELSE ISNULL(GM2.Title,'Not Known') END)
	END AS Gender,
	Isnull(CM.Id,0) As CauseId,
	isnull(CM.Title,'N/A') As CauseName,
	--ISNULL(ETM.Title,'NA') AS ParticipantType,
	CASE ED.ParticipantSourceTypeId
		WHEN 95 THEN ISNULL(ETM.Title,'NA')
		WHEN 1001 THEN 'Dependent'
		WHEN 1009 THEN ISNULL(BTM.Title,'NA')
	END AS ParticipantType,
	ED.ParticipantSourceTypeId,
	CASE ED.ParticipantSourceTypeId WHEN 95 THEN 'Employee'
	WHEN 1001 THEN 'Dependent' WHEN 1009 THEN 'Other' END AS EMPType,
	U.DisplayTitle as LoginTitle,
	UL.UserId,
	ED.StoreLocationId,
	DEM.Id as DoctorId,
	DEM.FirstName + ' ' + isnull(DEM.LastName,'') as DoctorName,
	CASE 
		WHEN ED.ParticipantSourceTypeId = 95 THEN PM.Id
		ELSE PMO.Id
	END AS ProgramId,
	CASE 
		WHEN ED.ParticipantSourceTypeId = 95 THEN ISNULL(PM.Title,'Not Applicable')
		ELSE ISNULL(PMO.Title,'Not Applicable')
	END AS ProgramName
	--PM.Id as ProgramId, ISNULL(PM.Title,'Not Applicable') as ProgramName

	FROM sWellness.tWellnessConsultation ED
	LEFT JOIN sHrm.tEmployeeMaster EM on ED.ParticipantSourceId = EM.Id and ED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tCsrBenefiterMaster BM ON BM.Id = ED.ParticipantSourceId AND ED.ParticipantSourceTypeId = 1009
	LEFT JOIN sWellness.tMHIScore MS ON MS.EmployeeId = EM.Id and MS.EmployeeSourceTypeId = 95
	LEFT JOIN sWellness.tMHIScore MSO ON MS.EmployeeId = BM.Id and MS.EmployeeSourceTypeId = 1009
	LEFT JOIN sWellness.tProgramMaster PM ON PM.Id = MS.ProgramId
	LEFT JOIN sWellness.tProgramMaster PMO ON PM.Id = MSO.ProgramId
	LEFT JOIN sHrm.tEmployeeMaster DEM on DEM.Id = ED.DoctorEmployeeId
	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 sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId  
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM on ETM.Id = EJD.EmployeeTypeId
	LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM ON BM.CSRBenefiterTypeId = BTM.Id
	LEFT JOIN sCommon.tOrganizationDepartmentMaster OD on EJD.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 sWellness.tWellnessVisitPurposeMaster CM ON CM.Id = ED.CauseId
	INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = ED.StoreLocationId
	INNER JOIN sSecurity.tUser U ON U.Id = ED.CreatedUserId
	INNER JOIN sExamination.tSetupMaster SSM on ED.SetupId = SSM.Id
	INNER JOIN sExamination.tSubTypeMaster ST on SSM.SubTypeId = ST.Id
	INNER JOIN sIp.tStoreLocationMaster SLM on SLM.Id = ED.StoreLocationId
	WHERE ST.MainTypeId = 17 and isnull(IsCancel,0) = 0
	AND (
	((PM.Id = @rProgramId) OR (@rProgramId = -1) OR (@rProgramId = -2 AND ISNULL(PM.Id,0)=0) AND ED.ParticipantSourceTypeId = 95)
	OR
	((PMO.Id = @rProgramId) OR (@rProgramId = -1) OR (@rProgramId = -2 AND ISNULL(PMO.Id,0)=0) AND ED.ParticipantSourceTypeId = 1009)
	)
	AND ((ED.DoctorEmployeeId = @rDoctorId) OR (@rDoctorId = 0))
	AND ((CM.Id = @rCauseId) OR (@rCauseId = -1))
	AND ((ED.StoreLocationId = @rStoreLocationId)OR @rStoreLocationId=0)
	AND (
	@rEmployeeCode = '' OR
		(
			(ED.ParticipantSourceTypeId = 95 AND EM.Code = @rEmployeeCode)
			OR (ED.ParticipantSourceTypeId = 1009 AND BM.Code = @rEmployeeCode)
		)
	)
	AND (EJD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND
	(
		(PD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 95)
		OR (BM.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1009)
		OR @rGenderId = 0
	)
	--AND
	--(
	--	(PD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 95)
	--	OR @rGenderId = 0
	--)
	AND(EM.StatusId=@rStatusId OR @rStatusId=0)
	AND ((ED.ConsultationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((ED.ConsultationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND ED.OrgId =  @rOrgId
	--AND ED.ParticipantSourceTypeId=95
	AND UL.UserId = @rUserId



	SELECT ISnull(CauseName,'N/A') AS CauseName,
	COUNT(Isnull(CauseId,0)) AS CauseCnt
	FROM #TempTable TM
	inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id
	where L.IsActiveHealth=1
	GROUP BY CauseName
	ORDER BY CauseCnt desc

	SELECT ISnull(DoctorName,'N/A') AS DoctorName,
	COUNT(Isnull(DoctorId,0)) AS DoctorCnt
	FROM #TempTable TM
	inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id
	where L.IsActiveHealth=1
	GROUP BY DoctorName
	ORDER BY DoctorCnt desc

	SELECT Isnull(ProgramName,'') AS ProgramName,
	COUNT(Isnull(ProgramId,0)) AS ProgramCnt
	FROM #TempTable TM
	inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id
	where L.IsActiveHealth=1
	GROUP BY ProgramName
	ORDER BY ProgramCnt desc

	SELECT ISnull(DepartmentName,'') AS DepartmentName,
	COUNT(Isnull(OrganizationDepartmentId,0)) AS DepartmentCnt
	FROM #TempTable TM
	inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id
	where L.IsActiveHealth=1
	GROUP BY OrganizationDepartmentId,DepartmentName
	ORDER BY DepartmentCnt desc

	SELECT ISnull(LoginTitle,'') AS LoginTitle,
	COUNT(Isnull(UserId,0)) AS UserCnt
	FROM #TempTable TM
	inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id
	where L.IsActiveHealth=1
	GROUP BY UserId,LoginTitle
	ORDER BY UserCnt desc

	SELECT ISnull(Gender,'') AS Gender,
	COUNT(Isnull(Gender,'')) AS Gendercnt
	FROM #TempTable TM
	inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id
	where L.IsActiveHealth=1
	GROUP BY Gender
	ORDER BY Gendercnt desc

	SELECT ISnull(EMPType,'') AS EmployeeType,
	COUNT(Isnull(EMPType,'')) AS EmployeeTypecnt
	FROM #TempTable TM
	inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id
	where L.IsActiveHealth=1
	GROUP BY EMPType
	ORDER BY EMPType desc
	--select * from #TempTable
	DROP TABLE #TempTable
END


GO


CREATE OR ALTER PROCEDURE[sWellness].[pDeleteWellnessSessionSybType]  
(  
 @rId INT,  
 @rOrgId SMALLINT  
)  
AS  
BEGIN  
 SET NOCOUNT ON;  
  
    BEGIN TRY      
  DELETE FROM [sWellness].[tWellnessSessionSubTypeMaster] WHERE OrgId = @rOrgId AND Id = @rId ;  
  
        IF @@ROWCOUNT > 0  
            SELECT 1 AS Result;  -- Return 1 if deletion is successful  
        ELSE  
            SELECT 0 AS Result;  -- Return 0 if no record was found  
  
    END TRY  
    BEGIN CATCH   
        SELECT -101 AS Result;  -- Return -101 in case of an error  
    END CATCH  
END  

GO

  
CREATE OR ALTER PROCEDURE[sWellness].[pDeleteWellnessSessionType]   
(    
 @rId INT,    
 @rOrgId SMALLINT    
)    
AS    
BEGIN    
 SET NOCOUNT ON;    
    
    BEGIN TRY        
  DELETE FROM sWellness.tWellnessSessionTypeMaster  WHERE OrgId = @rOrgId AND Id = @rId ;    
    
        IF @@ROWCOUNT > 0    
            SELECT 1 AS Result;  -- Return 1 if deletion is successful    
        ELSE    
            SELECT 0 AS Result;  -- Return 0 if no record was found    
    
    END TRY    
    BEGIN CATCH     
        SELECT -101 AS Result;  -- Return -101 in case of an error    
    END CATCH    
END 

GO


CREATE OR ALTER PROCEDURE[sWellness].[pGetAllConsultationDetails]     
@rConsultationId bigint,        
@rOrgId int,        
@rStoreLocationId int        
as        
SET NOCOUNT ON        
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED        
begin    
 select EE.Id, EE.Id as ConsultationId,    
 isnull(EE.ConsultationNumber,'') as ConsultationNumber,    
 EE.ConsultationDate,    
 ParticipantName = CASE WHEN EE.ParticipantSourceTypeId = 1009 THEN CBR.FirstName + ' ' + CBR.LastName     
      ELSE EM.FirstName + ' ' + EM.LastName END,    
 ParticipantCode = CASE WHEN EE.ParticipantSourceTypeId = 1009 THEN CBR.Code ELSE EM.Code END,    
 EE.ParticipantSourceTypeId,        
 EE.ParticipantSourceId,      
 EE.SetupId,      
 EE.DoctorEmployeeId,    
 isnull(C.Id,0) as CauseId,    
 isnull(EM.StatusId,0) as EmployeeStatusId,       
 isnull(convert(varchar,EE.ConsultationDate,103),'') as ExDate,    
-- isnull(G.Title,'') AS Gender,    
 isnull(CASE 
	WHEN EE.ParticipantSourceTypeId = 1009 then G2.Title
	WHEN EE.ParticipantSourceTypeId = 1001 then ''
	ELSE G.Title
 End,'') AS Gender,
-- Age = case when EP.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EP.DateOfBirth,getdate()) end,       
Age = CASE 
        WHEN EE.ParticipantSourceTypeId = 95
             THEN CASE 
                    WHEN EP.DateOfBirth = '1900-01-01'
                         OR EP.DateOfBirth IS NULL
                    THEN 0
                    ELSE DATEDIFF(YY, EP.DateOfBirth, GETDATE())
                  END

        WHEN EE.ParticipantSourceTypeId = 1009
             THEN CASE 
                    WHEN CBR.DateOfBirth = '1900-01-01'
                         OR CBR.DateOfBirth IS NULL
                    THEN 0
                    ELSE DATEDIFF(YY, CBR.DateOfBirth, GETDATE())
                  END
        ELSE 0
      END,
 isnull(SA.Id,'') as WellnessAppointmentId,        
 isnull(convert(varchar,SA.AppointmentDate,103),'') as AppointmentDate,        
 isnull(SA.FollowupRemark,'') as FollowupRemark,    
 isnull(EE.ConsultationNotes,'') as ConsultationNotes,    
 isnull(EE.ConsultationRemarks,'') as ConsultationRemarks,      
 EM2.FirstName + ' ' + isnull(EM2.LastName,'') as DoctorName,     
 isnull(EE.ConsultationTime,'') as ConsultationTime,        
 isnull(EE.ConsultationOutTime,'') as ConsultationOutTime,    
 EJD.EmployeeLocationId as EmployeeLocationId,    
 ISNULL(EE.OtherName,'') as OtherName,  
 EE.Age as OtherAge,  
 EE.Months as OtherMonth,  
 EE.GenderId as OtherGenderId,    
 ISNULL(EE.EmailAddress,'') as EmailAddress,    
 ISNULL(EE.MobileNumber,'') as MobileNumber, ISNULL(EE.ReferredToOHCDoctorId, 0) as ReferredToOHCDoctorId, 
 ISNULL(PM.Title,'') as ProgramName,    
 EE.CreatedDateTime,  
 DATEDIFF(SECOND, EE.CreatedDateTime, GETDATE()) / 3600.0 AS TotalConsultationHours    
 from sWellness.tWellnessConsultation EE        
 left join sHrm.tEmployeeMaster EM on EE.ParticipantSourceId = EM.Id and EE.ParticipantSourceTypeId = 95    
 left join sHrm.tCsrBenefiterMaster CBR on EE.ParticipantSourceId = CBR.Id and EE.ParticipantSourceTypeId = 1009    
 LEFT JOIN sWellness.tMHIScore MS ON MS.EmployeeId = EM.Id and MS.EmployeeSourceTypeId = 95    
 LEFT JOIN sWellness.tProgramMaster PM ON PM.Id = MS.ProgramId    
 left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId    
 left join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId = EM.Id    
 left join sHrm.tEmployeePersonalDetail EP on EE.ParticipantSourceId = EP.EmployeeId and EE.ParticipantSourceTypeId = 95    
 left join sWellness.tWellnessVisitPurposeMaster C on C.Id = EE.CauseId    
 left join sHrm.tEmployeePersonalDetail PD on EE.ParticipantSourceId = PD.EmployeeId and EE.ParticipantSourceTypeId = 95    
 left join sWellness.tAppointment SA on EE.Id = SA.ReferSourceId         
 left join sHrm.tEmployeeMaster EM2 on EM2.Id = EE.DoctorEmployeeId    
 left join sCommon.tGenderMaster G ON EP.GenderId = G.Id    
 left join sCommon.tGenderMaster G2 ON CBR.GenderId = G2.Id   
 where EE.Id = @rConsultationId    
 OPTION (RECOMPILE)        
      
 select AA.AssignedActivityId as Id,     
 AA.WellnessActivityCategoryId,WAC.Title as WellnessActivityCategoryName,    
 AA.WellnessActivityId, WA.ActivityName as WellnessActivityName,    
 ISNULL(AA.WellnessActivityTaskId,0) as WellnessActivityTaskId,     
 CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN ISNULL(AA.WellnessActivityCustom,'')     
 ELSE ISNULL(WAT.[Name],'') END as WellnessActivityTask,    
 ISNULL(AA.IsCustomActivityTask,0) as IsCustomActivityTask,    
 CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN 2 ELSE 1 END AS TypeId,    
 CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN 'Custom' ELSE 'Pre Define' END AS TypeName,    
 ISNULL(AA.WellnessActivityCustom,'') as WellnessActivityCustomTask,    
 ISNULL(AA.TargetValue, 0) as TargetValue, AA.UnitId, AA.FrequencyTypeId, AA.FrequencyCount,    
 AA.WeekNo as WeekNoId,    
 CASE AA.WeekNo WHEN 1 THEN 'Week 1' WHEN 2 THEN 'Week 2' WHEN 3 THEN 'Week 3' WHEN 4 THEN 'Week 4' END AS WeekName,    
 CASE AA.UnitId WHEN 1 THEN 'Steps' WHEN 2 THEN 'Min' WHEN 3 THEN 'ML' WHEN 4 THEN 'Times' END AS UnitNo,    
 CASE AA.FrequencyTypeId WHEN 1 THEN 'Daily' WHEN 2 THEN 'Weekly' END AS FrequencyType,    
 CASE WHEN AA.WeekStart IS NULL THEN 'Assigned' WHEN GETDATE() < AA.WeekStart THEN 'Assigned'    WHEN GETDATE() BETWEEN AA.WeekStart AND AA.WeekEnd THEN 'Active'    WHEN GETDATE() > AA.WeekEnd THEN 'Expired' ELSE '-'   END AS [Status]    
 from sWellness.tAssignedActivity AA        
 INNER JOIN sWellness.tWellnessActivityCategoryMaster WAC on WAC.Id = AA.WellnessActivityCategoryId    
 INNER JOIN sWellness.tWellnessActivityMaster WA on WA.ActivityId = AA.WellnessActivityId    
 LEFT JOIN sWellness.tWellnessActivityTaskMaster WAT on WAT.Id = AA.WellnessActivityTaskId    
 where AA.ConsultationId = @rConsultationId    
 OPTION (RECOMPILE)    
    
 SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off        
end 




GO


CREATE OR ALTER PROCEDURE[sWellness].[pGetReferToCoachList]
@rStoreLocationId INT,
@rOrgId SMALLINT
AS
BEGIN
	SELECT d.EmployeeId as Id,
			ISNULL(e.EmployeePrefix + ' ', '') + e.FirstName + ' ' + e.LastName AS Title 
		FROM sCwb.tDoctorMaster d 
		INNER JOIN sHrm.tEmployeeMaster e ON d.EmployeeId = e.Id 
		INNER JOIN sCwb.tDoctorStoreLocation S ON d.EmployeeId = S.EmployeeId 
		WHERE S.SubLocationId = @rStoreLocationId AND d.OrgId = @rOrgId
			AND e.StatusId = 7 AND ISNULL(d.IsWellness,0) = 1;
END

GO


CREATE OR ALTER PROCEDURE[sWellness].[pGetWellnessAppointmentSchedulingList]          
    @rOrgId INT,         
    @rId BIGINT = 0,    
    @rEmployeeCode NVARCHAR(20) = '',          
    @rPatientName NVARCHAR(500) = '',          
    @rStoreLocationId INT = 0,          
    @rLocationId INT = 0,          
    @rSetupId INT = 0,          
    @rDoctorEmployeeId BIGINT = 0,          
    @rEmployeeStoreLocationId INT = 0,    
    @rDescription nvarchar(4000)=''    
AS          
BEGIN        
    SET @rEmployeeCode = CASE         
        WHEN CHARINDEX('*', @rEmployeeCode) > 0        
            THEN REPLACE(@rEmployeeCode, '*', '%')        
        ELSE '%' + @rEmployeeCode + '%'        
    END;        
        
    SELECT         
        A.Id,        
        A.AppointmentNumber,        
        A.PatientSourceTypeId,        
        A.PatientSourceId,        
        A.PatientName,        
        A.AppointmentDate,        
        ISNULL(A.FromTime, CONVERT(DATETIME, A.AppointmentDate)) AS FromTime,        
        ISNULL(A.ToTime, CONVERT(DATETIME, A.AppointmentDate)) AS ToTime,        
        ISNULL(A.DoctorEmployeeId, 0) AS DoctorEmployeeId,        
        A.EmployeeCode,        
        A.EmployeeId,        
        REPLACE(A.Relation, 'Ohter', 'Other') AS Relation,        
        A.Gender,        
        A.DoctorName,        
        A.OrgId,        
        A.IsRegister,        
        A.IsObsolete,        
        A.StatusName,        
        A.DepartmentName,        
        ISNULL(A.DepartmentId, 0) AS DepartmentId,        
        A.DependentId,        
        A.StoreLocationId,        
        A.SetupId,        
        A.ExaminationTypeId,        
        A.MainType,        
        A.Setup,        
        A.ReferSourceId,        
        A.LocationId,        
        ISNULL(A.CauseId, -1) AS CauseId,        
        A.StoreLocation,        
        ISNULL(A.OtherName, '') AS OtherName,        
        ISNULL(A.FollowupRemark, '') AS FollowupRemark,        
        ISNULL(A.Age,0) as Age,        
        ISNULL(A.Months,0) as Months,        
        A.GenderId,    
        A.ExaminationId,        
        A.Timeslot,    
  ISNULL(A.CompliantRemark, '') AS CompliantRemark ,  
 -- A.MobileNumber,
     A.MobileNumber 
    FROM    
  [sWellness].[vExtPatientWellnessAppointmentDetail] A    
    LEFT JOIN         
        sWellness.tWellnessConsultation E ON A.ExaminationId = E.Id        
        OR A.ReferSourceId = E.Id    
    WHERE         
        A.ApprovalStatusId = 548       
  AND A.AppointmentDate = CONVERT(DATE, sCommon.fGetDate())        
        AND (A.Id = @rId OR @rId = 0)        
        AND A.OrgId = @rOrgId        
        AND (A.PatientName LIKE @rPatientName + '%' OR A.OtherName LIKE @rPatientName + '%' OR ISNULL(@rPatientName, '') = '')        
  AND ((ISNULL(Relation, '')  Like @rDescription + '%') OR(@rDescription = ''))    
        AND (A.EmployeeCode LIKE @rEmployeeCode OR ISNULL(@rEmployeeCode, '') = '')        
        AND (A.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)        
        AND (A.LocationId = @rLocationId OR @rLocationId = 0)        
        AND (A.SetupId = @rSetupId OR @rSetupId = 0)        
        AND (A.DoctorEmployeeId = @rDoctorEmployeeId OR @rDoctorEmployeeId = 0)        
        AND ISNULL(A.ExaminationId, 0) = 0        
        AND ISNULL(E.IsCancel, 0) = 0    
 ORDER BY A.Id DESC;    
END 

go


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

    SELECT
        Id,
        Title,
        Code,
        OrgId,
        IsObsolete
    FROM [sWellness].[tWellnessSessionTypeMaster]
    WHERE OrgId = @rOrgId
      AND ISNULL(IsObsolete, 0) = 0
    ORDER BY Id DESC;

    SELECT
        Id,
        WellnessSessionTypeId,
        Title,
        Code,
        OrgId,
        IsObsolete
    FROM [sWellness].[tWellnessSessionSubTypeMaster]
    WHERE OrgId = @rOrgId
      AND ISNULL(IsObsolete, 0) = 0
    ORDER BY Id DESC;
END


GO


CREATE OR ALTER PROCEDURE[sWellness].[pGetWellnessSessionList]    
(        
    @rSessionFromDate Date = '',       
    @rSessionToDate Date = '',  
    @rSessionTitle VARCHAR(100) = '',
	@rStoreLocationId INT =0, 
    @rOrgId INT        
)        
AS        
BEGIN        
    SET NOCOUNT ON;      
      
    SELECT DISTINCT               
     P.Id AS Id,       
     P.Id AS SessionId,        
     P.Title AS Session,    
     P.Title AS SessionTitle,     
     P.ActivityDate AS SessionActivityDate,       
     P.ActivityDate AS SessionDate,          
     P.Description AS Description,         
     P.Description AS SessionDescription,       
     P.IsObsolete AS IsObsolete,         CAST(CASE WHEN ISNULL(P.IsObsolete, 0) = 0 THEN 1 ELSE 0 END AS BIT) AS IsActive,       
        -- Added in base table also      
        P.WellnessSessionTypeMasterId AS ActivityWellnessSessionTypeId,      
        P.WellnessSessionSubTypeMasterId AS ActivityWellnessSessionSubTypeId,      
      
        -- Type Master      
        PL.Id AS WellnessSessionTypeId,      
        PL.Title AS WellnessSessionType,      
        PL.Code AS WellnessSessionTypeCode,      
      
        -- Sub Type Master      
        PUL.Id AS WellnessSessionSubTypeId,      
        PUL.Title AS WellnessSessionSubType,      
        PUL.Code AS WellnessSessionSubTypeCode      
        FROM [sWellness].[tWellnessSessionActivityDetail] AS P        
      
        INNER JOIN [sWellness].[tWellnessSessionTypeMaster] AS PL        
            ON P.WellnessSessionTypeMasterId = PL.Id        
      
        INNER JOIN [sWellness].[tWellnessSessionSubTypeMaster] AS PUL      
            ON P.WellnessSessionSubTypeMasterId = PUL.Id    
			INNER JOIN [sHrm].[tEmployeeJobDetail]  AS Emp      
            ON Emp.EmployeeStoreLocationId = P.StoreLocationId   
			
    WHERE             
    P.OrgId = @rOrgId             
   -- AND (( P.ActivityDate = @rSessionFromDate) OR (ISNULL(@rSessionFromDate,'') = ''))   
 --  AND (( P.ActivityDate = @rSessionToDate) OR (ISNULL(@rSessionToDate,'') = ''))   
  
     AND ((P.ActivityDate >= @rSessionFromDate) OR (ISNULL(@rSessionFromDate,'') = ''))          
  AND ((P.ActivityDate <= @rSessionToDate) OR (ISNULL(@rSessionToDate,'') = ''))     
     AND (P.Title = @rSessionTitle OR ISNULL(@rSessionTitle, '') = '')    
	  AND (P.StoreLocationId = @rStoreLocationId OR ISNULL(@rStoreLocationId,0) = 0)    
    ORDER BY P.Id DESC;      
      
END 

Go


CREATE OR ALTER PROCEDURE[sWellness].[pGetWellnessSessionListId]  
(    
    @rId INT,    
    @rOrgId INT    
)    
AS    
BEGIN    
    SET NOCOUNT ON;  
  
    SELECT DISTINCT          
	P.Id AS Id,      
	P.Id AS SessionId,    
	P.Title AS Session, 
	P.Title AS SessionTitle,    
	P.ActivityDate AS SessionActivityDate,  
	P.ActivityDate AS SessionDate,  
	P.Description AS Description,
	P.Description AS SessionDescription,    
    P.IsObsolete AS IsObsolete,      
    CAST(CASE WHEN ISNULL(P.IsObsolete, 0) = 0 THEN 1 ELSE 0 END AS BIT) AS IsActive,   
        -- Added in base table also  
        P.WellnessSessionTypeMasterId AS ActivityWellnessSessionTypeId,  
        P.WellnessSessionSubTypeMasterId AS ActivityWellnessSessionSubTypeId,  
  
        -- Type Master  
        PL.Id AS WellnessSessionTypeId,  
        PL.Title AS WellnessSessionType,  
        PL.Code AS WellnessSessionTypeCode,  
  
        -- Sub Type Master  
        PUL.Id AS WellnessSessionSubTypeId,  
        PUL.Title AS WellnessSessionSubType,  
        PUL.Code AS WellnessSessionSubTypeCode,  
  
        -- Document  
        PUD.Id AS WellnessActivityDocumentId,    
		PUD.FileName AS FileName,        
		PUD.FilePath AS FilePath,      
		PUD.ConfigurationTypeId AS ConfigurationTypeId,     
		(             SELECT COUNT(1)     
		FROM [sWellness].[tWellnessSessionActivityDocument] AD      
		WHERE AD.WellnessSessionActivityId = P.Id     
		AND ISNULL(AD.IsObsolete, 0) = 0         ) 
		AS AttachmentCount   ,
		P.EmployeeCount  
		FROM [sWellness].[tWellnessSessionActivityDetail] AS P    
  
        LEFT JOIN [sWellness].[tWellnessSessionTypeMaster] AS PL    
            ON P.WellnessSessionTypeMasterId = PL.Id    
  
        INNER JOIN [sWellness].[tWellnessSessionSubTypeMaster] AS PUL  
            ON P.WellnessSessionSubTypeMasterId = PUL.Id  
  
        LEFT JOIN [sWellness].[tWellnessSessionActivityDocument] AS PUD  
            ON PUD.WellnessSessionActivityId = P.Id  
  
    WHERE         
	P.OrgId = @rOrgId        
	AND (@rId = 0 OR P.Id = @rId)     
    ORDER BY P.Id DESC;  
  
END 

GO

  
CREATE OR ALTER PROCEDURE[sWellness].[pGetWellnessSessionSybType]  
(  
 @rId INT,  
 @rOrgId SMALLINT  
)  
AS  
BEGIN  
 SET NOCOUNT ON;  
  
 BEGIN TRY  
  SELECT   
   PSTM.Id,  
   PSTM.WellnessSessionTypeId,  
   PSTM.Code,  
   PSTM.Title,  
   PSTM.IsObsolete     
  FROM  
   [sWellness].[tWellnessSessionSubTypeMaster] PSTM  
  WHERE  
   PSTM.OrgId = @rOrgId  
  AND  
   PSTM.Id = @rId  
 END TRY  
 BEGIN CATCH   
   SELECT -101 AS Result  
 END CATCH  
END  

GO

  
CREATE OR ALTER PROCEDURE[sWellness].[pGetWellnessSessionType]  
(  
 @rId INT,  
 @rOrgId SMALLINT  
)  
AS  
BEGIN  
 SET NOCOUNT ON;  
  
 BEGIN TRY  
  SELECT   
   PTM.Id,  
   PTM.Code,  
   PTM.Title,  
   PTM.IsObsolete     
  FROM  
  [sWellness].[tWellnessSessionTypeMaster]  PTM  
  WHERE  
   PTM.OrgId = @rOrgId  
  AND  
   PTM.Id = @rId  
 END TRY  
 BEGIN CATCH   
   SELECT -101 AS Result  
 END CATCH  
END  

Go


CREATE OR ALTER PROCEDURE[sWellness].[pIsWellnessSessionSybTypeUsed]   
(    
 @rId INT,    
 @rOrgId SMALLINT    
)    
AS    
BEGIN    
 SET NOCOUNT ON;    
    
    BEGIN TRY        
SELECT CASE 
    WHEN EXISTS (
        SELECT 1 FROM [sWellness].[tWellnessSessionActivityDetail] 
        WHERE OrgId = @rOrgId AND WellnessSessionSubTypeMasterId = @rId
    )
    OR EXISTS (
        SELECT 1 FROM [SomeOtherTable] 
        WHERE OrgId = @rOrgId AND SubTypeId = @rId
    )
    THEN 1 ELSE 0 
END AS IsUsed; 
    END TRY    
    BEGIN CATCH     
        SELECT -101 AS Result;  -- Return -101 in case of an error    
    END CATCH    
END 

GO

    
CREATE OR ALTER PROCEDURE[sWellness].[pIsWellnessSessionTypeUsed]  
(    
 @rId INT,    
 @rOrgId SMALLINT    
)    
AS    
BEGIN    
 SET NOCOUNT ON;    
    
    BEGIN TRY        
SELECT CASE 
    WHEN EXISTS (
        SELECT 1 FROM [sWellness].[tWellnessSessionSubTypeMaster] 
        WHERE OrgId = @rOrgId AND WellnessSessionTypeId = @rId
        UNION ALL
        SELECT 1 FROM [sWellness].[tWellnessSessionActivityDetail] 
        WHERE OrgId = @rOrgId AND WellnessSessionTypeMasterId = @rId
    ) THEN 1 
    ELSE 0 
END AS IsUsed; 
    END TRY    
    BEGIN CATCH     
        SELECT -101 AS Result;  -- Return -101 in case of an error    
    END CATCH    
END 

Go


CREATE OR ALTER PROCEDURE[sWellness].[pIsWellnessSessionSybTypeUsed]   
(    
 @rId INT,    
 @rOrgId SMALLINT    
)    
AS    
BEGIN    
 SET NOCOUNT ON;    
    
    BEGIN TRY        
SELECT CASE 
    WHEN EXISTS (
        SELECT 1 FROM [sWellness].[tWellnessSessionActivityDetail] 
        WHERE OrgId = @rOrgId AND WellnessSessionSubTypeMasterId = @rId
    )
    OR EXISTS (
        SELECT 1 FROM [SomeOtherTable] 
        WHERE OrgId = @rOrgId AND SubTypeId = @rId
    )
    THEN 1 ELSE 0 
END AS IsUsed; 
    END TRY    
    BEGIN CATCH     
        SELECT -101 AS Result;  -- Return -101 in case of an error    
    END CATCH    
END 

GO

    
CREATE OR ALTER PROCEDURE[sWellness].[pIsWellnessSessionTypeUsed]  
(    
 @rId INT,    
 @rOrgId SMALLINT    
)    
AS    
BEGIN    
 SET NOCOUNT ON;    
    
    BEGIN TRY        
SELECT CASE 
    WHEN EXISTS (
        SELECT 1 FROM [sWellness].[tWellnessSessionSubTypeMaster] 
        WHERE OrgId = @rOrgId AND WellnessSessionTypeId = @rId
        UNION ALL
        SELECT 1 FROM [sWellness].[tWellnessSessionActivityDetail] 
        WHERE OrgId = @rOrgId AND WellnessSessionTypeMasterId = @rId
    ) THEN 1 
    ELSE 0 
END AS IsUsed; 
    END TRY    
    BEGIN CATCH     
        SELECT -101 AS Result;  -- Return -101 in case of an error    
    END CATCH    
END 

Go

      
CREATE OR ALTER PROCEDURE[sWellness].[pListWellnessSessionSybType]      
(      
 @rType SMALLINT,      
 @rCode NVARCHAR(100) = '',      
 @rTitle NVARCHAR(100) = '',      
 @rWellnessSessionTypeId INT = 0,      
 @rOrgId SMALLINT      
)      
AS      
BEGIN      
 SET NOCOUNT ON;      
      
 -- Normalize NULL values      
 SET @rCode  = ISNULL(@rCode, '');      
 SET @rTitle = ISNULL(@rTitle, '');      
 SET @rWellnessSessionTypeId = ISNULL(@rWellnessSessionTypeId, 0);      
      
 BEGIN TRY      
  SELECT       
   PSTM.Id,      
   PSTM.WellnessSessionTypeId,      
   PTM.Title AS WellnessSessionTypeTitle,      
   PTM.Code AS WellnessSessionTypeCode,      
   PSTM.Code,      
   PSTM.Title,      
   PSTM.IsObsolete         
  FROM      
   [sWellness].[tWellnessSessionSubTypeMaster] PSTM      
  INNER JOIN      
   [sWellness].[tWellnessSessionTypeMaster] PTM      
   ON PTM.Id = PSTM.WellnessSessionTypeId      
  WHERE         
   PSTM.OrgId = @rOrgId      
  AND      
   (@rCode = '' OR PSTM.Code LIKE '%' + @rCode + '%')      
  AND      
   (@rTitle = '' OR PSTM.Title LIKE '%' + @rTitle + '%')      
  AND      
   (@rWellnessSessionTypeId = 0 OR PSTM.WellnessSessionTypeId = @rWellnessSessionTypeId)      
  AND      
   (@rType <> 1 OR PSTM.IsObsolete = 0)      
  ORDER BY      
   PSTM.Id DESC      
 END TRY      
 BEGIN CATCH       
  SELECT -101 AS Result      
 END CATCH      
END 

GO


CREATE OR ALTER PROCEDURE[sWellness].[pListWellnessSessionType] 
(  
 @rType SMALLINT,  
 @rOrgId SMALLINT,  
 @rCode NVARCHAR(100) = '',  
 @rTitle NVARCHAR(100) = ''  
)  
AS  
BEGIN  
 SET NOCOUNT ON;  
  
 BEGIN TRY  
  SELECT   
   PTM.Id,  
   PTM.Code,  
   PTM.Title,  
   PTM.IsObsolete     
  FROM  
   [sWellness].[tWellnessSessionTypeMaster] PTM  
  WHERE    
   PTM.OrgId = @rOrgId  
  
  AND (  
   @rCode IS NULL   
   OR @rCode = ''   
   OR PTM.Code LIKE '%' + @rCode + '%'  
  )  
  
  AND (  
   @rTitle IS NULL   
   OR @rTitle = ''   
   OR PTM.Title LIKE '%' + @rTitle + '%'  
  )  
  
  AND (  
   @rType <> 1   
   OR PTM.IsObsolete = 0  
  )  
  
  ORDER BY PTM.Id DESC  
 END TRY  
 BEGIN CATCH   
  SELECT -101 AS Result  
 END CATCH  
END  
  

  Go

  
CREATE OR ALTER PROCEDURE[sWellness].[pReferredConsultationSearch]
@rDoctorEmployeeId BIGINT,
@rEmployeeCode nvarchar(50),
@rEmployeeName nvarchar(200),
@rOrgId smallint,
@rStoreLocationId int
AS
BEGIN
	select WC.Id, WC.ConsultationNumber, WC.ParticipantSourceId AS EmployeeId,
	CASE WHEN WC.ParticipantSourceTypeId = 1009 THEN ISNULL(CBM.Code,'') 
		 WHEN WC.ParticipantSourceTypeId = 95 THEN ISNULL(EM.Code,'') END AS EmployeeCode,
	CASE WHEN WC.ParticipantSourceTypeId = 1009 THEN ISNULL(CBM.FirstName,'') + ' ' + ISNULL(CBM.LastName,'')
		 WHEN WC.ParticipantSourceTypeId = 95 THEN ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') 
		 END AS EmployeeName, 
	CASE WHEN WC.ParticipantSourceTypeId = 1009 THEN 'Other'
		 WHEN WC.ParticipantSourceTypeId = 95 THEN 'Employee' END AS Relation,
	ISNULL(DM.FirstName,'') + ' ' + ISNULL(DM.LastName,'') as CoachName,
	WC.ConsultationNotes, WC.ParticipantSourceTypeId, ISNULL(WC.OtherName, '') as OtherName,
	CASE WHEN WC.ParticipantSourceTypeId = 1009 THEN 
	  (CASE WHEN CBM.DateOfBirth <> '1900-01-01' and ISNULL(CBM.DateOfBirth, '') <> ''
			     THEN ISNULL(DATEDIFF(yy,CBM.DateOfBirth,sCommon.fGetDate()),0) ELSE 0 END)
    WHEN WC.ParticipantSourceTypeId = 95 THEN
	  (CASE WHEN EPD.DateOfBirth <> '1900-01-01' and ISNULL(EPD.DateOfBirth, '') <> ''
			     THEN ISNULL(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) ELSE 0 END)
	END AS Age,
	CASE WHEN WC.ParticipantSourceTypeId = 1009 THEN GCBM.Title
	     WHEN WC.ParticipantSourceTypeId = 95 THEN GEM.Title END AS Gender,
    CASE WHEN WC.ParticipantSourceTypeId = 1009 THEN WC.Age ELSE 0 END AS OtherAge,
	CASE WHEN WC.ParticipantSourceTypeId = 1009 THEN WC.Months ELSE 0 END AS OtherMonth,
	CASE WHEN WC.ParticipantSourceTypeId = 1009 THEN WC.GenderId ELSE 0 END AS OtherGenderId,
	ISNULL(WC.EmailAddress,'') as EmailAddress, ISNULL(WC.MobileNumber,'') as MobileNumber,
	MAX(CASE WHEN GTM.StaticGeneralTemplateParameterId = 502 THEN GTCD.ParameterValue END) AS Height,
	MAX(CASE WHEN GTM.StaticGeneralTemplateParameterId = 501 THEN GTCD.ParameterValue END) AS Weight,
    MAX(CASE WHEN GTM.StaticGeneralTemplateParameterId = 503 THEN GTCD.ParameterValue END) AS BMI,
    MAX(CASE WHEN GTM.StaticGeneralTemplateParameterId = 506 THEN GTCD.ParameterValue END) AS BPSys,
    MAX(CASE WHEN GTM.StaticGeneralTemplateParameterId = 507 THEN GTCD.ParameterValue END) AS BPDia
	from sWellness.tWellnessConsultation WC
	LEFT JOIN sExamination.tOPD OP ON OP.WellnessConsultationId = WC.Id
	LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = WC.ParticipantSourceId AND WC.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeePersonalDetail AS EPD ON EM.Id = EPD.EmployeeId
	LEFT JOIN sCommon.tGenderMaster GEM ON EPD.GenderId = GEM.Id
	LEFT JOIN sHrm.tCsrBenefiterMaster CBM ON CBM.Id = WC.ParticipantSourceId AND WC.ParticipantSourceTypeId = 1009
	LEFT JOIN sCommon.tGenderMaster GCBM ON CBM.GenderId = GCBM.Id
	INNER JOIN sHrm.tEmployeeMaster DM ON DM.Id = WC.DoctorEmployeeId
	LEFT JOIN sWellness.tGeneralTemplateConsultation GTC ON GTC.SourceId = WC.Id
	LEFT JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	LEFT JOIN sExamination.tGeneralTemplateParameter GTM ON GTM.Id = GTCD.GeneralTemplateParameterId
    AND GTM.StaticGeneralTemplateParameterId IN (501,502,503,506,507)
	WHERE WC.ReferredToOHCDoctorId = @rDoctorEmployeeId AND WC.OrgId = @rOrgId 
	AND WC.StoreLocationId = @rStoreLocationId AND OP.WellnessConsultationId IS NULL
	AND (EM.Code Like @rEmployeeCode or CBM.Code Like @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '' OR ISNULL(@rEmployeeCode,'') = '*')
	AND (EM.FirstName Like @rEmployeeName  + '%' or CBM.FirstName like @rEmployeeName  + '%' OR ISNULL(@rEmployeeName,'') = '' OR ISNULL(@rEmployeeName,'') = '*')
	GROUP BY WC.Id, WC.ConsultationNumber, WC.ParticipantSourceId, WC.ParticipantSourceTypeId, CBM.Code, EM.Code, CBM.FirstName, CBM.LastName,
    EM.FirstName, EM.LastName, DM.FirstName, DM.LastName, WC.ConsultationNotes, WC.OtherName, 
	EPD.DateOfBirth, CBM.DateOfBirth, GEM.Title, GCBM.Title, WC.Age, WC.Months, WC.GenderId,
	WC.EmailAddress, WC.MobileNumber
END

GO


CREATE OR ALTER PROCEDURE[sWellness].[pWellnessSessionDocumentAdd]    
(    
    @rWellnessSessionActivityId BIGINT,    
    @rFileName NVARCHAR(500),    
    @rFilePath NVARCHAR(MAX) = '',    
    @rFileSize NVARCHAR(MAX) = '',    
    @rConfigurationTypeId INT, 
	@rOrgId VARCHAR(20) = '',
    @rCreatedUserId BIGINT    
)    
AS    
BEGIN    
    SET NOCOUNT ON;    
    
    INSERT INTO [sWellness].[tWellnessSessionActivityDocument]    
    (    
        WellnessSessionActivityId,    
		OrgId,
        FileName,    
        FilePath,    
        ConfigurationTypeId,    
        IsObsolete,    
        CreatedUserId,    
        CreatedDatetime  ,  
  FileSize  
    )    
    VALUES    
    (    
        @rWellnessSessionActivityId,   
		@rOrgId,
        @rFileName,    
        @rFilePath,    
        @rConfigurationTypeId,    
        0,    
        @rCreatedUserId,    
        GETDATE()  ,  
  @rFileSize  
    );    
    
    SELECT SCOPE_IDENTITY();    
END 

GO


CREATE OR ALTER PROCEDURE[sWellness].[pWellnessSessionDocumentDelete]
(
    @rId INT,
    @rWellnessSessionActivityId BIGINT
)
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE [sWellness].[tWellnessSessionActivityDocument]
    SET IsObsolete = 1
    WHERE Id = @rId
      AND WellnessSessionActivityId = @rWellnessSessionActivityId;

    IF @@ROWCOUNT > 0
        SELECT 1;
    ELSE
        SELECT -101;
END


GO


CREATE OR ALTER PROCEDURE[sWellness].[pWellnessSessionDocumentsDelete]
(
    @rWellnessSessionActivityId BIGINT,
    @rOrgId INT,
    @rConfigId INT
)
AS
BEGIN
    SET NOCOUNT ON;

    DELETE FROM [sWellness].[tWellnessSessionActivityDocument]
    WHERE WellnessSessionActivityId = @rWellnessSessionActivityId;

    DELETE FROM [sWellness].[tWellnessSessionActivityDetail]
    WHERE Id = @rWellnessSessionActivityId;

    SELECT 1 AS Result;
END

GO


CREATE OR ALTER PROCEDURE[sWellness].[pWellnessSessionDocumentsGet]
(
    @rWellnessSessionActivityId BIGINT,
    @rOrgId INT,
    @rConfigId INT
)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        D.Id,
        D.WellnessSessionActivityId,
        @rOrgId AS OrgId,
        D.FileName,
        D.FilePath,
        D.ConfigurationTypeId AS ConfigId,
        D.ConfigurationTypeId,
        D.IsObsolete,
		D.FileSize,
		D.CreatedDatetime
    FROM [sWellness].[tWellnessSessionActivityDocument] D
    INNER JOIN [sWellness].[tWellnessSessionActivityDetail] S
        ON S.Id = D.WellnessSessionActivityId
    WHERE D.WellnessSessionActivityId = @rWellnessSessionActivityId
      AND S.OrgId = @rOrgId
      AND ISNULL(D.IsObsolete, 0) = 0
    ORDER BY D.Id DESC;
END




GO