
IF NOT EXISTS (select Id from sExamination.tSubTypeMaster where Id = 17)
BEGIN
	Insert into sExamination.tSubTypeMaster(Id,	OrgId,	MainTypeId,	Title,	IsObsolete,	CreatedUserId,	CreatedDateTime,	UpdatedUserId,	UpdatedDateTime)
	VALUES(17,	0,	17,	'WELLNESS CONSULTATION',	0,	1,	sCommon.fGetDate(),	1,	sCommon.fGetDate())
END

Go
  
CReate Or Alter PROCEDURE [sCommon].[pLoadAllSubLocationDropDownLists]  
    @rIsObsolete BIT,  
    @rUserId varchar(50),  
    @rOrgId SMALLINT  
AS  
BEGIN  
    SELECT Id, Title, LocationId  
    FROM [sIp].[tStoreLocationMaster] SLM WITH (NOLOCK)  
    INNER JOIN sSecurity.tUserLocation UL WITH (NOLOCK)  
        ON SLM.Id = UL.StoreLocationId  
    WHERE IsObsolete = @rIsObsolete  
        AND OrgId = @rOrgId  
        AND UL.UserId = @rUserId  
    ORDER BY SLM.Title  
END  

GO

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

GO

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

GO

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

GO

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

                    END
                ) = @rStatus                          -- Match against the calculated status
            )       
			AND PAL.TicketStatus = 'New'
AND DATEDIFF(HOUR, PAL.CreatedDateTime, @CurrentDateTime) < 24
       AND (@rState IS NULL OR @rState = '' OR @rState = '0' OR @rState = '- All -' OR PAL.State = @rState)             
       AND (@rBussnessid IS NULL OR @rBussnessid = '' OR @rBussnessid = '0' OR @rBussnessid = '- All -' OR SCT.id = @rBussnessid)          
 )tmp            
 ORDER BY tmp.CreatedDateTime ASC;                    
END 

GO


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


       AND PAL.TicketStatus ='Open'          
       AND (@rState IS NULL OR @rState = '' OR @rState = '0' OR @rState = '- All -' OR PAL.State = @rState)        
       AND (@rBussnessid IS NULL OR @rBussnessid = '' OR @rBussnessid = '0' OR @rBussnessid = '- All -' OR SCT.id = @rBussnessid)        
 )tmp          
 ORDER BY tmp.CreatedDateTime ASC;           
END 

GO

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

GO

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

GO

      
CReate Or Alter Procedure [sHospitalization].[pGetDoctorHospitalizationReview]      
AS      
BEGIN    
    
  Select DISTINCT EM.Id,    
  ISNULL(    
    CASE      
     WHEN ISNULL(EM.EmployeePrefix, '') = ''      
     THEN EM.FirstName + ' ' + EM.LastName      
     ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName      
    END,     
   '') AS Title      
  from [sHospitalization].[tIntimationDetails]  EH      
  INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.AssignedDoctorId      
  
    
  UNION     
    
  Select DISTINCT EM.Id,    
  ISNULL(    
    CASE      
     WHEN ISNULL(EM.EmployeePrefix, '') = ''      
     THEN EM.FirstName + ' ' + EM.LastName      
     ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName      
    END,     
   '') AS Title      
  from [sHospitalization].[tIntimationDetails]  EH    
  INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.AssignedDoctorId      
      
END

GO

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

GO

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

GO

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

GO

CReate Or Alter PROCEDURE [sHospitalization].[pHospitalizationDoctorAssignmentMailGet]          
(          
    @rOrgId INT,          
    @rTemplate NVARCHAR(MAX),          
    @rMailSubject NVARCHAR(MAX),          
    @rIntimationDetailIds NVARCHAR(MAX),          
    @rEventId INT          
)          
AS          
BEGIN          
    SET NOCOUNT ON;          
        
    SELECT DISTINCT
	  IDE.AssignedDoctorId,
        @rOrgId AS OrgGroupId,          
        95 AS SourceTypeId,          
        EC.MobileNumber AS MobileNo,          
        EC.CompanyEmail AS EmailId,        
        EM.FirstName,          
        EC.ExtensionNo,        
        
        -- 🔹 Message text with ALL replacements        
        REPLACE(        
            REPLACE(        
                REPLACE(        
                    REPLACE(        
                        REPLACE(   
                                @rTemplate,        
                                '[DoctorName]',        
                                LTRIM(RTRIM(        
                                    ISNULL(EM.FirstName, '') +        
                                    CASE WHEN ISNULL(EM.MiddleName, '') <> '' THEN ' ' + EM.MiddleName ELSE '' END +        
                                    CASE WHEN ISNULL(EM.LastName, '') <> '' THEN ' ' + EM.LastName ELSE '' END        
                                ))        
                            ),
                        '[Extension]', ISNULL(EC.ExtensionNo, '')        
                    ),        
                    '[MobileNumber]', ISNULL(EC.MobileNumber, '')        
                ),        
                '[NewAssignedCount]',        
                CAST(        
                    (        
               SELECT COUNT(1)        
                FROM sHospitalization.tIntimationDetails ID2        
                WHERE ID2.AssignedDoctorId = EM.Id        
        
                    ) AS NVARCHAR(10)        
                )        
            ),        
              '[OpenFrom]',        
             CAST(        
             (        
                SELECT COUNT(1)            
                 FROM sHospitalization.tIntimationDetails ID2             
                 WHERE ID2.AssignedDoctorId = EM.Id            
                   AND ISNULL(ID2.IsObsolete, 0) = 0            
                  AND TicketStatus IN ('Open', 'New')           
                  AND ID2.CreatedDateTime <= DATEADD(HOUR, -48, GETDATE())            
             ) AS NVARCHAR(10)        
             )        
        
        ) AS MsgText,        
        
        @rMailSubject AS Subject          
        
    FROM sHospitalization.tIntimationDetails IDE          
    LEFT JOIN sHrm.tEmployeeMaster EM          
        ON IDE.AssignedDoctorId = EM.Id          
    LEFT JOIN sHrm.tEmployeeCommunications EC          
        ON EM.Id = EC.EmployeeId      
	  WHERE (ISNULL(IDE.Id,0) IN (SELECT cast(item as Bigint) FROM  sCommon.fnsplit(ISNULL(@rIntimationDetailIds,''),',')) OR ISNULL(@rIntimationDetailIds,'')='');
  
END; 

GO

CReate Or Alter PROCEDURE [sHospitalization].[pHospitalizationDoctorMailGetAssignButton]              
(              
    @rOrgId INT,              
    @rTemplate NVARCHAR(MAX),              
    @rMailSubject NVARCHAR(MAX),              
    @rIntimationDetailIds NVARCHAR(MAX),              
    @rEventId INT              
)              
AS              
BEGIN              
    SET NOCOUNT ON;              
            
    SELECT DISTINCT    
   IDE.AssignedDoctorId,    
        @rOrgId AS OrgGroupId,              
        95 AS SourceTypeId,              
        EC.MobileNumber AS MobileNo,              
        EC.CompanyEmail AS EmailId,            
        EM.FirstName,              
        EC.ExtensionNo,            
            
        -- 🔹 Message text with ALL replacements            
        REPLACE(            
            REPLACE(            
                REPLACE(            
                    REPLACE(            
                        REPLACE(       
                                @rTemplate,            
                                '[DoctorName]',            
                                LTRIM(RTRIM(            
                                    ISNULL(EM.FirstName, '') +            
                                    CASE WHEN ISNULL(EM.MiddleName, '') <> '' THEN ' ' + EM.MiddleName ELSE '' END +            
                                    CASE WHEN ISNULL(EM.LastName, '') <> '' THEN ' ' + EM.LastName ELSE '' END            
                                ))            
                            ),    
                        '[Extension]', ISNULL(EC.ExtensionNo, '')            
                    ),            
                    '[MobileNumber]', ISNULL(EC.MobileNumber, '')            
                ),            
                '[NewAssignedCount]',            
                CAST(            
                    (            
               SELECT COUNT(1)            
                FROM sHospitalization.tIntimationDetails ID2            
                WHERE ID2.AssignedDoctorId = EM.Id and ID2.TicketStatus = 'New'    
                AND CONVERT(DATE,ID2.UpdatedDateTime,103)=CONVERT(DATE,GETDATE(),103)           
            
                    ) AS NVARCHAR(10)            
                )            
            ),            
              '[OpenFrom]',            
             CAST(            
             (            
                SELECT COUNT(1)                
                 FROM sHospitalization.tIntimationDetails ID2                 
                 WHERE ID2.AssignedDoctorId = EM.Id                
                   AND ISNULL(ID2.IsObsolete, 0) = 0                
                  AND TicketStatus IN ('Open', 'New')               
                  AND ID2.CreatedDateTime <= DATEADD(HOUR, -48, GETDATE())                
             ) AS NVARCHAR(10)            
             )            
            
        ) AS MsgText,            
            
        @rMailSubject AS Subject              
            
    FROM sHospitalization.tIntimationDetails IDE              
    LEFT JOIN sHrm.tEmployeeMaster EM              
        ON IDE.AssignedDoctorId = EM.Id              
    LEFT JOIN sHrm.tEmployeeCommunications EC              
        ON EM.Id = EC.EmployeeId          
   WHERE (ISNULL(IDE.Id,0) IN (SELECT cast(item as Bigint) FROM  sCommon.fnsplit(ISNULL(@rIntimationDetailIds,''),',')) OR ISNULL(@rIntimationDetailIds,'')='');        
            
END; 

GO

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

GO

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

GO


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

GO

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

GO

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

GO

CReate Or Alter PROCEDURE [sHospitalization].[pIntimationDetailsUpdate]    
   @rEmpCode NVARCHAR(100),    
   @TicketNumber NVARCHAR(50),    
   @AssignedDoctorId BIGINT = NULL,    
   @IntimationAssignedDoctorId INT = NULL,    
   @rOrgId INT = NULL,    
   @rCreatedUserId BIGINT = NULL  
AS  
BEGIN  
    SET NOCOUNT ON;  
  
    BEGIN TRY  
        DECLARE @CurrentDateTime DATETIME = GETUTCDATE();  
        DECLARE @IntimationDetailId BIGINT;  
        DECLARE @PreviousDoctorId BIGINT;  
        DECLARE @FinalDoctorId BIGINT;
        DECLARE @FinalIntimationDoctorId INT;
  
        -- Find the existing Intimation record  
        SELECT @IntimationDetailId = Id,  
               @PreviousDoctorId = AssignedDoctorId  
        FROM [sHospitalization].[tIntimationDetails]  
        WHERE EmpCode = @rEmpCode  
          AND TicketNumber = @TicketNumber  
          AND OrgId = @rOrgId;  
  
        IF @IntimationDetailId IS NULL  
        BEGIN  
            RAISERROR('Intimation record not found for Employee %s and Ticket %s', 16, 1, @rEmpCode, @TicketNumber);  
            RETURN;  
        END  
  
        -- Determine the doctor to assign
        IF @AssignedDoctorId IS NOT NULL AND @AssignedDoctorId > 0
        BEGIN
            -- Use provided doctor
            SET @FinalDoctorId = @AssignedDoctorId;
            SET @FinalIntimationDoctorId = @IntimationAssignedDoctorId;
        END
        ELSE
        BEGIN
            -- Need to determine doctor based on business rules
            -- This is where you'd implement the same logic as your C# code
            -- For now, let's implement a simple round-robin for central doctors
            
            DECLARE @NextDoctorId BIGINT;
            DECLARE @NextDoctorIndexId INT;
            
            -- Call a helper procedure to get the next central doctor
            EXEC sHospitalization.pGetNextCentralDoctor 
                @rOrgId,
                @NextDoctorId OUTPUT,
                @NextDoctorIndexId OUTPUT;
            
            SET @FinalDoctorId = @NextDoctorId;
            SET @FinalIntimationDoctorId = @NextDoctorIndexId;
        END
  
         IF EXISTS (
             SELECT 1
             FROM [sHospitalization].[tIntimationDetails]
             WHERE EmpCode = @rEmpCode
             AND BeneficiaryName = (
                 SELECT BeneficiaryName
                 FROM [sHospitalization].[tIntimationDetails]
                 WHERE TicketNumber = @TicketNumber
             )
         )
        BEGIN
            -- Update and set Flag = 1
            UPDATE [sHospitalization].[tIntimationDetails]
            SET  
                AssignedDoctorId = @FinalDoctorId,
                IntimationAssignedDoctorId = @FinalIntimationDoctorId,
                UpdatedUserId = @rCreatedUserId,
                UpdatedDateTime = @CurrentDateTime,
                Flag = 1
            WHERE Id = @IntimationDetailId;
        END
        ELSE
        BEGIN
            -- Update without changing Flag
            UPDATE [sHospitalization].[tIntimationDetails]
            SET  
                AssignedDoctorId = @FinalDoctorId,
                IntimationAssignedDoctorId = @FinalIntimationDoctorId,
                UpdatedUserId = @rCreatedUserId,
                UpdatedDateTime = @CurrentDateTime
            WHERE Id = @IntimationDetailId;
        END
  
        -- Always insert log if doctor was assigned  
        IF @FinalDoctorId IS NOT NULL  
        BEGIN  
            DECLARE @lAssignLogId BIGINT;  
  
            EXEC scommon.ptablerowidget   
                @rOrgId = @rOrgId,  
                @rTableTitle = 'sHospitalization.tIntimationDoctorAssignmentLog',  
                @rIsCurrentNumber = 0,  
                @rSeed = 1,  
                @rIncrement = 1,  
                @outNextNumber = @lAssignLogId OUTPUT;  
  
            -- Insert log  
            INSERT INTO [sHospitalization].[tIntimationDoctorAssignmentLog]  
            (  
                Id,   
                OrgId,   
                HospitalizationIntimationDetailId,   
                PreviousDoctorEmployeeId,   
                NewDoctorEmployeeId,  
                AssignedDate,   
                TicketNumber,   
                CreatedUserId,   
                CreatedDateTime,   
                UpdatedUserId,   
                UpdatedDateTime,   
                Status  
            )  
            VALUES  
            (  
                @lAssignLogId,   
                @rOrgId,   
                @IntimationDetailId,   
                @PreviousDoctorId,   
                @FinalDoctorId,  
                @CurrentDateTime,   
                @TicketNumber,   
                @rCreatedUserId,   
                @CurrentDateTime,   
                @rCreatedUserId,   
                @CurrentDateTime,   
                'Open'  
            );  
        END  
  
        -- Return updated record id  
        SELECT @IntimationDetailId AS updatedrecordid;  
  
    END TRY  
    BEGIN CATCH  
        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();  
        RAISERROR(@ErrorMessage, 16, 1);  
    END CATCH  
END;

GO

CReate Or Alter PROCEDURE [sHospitalization].[pMedicalReviewLogGet]        
    @rTicketNumber NVARCHAR(50)       
AS        
BEGIN        
    SET NOCOUNT ON;      
      
    ;WITH CombinedActivities AS      
    (      
        ---------------------------------------------------------      
        -- 1. Remarks      
        ---------------------------------------------------------      
        SELECT        
           -- UR.DisplayTitle AS UserName,      
           --  CASE         
          -- WHEN PAL.TicketStatus <> 'New'         
            --    THEN    
    ISNULL(UR.DisplayTitle, '')      
          -- ELSE ''        
          --END     
    AS UserName,        
            'Remark' AS ActivityType,      
            CONVERT(VARCHAR(10), R.CreatedDateTime, 103) + ' ' +      
           sCommon.fn_ConvertToIST(CONVERT(VARCHAR(8), R.CreatedDateTime, 24)) AS ActivityDateTime,      
            R.Remark AS Remark,      
            ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS AssignedDoctor,      
            R.CreatedDateTime AS SortDate,      
            'TKT-' + RIGHT(PAL.TicketNumber, 5) AS TicketNumber,      
            R.Status AS Status      
        FROM sHospitalization.tIntimationRemark R      
        Inner JOIN sHospitalization.tIntimationDetails PAL      
            ON PAL.Id = R.HospitalizationIntimationDetailId      
        Inner JOIN sSecurity.tUser UR        
            ON UR.id = R.CreatedUserId and ur.OrgId=R.OrgId      
        LEFT JOIN sHrm.tEmployeeMaster EM      
            ON EM.Id = R.DoctorEmployeeId        
        WHERE PAL.TicketNumber = @rTicketNumber      
      
      
        UNION ALL      
      
        ---------------------------------------------------------      
        -- 2. Doctor Assignment Logs      
        ---------------------------------------------------------      
        SELECT        
          --  UR.DisplayTitle AS UserName,      
          CASE         
       WHEN SM.Status = 'New'     
         AND SM.PreviousDoctorEmployeeId IS NULL    
        THEN 'System'    
  else     
  UR.DisplayTitle    
          END AS UserName,        
            'Doctor Assignment' AS ActivityType,      
            CONVERT(VARCHAR(10), SM.AssignedDate, 103) + ' ' +      
                 
   sCommon.fn_ConvertToIST(CONVERT(VARCHAR(8),  SM.AssignedDate, 24)) AS ActivityDateTime,      
            '' AS Remark,      
            ISNULL(E2.FirstName,'') + ' ' + ISNULL(E2.LastName,'') AS AssignedDoctor,      
            SM.AssignedDate AS SortDate,      
            'TKT-' + RIGHT(PAL.TicketNumber, 5) AS TicketNumber,      
            SM.Status AS Status      
        FROM sHospitalization.tIntimationDoctorAssignmentLog SM      
        INNER JOIN sHospitalization.tIntimationDetails PAL      
            ON PAL.Id = SM.HospitalizationIntimationDetailId      
        LEFT JOIN sSecurity.tUser UR        
            ON UR.Id = SM.CreatedUserId and UR.OrgId=SM.OrgId      
        LEFT JOIN sHrm.tEmployeeMaster E2      
            ON E2.Id = SM.NewDoctorEmployeeId      
        WHERE PAL.TicketNumber = @rTicketNumber      
    )      
      
    SELECT       
        UserName,      
        ActivityType,      
        ActivityDateTime,      
        Remark,      
        AssignedDoctor,      
        SortDate,      
        TicketNumber,      
        Status      
    FROM CombinedActivities      
    ORDER BY SortDate ASC;      
END      

GO

CReate Or Alter PROCEDURE [sHospitalization].[pSubmitRemark]
(
    @rHospitalizationIntimationDetailId BIGINT = 0,
    @rCreatedDateTime DATETIME,
    @rRemark NVARCHAR(MAX),
    @rDoctorEmployeeId BIGINT = 0,
	@rCreatedUserId BIGINT = 0,
    @rOrgId INT,
    @rStatus NVARCHAR(500) = NULL  
)
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY
        BEGIN TRANSACTION;

        DECLARE @lNextNumber BIGINT;

        -------------------------------------------------------------
        -- Generate Unique ID for Remark Entry
        -------------------------------------------------------------
        EXEC sCommon.pTableRowIdGet 
            @rOrgId,
            'sHospitalization.tIntimationRemark',
            0, 1, 1,
            @outNextNumber = @lNextNumber OUTPUT;

        -------------------------------------------------------------
        -- Insert Remark Record
        -------------------------------------------------------------
        INSERT INTO sHospitalization.tIntimationRemark
        (
            Id,
            OrgId,
            HospitalizationIntimationDetailId,
            DoctorEmployeeId,
            Remark,
            CreatedUserId,
            CreatedDateTime,
            UpdatedUserId,
            UpdatedDateTime,
			Status
        )
        VALUES
        (
            @lNextNumber,
            @rOrgId,
            @rHospitalizationIntimationDetailId,
            @rDoctorEmployeeId,
            @rRemark,
            @rCreatedUserId,         
            GETUTCDATE(),
            @rCreatedUserId,
            GETUTCDATE(),
			@rStatus
        );

        -------------------------------------------------------------
        -- Update Intimation Details Table (Doctor & Status)
        -------------------------------------------------------------
        UPDATE D
        SET 
            D.TicketStatus = LTRIM(RTRIM(ISNULL(@rStatus, D.TicketStatus))),
            D.UpdatedUserId = @rCreatedUserId,
            D.UpdatedDateTime = sCommon.fGetDate()
        FROM sHospitalization.tIntimationDetails D
        WHERE D.Id = @rHospitalizationIntimationDetailId
          AND D.OrgId = @rOrgId;

        -------------------------------------------------------------
        -- Insert into Doctor Assignment Log (NEW)
        -------------------------------------------------------------

   --     DECLARE @logId BIGINT;
   --     EXEC sCommon.pTableRowIdGet 
   --         @rOrgId,
   --         'sHospitalization.tIntimationDoctorAssignmentLog',
   --         0, 1, 1,
   --         @outNextNumber = @logId OUTPUT;

   --     INSERT INTO sHospitalization.tIntimationDoctorAssignmentLog
   --     (
   --         Id,
   --         OrgId,
   --         HospitalizationIntimationDetailId,
   --         PreviousDoctorEmployeeId,
   --         NewDoctorEmployeeId,
   --         AssignedDate,
   --         TicketNumber,
   --         CreatedUserId,
   --         CreatedDateTime,
   --         UpdatedUserId,
   --         UpdatedDateTime,
			--Status
   --     )
   --     SELECT 
   --         @logId,
   --         @rOrgId,
   --         D.Id,
   --         D.AssignedDoctorId,
   --         @rDoctorEmployeeId,
   --         sCommon.fGetDate(),
   --         D.TicketNumber,
   --         @rCreatedUserId,
   --         sCommon.fGetDate(),
   --         @rCreatedUserId,
   --         sCommon.fGetDate(),
			--@rStatus
   --     FROM sHospitalization.tIntimationDetails D
   --     WHERE D.Id = @rHospitalizationIntimationDetailId
   --       AND D.OrgId = @rOrgId;

        -------------------------------------------------------------
        -- Commit and Return Success
        -------------------------------------------------------------
        COMMIT TRANSACTION;

        SELECT 
            1 AS Status,
            'Remarks Saved' AS Message,
            @lNextNumber AS InsertedId;
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

        SELECT 
            0 AS Status,
            'An unexpected error occurred: ' + ERROR_MESSAGE() AS Message,
            ERROR_NUMBER() AS ErrorNumber,
            ERROR_LINE() AS ErrorLine;
    END CATCH
END;

GO

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

GO

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

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

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

    
            UPDATE sHospitalization.tClaimIntimationAssignedDoctor        
            SET        
                BusinessId              = @rBusinessId,    
                SubBusinessId           = @rSubBusinessId,    
                LocationId              = @rLocationId,    
                SubLocationId           = @rSubLocationId,    
                StateId                 = @rStateId,    
                OrganizationId          = @rOrganizationId,    
                DoctorEmployeeId        = @rDoctorEmployeeId,    
                AssignDesignationId     = @rDesignationId,
                AssignDesignationName   = @lDesignationName,
                IsObsolete              = @rIsObsolete,    
                UpdatedUserId           = @rUpdatedUserId,    
                UpdatedDateTime         = sCommon.fGetDate()    
            WHERE Id = @rId;        
        
            SELECT @rId AS RESULT, 
                   @rDesignationId AS AssignDesignationId,
                   @lDesignationName AS AssignDesignationName; 
        END        
    
    END TRY        
    BEGIN CATCH        
         SELECT         
            -1 AS RESULT,        
            ERROR_NUMBER() AS ErrorNumber,        
            ERROR_SEVERITY() AS ErrorSeverity,        
            ERROR_STATE() AS ErrorState,        
            ERROR_LINE() AS ErrorLine,        
            ERROR_MESSAGE() AS ErrorMessage;        
    END CATCH        
END;

GO

CReate Or Alter VIEW [sHospitalization].[vIntimationAssignedDoctor]
AS
WITH ConfigCheck AS (
    SELECT 
        CASE 
            WHEN EXISTS (
                SELECT 1 
                FROM [sConfig].[tConfigurationMaster] 
                WHERE ItemKey = 'ClaimIntimation.HospitalizationAssignDoctorMaster'
                AND ItemValue = 'True'
                AND IsObsolete = 0
            ) THEN 1  -- Use New table
            ELSE 0   -- Use Old table
        END AS UseNewTable
)
SELECT 
    Id,
    OrgId,
    BusinessId,
    SubBusinessId,
    LocationId,
    SubLocationId,
    StateId,
    OrganizationId,
    DoctorEmployeeId,
    AssignDesignationId,
    AssignDoctorIndex,
    IsObsolete,
    CreatedUserId,
    CreatedDateTime,
    UpdatedUserId,
    UpdatedDateTime,
    AssignDesignationName,
    -- Additional columns with NULL for old table compatibility
    NULL AS AssignTypeId,
    NULL AS AssignSubTypeId,
    NULL AS DesignationId
FROM (
    -- New table data (when config is True)
    SELECT 
        Id,
        OrgId,
        BusinessId,
        SubBusinessId,
        LocationId,
        SubLocationId,
        StateId,
        OrganizationId,
        DoctorEmployeeId,
        AssignDesignationId,
        AssignDoctorIndex,
        IsObsolete,
        CreatedUserId,
        CreatedDateTime,
        UpdatedUserId,
        UpdatedDateTime,
        AssignDesignationName,
        1 AS TableType  -- 1 for New table
    FROM [sHospitalization].[tClaimIntimationAssignedDoctor]
    WHERE IsObsolete = 0
    
    UNION ALL
    
    -- Old table data (when config is False)
    SELECT 
        Id,
        OrgId,
        NULL AS BusinessId,  -- Old table doesn't have this
        NULL AS SubBusinessId,
        NULL AS LocationId,
        NULL AS SubLocationId,
        NULL AS StateId,
        NULL AS OrganizationId,
        DoctorEmployeeId,
        DesignationId AS AssignDesignationId,
        NULL AS AssignDoctorIndex,
        IsObsolete,
        CreatedUserId,
        CreatedDateTime,
        UpdatedUserId,
        UpdatedDateTime,
        NULL AS AssignDesignationName,
        0 AS TableType  -- 0 for Old table
    FROM [sHospitalization].[tIntimationAssignedDoctor]
    WHERE IsObsolete = 0
) AS AllData
CROSS JOIN ConfigCheck
WHERE (
    (ConfigCheck.UseNewTable = 1 AND TableType = 1)  -- Config True: Show only New table data
    OR 
    (ConfigCheck.UseNewTable = 0 AND TableType = 0)  -- Config False: Show only Old table data
);

GO

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

GO

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

GO

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

GO

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

GO

alter PROCEDURE [sHospitalization].[pIntimationDetailsUpdate]    
   @rEmpCode NVARCHAR(100),    
   @TicketNumber NVARCHAR(50),    
   @AssignedDoctorId BIGINT = NULL,    
   @IntimationAssignedDoctorId INT = NULL,    
   @rOrgId INT = NULL,    
   @rCreatedUserId BIGINT = NULL  
AS  
BEGIN  
    SET NOCOUNT ON;  
  
    BEGIN TRY  
        DECLARE @CurrentDateTime DATETIME = GETUTCDATE();  
        DECLARE @IntimationDetailId BIGINT;  
        DECLARE @PreviousDoctorId BIGINT;  
        DECLARE @FinalDoctorId BIGINT;
        DECLARE @FinalIntimationDoctorId INT;
  
        -- Find the existing Intimation record  
        SELECT @IntimationDetailId = Id,  
               @PreviousDoctorId = AssignedDoctorId  
        FROM [sHospitalization].[tIntimationDetails]  
        WHERE EmpCode = @rEmpCode  
          AND TicketNumber = @TicketNumber  
          AND OrgId = @rOrgId;  
  
        IF @IntimationDetailId IS NULL  
        BEGIN  
            RAISERROR('Intimation record not found for Employee %s and Ticket %s', 16, 1, @rEmpCode, @TicketNumber);  
            RETURN;  
        END  
  
        -- Determine the doctor to assign
        IF @AssignedDoctorId IS NOT NULL AND @AssignedDoctorId > 0
        BEGIN
            -- Use provided doctor
            SET @FinalDoctorId = @AssignedDoctorId;
            SET @FinalIntimationDoctorId = @IntimationAssignedDoctorId;
        END
        ELSE
        BEGIN
            -- Need to determine doctor based on business rules
            -- This is where you'd implement the same logic as your C# code
            -- For now, let's implement a simple round-robin for central doctors
            
            DECLARE @NextDoctorId BIGINT;
            DECLARE @NextDoctorIndexId INT;
            
            -- Call a helper procedure to get the next central doctor
            EXEC sHospitalization.pGetNextCentralDoctor 
                @rOrgId,
                @NextDoctorId OUTPUT,
                @NextDoctorIndexId OUTPUT;
            
            SET @FinalDoctorId = @NextDoctorId;
            SET @FinalIntimationDoctorId = @NextDoctorIndexId;
        END
  
         IF EXISTS (
             SELECT 1
             FROM [sHospitalization].[tIntimationDetails]
             WHERE EmpCode = @rEmpCode
             AND BeneficiaryName = (
                 SELECT BeneficiaryName
                 FROM [sHospitalization].[tIntimationDetails]
                 WHERE TicketNumber = @TicketNumber
             )
         )
        BEGIN
            -- Update and set Flag = 1
            UPDATE [sHospitalization].[tIntimationDetails]
            SET  
                AssignedDoctorId = @FinalDoctorId,
                IntimationAssignedDoctorId = @FinalIntimationDoctorId,
                UpdatedUserId = @rCreatedUserId,
                UpdatedDateTime = @CurrentDateTime,
                Flag = 1
            WHERE Id = @IntimationDetailId;
        END
        ELSE
        BEGIN
            -- Update without changing Flag
            UPDATE [sHospitalization].[tIntimationDetails]
            SET  
                AssignedDoctorId = @FinalDoctorId,
                IntimationAssignedDoctorId = @FinalIntimationDoctorId,
                UpdatedUserId = @rCreatedUserId,
                UpdatedDateTime = @CurrentDateTime
            WHERE Id = @IntimationDetailId;
        END
  
        -- Always insert log if doctor was assigned  
        IF @FinalDoctorId IS NOT NULL  
        BEGIN  
            DECLARE @lAssignLogId BIGINT;  
  
            EXEC scommon.ptablerowidget   
                @rOrgId = @rOrgId,  
                @rTableTitle = 'sHospitalization.tIntimationDoctorAssignmentLog',  
                @rIsCurrentNumber = 0,  
                @rSeed = 1,  
                @rIncrement = 1,  
                @outNextNumber = @lAssignLogId OUTPUT;  
  
            -- Insert log  
            INSERT INTO [sHospitalization].[tIntimationDoctorAssignmentLog]  
            (  
                Id,   
                OrgId,   
                HospitalizationIntimationDetailId,   
                PreviousDoctorEmployeeId,   
                NewDoctorEmployeeId,  
                AssignedDate,   
                TicketNumber,   
                CreatedUserId,   
                CreatedDateTime,   
                UpdatedUserId,   
                UpdatedDateTime,   
                Status  
            )  
            VALUES  
            (  
                @lAssignLogId,   
                @rOrgId,   
                @IntimationDetailId,   
                @PreviousDoctorId,   
                @FinalDoctorId,  
                @CurrentDateTime,   
                @TicketNumber,   
                @rCreatedUserId,   
                @CurrentDateTime,   
                @rCreatedUserId,   
                @CurrentDateTime,   
                'Open'  
            );  
        END  
  
        -- Return updated record id  
        SELECT @IntimationDetailId AS updatedrecordid;  
  
    END TRY  
    BEGIN CATCH  
        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();  
        RAISERROR(@ErrorMessage, 16, 1);  
    END CATCH  
END;

GO

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

GO

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

GO

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

GO

alter PROCEDURE [sHospitalization].[pHospitalizationDoctorAssignmentMailGet]            
(            
    @rOrgId INT,            
    @rTemplate NVARCHAR(MAX),            
    @rMailSubject NVARCHAR(MAX),            
    @rIntimationDetailIds NVARCHAR(MAX),            
    @rEventId INT            
)            
AS            
BEGIN            
    SET NOCOUNT ON;            
          
    SELECT DISTINCT  
   IDE.AssignedDoctorId,  
        @rOrgId AS OrgGroupId,            
        95 AS SourceTypeId,            
        EC.MobileNumber AS MobileNo,            
        EC.CompanyEmail AS EmailId,          
        EM.FirstName,            
        EC.ExtensionNo,          
          
        -- 🔹 Message text with ALL replacements          
        REPLACE(          
            REPLACE(          
                REPLACE(          
                    REPLACE(          
                        REPLACE(     
                                @rTemplate,          
                                '[DoctorName]',          
                                LTRIM(RTRIM(          
                                    ISNULL(EM.FirstName, '') +          
                                    CASE WHEN ISNULL(EM.MiddleName, '') <> '' THEN ' ' + EM.MiddleName ELSE '' END +          
                                    CASE WHEN ISNULL(EM.LastName, '') <> '' THEN ' ' + EM.LastName ELSE '' END          
                                ))          
                            ),  
                        '[Extension]', ISNULL(EC.ExtensionNo, '')          
                    ),          
                    '[MobileNumber]', ISNULL(EC.MobileNumber, '')          
                ),          
                '[NewAssignedCount]',          
                CAST(          
                    (          
               SELECT COUNT(1)          
                FROM sHospitalization.tIntimationDetails ID2          
                WHERE ID2.AssignedDoctorId = EM.Id  and ID2.TicketStatus = 'New'  
    AND CONVERT(DATE,ID2.CreatedDateTime,103)=CONVERT(DATE,GETDATE(),103)        
          
                    ) AS NVARCHAR(10)          
                )          
            ),          
              '[OpenFrom]',          
             CAST(          
             (          
                SELECT COUNT(1)              
                 FROM sHospitalization.tIntimationDetails ID2               
                 WHERE ID2.AssignedDoctorId = EM.Id              
                   AND ISNULL(ID2.IsObsolete, 0) = 0              
                  AND TicketStatus IN ('Open', 'New')             
                  AND ID2.CreatedDateTime <= DATEADD(HOUR, -48, GETDATE())              
             ) AS NVARCHAR(10)          
             )          
          
        ) AS MsgText,          
          
        @rMailSubject AS Subject            
          
    FROM sHospitalization.tIntimationDetails IDE            
    LEFT JOIN sHrm.tEmployeeMaster EM            
        ON IDE.AssignedDoctorId = EM.Id            
    LEFT JOIN sHrm.tEmployeeCommunications EC            
        ON EM.Id = EC.EmployeeId        
   WHERE (ISNULL(IDE.Id,0) IN (SELECT cast(item as Bigint) FROM  sCommon.fnsplit(ISNULL(@rIntimationDetailIds,''),',')) OR ISNULL(@rIntimationDetailIds,'')='');  
            
END; 

GO

alter PROCEDURE [sHospitalization].[pHospitalizationDoctorMailGetAssignButton]                
(                
    @rOrgId INT,                
    @rTemplate NVARCHAR(MAX),                
    @rMailSubject NVARCHAR(MAX),                
    @rIntimationDetailIds NVARCHAR(MAX),                
    @rEventId INT                
)                
AS                
BEGIN                
    SET NOCOUNT ON;                
              
    SELECT DISTINCT      
   IDE.AssignedDoctorId,      
        @rOrgId AS OrgGroupId,                
        95 AS SourceTypeId,                
        EC.MobileNumber AS MobileNo,                
        EC.CompanyEmail AS EmailId,              
        EM.FirstName,                
        EC.ExtensionNo,              
              
        -- 🔹 Message text with ALL replacements              
        REPLACE(              
            REPLACE(              
                REPLACE(              
                    REPLACE(              
                        REPLACE(         
                                @rTemplate,              
                                '[DoctorName]',              
                                LTRIM(RTRIM(              
                                    ISNULL(EM.FirstName, '') +              
                                    CASE WHEN ISNULL(EM.MiddleName, '') <> '' THEN ' ' + EM.MiddleName ELSE '' END +              
                                    CASE WHEN ISNULL(EM.LastName, '') <> '' THEN ' ' + EM.LastName ELSE '' END              
                                ))              
                            ),      
                        '[Extension]', ISNULL(EC.ExtensionNo, '')              
                    ),              
                    '[MobileNumber]', ISNULL(EC.MobileNumber, '')              
                ),              
      '[NewAssignedCount]',
CAST(
(
    SELECT COUNT(1)
    FROM sHospitalization.tIntimationDetails ID2
    WHERE ID2.AssignedDoctorId = EM.Id 
    AND ID2.TicketStatus = 'New'
    AND ID2.Id IN (
        SELECT CAST(item AS BIGINT)
        FROM sCommon.fnsplit(ISNULL(@rIntimationDetailIds,''),',')
    )
) AS NVARCHAR(10))      
            ),              
              '[OpenFrom]',              
             CAST(              
             (              
                SELECT COUNT(1)                  
                 FROM sHospitalization.tIntimationDetails ID2                   
                 WHERE ID2.AssignedDoctorId = EM.Id                  
                   AND ISNULL(ID2.IsObsolete, 0) = 0                  
                  AND TicketStatus IN ('Open', 'New')                 
                  AND ID2.CreatedDateTime <= DATEADD(HOUR, -48, GETDATE())                  
             ) AS NVARCHAR(10)              
             )              
              
        ) AS MsgText,              
              
        @rMailSubject AS Subject                
              
    FROM sHospitalization.tIntimationDetails IDE                
    LEFT JOIN sHrm.tEmployeeMaster EM                
        ON IDE.AssignedDoctorId = EM.Id                
    LEFT JOIN sHrm.tEmployeeCommunications EC                
        ON EM.Id = EC.EmployeeId            
   WHERE (ISNULL(IDE.Id,0) IN (SELECT cast(item as Bigint) FROM  sCommon.fnsplit(ISNULL(@rIntimationDetailIds,''),',')) OR ISNULL(@rIntimationDetailIds,'')='');          
              
END; 

GO

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

GO

-- Add new column to store unattended date
ALTER TABLE sHospitalization.tIntimationDetails
ADD UnattendedDate DATETIME NULL;

GO

-- Update UnattendedDate for existing records that are unattended (New and older than 24 hours)
UPDATE sHospitalization.tIntimationDetails
SET UnattendedDate = CreatedDateTime

GO

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

GO

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

GO

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

GO

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

GO

        
ALTER PROCEDURE [sHospitalization].[pHospitalizationReferDoctor]        
(        
    @rDoctorId       BIGINT,        
    @rStatusId       INT,        
    @rstrXML         NVARCHAR(MAX),        
    @rCreatedUserId  BIGINT,        
    @runattendatedDate NVARCHAR(50) = NULL,        
    @rOrgId          INT        
)        
AS        
BEGIN        
    SET NOCOUNT ON;        
        
    BEGIN TRY        
        BEGIN TRANSACTION;        
        
        DECLARE @xml XML = TRY_CAST(@rstrXML AS XML);        
        
        IF @xml IS NULL        
        BEGIN        
            RAISERROR('Invalid XML format.', 16, 1);        
            ROLLBACK TRANSACTION;        
            RETURN;        
        END;        
        
        -------------------------------------------------------------        
        -- PARSE XML (REMOVE DUPLICATES)        
        -------------------------------------------------------------        
        DECLARE @Parsed TABLE        
        (        
            HospitalizationIntimationDetailId BIGINT PRIMARY KEY,        
            DoctorEmployeeId BIGINT,        
            StatusText NVARCHAR(50)        
        );        
        
        INSERT INTO @Parsed        
        SELECT DISTINCT        
            X.value('@IntimationDetailid', 'BIGINT'),        
            @rDoctorId,        
            CASE         
                WHEN @rStatusId = 1 THEN 'New'        
                WHEN @rStatusId = 2 THEN 'Open'        
                WHEN @rStatusId = 3 THEN 'Close'        
                ELSE 'Unknown'        
            END        
        FROM @xml.nodes('/StatusChange/StatusData') AS T(X)        
        WHERE X.value('@IntimationDetailid', 'BIGINT') IS NOT NULL;        
        
        
        -------------------------------------------------------------        
        -- UPDATE MAIN TABLE (tIntimationDetails)        
        -------------------------------------------------------------        
        UPDATE D        
        SET         
            D.AssignedDoctorId = P.DoctorEmployeeId,        
            D.TicketStatus = P.StatusText,        
            D.TicketOpenDate = sCommon.fGetDate(),        
            D.UpdatedUserId = @rCreatedUserId,        
            D.UpdatedDateTime = sCommon.fGetDate() ,     
   D.UnattendedDate =sCommon.fGetDate()   
        FROM sHospitalization.tIntimationDetails D        
        INNER JOIN @Parsed P         
            ON D.Id = P.HospitalizationIntimationDetailId        
        WHERE D.OrgId = @rOrgId;        
        
        
        -------------------------------------------------------------        
        -- INSERT LOGS INTO tIntimationDoctorAssignmentLog        
        -------------------------------------------------------------        
        DECLARE @Log TABLE        
        (        
            Id BIGINT,        
            OrgId INT,        
            HospitalizationIntimationDetailId BIGINT,        
            PreviousDoctorEmployeeId BIGINT,        
            NewDoctorEmployeeId BIGINT,        
            AssignedDate DATETIME,        
            TicketNumber NVARCHAR(50),        
            CreatedUserId BIGINT,        
            CreatedDateTime DATETIME,        
            UpdatedUserId BIGINT,        
            UpdatedDateTime DATETIME,        
            Status NVARCHAR(50)        
        );        
        
        INSERT INTO @Log        
        SELECT         
            NULL,        
            @rOrgId,        
            P.HospitalizationIntimationDetailId,        
            D.AssignedDoctorId,        
            P.DoctorEmployeeId,        
            sCommon.fGetDate(),        
            D.TicketNumber,        
            @rCreatedUserId,        
            sCommon.fGetDate(),        
            @rCreatedUserId,        
            sCommon.fGetDate(),        
            P.StatusText        
        FROM @Parsed P        
        INNER JOIN sHospitalization.tIntimationDetails D         
            ON D.Id = P.HospitalizationIntimationDetailId    
        WHERE D.OrgId = @rOrgId;        
        
        -- Assign unique IDs        
        DECLARE @DetailId BIGINT, @NextId BIGINT;        
        DECLARE cur CURSOR FOR SELECT HospitalizationIntimationDetailId FROM @Log;        
        OPEN cur;     
        FETCH NEXT FROM cur INTO @DetailId;        
        WHILE @@FETCH_STATUS = 0        
        BEGIN        
            EXEC sCommon.pTableRowIdGet         
                 @rOrgId,        
                 'sHospitalization.tIntimationDoctorAssignmentLog',        
                 0, 1, 1,        
                 @outNextNumber = @NextId OUTPUT;        
        
            UPDATE @Log        
            SET Id = @NextId        
            WHERE HospitalizationIntimationDetailId = @DetailId;        
        
            FETCH NEXT FROM cur INTO @DetailId;        
        END;        
        CLOSE cur;        
        DEALLOCATE cur;        
        
        -- Insert into log table        
        INSERT INTO sHospitalization.tIntimationDoctorAssignmentLog        
        (        
            Id, OrgId, HospitalizationIntimationDetailId,        
            PreviousDoctorEmployeeId, NewDoctorEmployeeId,        
            AssignedDate, TicketNumber,        
            CreatedUserId, CreatedDateTime,        
            UpdatedUserId, UpdatedDateTime,        
            Status        
        )        
        SELECT * FROM @Log;        
        
        
        ---------------------------------------------------------------        
        ---- INSERT NULL REMARKS INTO tIntimationRemark        
        ---------------------------------------------------------------        
        --INSERT INTO sHospitalization.tIntimationRemark        
        --(        
        --    HospitalizationIntimationDetailId,        
        --    Remark,        
        --    CreatedUserId,        
        --    CreatedDateTime,        
        --    UpdatedUserId,        
        --    UpdatedDateTime        
        --)        
        --SELECT        
        --    HospitalizationIntimationDetailId,        
        --    NULL,  -- NULL remark        
        --    @rCreatedUserId,        
        --    sCommon.fGetDate(),        
        --    @rCreatedUserId,        
        --    sCommon.fGetDate()        
        --FROM @Parsed;        
        
        
        -------------------------------------------------------------        
        COMMIT TRANSACTION;        
        
        SELECT 1 AS Result, 'Updated, log & null remarks inserted successfully.' AS Message;        
        
    END TRY        
    BEGIN CATCH        
        IF @@TRANCOUNT > 0        
           ROLLBACK TRANSACTION;        
        
        SELECT         
            -1 AS Result,        
            ERROR_MESSAGE() AS ErrorMessage;        
    END CATCH        
END; 

GO

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

                    END
                ) = @rStatus                          -- Match against the calculated status
            )       
			AND PAL.TicketStatus = 'New'
AND DATEDIFF(HOUR, PAL.CreatedDateTime, @CurrentDateTime) < 24
       AND (@rState IS NULL OR @rState = '' OR @rState = '0' OR @rState = '- All -' OR PAL.State = @rState)             
       AND (@rBussnessid IS NULL OR @rBussnessid = '' OR @rBussnessid = '0' OR @rBussnessid = '- All -' OR SCT.id = @rBussnessid)          
 )tmp            
 ORDER BY tmp.CreatedDateTime ASC;                    
END 

GO

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

GO

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

GO

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

GO

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

GO

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

GO

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

GO

alter PROCEDURE [sHospitalization].[pHospitalizationDoctorAssignmentMailGet]            
(            
    @rOrgId INT,            
    @rTemplate NVARCHAR(MAX),            
    @rMailSubject NVARCHAR(MAX),            
    @rIntimationDetailIds NVARCHAR(MAX),            
    @rEventId INT            
)            
AS            
BEGIN            
    SET NOCOUNT ON;            
          
    SELECT DISTINCT  
   IDE.AssignedDoctorId,  
        @rOrgId AS OrgGroupId,            
        95 AS SourceTypeId,            
        EC.MobileNumber AS MobileNo,            
        EC.CompanyEmail AS EmailId,          
        EM.FirstName,            
        EC.ExtensionNo,          
          
        -- 🔹 Message text with ALL replacements          
        REPLACE(          
            REPLACE(          
                REPLACE(          
                    REPLACE(          
                        REPLACE(     
                                @rTemplate,          
                                '[DoctorName]',          
                                LTRIM(RTRIM(          
                                    ISNULL(EM.FirstName, '') +          
                                    CASE WHEN ISNULL(EM.MiddleName, '') <> '' THEN ' ' + EM.MiddleName ELSE '' END +          
                                    CASE WHEN ISNULL(EM.LastName, '') <> '' THEN ' ' + EM.LastName ELSE '' END          
                                ))          
                            ),  
                        '[Extension]', ISNULL(EC.ExtensionNo, '')          
                    ),          
                    '[MobileNumber]', ISNULL(EC.MobileNumber, '')          
                ),          
                '[NewAssignedCount]',          
                CAST(          
                    (          
               SELECT COUNT(1)          
                FROM sHospitalization.tIntimationDetails ID2          
                WHERE ID2.AssignedDoctorId = EM.Id  and ID2.TicketStatus = 'New'  
    AND CONVERT(DATE,ID2.UnattendedDate,103)=CONVERT(DATE,GETDATE(),103)        
          
                    ) AS NVARCHAR(10)          
                )          
            ),          
              '[OpenFrom]',          
             CAST(          
             (          
                SELECT COUNT(1)              
                 FROM sHospitalization.tIntimationDetails ID2               
                 WHERE ID2.AssignedDoctorId = EM.Id              
                   AND ISNULL(ID2.IsObsolete, 0) = 0              
                  AND TicketStatus IN ('Open', 'New')             
                  AND ID2.UnattendedDate <= DATEADD(HOUR, -48, GETDATE())              
             ) AS NVARCHAR(10)          
             )          
          
        ) AS MsgText,          
          
        @rMailSubject AS Subject            
          
    FROM sHospitalization.tIntimationDetails IDE            
    LEFT JOIN sHrm.tEmployeeMaster EM            
        ON IDE.AssignedDoctorId = EM.Id            
    LEFT JOIN sHrm.tEmployeeCommunications EC            
        ON EM.Id = EC.EmployeeId        
   WHERE (ISNULL(IDE.Id,0) IN (SELECT cast(item as Bigint) FROM  sCommon.fnsplit(ISNULL(@rIntimationDetailIds,''),',')) OR ISNULL(@rIntimationDetailIds,'')='');  
     
END; 

GO

Create PROCEDURE [sHospitalization].[pHospitalizationDoctorAssignmentMailGetAssignButton]              
(              
    @rOrgId INT,              
    @rTemplate NVARCHAR(MAX),              
    @rMailSubject NVARCHAR(MAX),              
    @rIntimationDetailIds NVARCHAR(MAX),              
    @rEventId INT              
)              
AS              
BEGIN              
    SET NOCOUNT ON;              
            
    SELECT DISTINCT    
   IDE.AssignedDoctorId,    
        @rOrgId AS OrgGroupId,              
        95 AS SourceTypeId,              
        EC.MobileNumber AS MobileNo,              
        EC.CompanyEmail AS EmailId,            
        EM.FirstName,              
        EC.ExtensionNo,            
            
        -- 🔹 Message text with ALL replacements            
        REPLACE(            
            REPLACE(            
                REPLACE(            
                    REPLACE(            
                        REPLACE(       
                                @rTemplate,            
                                '[DoctorName]',            
                                LTRIM(RTRIM(            
                                    ISNULL(EM.FirstName, '') +            
                                    CASE WHEN ISNULL(EM.MiddleName, '') <> '' THEN ' ' + EM.MiddleName ELSE '' END +            
                                    CASE WHEN ISNULL(EM.LastName, '') <> '' THEN ' ' + EM.LastName ELSE '' END            
                                ))            
                            ),    
                        '[Extension]', ISNULL(EC.ExtensionNo, '')            
                    ),            
                    '[MobileNumber]', ISNULL(EC.MobileNumber, '')            
                ),            
                '[NewAssignedCount]',            
                CAST(            
                    (            
               SELECT COUNT(1)            
                FROM sHospitalization.tIntimationDetails ID2            
                WHERE ID2.AssignedDoctorId = EM.Id and ID2.TicketStatus = 'New'    
    AND CONVERT(DATE,ID2.UnattendedDate,103)=CONVERT(DATE,GETDATE(),103)           
            
                    ) AS NVARCHAR(10)            
                )            
            ),            
              '[OpenFrom]',            
             CAST(            
             (            
                SELECT COUNT(1)                
                 FROM sHospitalization.tIntimationDetails ID2                 
                 WHERE ID2.AssignedDoctorId = EM.Id                
                   AND ISNULL(ID2.IsObsolete, 0) = 0                
                  AND TicketStatus IN ('Open', 'New')               
                  AND ID2.UnattendedDate <= DATEADD(HOUR, -48, GETDATE())                
             ) AS NVARCHAR(10)            
             )            
            
        ) AS MsgText,            
            
        @rMailSubject AS Subject              
            
    FROM sHospitalization.tIntimationDetails IDE              
    LEFT JOIN sHrm.tEmployeeMaster EM              
        ON IDE.AssignedDoctorId = EM.Id              
    LEFT JOIN sHrm.tEmployeeCommunications EC              
        ON EM.Id = EC.EmployeeId          
   WHERE (ISNULL(IDE.Id,0) IN (SELECT cast(item as Bigint) FROM  sCommon.fnsplit(ISNULL(@rIntimationDetailIds,''),',')) OR ISNULL(@rIntimationDetailIds,'')='');        
            
END; 

GO


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

GO

alter PROCEDURE [sHospitalization].[pIntimationDetailsUpdate]    
   @rEmpCode NVARCHAR(100),    
   @TicketNumber NVARCHAR(50),    
   @AssignedDoctorId BIGINT = NULL,    
   @IntimationAssignedDoctorId INT = NULL,    
   @rOrgId INT = NULL,    
   @rCreatedUserId BIGINT = NULL  
AS  
BEGIN  
    SET NOCOUNT ON;  
  
    BEGIN TRY  
        DECLARE @CurrentDateTime DATETIME = GETUTCDATE();  
        DECLARE @IntimationDetailId BIGINT;  
        DECLARE @PreviousDoctorId BIGINT;  
        DECLARE @FinalDoctorId BIGINT;
        DECLARE @FinalIntimationDoctorId INT;
  
        -- Find the existing Intimation record  
        SELECT @IntimationDetailId = Id,  
               @PreviousDoctorId = AssignedDoctorId  
        FROM [sHospitalization].[tIntimationDetails]  
        WHERE EmpCode = @rEmpCode  
          AND TicketNumber = @TicketNumber  
          AND OrgId = @rOrgId;  
  
        IF @IntimationDetailId IS NULL  
        BEGIN  
            RAISERROR('Intimation record not found for Employee %s and Ticket %s', 16, 1, @rEmpCode, @TicketNumber);  
            RETURN;  
        END  
  
        -- Determine the doctor to assign
        IF @AssignedDoctorId IS NOT NULL AND @AssignedDoctorId > 0
        BEGIN
            -- Use provided doctor
            SET @FinalDoctorId = @AssignedDoctorId;
            SET @FinalIntimationDoctorId = @IntimationAssignedDoctorId;
        END
        ELSE
        BEGIN
            -- Need to determine doctor based on business rules
            -- This is where you'd implement the same logic as your C# code
            -- For now, let's implement a simple round-robin for central doctors
            
            DECLARE @NextDoctorId BIGINT;
            DECLARE @NextDoctorIndexId INT;
            
            -- Call a helper procedure to get the next central doctor
            EXEC sHospitalization.pGetNextCentralDoctor 
                @rOrgId,
                @NextDoctorId OUTPUT,
                @NextDoctorIndexId OUTPUT;
            
            SET @FinalDoctorId = @NextDoctorId;
            SET @FinalIntimationDoctorId = @NextDoctorIndexId;
        END
  
         IF EXISTS (
             SELECT 1
             FROM [sHospitalization].[tIntimationDetails]
             WHERE EmpCode = @rEmpCode
             AND BeneficiaryName = (
                 SELECT BeneficiaryName
                 FROM [sHospitalization].[tIntimationDetails]
                 WHERE TicketNumber = @TicketNumber
             )
         )
        BEGIN
            -- Update and set Flag = 1
            UPDATE [sHospitalization].[tIntimationDetails]
            SET  
                AssignedDoctorId = @FinalDoctorId,
                IntimationAssignedDoctorId = @FinalIntimationDoctorId,
                UpdatedUserId = @rCreatedUserId,
                UpdatedDateTime = @CurrentDateTime,
				UnattendedDate = @CurrentDateTime,
                Flag = 1
            WHERE Id = @IntimationDetailId;
        END
        ELSE
        BEGIN
            -- Update without changing Flag
            UPDATE [sHospitalization].[tIntimationDetails]
            SET  
                AssignedDoctorId = @FinalDoctorId,
                IntimationAssignedDoctorId = @FinalIntimationDoctorId,
                UpdatedUserId = @rCreatedUserId,
                UpdatedDateTime = @CurrentDateTime,
				UnattendedDate=@CurrentDateTime
            WHERE Id = @IntimationDetailId;
        END
  
        -- Always insert log if doctor was assigned  
        IF @FinalDoctorId IS NOT NULL  
        BEGIN  
            DECLARE @lAssignLogId BIGINT;  
  
            EXEC scommon.ptablerowidget   
                @rOrgId = @rOrgId,  
                @rTableTitle = 'sHospitalization.tIntimationDoctorAssignmentLog',  
                @rIsCurrentNumber = 0,  
                @rSeed = 1,  
                @rIncrement = 1,  
                @outNextNumber = @lAssignLogId OUTPUT;  
  
            -- Insert log  
            INSERT INTO [sHospitalization].[tIntimationDoctorAssignmentLog]  
            (  
                Id,   
                OrgId,   
                HospitalizationIntimationDetailId,   
                PreviousDoctorEmployeeId,   
                NewDoctorEmployeeId,  
                AssignedDate,   
                TicketNumber,   
                CreatedUserId,   
                CreatedDateTime,   
                UpdatedUserId,   
                UpdatedDateTime,   
                Status  
            )  
            VALUES  
            (  
                @lAssignLogId,   
                @rOrgId,   
                @IntimationDetailId,   
                @PreviousDoctorId,   
                @FinalDoctorId,  
                @CurrentDateTime,   
                @TicketNumber,   
                @rCreatedUserId,   
                @CurrentDateTime,   
                @rCreatedUserId,   
                @CurrentDateTime,   
                'Open'  
            );  
        END  
  
        -- Return updated record id  
        SELECT @IntimationDetailId AS updatedrecordid;  
  
    END TRY  
    BEGIN CATCH  
        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();  
        RAISERROR(@ErrorMessage, 16, 1);  
    END CATCH  
END;

GO

CReate Or Alter PROCEDURE [sHospitalization].[pMedicalReviewLogGet]        
    @rTicketNumber NVARCHAR(50)       
AS        
BEGIN        
    SET NOCOUNT ON;      
      
    ;WITH CombinedActivities AS      
    (      
        ---------------------------------------------------------      
        -- 1. Remarks      
        ---------------------------------------------------------      
        SELECT        
           -- UR.DisplayTitle AS UserName,      
           --  CASE         
          -- WHEN PAL.TicketStatus <> 'New'         
            --    THEN    
    ISNULL(UR.DisplayTitle, '')      
          -- ELSE ''        
          --END     
    AS UserName,        
            'Remark' AS ActivityType,      
            CONVERT(VARCHAR(10), R.CreatedDateTime, 103) + ' ' +      
           sCommon.fn_ConvertToIST(CONVERT(VARCHAR(8), R.CreatedDateTime, 24)) AS ActivityDateTime,      
            R.Remark AS Remark,      
            ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS AssignedDoctor,      
            R.CreatedDateTime AS SortDate,      
            'TKT-' + RIGHT(PAL.TicketNumber, 5) AS TicketNumber,      
            R.Status AS Status      
        FROM sHospitalization.tIntimationRemark R      
        Inner JOIN sHospitalization.tIntimationDetails PAL      
            ON PAL.Id = R.HospitalizationIntimationDetailId      
        Inner JOIN sSecurity.tUser UR        
            ON UR.id = R.CreatedUserId and ur.OrgId=R.OrgId      
        LEFT JOIN sHrm.tEmployeeMaster EM      
            ON EM.Id = R.DoctorEmployeeId        
        WHERE PAL.TicketNumber = @rTicketNumber      
      
      
        UNION ALL      
      
        ---------------------------------------------------------      
        -- 2. Doctor Assignment Logs      
        ---------------------------------------------------------      
        SELECT        
          --  UR.DisplayTitle AS UserName,      
          CASE         
       WHEN SM.Status = 'New'     
         AND SM.PreviousDoctorEmployeeId IS NULL    
        THEN 'System'    
  else     
  UR.DisplayTitle    
          END AS UserName,        
            'Doctor Assignment' AS ActivityType,      
            CONVERT(VARCHAR(10), SM.AssignedDate, 103) + ' ' +      
                 
   sCommon.fn_ConvertToIST(CONVERT(VARCHAR(8),  SM.AssignedDate, 24)) AS ActivityDateTime,      
            '' AS Remark,      
            ISNULL(E2.FirstName,'') + ' ' + ISNULL(E2.LastName,'') AS AssignedDoctor,      
            SM.AssignedDate AS SortDate,      
            'TKT-' + RIGHT(PAL.TicketNumber, 5) AS TicketNumber,      
            SM.Status AS Status      
        FROM sHospitalization.tIntimationDoctorAssignmentLog SM      
        INNER JOIN sHospitalization.tIntimationDetails PAL      
            ON PAL.Id = SM.HospitalizationIntimationDetailId      
        LEFT JOIN sSecurity.tUser UR        
            ON UR.Id = SM.CreatedUserId and UR.OrgId=SM.OrgId      
        LEFT JOIN sHrm.tEmployeeMaster E2      
            ON E2.Id = SM.NewDoctorEmployeeId      
        WHERE PAL.TicketNumber = @rTicketNumber      
    )      
      
    SELECT       
        UserName,      
        ActivityType,      
        ActivityDateTime,      
        Remark,      
        AssignedDoctor,      
        SortDate,      
        TicketNumber,      
        Status      
    FROM CombinedActivities      
    ORDER BY SortDate ASC;      
END      

GO

Alter PROCEDURE [sHospitalization].[pSubmitRemark]  
(  
    @rHospitalizationIntimationDetailId BIGINT = 0,  
    @rCreatedDateTime DATETIME,  
    @rRemark NVARCHAR(MAX),  
    @rDoctorEmployeeId BIGINT = 0,  
 @rCreatedUserId BIGINT = 0,  
    @rOrgId INT,  
    @rStatus NVARCHAR(500) = NULL    
)  
AS  
BEGIN  
    SET NOCOUNT ON;  
  
    BEGIN TRY  
        BEGIN TRANSACTION;  
  
        DECLARE @lNextNumber BIGINT;  
  
        -------------------------------------------------------------  
        -- Generate Unique ID for Remark Entry  
        -------------------------------------------------------------  
        EXEC sCommon.pTableRowIdGet   
            @rOrgId,  
            'sHospitalization.tIntimationRemark',  
            0, 1, 1,  
            @outNextNumber = @lNextNumber OUTPUT;  
  
        -------------------------------------------------------------  
        -- Insert Remark Record  
        -------------------------------------------------------------  
        INSERT INTO sHospitalization.tIntimationRemark  
        (  
            Id,  
            OrgId,  
            HospitalizationIntimationDetailId,  
            DoctorEmployeeId,  
            Remark,  
            CreatedUserId,  
            CreatedDateTime,  
            UpdatedUserId,  
            UpdatedDateTime,  
   Status  
        )  
        VALUES  
        (  
            @lNextNumber,  
            @rOrgId,  
            @rHospitalizationIntimationDetailId,  
            @rDoctorEmployeeId,  
            @rRemark,  
            @rCreatedUserId,           
             sCommon.fGetDate(),  
            @rCreatedUserId,  
              sCommon.fGetDate(),  
   @rStatus  
        );  
  
        -------------------------------------------------------------  
        -- Update Intimation Details Table (Doctor & Status)  
        -------------------------------------------------------------  
        UPDATE D  
        SET   
            D.TicketStatus = LTRIM(RTRIM(ISNULL(@rStatus, D.TicketStatus))),  
            D.UpdatedUserId = @rCreatedUserId,  
            D.UpdatedDateTime = sCommon.fGetDate()  
        FROM sHospitalization.tIntimationDetails D  
        WHERE D.Id = @rHospitalizationIntimationDetailId  
          AND D.OrgId = @rOrgId;  
  
        -------------------------------------------------------------  
        -- Insert into Doctor Assignment Log (NEW)  
        -------------------------------------------------------------  
  
   --     DECLARE @logId BIGINT;  
   --     EXEC sCommon.pTableRowIdGet   
   --         @rOrgId,  
   --         'sHospitalization.tIntimationDoctorAssignmentLog',  
   --         0, 1, 1,  
   --         @outNextNumber = @logId OUTPUT;  
  
   --     INSERT INTO sHospitalization.tIntimationDoctorAssignmentLog  
   --     (  
   --         Id,  
   --         OrgId,  
   --         HospitalizationIntimationDetailId,  
   --         PreviousDoctorEmployeeId,  
   --         NewDoctorEmployeeId,  
   --         AssignedDate,  
   --         TicketNumber,  
   --         CreatedUserId,  
   --         CreatedDateTime,  
   --         UpdatedUserId,  
   --         UpdatedDateTime,  
   --Status  
   --     )  
   --     SELECT   
   --         @logId,  
   --         @rOrgId,  
   --         D.Id,  
   --         D.AssignedDoctorId,  
   --         @rDoctorEmployeeId,  
   --         sCommon.fGetDate(),  
   --         D.TicketNumber,  
   --         @rCreatedUserId,  
   --         sCommon.fGetDate(),  
   --         @rCreatedUserId,  
   --         sCommon.fGetDate(),  
   --@rStatus  
   --     FROM sHospitalization.tIntimationDetails D  
   --     WHERE D.Id = @rHospitalizationIntimationDetailId  
   --       AND D.OrgId = @rOrgId;  
  
        -------------------------------------------------------------  
        -- Commit and Return Success  
        -------------------------------------------------------------  
        COMMIT TRANSACTION;  
  
        SELECT   
            1 AS Status,  
            'Remarks Saved' AS Message,  
            @lNextNumber AS InsertedId;  
    END TRY  
    BEGIN CATCH  
        IF @@TRANCOUNT > 0  
            ROLLBACK TRANSACTION;  
  
        SELECT   
            0 AS Status,  
            'An unexpected error occurred: ' + ERROR_MESSAGE() AS Message,  
            ERROR_NUMBER() AS ErrorNumber,  
            ERROR_LINE() AS ErrorLine;  
    END CATCH  
END;  

GO

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

GO

ALTER TABLE sHospitalization.tIntimationDetails
ALTER COLUMN TreatingDoctor NVARCHAR(100);

GO

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

GO

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

GO

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

GO

ALTER PROCEDURE [sHospitalization].[pIntimationDetailsUpdate]    
   @rEmpCode NVARCHAR(100),    
   @TicketNumber NVARCHAR(50),    
   @AssignedDoctorId BIGINT = NULL,    
   @IntimationAssignedDoctorId INT = NULL,    
   @rOrgId INT = NULL,    
   @rCreatedUserId BIGINT = NULL  
AS  
BEGIN  
    SET NOCOUNT ON;  
  
    BEGIN TRY  
        DECLARE @CurrentDateTime DATETIME = sCommon.fGetDate();  
        DECLARE @IntimationDetailId BIGINT;  
        DECLARE @PreviousDoctorId BIGINT;  
        DECLARE @FinalDoctorId BIGINT;
        DECLARE @FinalIntimationDoctorId INT;
  
        -- Find the existing Intimation record  
        SELECT @IntimationDetailId = Id,  
               @PreviousDoctorId = AssignedDoctorId  
        FROM [sHospitalization].[tIntimationDetails]  
        WHERE EmpCode = @rEmpCode  
          AND TicketNumber = @TicketNumber  
          AND OrgId = @rOrgId;  
  
        IF @IntimationDetailId IS NULL  
        BEGIN  
            RAISERROR('Intimation record not found for Employee %s and Ticket %s', 16, 1, @rEmpCode, @TicketNumber);  
            RETURN;  
        END  
  
        -- Determine the doctor to assign
        IF @AssignedDoctorId IS NOT NULL AND @AssignedDoctorId > 0
        BEGIN
            -- Use provided doctor
            SET @FinalDoctorId = @AssignedDoctorId;
            SET @FinalIntimationDoctorId = @IntimationAssignedDoctorId;
        END
        ELSE
        BEGIN
            -- Need to determine doctor based on business rules
            -- This is where you'd implement the same logic as your C# code
            -- For now, let's implement a simple round-robin for central doctors
            
            DECLARE @NextDoctorId BIGINT;
            DECLARE @NextDoctorIndexId INT;
            
            -- Call a helper procedure to get the next central doctor
            EXEC sHospitalization.pGetNextCentralDoctor 
                @rOrgId,
                @NextDoctorId OUTPUT,
                @NextDoctorIndexId OUTPUT;
            
            SET @FinalDoctorId = @NextDoctorId;
            SET @FinalIntimationDoctorId = @NextDoctorIndexId;
        END
  
         IF EXISTS (
             SELECT 1
             FROM [sHospitalization].[tIntimationDetails]
             WHERE EmpCode = @rEmpCode
             AND BeneficiaryName = (
                 SELECT BeneficiaryName
                 FROM [sHospitalization].[tIntimationDetails]
                 WHERE TicketNumber = @TicketNumber
             )
         )
        BEGIN
            -- Update and set Flag = 1
            UPDATE [sHospitalization].[tIntimationDetails]
            SET  
                AssignedDoctorId = @FinalDoctorId,
                IntimationAssignedDoctorId = @FinalIntimationDoctorId,
                UpdatedUserId = @rCreatedUserId,
                UpdatedDateTime = @CurrentDateTime,
				UnattendedDate = @CurrentDateTime,
                Flag = 1
            WHERE Id = @IntimationDetailId;
        END
        ELSE
        BEGIN
            -- Update without changing Flag
            UPDATE [sHospitalization].[tIntimationDetails]
            SET  
                AssignedDoctorId = @FinalDoctorId,
                IntimationAssignedDoctorId = @FinalIntimationDoctorId,
                UpdatedUserId = @rCreatedUserId,
                UpdatedDateTime = @CurrentDateTime,
				UnattendedDate=@CurrentDateTime
            WHERE Id = @IntimationDetailId;
        END
  
        -- Always insert log if doctor was assigned  
        IF @FinalDoctorId IS NOT NULL  
        BEGIN  
            DECLARE @lAssignLogId BIGINT;  
  
            EXEC scommon.ptablerowidget   
                @rOrgId = @rOrgId,  
                @rTableTitle = 'sHospitalization.tIntimationDoctorAssignmentLog',  
                @rIsCurrentNumber = 0,  
                @rSeed = 1,  
                @rIncrement = 1,  
                @outNextNumber = @lAssignLogId OUTPUT;  
  
            -- Insert log  
            INSERT INTO [sHospitalization].[tIntimationDoctorAssignmentLog]  
            (  
                Id,   
                OrgId,   
                HospitalizationIntimationDetailId,   
                PreviousDoctorEmployeeId,   
                NewDoctorEmployeeId,  
                AssignedDate,   
                TicketNumber,   
                CreatedUserId,   
                CreatedDateTime,   
                UpdatedUserId,   
                UpdatedDateTime,   
                Status  
            )  
            VALUES  
            (  
                @lAssignLogId,   
                @rOrgId,   
                @IntimationDetailId,   
                @PreviousDoctorId,   
                @FinalDoctorId,  
                @CurrentDateTime,   
                @TicketNumber,   
                @rCreatedUserId,   
                @CurrentDateTime,   
                @rCreatedUserId,   
                @CurrentDateTime,   
                'Open'  
            );  
        END  
  
        -- Return updated record id  
        SELECT @IntimationDetailId AS updatedrecordid;  
  
    END TRY  
    BEGIN CATCH  
        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();  
        RAISERROR(@ErrorMessage, 16, 1);  
    END CATCH  
END;

GO

ALTER PROCEDURE [sHospitalization].[pGetDoctorsWithZeroCountAndOpenTickets]        
    @OrgId INT,        
    @HoursThreshold INT = 48,        
    @DaysLookback INT = 30        
AS        
BEGIN        
    SET NOCOUNT ON;        
      SELECT DISTINCT        
        --id.Id AS RecordId1s,
		 STUFF((
        SELECT DISTINCT ',' + Cast(id.Id as NVARCHAR(MAX))
        FROM sHospitalization.tIntimationDetails id	       
    INNER JOIN sHrm.tEmployeeMaster emp         
        ON id.AssignedDoctorId = emp.Id        
        AND emp.OrgId = @OrgId
    WHERE emp.Id = U.SourceId 
	and id.OrgId = @OrgId        
        AND id.IsObsolete = 0        
        AND id.TicketStatus IN ('Open')        
        AND id.CreatedDateTime <= DATEADD(HOUR, -@HoursThreshold, GETDATE()) 
		AND NOT EXISTS (  
		      SELECT 1
		      FROM sHospitalization.tIntimationDetails id2  
		      WHERE id2.AssignedDoctorId = id.AssignedDoctorId   
		      AND CAST(id2.UnattendedDate AS DATE) = CAST(GETDATE() AS DATE) 
		      AND id2.IsObsolete = 0)
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS RecordIds,
 
       -- iad.DoctorEmployeeId AS ParticipantSourceId ,      
     U.id AS ParticipantSourceId ,      
  id.orgid as orgId      
    FROM sHospitalization.tIntimationDetails id        
   -- INNER JOIN sHospitalization.tIntimationAssignedDoctor iad         
    --    ON id.AssignedDoctorId = iad.DoctorEmployeeId        
    INNER JOIN sHrm.tEmployeeMaster emp         
        ON id.AssignedDoctorId = emp.Id        
        AND emp.OrgId = @OrgId        
   INNER JOIN sSecurity.tUser U ON U.SourceId=id.AssignedDoctorId       
    LEFT JOIN sHrm.tEmployeeCommunications EC         
        ON emp.Id = EC.EmployeeId        
    WHERE         
        id.OrgId = @OrgId        
  And emp.OrgID =  @OrgId        
        AND id.IsObsolete = 0        
        AND id.TicketStatus IN ('Open')        
        AND id.CreatedDateTime <= DATEADD(HOUR, -@HoursThreshold, GETDATE()) 
		AND NOT EXISTS (  
		      SELECT 1
		      FROM sHospitalization.tIntimationDetails id2  
		      WHERE id2.AssignedDoctorId = id.AssignedDoctorId   
		      AND CAST(id2.UnattendedDate AS DATE) = CAST(GETDATE() AS DATE) 
		      AND id2.IsObsolete = 0     );  
END

GO


PRINT N'Creating User-Defined Table Type [sWellness].[udt_MHIScoreUpdateBulk]...';


GO
CREATE TYPE [sWellness].[udt_MHIScoreUpdateBulk] AS TABLE (
    [EmployeeCode] NVARCHAR (50)   NOT NULL,
    [BMI]          NUMERIC (10, 2) NULL,
    [SystolicBP]   NUMERIC (10)    NULL,
    [DiastolicBP]  NUMERIC (10)    NULL,
    [HBA1C]        NUMERIC (10, 2) NULL,
    [LDL]          NUMERIC (10, 2) NULL,
    [Stress]       NUMERIC (10, 2) NULL,
    [LifeStyle]    NUMERIC (10, 2) NULL);


GO
PRINT N'Creating User-Defined Table Type [sWellness].[udt_MHIScoreUpdation]...';


GO
CREATE TYPE [sWellness].[udt_MHIScoreUpdation] AS TABLE (
    [EmployeeCode] NVARCHAR (100)  NULL,
    [BMI]          NUMERIC (10, 2) NULL,
    [SystolicBP]   NUMERIC (10)    NULL,
    [DiastolicBP]  NUMERIC (10)    NULL,
    [HBA1C]        NUMERIC (10, 2) NULL,
    [LDL]          NUMERIC (10, 2) NULL,
    [Stress]       NUMERIC (10, 2) NULL,
    [LifeStyle]    NUMERIC (10, 2) NULL);


GO
PRINT N'Altering Table [sExamination].[tAdditionalFieldSetup]...';


GO
ALTER TABLE [sExamination].[tAdditionalFieldSetup]
    ADD [VisitPurposeId] INT NULL;


GO
PRINT N'Altering Table [sWellness].[tWellnessActivityCategoryMaster]...';


GO
ALTER TABLE [sWellness].[tWellnessActivityCategoryMaster]
    ADD [OrgId] SMALLINT NULL;


GO
PRINT N'Altering Table [sWellness].[tWellnessActivityMaster]...';


GO
ALTER TABLE [sWellness].[tWellnessActivityMaster]
    ADD [OrgId] SMALLINT NULL;


GO
PRINT N'Altering Table [sWellness].[tWellnessActivityTaskMaster]...';


GO
ALTER TABLE [sWellness].[tWellnessActivityTaskMaster]
    ADD [OrgId] SMALLINT NULL;


GO
PRINT N'Creating Table [sWellness].[tConsultationRemarkLog]...';


GO
CREATE TABLE [sWellness].[tConsultationRemarkLog] (
    [Id]              INT             IDENTITY (1, 1) NOT NULL,
    [ConsultationId]  BIGINT          NOT NULL,
    [Remark]          NVARCHAR (1000) NULL,
    [CreatedUserId]   BIGINT          NOT NULL,
    [CreatedDateTime] DATETIME        NOT NULL,
    [UpdatedUserId]   BIGINT          NULL,
    [UpdatedDateTime] DATETIME        NULL,
    CONSTRAINT [PK_sWellness.tConsultationRemarkLog] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Index [sWellness].[tMHIScore].[IX_tMHIScore_EmployeeId]...';


GO
CREATE NONCLUSTERED INDEX [IX_tMHIScore_EmployeeId]
    ON [sWellness].[tMHIScore]([EmployeeId] ASC);


GO
PRINT N'Creating Default Constraint [sWellness].[DF__tAssigned__Remin__30614D9F]...';


GO
ALTER TABLE [sWellness].[tAssignedActivity]
    ADD DEFAULT ((0)) FOR [ReminderEnabled];


GO
PRINT N'Creating Default Constraint [sWellness].[DF__tAssigned__Statu__315571D8]...';


GO
ALTER TABLE [sWellness].[tAssignedActivity]
    ADD DEFAULT ((1)) FOR [Status];


GO
PRINT N'Creating Default Constraint [sWellness].[DF__tMHIScore__Actio__1AAA123C]...';


GO
ALTER TABLE [sWellness].[tMHIScore_History]
    ADD DEFAULT ([scommon].[fgetdate]()) FOR [ActionDateTime];


GO
PRINT N'Creating Default Constraint [sWellness].[DF__tWellness__IsObs__3C080A75]...';


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


GO
PRINT N'Creating Default Constraint [sWellness].[DF_tWellnessVisitPurposeMaster_IsObsolete]...';


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


IF NOT EXISTS (SELECT 1 FROM [sSecurity].[tTask] WHERE Id = 21070)
BEGIN
	INSERT INTO [sSecurity].[tTask] (Id, Title, TitleResourceKeyId, IsObsolete, ModuleId, AvailablePermission, OrderIndex, ResourceTypeId, IsClientSpecific) 
	VALUES (21070, 'Consultation DashBoard', 0, 0, 197, 2, 19, 2, 0);
END


IF NOT EXISTS (SELECT 1 FROM [sSecurity].[tScreen] WHERE Id = 20922)
BEGIN
	INSERT INTO [sSecurity].[tScreen] (Id, Title, TitleResourceKeyId, TaskId, Page, IsObsolete, ScreenGroupId, OrderIndex, ScreenTypeId, IconPath, IsHideInScreenGroup, HelpPath, PHIAccessLevel) 
	VALUES (20922, 'Consultation DashBoard', NULL, 21070, '~/main/wellness/ConsultationDashBoard', 0, 220, 17, NULL, '', 0, NULL, 0);
END

IF NOT EXISTS (SELECT 1 FROM [sConfig].[tConfigurationMaster] WHERE Id = 347)
BEGIN
	INSERT INTO [sConfig].[tConfigurationMaster] (Id, ModuleId, ValidationTypeId, Title, Remark, ItemKey, ItemValue, IsObsolete, SortOrder, ConfigurationLevelId, IsHide, ScreenId) 
	VALUES (347, 197, 2, 'Restrict Consultation Edit after selected hours. Select 0 for no Edit restrictions', 'Restrict Consultation Edit after selected hours. Select 0 for no Edit restrictions', 'Wellness.SetEditConsultationHours', '0', 0, 200, 1, NULL, NULL);
END

GO

UPDATE sSecurity.tMenu SET Title='Wellness Consultation' WHERE Id=191810373;
UPDATE sSecurity.tTask set Title = 'Wellness Request Appointment' where title = 'Request Wellness Appointment'
UPDATE sSecurity.tScreen set Title = 'Wellness Request Appointment' where title = 'Request Wellness Appointment'

GO


PRINT N'Altering View [sWellness].[vExtPatientWellnessAppointmentDetail]...';


GO

ALTER VIEW [sWellness].[vExtPatientWellnessAppointmentDetail]
AS  
SELECT     A.Id, A.AppointmentNumber, A.PatientSourceTypeId, A.PatientSourceId,   
                      CASE WHEN A.PatientSourceTypeId = 95 THEN EM.Id WHEN A.PatientSourceTypeId = 1009 THEN CSB.Id ELSE EFD.Id END AS DependentId,	 
    CASE 
        WHEN A.PatientSourceTypeId = 95 THEN
            LTRIM(RTRIM(
                ISNULL(EM.FirstName,'') +
                CASE WHEN ISNULL(EM.MiddleName,'') <> '' THEN ' ' + EM.MiddleName ELSE '' END +
                CASE WHEN ISNULL(EM.LastName,'') <> '' THEN ' ' + EM.LastName ELSE '' END
            ))
        WHEN A.PatientSourceTypeId = 1009 THEN
            CASE 
                WHEN ISNULL(A.OtherName,'') <> '' THEN A.OtherName
                ELSE LTRIM(RTRIM(
                    ISNULL(CSB.FirstName,'') +
                    CASE WHEN ISNULL(CSB.MiddleName,'') <> '' THEN ' ' + CSB.MiddleName ELSE '' END +
                    CASE WHEN ISNULL(CSB.LastName,'') <> '' THEN ' ' + CSB.LastName ELSE '' END
                ))
            END
        ELSE EFD.Name
    END AS PatientName,
                      A.AppointmentDate, A.FromTime, A.ToTime, A.DoctorEmployeeId, A.StoreLocationId, A.SetupId,   
                      CASE WHEN A.PatientSourceTypeId = 95 THEN EM.Code WHEN A.PatientSourceTypeId = 1009 THEN CSB.Code ELSE EM2.Code END AS EmployeeCode,   
                      CASE WHEN A.PatientSourceTypeId = 95 THEN EM.Id WHEN A.PatientSourceTypeId = 1009 THEN CSB.Id ELSE EFD.Id END AS EmployeeId,   
                      CASE WHEN A.PatientSourceTypeId = 95 THEN 'Self' WHEN A.PatientSourceTypeId = 1009 THEN 'Other' ELSE RM.Title END AS Relation,   
                      CASE WHEN A.PatientSourceTypeId = 95 THEN ISNULL(GM.Title, '') WHEN A.PatientSourceTypeId = 1009 THEN ISNULL(GM2.Title, '')   
                      ELSE CASE WHEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId), '') = '' THEN  
                      (select Title from sCommon.tGenderMaster where Id = EFD.GenderId) ELSE  
                      ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId), '') END END AS Gender,   
                      CASE WHEN A.PatientSourceTypeId = 95 THEN EJD.EmployeeLocationId WHEN A.PatientSourceTypeId = 1009 THEN CSB.LocationId ELSE EJD1.EmployeeLocationId END  
                       AS LocationId, CASE WHEN ISNULL(EM1.EmployeePrefix,'') <> '' THEN ISNULL(EM1.EmployeePrefix,'') + ' ' ELSE '' END
												+ EM1.FirstName + ' ' + EM1.LastName AS DoctorName,
					   A.OrgId, A.IsRegister, A.IsObsolete,   
                      ODM.Title AS DepartmentName, ODM.Id AS DepartmentId, SM.Title AS StatusName, SLM.Title AS StoreLocation, VSM.MainTypeId AS ExaminationTypeId,   
                      VSM.MainType, VSM.Title AS Setup, A.ReferSourceId, CASE A.PatientSourceTypeId WHEN 95 THEN ISNULL(EJD.EmployeeStoreLocationId, 0)   
                      WHEN 1001 THEN ISNULL(EJD1.EmployeeStoreLocationId, 0) END AS EmployeeStoreLocationId,  
                      A.CauseId,A.OtherName,A.FollowupRemark,A.CompliantRemark,isnull(A.Age,0) as Age,isnull(A.Months,0) as Months,  
                      isnull(A.GenderId,0) as GenderId,  
                      isnull(A.ExaminationId,0) as ExaminationId,
					  A.TimeslotId,
       (Left(convert(varchar,TSM.FromTime,108),5) + '-' + Left(convert(varchar,TSM.ToTime,108),5)) as TimeSlot,  
       A.ApprovalStatusId,ISNULL(A.AppointmentType,0) as AppointmentType,
	   ISNULL(A.AppointmentFlag,'New Wellness Appointment') AS AppointmentFlag
	FROM [sWellness].[tAppointment] AS A  
        LEFT JOIN sHrm.tEmployeeFamilyDetails AS EFD ON A.PatientSourceId = EFD.Id AND A.PatientSourceTypeId = 1001  
		LEFT JOIN sHrm.tEmployeeMaster AS EM2 ON EM2.Id = EFD.EmployeeId AND A.PatientSourceTypeId = 1001  
		LEFT JOIN sHrm.tEmployeeMaster AS EM ON (EM.Id = A.PatientSourceId OR EM.Id = EFD.EmployeeId) AND A.PatientSourceTypeId = 95  
		LEFT JOIN sHrm.tCsrBenefiterMaster AS CSB ON CSB.Id = A.PatientSourceId AND A.PatientSourceTypeId = 1009  
		LEFT JOIN sHrm.tEmployeePersonalDetail AS EPD ON EPD.EmployeeId = EM.Id  
		LEFT JOIN sCommon.tGenderMaster AS GM ON GM.Id = EPD.GenderId  
		LEFT JOIN sCommon.tGenderMaster AS GM2 ON GM.Id = CSB.GenderId  
		LEFT JOIN sCommon.tStatusMaster AS SM ON SM.Id = A.StatusId  
		LEFT JOIN sHrm.tEmployeeMaster AS EM1 ON EM1.Id = A.DoctorEmployeeId  
		LEFT JOIN sCommon.tRelationshipMaster AS RM ON RM.Id = EFD.RelationshipId  
		LEFT JOIN sHrm.tEmployeeJobDetail AS EJD ON EJD.EmployeeId = EM.Id  
		LEFT JOIN sHrm.tEmployeeJobDetail AS EJD1 ON EJD1.EmployeeId = EFD.EmployeeId  
		LEFT JOIN sCommon.tOrganizationDepartmentMaster AS ODM ON ODM.Id = EJD.OrganizationDepartmentId  
		INNER JOIN sIp.tStoreLocationMaster AS SLM ON SLM.Id = A.StoreLocationId  
		INNER JOIN sExamination.vExtSetupMaster AS VSM ON VSM.Id = A.SetupId  
		LEFT JOIN sAppointment.tTimeSlotMaster TSM On TSM.Id=A.TimeslotId
GO
PRINT N'Altering Procedure [sExamination].[pGetAdditionalFieldConsultation]...';


GO

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

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

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


GO

ALTER PROCEDURE [sExamination].[pAdditionalFieldSetupAdd]	 
	@rId int,
	@rOrgId int,	
	@rFieldRemark nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	@rFieldOrder smallint,
	@rIsShowInReport bit,
	@rSourceTypeId int = 0,
	@rExaminationTypeId int = 0,
	@rVisitPurposeId int = 0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
BEGIN TRANSACTION	
 
IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sExamination.tAdditionalFieldSetup', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO [sExamination].[tAdditionalFieldSetup]
	(
		Id		
		,FieldRemark
		,FieldTypeId
		,FieldList
		,IsFieldMandatory
		,FieldGroup
		,FieldOrder
		,IsShowInReport
		,SourceTypeId
		,ExaminationTypeId
		,VisitPurposeId
	)
	VALUES
	(
		@lNextNumber		
		,@rFieldRemark
		,@rFieldTypeId
		,@rFieldList
		,@rIsFieldMandatory
		,@rFieldGroup
		,@rFieldOrder
		,@rIsShowInReport
		,ISNULL(@rSourceTypeId,0)
		,ISNULL(@rExaminationTypeId,0)
		,ISNULL(@rVisitPurposeId, 0)
	)
END	 
ELSE
BEGIN
	SET @lNextNumber = @rId
	UPDATE [sExamination].[tAdditionalFieldSetup]
	SET 
		FieldRemark = @rFieldRemark
		,FieldTypeId = @rFieldTypeId
		,FieldList=@rFieldList
		,IsFieldMandatory=@rIsFieldMandatory
		,FieldGroup=@rFieldGroup
		,FieldOrder=@rFieldOrder
		,IsShowInReport=ISNULL(@rIsShowInReport,0)
		,SourceTypeId=ISNULL(@rSourceTypeId,0)
		,ExaminationTypeId=ISNULL(@rExaminationTypeId,0)
		,VisitPurposeId=ISNULL(@rVisitPurposeId, 0)
	WHERE Id = @rId
END
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sExamination].[pAdditionalFieldSetupGet]...';


GO

ALTER PROCEDURE [sExamination].[pAdditionalFieldSetupGet]	
	@rOrgId int,
	@rSourceTypeId int = 1,
	@rExaminationTypeId int = 1,
	@rVisitPurposeId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		Id,
		FieldRemark,
		FieldTypeId,
		FieldList,
		IsFieldMandatory,
		FieldGroup,
		FieldOrder,
		ISNULL(IsShowInReport,0)IsShowInReport
	FROM [sExamination].[tAdditionalFieldSetup]
	Where ISNULL(SourceTypeId, 0) = @rSourceTypeId and ISNULL(ExaminationTypeId, 0) = @rExaminationTypeId
	and ISNULL(VisitPurposeId, 0) = @rVisitPurposeId
END
GO
PRINT N'Altering Procedure [sWellness].[pActivityCategoryMasterAddUpdate]...';


GO

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

BEGIN
	
	BEGIN TRY

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

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

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

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

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


GO

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

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

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


GO

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

BEGIN
	
	BEGIN TRY

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

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

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

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

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


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

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

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

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

	IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

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

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

        RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
	END CATCH
END
GO
PRINT N'Altering Procedure [dbo].[prc_getAzureDocuments_newsearch_Ng]...';


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

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

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

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

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


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

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

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


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

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

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

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


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


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

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

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

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

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

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

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


GO


ALTER PROC [sCommon].[pRangeDetailsGet] @rRangeTableId int,@rOrgId int=1
AS
BEGIN

	Declare @lBPRangeCalculationVal nvarchar(10);

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

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

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

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

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

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

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

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

        FROM sExamination.tPulmonaryObserved
        ORDER BY id

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

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



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


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

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

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

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


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


GO

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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


GO

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


GO

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

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

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

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

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

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


GO

ALTER proc [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),600),                
  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),600),  
   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)            
 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,   
 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            
 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,OtherName,FollowupRemark,age,ApprovalStatusId, GenderId,AppointmentFlag               
   )                
  SELECT                             
    @lFromNextNumber + tid,a_EmpId,a_PatientSourceTypeId,                
    case when len(a_AppointmentDate) = 10 then convert(Datetime, a_AppointmentDate, 104) else CONVERT(VARCHAR(11), a_AppointmentDate) end,                
    a_AppointNumber,case when a_doctorId > 0 then a_doctorId else null end,                
    null,null,0,a_obsolete,a_OrgId,1,a_ExamId,0,a_StoreLocationId,a_SetupId,a_CauseId,                
    case when a_OtherName <> '' then a_OtherName else null end,left(a_FollowupRemark,200),case when Isnull(a_age,0)=0 then null else a_age end,548, a_genderId,@AppointmentFlag            
   FROM @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_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 PrescriptionId,                
 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_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,                
  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,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_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(250),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,m_MobileNumber nvarchar(20))            
 insert into @tblOthers                
 select T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@ReferenceEmployeeId','bigint') as ReferenceEmployeeId,                
 T.c.value('@IsWaive','bit') as IsWaive,                
 T.c.value('@OutSideMedicine','varchar(max)') as OutSideMedicine,                
 T.c.value('@OutSideTest','varchar(max)') as OutSideTest,                
 T.c.value('@OtherName','varchar(300)') as OtherName,                
 T.c.value('@OtherAge','varchar(20)') as OtherAge,                
 T.c.value('@OtherAgeMonth','varchar(20)') as OtherAgeMonth,                
 case when T.c.value('@OtherGenderId','varchar(10)') = '-1' then null else T.c.value('@OtherGenderId','varchar(10)') end as OtherGenderId,                
 T.c.value('@NursingRemark','varchar(max)') as NursingRemark,                
 T.c.value('@IsPediatric','bit') as IsPediatric,null,                
 T.c.value('@FurtherActionId','int') as FurtherActionId,                
 left(T.c.value('@FurtherActionRemark','varchar(250)'),250) 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('@MobileNumber','nvarchar(20)') as MobileNumber  
 from @lxmlOthers.nodes('/ExaminOther/OhterDetail')T(c)      
                 
 update w set w.o_ParticipantSourceTypeId = E.ParticipantSourceTypeId from @tblOthers w inner join sExamination.tExamination E                
 on w.o_ExaminationId = E.Id                
                 
 update OSP set OSP.SourceId=w.o_ExaminationId ,UpdatedDateTime=sCommon.fGetDate(),UpdatedUserId=@rUserId from sExamination.tOutSidePrescription OSP                
 inner join @tblOthers w on w.OutSidePrescriptionId=OSP.id                
 where Isnull(w.OutSidePrescriptionId,0) >0                
          declare  @Fitnessstatus int , @ReferenceOPdId bigint, @ReferenceOPdIdNew bigint,@ExaminationId bigint      
  set @Fitnessstatus = (select o_FitnessStatus from  @tblOthers )    
  set @ReferenceOPdId = (select r_ReferenceOPDId from  @tblOthers )    
  set @ExaminationId = (select o_ExaminationId from  @tblOthers )    
  if (@Fitnessstatus != -1)
  begin
	  if(@ReferenceOPdId > 0)
	  set @ReferenceOPdIdNew = @ReferenceOPdId
	  else
	  set @ReferenceOPdIdNew = @ExaminationId
  end
 MERGE sExamination.tOPD AS Target USING                 
 (                
  SELECT ExaminationId,o_ExaminationId,o_ReferenceEmployeeId,o_IsWaive,o_OutSideMedicine,o_OutSideTest,o_OtherName,                
  o_OtherAge,o_NursingRemark,o_OtherAgeMonth,o_OtherGenderId,o_IsPediatric,o_ParticipantSourceTypeId,                
  o_FurterActionId,o_FurtherActionRemark,o_Time,o_OutTime,o_IsFit,o_FitnessStatus, o_OtherSubGroupId, o_ReferToDoctorId, tid,      
  o_UniqueIdType, o_UniqueIdTypeOther, o_UniqueId, o_OtherEmail,v_VendorCompanyName,r_ReferenceOPDId,m_MobileNumber      
  FROM @tblOthers TT LEFT JOIN sExamination.tOPD T with(nolock) ON TT.o_ExaminationId = T.ExaminationId                
 ) AS Source ON Target.ExaminationId = Source.o_ExaminationId                
 WHEN MATCHED THEN                
  UPDATE SET ReferenceEmployeeId = o_ReferenceEmployeeId,IsWaiveOff = o_IsWaive,                
  OutsideMedicine = left([sSetup].[fPortalXMLTagsReplaceReverse](o_OutSideMedicine),1000),                
  OutsideTest = left([sSetup].[fPortalXMLTagsReplaceReverse](o_OutSideTest),1000),                
  NursingRemark = left([sSetup].[fPortalXMLTagsReplaceReverse](o_NursingRemark),200),                
  Age = o_OtherAge,OtherName = o_OtherName,Months = o_OtherAgeMonth,                
  GenderId = case when o_OtherGenderId = '-1' then null else o_OtherGenderId end,                
  IsPediatric = case when o_ParticipantSourceTypeId in (1001,1009) then o_IsPediatric else null end,                
  FurtherActionId = o_FurterActionId,FurtherActionRemark = [sSetup].[fPortalXMLTagsReplaceReverse](o_FurtherActionRemark),                
  OPDTime = [sSetup].[fPortalXMLTagsReplaceReverse](o_Time),                
  OPDOutTime = [sSetup].[fPortalXMLTagsReplaceReverse](o_OutTime),                
  IsFit = case when o_IsFit = 1 then 1 else 0 end,                
  FitnessStatus = o_FitnessStatus,              
  OtherSubGroupId = o_OtherSubGroupId, ReferToDoctorId = o_ReferToDoctorId,       
  UniqueIdType = o_UniqueIdType, UniqueIdTypeOther = o_UniqueIdTypeOther, UniqueId = o_UniqueId ,OtherEmail = o_OtherEmail  ,VendorCompanyName = v_VendorCompanyName  ,ReferenceOPDId = r_ReferenceOPDId,MobileNumber = m_MobileNumber
 WHEN NOT MATCHED THEN      
  INSERT                
  (                
   ExaminationId,ReferenceEmployeeId,IsWaiveOff,OutsideMedicine,OutsideTest,OtherName,                
   NursingRemark,Age,Months,GenderId,IsPediatric,FurtherActionId,FurtherActionRemark,OPDTime,                
   OPDOutTime,IsFit,FitnessStatus,OtherSubGroupId,ReferToDoctorId, UniqueIdType, UniqueIdTypeOther, UniqueId ,OtherEmail  ,VendorCompanyName,ReferenceOPDId,MobileNumber  
  )                
  VALUES                
  (                
   o_ExaminationId,o_ReferenceEmployeeId,o_IsWaive,left([sSetup].[fPortalXMLTagsReplaceReverse](o_OutSideMedicine),1000),                
   left([sSetup].[fPortalXMLTagsReplaceReverse](o_OutSideTest),1000),                
   o_OtherName,left([sSetup].[fPortalXMLTagsReplaceReverse](o_NursingRemark),200),                
   o_OtherAge,o_OtherAgeMonth,case when o_OtherGenderId = -1 then null else o_OtherGenderId end,                
   case when o_ParticipantSourceTypeId in (1001,1009) then o_IsPediatric else null end,o_FurterActionId,                
   [sSetup].[fPortalXMLTagsReplaceReverse](o_FurtherActionRemark),[sSetup].[fPortalXMLTagsReplaceReverse](o_Time),                
   [sSetup].[fPortalXMLTagsReplaceReverse](o_OutTime),case when o_IsFit = 1 then 1 else 0 end,o_FitnessStatus,o_OtherSubGroupId,o_ReferToDoctorId,      
   o_UniqueIdType, o_UniqueIdTypeOther, o_UniqueId,o_OtherEmail, v_VendorCompanyName,@ReferenceOPdIdNew,m_MobileNumber  
  );      
            
  Declare @rCauseId int = 0, @rIsTrackIncidentLog bit = 0, @rIsTrackForFitness bit = 0, @rIsFit bit = 0, @rUnfitListingId bigint = 0;            
  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);            
            
  IF ((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
PRINT N'Altering Procedure [sExamination].[pSaveClinicalTests]...';


GO

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

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


GO
-- exec [sExamination].[pSetupMasterGet]  
-- drop proc [sExamination].[pSetupMasterGet]  
ALTER PROCEDURE [sExamination].[pSetupMasterGet]   
 @rId [bigint] = 0,  
 @rTitle [nvarchar](20) = '',    
 @rOrgId int,  
 @rSubTypeId int,  
 @rMainTypeId int,  
 @rParticipantTypeId bigint,  
 @rIsWildCardSearch [bit] = 1,  
 @rStoreLocationId int,  
 @rIsClosed bit =null,  
 @rRoundNumber int=null,  
 @rFromDate Datetime  =null,  
 @rToDate Datetime  =null,  
 @rSetupGroupId int=null  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
 IF @rIsWildCardSearch = 1  
 BEGIN  
  SET @rTitle = sCommon.fSearchStringGet(@rTitle)  
 END     
  SELECT S.Id,  
   S.Title,  
   SGM.Title as SetupGroup,  
   S.Remark,  
   S.CreatedUserId,  
   S.CreatedDateTime,  
   S.IsObsolete,  
   isnull(S.IsPublishSetup,0) as IsPublishSetup,  
   S.UpdatedUserId,  
   S.UpdatedDateTime,     
   S.FromDate,  
   S.ToDate,  
   S.AgeFrom,  
   S.AgeTo,  
   ISNULL(S.Uid,0) as Uid,  
   S.RoundNumber,  
   S.ParticipantTypeId,  
   S.GenderId,  
   S.SubTypeId,  
   SM.MainTypeId,        
   PM.Title AS ParticipantName,  
   SM.Title AS SubTypeName,  
   S.IsClosed,  
   ISNULL(S.GradeFrom,0) AS GradeFrom,  
   ISNULL(S.GradeTo,0) AS GradeTo,  
   ISNULL(S.ProcessTypeId,0) AS ProcessTypeId,  
   isnull(s.SetupGroupId,-1) as SetupGroupId,  
   isnull(S.IsTargetGroupRestrictInHR,0) as IsTargetGroupRestrictInHR        
    FROM sExamination.tSetupMaster S   
         left join sExamination.tSetupGroupMaster SGM on SGM.Id=S.SetupGroupId  
         INNER JOIN sExamination.tSubTypeMaster  SM ON S.SubTypeId = SM.Id   
         INNER JOIN sExamination.tMainTypeMaster MT ON SM.MainTypeId = MT.Id  
         LEFT JOIN sHrm.tParticipantTypeMaster PM ON S.ParticipantTypeId = PM.Id   
      
    WHERE (S.Id = @rId OR @rId = 0)  
    AND (S.Title LIKE @rTitle OR ISNULL(@rTitle, '') = '')      
    AND (S.SetupGroupId = @rSetupGroupId or @rSetupGroupId=0 or @rSetupGroupId is null)  
    AND (S.SubTypeId = @rSubTypeId OR @rSubTypeId = 0)  
    AND SM.MainTypeId = @rMainTypeId  
    AND ((S.ParticipantTypeId = @rParticipantTypeId) OR (@rParticipantTypeId = 0))  
    AND S.OrgId = @rOrgId And S.StoreLocationId = @rStoreLocationId  
    AND (S.RoundNumber=ISNULL(@rRoundNumber,S.RoundNumber) or (Isnull(@rRoundNumber,0)=0))  
    AND (ISNULL(S.IsClosed,0)= ISNULL(@rIsClosed,0) or (Isnull(@rIsClosed,0)=0))  
       And  S.FromDate BEtWEEN (ISNULL(CONVERT(DATE,@rFromDate),S.FromDate))  AND (ISNULL(CONVERT(DATE,@rToDate),S.FromDate))  
    ORDER BY S.CreatedDateTime desc   
END
GO
PRINT N'Altering Procedure [sHrm].[PEmpDashboardDetailGet]...';


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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


GO
ALTER proc [sHrm].[pMobEmployeeMasterListingGet]

(

	@rOrgId INT,

	@rSetupGroupId INT,

	@rCode VARCHAR(20) = '',

	@rName VARCHAR(200) = '',	

	@rSurName VARCHAR(200) = '',

	@rEmployeeId BIGINT = 0,

	@rHealthIndicatorId INT=0,

	@rCodeLike VARCHAR(200) = ''

)

AS
 
	IF(@rSurName IS NULL)	

		SET @rSurName = ''

	IF(@rCode IS NULL)	

		SET @rCode = ''	

	IF(@rName IS NULL)	

		SET @rName = ''	

	SET NOCOUNT ON

	BEGIN

	SET @rName = sCommon.fSearchStringGet(@rName)

	SET @rSurName = sCommon.fSearchStringGet(@rSurName)

	DECLARE @lCondition1 VARCHAR(MAX)='',

			@lCondition2 VARCHAR(MAX)='',

			@lCondition3 VARCHAR(MAX)='',

			@lCondition4 VARCHAR(MAX)=''

	DECLARE @lCondition VARCHAR(MAX) = '',

			@lQuery VARCHAR(MAX)=''

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	BEGIN

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

		SELECT @lCondition1 = @lCondition1 + ') '

	END	

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

	BEGIN	

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

		SELECT @lCondition2 = @lCondition2 + ') '

	END	

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

	BEGIN

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

		SELECT @lCondition3 = @lCondition3 + ') '

	end

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

	BEGIN

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

		SELECT @lCondition4 = @lCondition4 + ') '

	END

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

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

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

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

	--select @lCondition

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

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

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

	FROM sHrm.tEmployeeMaster EM

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	AND E.StatusId = 4 '

	+ @lCondition + 

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

	END

	+  'Order By EM.Code'

	EXEC (@lQuery)

END
GO
PRINT N'Altering Procedure [sMro].[pDaignosisViewGet]...';


GO

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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

			Union all

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

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

			union all

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

			union all

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

			--union all

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

			--union all

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

			union all

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

			union all

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

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

			union all

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

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

			union all

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

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

			union all

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

			union all

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

			union all

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

			union all

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

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

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

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

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


GO

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

	select 1
end
GO
PRINT N'Altering Procedure [sSecurity].[pLoggedInUserGet]...';


GO


ALTER PROCEDURE [sSecurity].[pLoggedInUserGet]  
 @rOrgId [smallint],  
 @rUserId [bigint],  
 @rStoreLocationId [int]  
   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
  
DECLARE @lLocationId int=null  
DECLARE @lStoreLocationId int=null  
DECLARE @lLocationName nvarchar(100)=null  
DECLARE @lStoreLocationName nvarchar(100)=null  

--Developer: Deval, Date: 03/08/2023, To Check Given User is Employee or not
Declare @RoleId int, @rIsEmployeePortal bit;
set @RoleId = (select [sCommon].[fGetIntIdForOrg] (10, @rOrgId))

IF EXISTS(select 1 from sSecurity.tUserRole WITH (NOLOCK) where RoleId=@RoleId and UserId=@rUserId)
BEGIN
	set @rIsEmployeePortal = 1
END
ELSE
BEGIN
	set @rIsEmployeePortal = 0
END
--Developer: Deval, Date: 03/08/2023
  
SELECT top 1  @lLocationId = LocationId, @lLocationName = LocationName,@lStoreLocationId = StoreLocationId,
@lStoreLocationName = StoreName FROM sSecurity.vExtUserLocation WITH (NOLOCK)  
WHERE StoreLocationId = @rStoreLocationId AND UserId = @rUserId   

		if(Isnull(@lLocationId,0)<=0 or Isnull(@lStoreLocationId,0)<=0)
		begin
			Select top 1 @lLocationId=Isnull(LM.Id,0),@lLocationName=Isnull(LM.Title,''),@lStoreLocationId=Isnull(SLM.Id,0),@lStoreLocationName=Isnull(SLM.Title,'')
			FROM sSecurity.tUser UserTbl WITH (NOLOCK)
			Inner JOIN sCommon.vEmployeeMaster EM WITH (NOLOCK) 
			ON EM.Id = UserTbl.SourceId AND UserTbl.OrgId = EM.OrgId AND UserTbl.SourceTypeId = 95
			Inner JOIN sHrm.tEmployeeJobDetail EJ WITH (NOLOCK) ON EJ.EmployeeId=EM.Id       
			Inner join sCommon.tLocationMaster LM WITH (NOLOCK) ON EJ.EmployeeLocationId = LM.Id
			Inner JOin sIp.tStoreLocationMaster SLM WITH (NOLOCK) ON SLM.LocationId=LM.Id
			WHERE (SLM.IsActiveHealth = 1) AND (LM.IsActiveHealth = 1) AND
			UserTbl.Id = @rUserId AND
			UserTbl.OrgId = @rOrgId
				
		end
  
 SELECT   
  UserTbl.OrgId,  
  UserTbl.Id AS UserId,     
  UserTbl.LoginTitle AS LoginTitle,  
  UserTbl.DisplayTitle  AS DisplayTitle,     
  --UserTbl.EmployeeId AS EmployeeId,   
  UserTbl.SourceId AS UserSourceId,  
  UserTbl.SourceTypeId AS UserSourceTypeId,  
    (EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ' ' + EM.LastName)  AS EmployeeFullName,   
    (EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ' ' + EM.LastName)  AS UserFullName,  
  EM.EmployeeJobTitleId,  
  ScreenTbl.Page AS HomePageUrl,  
  MenuTbl.Id AS MenuId,  
  UserPrefTbl.FavoriteScreenID AS ScreenID,  
  UserTbl.SessionId AS SessionId,  
  @lLocationId AS LocationId,  
  @lLocationName AS LocationName,  
  UR.RoleId,
  EI.EmployeePhoto as UserPhoto,  
     @lStoreLocationName as  StoreLocationName,
	@lStoreLocationId as    StoreLocationId,
	EC.MobileNumber,EC.PersonalEmail,EP.GenderId,	
	(select Title from sCommon.tGenderMaster WITH (NOLOCK) where Id=EP.GenderId) as Gender,
	EP.DateOfBirth,EP.BloodGroupId,
	(select Title from sCommon.tBloodGroupMaster WITH (NOLOCK) where Id=EP.BloodGroupId) as BloodGroup,
	EP.MaritalStatusId,
	(select Title from sCommon.tMaritalStatusMaster WITH (NOLOCK) where Id=EP.MaritalStatusId) as MaritalStatus,
	EC.EmergencyContactNo,
	EJ.EmployeeDesignationId as DesignationId,
	(select Title from sHrm.tEmployeeDesignationMaster WITH (NOLOCK) where id=EJ.EmployeeDesignationId) as Designation,
	EJ.OrganizationDepartMentId as DepartmentId,
	(select DepartmentName from sCommon.tOrganizationDepartmentMaster WITH (NOLOCK) where Id=EJ.OrganizationDepartMentId) as DepartmentName,
	EJ.DateOfJoining,
	@rIsEmployeePortal as IsEmployeePortal, --Developer: Deval, Date: 03/08/2023, To Check Given User is Employee or not
	R.AccessTypeId,  --Nidhi Pandey; To add AccessTypeId in session; DT - 14/10/2022
	EC.CompanyEmail,  --Yoges Banwe; Add for Employee profile; DT - 11-01-2023 
	ELP.LanguagePreferenceId, --Nidhi Pandey; mantis id: 29981 ; DT - 16/01/2024
	ISNULL(LP.Title,'English') as LanguagePreference, --Nidhi Pandey; mantis id: 29981 ; DT - 16/01/2024,
	EM.Code as EmployeeCode,  --Nidhi Pandey; suggested by Manthan Sir ; DT - 26/02/2024,
	(Case when exists(Select 1 from [sSecurity].[tPermissionUser] PU WITH (NOLOCK) where PU.UserId = UserTbl.Id) Then 'Y' else 'N' END) as UserPermission,
	CGM.Id as SafetyDepartmentId, CGM.Title as SafetyDepartmentName,
	CASE WHEN LOWER(LTRIM(RTRIM(VM.Title))) = 'central safety' AND EM.UserId = @rUserId THEN 1 ELSE 0 END AS IsCentralSafety
	 FROM sSecurity.tUser UserTbl WITH (NOLOCK) 
  INNER JOIN sSecurity.tUserRole UR WITH (NOLOCK) 
   ON UR.UserId=UserTbl.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND UR.UserId=@rUserId  
  LEFT JOIN sCommon.vEmployeeMaster EM WITH (NOLOCK) 
   ON EM.Id = UserTbl.SourceId AND UserTbl.OrgId = EM.OrgId AND UserTbl.SourceTypeId = 95      
  LEFT OUTER JOIN sSecurity.tUserPreference UserPrefTbl WITH (NOLOCK) 
   ON UserTbl.Id = UserPrefTbl.UserId AND  UserTbl.OrgId = UserPrefTbl.OrgId  
  LEFT OUTER JOIN sSecurity.tScreen ScreenTbl WITH (NOLOCK) 
   ON UserPrefTbl.FavoriteScreenId = ScreenTbl.Id     
  LEFT OUTER JOIN sSecurity.tMenu MenuTbl WITH (NOLOCK) 
   ON MenuTbl.ScreenId =  ScreenTbl.Id   
  LEFT JOIN sHrm.tEmployeeImages EI WITH (NOLOCK) 
   ON EI.EmployeeId=EM.Id
   LEFT JOIN sHrm.tEmployeePersonalDetail EP WITH (NOLOCK) 
   ON EP.EmployeeId=EM.Id
   LEFT JOIN sHrm.tEmployeeCommunications EC WITH (NOLOCK)
   ON EC.EmployeeId=EM.Id
   LEFT JOIN sHrm.tEmployeeJobDetail EJ WITH (NOLOCK)
   ON EJ.EmployeeId=EM.Id
   LEFT JOIN sHrm.tEmployeeCompanyMaster ECM WITH (NOLOCK) on ECM.Id = EJ.EmployeeCompanyId
   LEFT JOIN sHrm.tCompanyGroupMaster CGM WITH (NOLOCK) on CGM.Id = ECM.CompanyGroupId
   LEFT JOIN sSecurity.tRole R WITH (NOLOCK)  --Nidhi Pandey; To add AccessTypeId in session; DT - 14/10/2022
   ON R.Id = UR.RoleId  
   LEFT JOIN sHrm.tEmployeeLanguagePreference ELP WITH (NOLOCK) ON ELP.EmployeeId = EM.Id --Nidhi Pandey; mantis id: 29981 ; DT - 16/01/2024
   LEFT JOIN sHrm.tLanguagePreference LP WITH (NOLOCK) ON LP.Id = ELP.LanguagePreferenceId  --Nidhi Pandey; mantis id: 29981 ; DT - 16/01/2024
   LEFT JOIN [sHrm].[tVerticalMaster] VM WITH (NOLOCK) ON VM.Id = CGM.VerticalId
 WHERE   
  UserTbl.Id = @rUserId AND  
  UserTbl.OrgId = @rOrgId   
  
END
GO
PRINT N'Altering Procedure [sSecurity].[pMobilePermissionGet]...';


GO
ALTER PROCEDURE [sSecurity].[pMobilePermissionGet]
	@rOrgId [int],
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
	BEGIN
		SELECT B.*
			FROM
			(
			SELECT		TP.TaskId AS TaskID,
						CAST(MAX(TP.C) AS BIT) AS [Create],
						CAST(MAX(TP.R) AS BIT) AS [Read],
						CAST(MAX(TP.U) AS BIT) AS [Update],
						CAST(MAX(TP.D) AS BIT) AS [Delete],
						CAST(MAX(TP.S) AS BIT) AS [Search],
						CAST(MAX(TP.P) AS BIT) AS [Print],
						CAST(MAX(TP.X) AS BIT) AS [Execute],
						TP.O AS [OrderIndex]
				FROM
				(
					SELECT 	
						TaskId					AS	TaskID,
						(Permission & 1) 		AS	C, --[Create],
						(Permission & 2)/2		AS	R, --[Read],
						(Permission & 4)/4		AS	U, --[Update],
						(Permission & 8)/8		AS	D, --[Delete],
						(Permission & 16)/16 	AS	S, --[Search],
						(Permission & 32)/32 	AS	P, --[Print],
						(Permission & 64)/64 	AS	X, --[Execute],
						(isnull(T1.OrderIndex,0)) AS O
					FROM sSecurity.tPermissionUser P
					INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
					WHERE
					--P.OrgId = @rOrgId AND T1.ModuleId = 227 
					P.OrgId = @rOrgId AND (T1.ModuleId = 215 OR T1.ModuleId = 217 OR T1.ModuleId = 255 OR T1.ModuleId = 250 OR T1.Id = 20626 OR T1.ModuleId = 197 OR T1.ModuleId = 198)
					 AND P.UserId = @rUserId
					--AND	P.UserId IN (SELECT UserId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId )
				) TP 
				GROUP BY TP.TaskId,TP.O
				) B INNER JOIN sSecurity.tTask C ON B.TaskId = C.Id
				Order By C.OrderIndex
	END
	ELSE
	BEGIN	
		SELECT B.*
		FROM
		(
		SELECT		TP.TaskId AS TaskID,
					CAST(MAX(TP.C) AS BIT) AS [Create],
					CAST(MAX(TP.R) AS BIT) AS [Read],
					CAST(MAX(TP.U) AS BIT) AS [Update],
					CAST(MAX(TP.D) AS BIT) AS [Delete],
					CAST(MAX(TP.S) AS BIT) AS [Search],
					CAST(MAX(TP.P) AS BIT) AS [Print],
					CAST(MAX(TP.X) AS BIT) AS [Execute],
						TP.O AS [OrderIndex]
			FROM
			(
				SELECT 	
					TaskId					AS	TaskID,
					(Permission & 1) 		AS	C, --[Create],
					(Permission & 2)/2		AS	R, --[Read],
					(Permission & 4)/4		AS	U, --[Update],
					(Permission & 8)/8		AS	D, --[Delete],
					(Permission & 16)/16 	AS	S, --[Search],
					(Permission & 32)/32 	AS	P, --[Print],
					(Permission & 64)/64 	AS	X, --[Execute],
						(isnull(T1.OrderIndex,0)) AS O
				FROM sSecurity.tPermission P
				INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
				WHERE
				--P.OrgId = @rOrgId AND T1.ModuleId = 227 AND
				P.OrgId = @rOrgId AND (T1.ModuleId = 215 OR T1.ModuleId = 217 OR T1.ModuleId = 255 OR T1.ModuleId = 250 OR T1.Id = 20626 OR T1.ModuleId = 197 OR T1.ModuleId = 198) AND
			P.RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId )
			) TP 
			GROUP BY TP.TaskId , TP.O
			) B INNER JOIN sSecurity.tTask C ON B.TaskId = C.Id
			Order By C.OrderIndex
	END
END
GO
PRINT N'Altering Procedure [sSupport].[pAHCCounsellingListGet]...';


GO


ALTER PROCEDURE [sSupport].[pAHCCounsellingListGet]
 @rOrgId smallint,      
 @rProviderId bigint = 0,      
 @rRoundGroupId bigint = 0,      
 @rHealthIndicatorId bigint = 0,      
 @rEmployeeCode nvarchar(100) = '',      
 @rEmployeeName nvarchar(100) = '',      
 @rStatusId int = 0,      
 @rSectorId varchar(100) = '',        
 @rVerticalId varchar(100) = '',        
 @rCompanyGroupId varchar(100) = '',        
 @rEmployeeCompanyId varchar(100) = '',        
 @rLocationMainGroupId varchar(100) = '',        
 @rLocationSubGroupId varchar(100) = '',        
 @rLocationId varchar(100) = '',        
 @rFunctionId varchar(100) = '',        
 @rDepartmentGroupId varchar(100) = '',        
 @rDepartmentId varchar(100) = '',        
 @rEmployeeTypeId varchar(100) = '',        
 @rGradeId varchar(100) = '',      
 @rTargetGroupId varchar(100) = '',      
 @rEmployeeDesignationId varchar(100) = '',      
 @rSectorIdEntity nvarchar(max)= '',      
 @rVerticalIdEntity nvarchar(max)= '',      
 @rCompanyGroupIdEntity nvarchar(max)= '',      
 @rCompanyIdEntity nvarchar(max)= '',       
 @rGradeIdEntity nvarchar(max)= '',      
 @rFunctionIdEntity nvarchar(max)= '',      
 @rStoreLocationIdEntity nvarchar(max)= '',      
 @rEmployeeTypeGroupId int = 0,      
 @rDoctorId bigint = 0,    
 @rCode NVARCHAR(MAX) = ''     
AS      
SET NOCOUNT ON      
BEGIN
 declare @lAbnormalFindingsOrHealthIndicatorConfigVal varchar(5); 
            
 select @lAbnormalFindingsOrHealthIndicatorConfigVal = sConfig.fConfigurationValueGet('Provider.AbnormalFindingsOrHealthIndicatorParam',@rOrgId,0,0,0);

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


GO
ALTER PROCEDURE [sSupport].[pAssignEmployeeCustomSearchGet]
(
	@rOrgId smallint,
	@rAssignSurveyId int=0,
	@rCode [nvarchar](max) = '',
	@rDepartmentGroupId int = 0,	
	@rDepartmentId int = 0,	
	@rEmployeeTypeId int = 0,
	@rTargetGroupId int = 0,	
	@rBusinessId int = 0,	
	@rVerticalId int = 0,	
	@rCompanyGroupId int = 0,	
	@rCompanyId int = 0,	
	@rDesignationId int = 0,	
	@rGenderId int = 0,	
	@rProcessTypeId int = 0,
	@rLocationId int ,
    @rEmployeeId Bigint =0
 )
AS
SET NOCOUNT ON
BEGIN	
	SELECT ECS.EmployeeId,ECS.Code AS EmployeeCode,ECS.Name AS EmployeeName
	FROM sHrm.vEmployeeCustomSearch ECS
inner join sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id = ECS.OrganizationDepartmentId
 inner join sCommon.tDepartmentGroupMaster DGM on DGM.Id=ODM.DepartmentGroupId
 where ECS.IsObsolete=0
	AND ECS.StatusId=7 
    AND ECS.OrgId = @rOrgId 
    AND ECS.EmployeeLocationId=@rLocationId 
	AND (ECS.Code in (SELECT a.Item FROM dbo.fSplitStr(@rCode,',') AS a where a.Item!='') or ISNULL(@rCode,'')='')
	AND (DGM.Id = @rDepartmentGroupId or isnull(@rDepartmentGroupId,0) = 0)
	AND (ECS.OrganizationDepartmentId = @rDepartmentId or isnull(@rDepartmentId,0) = 0)
	AND (ECS.EmployeeTypeId = @rEmployeeTypeId or isnull(@rEmployeeTypeId,0) = 0)
	AND (ECS.TargetGroupId = @rTargetGroupId or isnull(@rTargetGroupId,0) = 0)
	AND (ECS.BusinessId = @rBusinessId or isnull(@rBusinessId,0) = 0)
	AND (ECS.VerticalId = @rVerticalId or isnull(@rVerticalId,0) = 0)
	AND (ECS.CompanyGroupId = @rCompanyGroupId or isnull(@rCompanyGroupId,0) = 0)
	AND (ECS.EmployeeCompanyId = @rCompanyId or isnull(@rCompanyId,0) = 0)
	AND (ECS.EmployeeDesignationId = @rDesignationId or isnull(@rDesignationId,0) = 0)
	AND (ECS.GenderId = @rGenderId or isnull(@rGenderId,0) = 0)
	AND (ECS.ProcessTypeId = @rProcessTypeId or isnull(@rProcessTypeId,0) = 0)	
	AND (ECS.EmployeeId = @rEmployeeId OR ISNULL(@rEmployeeId, 0) = 0)
	AND ECS.EmployeeId not in(select distinct ASD.SourceId from sSupport.tAssignSurveyMaster ASM inner join sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId where ASM.Id=@rAssignSurveyId and ASM.OrgId=@rOrgId)

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


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


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

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

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

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


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

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

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

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

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

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

END
GO
PRINT N'Altering Procedure [sWellness].[GetEmployeeMHIScoreDetail]...';


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

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

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

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


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


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


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


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

END
GO
PRINT N'Altering Procedure [sWellness].[pAppointmentWellnessSchedulingAdd]...';


GO

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


GO

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


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

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

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

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

   ISNULL(PM.Title, 'Not Assigned') AS ProgramName,
   CASE WHEN AP.ExaminationId IS NOT NULL THEN 
   'Completed'
   ELSE 
   'Pending'
   END AS Status,
   AP.ExaminationId as ConsultationId

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

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


GO
ALTER   Proc [sWellness].[PEmpDashboardDetailGet]  
@rEmpId bigint,  
@rOrgId int = 0  
as  
begin    
declare @lLatestVitalDisplayConfigVal varchar(5) = 'False';          
IF (@rOrgId > 0)  
BEGIN   
select @lLatestVitalDisplayConfigVal = sConfig.fConfigurationValueGet('Examination.LatestVitalDisplayOnDashboard',@rOrgId,0,0,0);  
END   

Declare @lHeight int =0,
        @lWeight decimal(8,2)=0,
		@lBMI decimal(8,2)=0,
		@lBloodPressureSystolic int=0,
		@lBloodPressureDiastolic int=0,
        @lHBA1C nvarchar(10)='0', 
		@lLDL nvarchar(10)='0',
		@lBMIDate nvarchar(20)='', 
		@lBPDate nvarchar(20)='', 
		@lHBA1CDate nvarchar(20)='', 
		@lLDLDate nvarchar(20)='';     
		
IF (@rEmpId > 0)
BEGIN

Select Top 1 @lHeight=Height,@lWeight=BodyWeight,@lBMI=BMI,@lBMIDate=convert(varchar(20),ExaminationDate,103)   
from sExamination.tExamination E   
inner join sExamination.tVital V on V.SourceId=E.Id  
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId    
inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId  
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95  
and Isnull(V.Height,0)>0 and Isnull(V.BodyWeight,0)>0 and Isnull(V.BMI,0)>0  
and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))  
Order by E.ExaminationDate desc;    


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


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


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

END

SELECT    
     'Ht : ' + Convert(varchar(10),Isnull(@lHeight,0)) + 'cm' as Height,   
	 'Wt : ' + Convert(varchar(10),Isnull(@lWeight,0)) + 'kg' as Weight,   
	 Isnull(@lHeight,0) as Height1,   
	 Isnull(@lWeight,0) as Weight1,   
	 Isnull(@lBMI,0) as BMI,   
	 convert(varchar(10),Isnull(@lBloodPressureSystolic,0)) + '/' + Convert(varchar(10),Isnull(@lBloodPressureDiastolic,0)) as BP,   
	 Isnull(@lHBA1C,'0') as HBA1C,   
	 Isnull(@lLDL,'0') as LDL,   
	 @lBMIDate as BMIDate,   
	 @lBPDate as BPDate,   
	 @lHBA1CDate as HBA1CDate,   
	 @lLDLDate as LDLDate;    
	 
EXEC [sWellness].[pGetEmployeeHealthIndex] @rEmpId , @lBMI ,@lBMIDate, @lBloodPressureSystolic , @lBloodPressureDiastolic ,@lBPDate, @lHBA1C ,@lHBA1CDate,  @lLDL, @lLDLDate;  
	 
END
GO
PRINT N'Altering Procedure [sWellness].[pGetCompletedHealthIndexEmployeeList]...';


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

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

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

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

        FROM sExamination.tExamination E

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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


GO
ALTER PROCEDURE [sWellness].[pListEmployeeConsultionHistory]    
(    
	@rEmployeeId BIGINT
)    
AS    
SET NOCOUNT ON    
BEGIN    
	SELECT 
		WC.ConsultationNumber,
		CASE WHEN WC.ConsultationDate IS NULL THEN '-' ELSE CONVERT(VARCHAR(15),WC.ConsultationDate,103) END AS ConsultationDate,
		EEM.DepartmentName AS DepartmentName,
		EEM2.EmployeePrefix + ' ' + EEM2.FirstName + ' ' + EEM2.LastName AS ConsultedBy
	FROM 
		[sWellness].[tWellnessConsultation] WC
	LEFT JOIN
		[sHrm].[vExtEmployeeMaster] EEM
	ON
		EEM.Id = WC.ParticipantSourceId
	LEFT JOIN
		[sHrm].[tEmployeeMaster] EEM2
	ON
		EEM2.Id = WC.DoctorEmployeeId
	WHERE
		ParticipantSourceId = @rEmployeeId
END
GO
PRINT N'Altering Procedure [sWellness].[pMHIScoreUpdationAddUpdate]...';


GO

ALTER PROCEDURE [sWellness].[pMHIScoreUpdationAddUpdate]
	@rId bigint=0,
	@rParticipantSourceTypeId smallint,
	@rParticipantSourceId bigint,
	@rBMI decimal(10,2),
	@rHBA1C decimal(10,2),
	@rLDL decimal(10,2),
	@rBPSystolic decimal(10,2),
	@rBPDiastolic decimal(10,2),
	@rStress decimal(10,2),
	@rLifeStyle decimal(10,2),
	@rUserId bigint
 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	BEGIN TRY

		--IF  EXISTS (SELECT 1 FROM [sWellness].[tMHIScoreUpdation] WHERE ParticipantSourceId = @rParticipantSourceId  and Id<>@rId)
		--BEGIN	 
		--	SELECT -102 AS RESULT
		--	return
		--END
		BEGIN TRAN
			DECLARE @lNextNumber BIGINT 
			IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScoreUpdation] WHERE ParticipantSourceId = @rParticipantSourceId and ParticipantSourceTypeId = @rParticipantSourceTypeId)
					BEGIN
					INSERT INTO [sWellness].[tMHIScoreUpdation]
							(
							ParticipantSourceTypeId,
							ParticipantSourceId,
							BMI,
							HBA1C,
							LDL,
							BPSystolic,
							BPDiastolic,
							Stress,
							LifeStyle,
							CreatedUserId,
							CreatedDateTime
							)
							values
							(
							@rParticipantSourceTypeId,
							@rParticipantSourceId,
							@rBMI,
							@rHBA1C,
							@rLDL,
							@rBPSystolic,
							@rBPDiastolic,
							@rStress,
							@rLifeStyle,
							@rUserId,
							sCommon.fGetDate()
							)
	                SET @lNextNumber = SCOPE_IDENTITY();
					END
			ELSE
				BEGIN
					--IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScoreUpdation] WHERE Id=@rId)
					--	BEGIN	 
					--		SELECT -101 AS RESULT
					--		return
					--	END
						Update [sWellness].[tMHIScoreUpdation]
							Set 
								BMI=@rBMI,
								HBA1C =@rHBA1C,
								LDL=@rLDL,
								BPSystolic=@rBPSystolic,
								BPDiastolic =@rBPDiastolic,
								Stress = @rStress,
								LifeStyle = @rLifeStyle,
								UpdatedUserId = @rUserId,
								UpdatedDateTime = sCommon.fGetDate()
							Where ParticipantSourceId=@rParticipantSourceId 
								  and ParticipantSourceTypeId = @rParticipantSourceTypeId

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

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


GO

ALTER PROCEDURE [sWellness].[pMobWellnessAppointmentListByDoctorId]
	@rDoctorEmployeeId Bigint,
	@rVisitPurposeId int=0,	
	@rOrgId Bigint,	
	@rFromDate Date,
	@rToDate Date,
	@rStatusId int=0,
	@rEmpCode nvarchar(50),
	@rStoreLocationId int=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
if @rStatusId=0
	SELECT A.Id,A.AppointmentNumber,A.DoctorEmployeeId,A.EmployeeCode,A.PatientName as EmployeeName,
		A.AppointmentDate,case when A.Timeslot is null then '' else A.Timeslot end as TimeSlot,A.StatusId,A.Status,A.AppointmentType,case when A.FollowupRemark is null then '' else A.FollowupRemark end as Remark,
		OMA.MeetingProviderId,case when OMA.MeetingProviderID=30 then 'Zoom' when OMA.MeetingProviderID=31 then 'Meet' when OMA.MeetingProviderID=32 then 'Teams' else '' end as MeetingProviderTitle,OMA.AccountName,OMA.AccountEmailId,OMA.AccountPassword,OMA.APIKey,OMA.APISecret,
		OMA.WebAPIKey,OMA.WebAPISecret,OMA.JWTToken,
		A.MeetingId,A.MeetingPassword,(select Count(*) from [sWellness].[tWellnessAppointmentDocuments] Where AppointmentId = A.Id) as DocumentCount
		,ISNULL(MainType,'') as MainType,A.FollowupRemark as Complaints,
		A.StoreLocation,CM.Title as VisitPurpose, A.CompliantRemark as AppointmentComplaints
	FROM [sWellness].[vMobExtPatientWellnessAppointmentDetail] A	
		left outer join sCommon.tOnlineMeetingAccount OMA on A.DoctorEmployeeId=OMA.EmployeeId
		LEFT JOIN sWellness.tWellnessVisitPurposeMaster CM on CM.Id = A.CauseId
	WHERE (A.DoctorEmployeeId=@rDoctorEmployeeId or A.DoctorEmployeeId = 0) and A.AppointmentDate >=@rFromDate 
		and A.AppointmentDate<=@rToDate
		and (A.CauseId=@rVisitPurposeId or isnull(@rVisitPurposeId,0)=0)
		AND (A.EmployeeCode = @rEmpCode OR ISNULL(@rEmpCode, '') = '')
		AND (A.StoreLocationId = @rStoreLocationId or isnull(@rStoreLocationId,0)=0)
	ORDER BY A.AppointmentDate DESC
else
	SELECT A.Id,A.AppointmentNumber,A.DoctorEmployeeId,A.EmployeeCode,A.PatientName as EmployeeName,
		A.AppointmentDate,case when A.Timeslot is null then '' else A.Timeslot end as TimeSlot,A.StatusId,A.Status,A.AppointmentType,case when A.FollowupRemark is null then '' else A.FollowupRemark end as Remark,
		OMA.MeetingProviderId,case when OMA.MeetingProviderID=30 then 'Zoom' when OMA.MeetingProviderID=31 then 'Meet' when OMA.MeetingProviderID=32 then 'Teams' else '' end as MeetingProviderTitle,OMA.AccountName,OMA.AccountEmailId,OMA.AccountPassword,OMA.APIKey,OMA.APISecret,
		OMA.WebAPIKey,OMA.WebAPISecret,OMA.JWTToken,
		A.MeetingId,A.MeetingPassword,(select Count(*) from [sWellness].[tWellnessAppointmentDocuments] Where AppointmentId = A.Id) as DocumentCount
		,ISNULL(MainType,'') as MainType,A.FollowupRemark as Complaints,
		A.StoreLocation,CM.Title as VisitPurpose
	FROM [sWellness].[vMobExtPatientWellnessAppointmentDetail] A	
		left outer join sCommon.tOnlineMeetingAccount OMA on A.DoctorEmployeeId=OMA.EmployeeId
		LEFT JOIN sWellness.tWellnessVisitPurposeMaster CM on CM.Id = A.CauseId
	WHERE (A.DoctorEmployeeId=@rDoctorEmployeeId or A.DoctorEmployeeId = 0) and A.OrgId=@rOrgId and A.AppointmentDate >=@rFromDate 
		and A.AppointmentDate<=@rToDate and A.StatusId=@rStatusId
		and (A.CauseId=@rVisitPurposeId or isnull(@rVisitPurposeId,0)=0)
		AND (A.EmployeeCode = @rEmpCode OR ISNULL(@rEmpCode, '') = '')  
		AND (A.StoreLocationId = @rStoreLocationId or isnull(@rStoreLocationId,0)=0)
	ORDER BY A.AppointmentDate DESC
END
GO
PRINT N'Altering Procedure [sWellness].[pMobWellnessAppointmentListGet]...';


GO

ALTER PROCEDURE [sWellness].[pMobWellnessAppointmentListGet] 
 @rEmployeeId Bigint,     
 @rOrgId int,    
 @rVisitPurposeId int=0,     
 @rStatusId int=0,    
 @rEmpCode nvarchar(50),    
 @rStoreLocationId int=0

WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
    
BEGIN    
SELECT    
 A.Id,A.AppointmentNumber,A.MainType,Setup as RoundType,    
 A.PatientName as EmployeeName,replace(A.Relation,'Ohter','Other') as Relation,    
 A.DoctorName,A.AppointmentDate,case when A.Timeslot is null then '' else A.Timeslot end as TimeSlot,    
 A.StatusId,A.Status,A.AppointmentType,case when A.MeetingId is null then '' else A.MeetingId end as MeetingId,
 case when A.MeetingPassword is null then '' else A.MeetingPassword end as MeetingPassword,A.IsCompleted,  
 A.IsMeetingStarted,IsMeetingCreated,OMA.MeetingProviderId,OMA.APIKey,OMA.APISecret,    
 OMA.WebAPIKey,OMA.WebAPISecret,A.FollowupRemark as Complaints, (select Count(*) from [sWellness].[tWellnessAppointmentDocuments] Where AppointmentId = A.Id) as DocumentCount ,
 A.StoreLocation,CM.Title as VisitPurpose , A.CompliantRemark as AppointmentComplaints
FROM [sWellness].[vMobExtPatientWellnessAppointmentDetail] A
 LEFT OUTER JOIN sCommon.tOnlineMeetingAccount OMA on A.DoctorEmployeeId=OMA.EmployeeId
 LEFT JOIN sWellness.tWellnessConsultation E ON A.ReferSourceId = E.Id
 LEFT JOIN sWellness.tWellnessVisitPurposeMaster CM on CM.Id = A.CauseId
WHERE (A.OrgId = @rOrgId)
 AND A.EmployeeCode=(select code from sHrm.tEmployeeMaster where Id=@rEmployeeId)
 AND IsNULL(E.IsCancel,0) = 0
 AND (A.StatusId=@rStatusId or ISNULL(@rStatusId,0)=0)
 AND (A.CauseId=@rVisitPurposeId or isnull(@rVisitPurposeId,0)=0)
 AND (A.EmployeeCode = @rEmpCode OR ISNULL(@rEmpCode, '') = '')
 AND (A.StoreLocationId = @rStoreLocationId or isnull(@rStoreLocationId,0)=0)
ORDER BY A.AppointmentNumber DESC
END
GO
PRINT N'Altering Procedure [sWellness].[pVisitPurposeMasterAddUpdate]...';


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

BEGIN
	
	BEGIN TRY

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

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

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

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

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


GO

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


GO

ALTER PROCEDURE [sWellness].[pWellnessConsultationList]
(
	@rOrgId INT,  
	@rSetupId INT, 
	@rConsultationNo VARCHAR(300) = NULL,
	@rDoctorId BIGINT = 0,
	@rFromDate DATETIME = null,
	@rToDate DATETIME = null,
	@rCode NVARCHAR (20),  
	@rName NVARCHAR(50),
	@rCaseCauseId INT,
	@rEmployeeTypeId INT,
	@rStatusId int = 0,
	@rStoreLocationId INT,	
	@rEmployeeId BIGINT = 0,
	@rProgramId BIGINT = 0,
	@SortColumnName NVARCHAR(MAX)= '',
	@IsAscendingOrder BIT= 0,
	@PageNumber INT = 1,
	@PageSize INT = 20,
	@GlobalSearch NVARCHAR(MAX)= ''
)
AS
SET NOCOUNT ON
BEGIN
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rName = sCommon.fSearchStringGet(@rName)
	
	SET @rFromDate = ISNULL (@rFromDate, '')
	SET @rToDate = ISNULL (@rToDate, '')

	
	;WITH PageNumbers AS(
	select 
	ROW_NUMBER() OVER(
			ORDER BY CASE WHEN @SortColumnName = 'ConsultationNumber' AND @IsAscendingOrder = 0 THEN t.ConsultationNumber END DESC,
					 CASE WHEN @SortColumnName = 'ConsultationNumber' AND @IsAscendingOrder = 1 THEN t.ConsultationNumber END,
					 CASE WHEN @SortColumnName = 'ParticipantCode' AND @IsAscendingOrder = 0 THEN t.ParticipantCode END DESC,
					 CASE WHEN @SortColumnName = 'ParticipantCode' AND @IsAscendingOrder = 1 THEN t.ParticipantCode END,
					 CASE WHEN @SortColumnName = 'ParticipantName' AND @IsAscendingOrder = 0 THEN t.ParticipantName END DESC,
					 CASE WHEN @SortColumnName = 'ParticipantName' AND @IsAscendingOrder = 1 THEN t.ParticipantName END,
					 CASE WHEN @SortColumnName = 'CreatedUserName' AND @IsAscendingOrder = 0 THEN t.CreatedUserName END DESC,
					 CASE WHEN @SortColumnName = 'CreatedUserName' AND @IsAscendingOrder = 1 THEN t.CreatedUserName END,
					 CASE WHEN @SortColumnName = 'CauseName' AND @IsAscendingOrder = 0 THEN t.CauseName END DESC,
					 CASE WHEN @SortColumnName = 'CauseName' AND @IsAscendingOrder = 1 THEN t.CauseName END,
					 CASE WHEN @SortColumnName = '' THEN t.Id END DESC
	) PageId,
	COUNT(*) OVER() 'RecordCount',
	* from (
		SELECT 
			Cons.Id as Id,
			Cons.ConsultationNumber,
			Cons.ConsultationDate,
			CONVERT(VARCHAR,Cons.ConsultationDate,103) AS  ConsultationDateStr,
			ISNULL(PM.Title,'Not Applicable') AS ProgramName,
			Cons.CauseId,
			ISNULL(WVPM.Title,'-') AS CauseName,
			SM.RoundNumber,	
			SM.Title AS Setup,
			EM.Code AS ParticipantCode,
		    EM.FirstName + ' ' + EM.LastName AS ParticipantName,
			[Status] = SS.Title,
			ODP.Title AS Department,
			StoreLocation = SLM.Title,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id = Cons.CreatedUserId) as CreatedUserName,
			ISNULL(EM1.FirstName,'') + ' ' + ISNULL( EM1.LastName,'') as DoctorName,
			ISNULL(ETM.Title,'-') AS EmployeeTypeName,
			ISNULL(PM.Id,-2) AS ProgramId
		FROM
			[sWellness].[tWellnessConsultation] Cons
		LEFT JOIN 
			[sHrm].[tEmployeeMaster] EM on Cons.ParticipantSourceId = EM.Id and Cons.ParticipantSourceTypeId = 95
		LEFT JOIN 
			[sExamination].[tStatusMaster] SS on Cons.StatusId = SS.Id
		LEFT JOIN 
			[sHrm].[tEmployeeMaster] EM1 ON EM1.Id=Cons.DoctorEmployeeId
		LEFT JOIN 
			[sSecurity].[tUser] Users on Users.Id = Cons.CreatedUserId
		INNER JOIN 
			[sWellness].[tWellnessVisitPurposeMaster] WVPM on WVPM.Id = Cons.CauseId
		INNER JOIN 
			[sExamination].[tSetupMaster] SM on Cons.SetupId = SM.Id
		INNER JOIN 
			[sExamination].[tSubTypeMaster] ST on SM.SubTypeId = ST.Id
		INNER JOIN 
			[sIp].[tStoreLocationMaster] SLM on SLM.Id = Cons.StoreLocationId
		INNER JOIN
			[sHrm].[tEmployeeJobDetail] EJD ON EJD.EmployeeId = EM.Id
		LEFT JOIN
			[sCommon].[tOrganizationDepartmentMaster] ODP ON ODP.Id = EJD.OrganizationDepartmentId
		LEFT JOIN
			[sHrm].[tEmployeeTypeMaster] ETM ON ETM.Id = EJD.EmployeeTypeId	
		LEFT JOIN	
			[sWellness].[tMHIScore] MHI  ON MHI.EmployeeId = Cons.ParticipantSourceId
		LEFT JOIN
			[sWellness].[tProgramMaster] PM ON PM.Id = MHI.ProgramId
		WHERE 
			Cons.OrgId = @rOrgId	
		AND 
			ISNULL(Cons.IsCancel,0) = 0
		AND 
			(EM.Code LIKE @rCode + '%')    
		AND 
			(EM.FirstName LIKE @rName + '%'OR @rName = '')			
		AND 
			((Cons.SetupId = @rSetupId) OR (@rSetupId = 0))
		AND 
			((EM.StatusId = @rStatusId) OR (@rStatusId = 0) OR (@rStatusId = -1))
		AND 
			(Cons.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)
		AND 
			((Cons.ConsultationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND 
			((Cons.ConsultationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))		
		AND
			((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = -1))
		AND 
			(Cons.CauseId = @rCaseCauseId OR @rCaseCauseId = 0 OR @rCaseCauseId = -1)
		AND 
			(Cons.DoctorEmployeeId = @rDoctorId OR @rDoctorId = 0)
		AND 
			(Cons.ConsultationNumber LIKE '%' + @rConsultationNo OR ISNULL(@rConsultationNo,'')='')
	)
		t where ((t.ProgramId = @rProgramId) OR (@rProgramId = -1)) 
	AND
		(ISNULL(@GlobalSearch,'') = '' 
	OR 
		ISNULL(t.ConsultationDate,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
	OR 
		ISNULL(t.ParticipantCode,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
	OR 
		ISNULL(t.ParticipantName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
	OR 
		ISNULL(t.CreatedUserName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
	OR 
		ISNULL(t.CauseName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%')
	)
	SELECT  *
	FROM    PageNumbers
	WHERE  (@PageSize = -1 OR PageId  BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize))
END
GO
PRINT N'Altering Procedure [sWellness].[pWellnessConsultationRemove]...';


GO

ALTER PROCEDURE [sWellness].[pWellnessConsultationRemove]
	@rSourceId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION	   
		DELETE FROM sWellness.tWellnessConsultation Where Id = @rSourceId	   
		DELETE FROM sWellness.tGeneralTemplateConsultationDetail Where GeneralTemplateConsultationId IN
		(
			select Id from sWellness.tGeneralTemplateConsultation where SourceId = @rSourceId
		)
		DELETE FROM sWellness.tGeneralTemplateConsultation Where SourceId = @rSourceId
		DELETE FROM sWellness.tConsultationTestRequestDetail Where TestRequestId IN
		(
			select Id from sWellness.tConsultationTestRequest where SourceId = @rSourceId
		)
		DELETE FROM sWellness.tConsultationTestRequest Where SourceId = @rSourceId
		DELETE FROM sWellness.tAssignedActivity Where ConsultationId = @rSourceId
		DELETE FROM sWellness.tConsultationAdditionalFieldDetails Where AdditionalFieldId IN
		(
			select Id from sWellness.tConsultationAdditionalFieldMaster where ConsultationId = @rSourceId
		)
		DELETE FROM sWellness.tConsultationAdditionalFieldMaster where ConsultationId = @rSourceId
		DELETE FROM sWellness.tConsultationRemarkLog where ConsultationId = @rSourceId
		
		update sWellness.tAppointment set ExaminationId=0 where ExaminationId=@rSourceId

		SELECT 1 AS Result	   
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Creating Procedure [sCommon].[pGetAllEmployeeOfLocation]...';


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


GO

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


GO

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


GO
  
CREATE PROCEDURE [sWellness].[GetConsultationDocumentsById]
@rConsultationId bigint,      
@rOrgId int     
AS      
BEGIN

 select HD.Id,STM.MainTypeId,MT.Title as MainType,SM.Title as SetupMaster, Code ,isnull(FirstName,'') + ' ' + isnull(LastName,'') as FullName,FileName,
	'../../../Content/' + convert(varchar,@rOrgId) + '/WellnessConsultationDocuments/'   
			+ convert(varchar,HD.ConsultationId) + '/' + FileName as FilePath,
	SM.Id as SetupMasterId,isnull(hd.ConsultationId,0) as ConsultationId, HD.ConfigId  
 from sWellness.tConsultationDocuments HD
 INNER JOIN sWellness.tWellnessConsultation WC ON WC.Id = HD.ConsultationId
 INNER JOIN sHrm.tEmployeeMaster EM on WC.ParticipantSourceId = EM.id and WC.ParticipantSourceTypeId = 95
 INNER JOIN sExamination.tSetupMaster SM on WC.SetupId = SM.id
 INNER JOIN sExamination.tSubTypeMaster STM on STM.Id = SM.SubTypeId
 INNER JOIN sExamination.tMainTypeMaster MT on STM.MainTypeId = MT.Id
 Where WC.Id = @rConsultationId AND WC.OrgId = @rOrgId

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


GO
CREATE PROCEDURE [sWellness].[pAddOrUpdateMHIUpdationBulk]
( 
    @rUserId BIGINT,
    @rEmployeeMHIBulkList [sWellness].[udt_MHIScoreUpdation] READONLY,
    @Result INT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ModifiedRows INT = 0;

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

    WHEN MATCHED THEN
        UPDATE SET
            T.BMI = S.BMI,
            T.HBA1C = S.HBA1C,
            T.LDL = S.LDL,
            T.BPSystolic = S.SystolicBP,
            T.BPDiastolic = S.DiastolicBP,
            T.Stress = S.Stress,
            T.LifeStyle = S.LifeStyle,
            T.UpdatedUserId = @rUserId,
            T.UpdatedDateTime = sCommon.fGetDate()

    WHEN NOT MATCHED THEN
        INSERT
        (
            ParticipantSourceTypeId,
            ParticipantSourceId,
            BMI,
            HBA1C,
            LDL,
            BPSystolic,
            BPDiastolic,
            Stress,
            LifeStyle,
            CreatedUserId,
            CreatedDateTime
        )
        VALUES
        (
            95,
            S.ParticipantSourceId,
            S.BMI,
            S.HBA1C,
            S.LDL,
            S.SystolicBP,
            S.DiastolicBP,
            S.Stress,
            S.LifeStyle,
            @rUserId,
            sCommon.fGetDate()
        );

    SET @ModifiedRows = @@ROWCOUNT;
    SET @Result = @ModifiedRows;
END
GO
PRINT N'Creating Procedure [sWellness].[pAddOrUpdateProgramMHIScoreBulk]...';


GO
CREATE PROCEDURE [sWellness].[pAddOrUpdateProgramMHIScoreBulk]
(
      @rOrgId SMALLINT
    , @rUserId BIGINT
    , @rMHIScoreList [sWellness].[udt_MHIScoreUpdateBulk] READONLY
    , @InsertedCount INT OUTPUT
    , @UpdatedCount INT OUTPUT
    , @SkippedEmployeeCodeCount INT OUTPUT
    , @TotalProcessed INT OUTPUT
)
AS
BEGIN

SET NOCOUNT ON;

BEGIN TRY
BEGIN TRANSACTION;

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

------------------------------------------------
-- Parameter ranges
------------------------------------------------
SELECT
      HIPM.StaticHealthIndexParameterId
    , HIPD.FromValue
    , HIPD.ToValue
    , CASE
        WHEN HIPD.Points = 10 THEN 1
        WHEN HIPD.Points = 6 THEN 2
        WHEN HIPD.Points = 3 THEN 3
        ELSE HIPD.Points
      END Score
    , HIPD.DiagnosisRemark Category
    , HIPD.GenderId
INTO #TempParameterRange
FROM sExamination.tHealthIndexParameterMaster HIPM
JOIN sExamination.tHealthIndexParameterDetail HIPD
ON HIPD.HealthIndexParameterId = HIPM.Id
WHERE HIPM.StaticHealthIndexParameterId IN (1,2,5,17,23);

------------------------------------------------
-- Map EmployeeCode → EmployeeId
------------------------------------------------
SELECT
      EM.EmployeeId
    , EM.GenderId
    , S.BMI
    , S.SystolicBP
    , S.DiastolicBP
    , S.HBA1C
    , S.LDL
    , S.Stress
    , S.LifeStyle
INTO #InputData
FROM @rMHIScoreList S
JOIN sHrm.vExtEmployeeMaster EM
ON EM.Code = S.EmployeeCode;

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

------------------------------------------------
-- Score calculation
------------------------------------------------
SELECT
      I.*
    , BMI.Score BMIScore
    , BMI.Category BMICategory
    , HBA1C.Score HBA1CScore
    , HBA1C.Category HBA1CCategory
    , LDL.Score LDLScore
    , LDL.Category LDLCategory
    , CASE WHEN SYS.Score > DIA.Score THEN SYS.Score ELSE DIA.Score END BPScore
    , CASE WHEN I.Stress >= 90 THEN 1 WHEN I.Stress >= 75 THEN 2 ELSE 3 END StressScore
    , CASE WHEN I.LifeStyle <=49 THEN 3 WHEN I.LifeStyle <=70 THEN 2 ELSE 1 END LifestyleScore
INTO #Calculated
FROM #InputData I

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=1
AND I.BMI BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) BMI

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=2
AND I.HBA1C BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) HBA1C

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=5
AND I.LDL BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) LDL

OUTER APPLY
(
SELECT TOP 1 Score
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=23
AND I.SystolicBP BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) SYS

OUTER APPLY
(
SELECT TOP 1 Score
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=17
AND I.DiastolicBP BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) DIA;

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

UPDATE #Calculated
SET Biometrics =
(100.0*(ISNULL(BMIScore,0)+ISNULL(HBA1CScore,0)+ISNULL(LDLScore,0)+ISNULL(BPScore,0)))/4;

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

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

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

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

------------------------------------------------
-- Program assignment
------------------------------------------------
UPDATE C
SET ProgramId = PM.Id
FROM #Calculated C
JOIN sWellness.tStaticMHICategoryIndicator I
ON I.Id=C.MHICategoryId
JOIN sWellness.tProgramMaster PM
ON PM.MHIIndicatorId=I.Id
AND PM.CategoryId=1
AND PM.IsObsolete=0;

------------------------------------------------
-- UPDATE existing rows
------------------------------------------------
UPDATE T
SET
BMI=C.BMI,
BMIScore=C.BMIScore,
BMICategory=C.BMICategory,

HBA1C=C.HBA1C,
HBA1CScore=C.HBA1CScore,
HBA1CCategory=C.HBA1CCategory,

LDL=C.LDL,
LDLScore=C.LDLScore,
LDLCategory=C.LDLCategory,

BP=CAST(C.SystolicBP AS VARCHAR(10))+'/'+CAST(C.DiastolicBP AS VARCHAR(10)),
BPScore=C.BPScore,
BPCategory=CASE C.BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' ELSE 'Alert' END,

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

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

Biometrics=C.Biometrics,
BiometricsCategory=C.BiometricsCategory,

SurveyCategory=C.SurveyCategory,
MHICategory=C.MHICategory,
MHICategoryId=C.MHICategoryId,

ProgramId=C.ProgramId,

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

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

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

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

OPEN curInsert;
FETCH NEXT FROM curInsert INTO @EmployeeId;

WHILE @@FETCH_STATUS=0
BEGIN

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

INSERT INTO sWellness.tMHIScore
(
Id,OrgId,ProgramId,EmployeeId,EmployeeSourceTypeId,LastUpdateType,
HBA1C,HBA1CScore,HBA1CCategory,
LDL,LDLScore,LDLCategory,
BMI,BMIScore,BMICategory,
BP,BPScore,BPCategory,
Stress,StressScore,StressCategory,
Lifestyle,LifestyleScore,LifestyleCategory,
Biometrics,BiometricsCategory,
SurveyCategory,MHICategory,MHICategoryId,
CreatedUserId,CreatedDatetime
)
SELECT
@NextId,@rOrgId,C.ProgramId,C.EmployeeId,95,4,
C.HBA1C,C.HBA1CScore,C.HBA1CCategory,
C.LDL,C.LDLScore,C.LDLCategory,
C.BMI,C.BMIScore,C.BMICategory,
CAST(C.SystolicBP AS VARCHAR(10))+'/'+CAST(C.DiastolicBP AS VARCHAR(10)),
C.BPScore,
CASE C.BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' ELSE 'Alert' END,
C.Stress,C.StressScore,
CASE C.StressScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' ELSE 'Alert' END,
C.LifeStyle,C.LifestyleScore,
CASE C.LifestyleScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' ELSE 'Alert' END,
C.Biometrics,C.BiometricsCategory,
C.SurveyCategory,C.MHICategory,C.MHICategoryId,
@rUserId,sCommon.fGetDate()
FROM #Calculated C
WHERE C.EmployeeId=@EmployeeId;

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

FETCH NEXT FROM curInsert INTO @EmployeeId;
END

CLOSE curInsert;
DEALLOCATE curInsert;

------------------------------------------------
-- History
------------------------------------------------
DECLARE @EmpId BIGINT;

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

OPEN curHistory;
FETCH NEXT FROM curHistory INTO @EmpId;

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

FETCH NEXT FROM curHistory INTO @EmpId;
END

CLOSE curHistory;
DEALLOCATE curHistory;

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

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

COMMIT TRANSACTION;

END TRY
BEGIN CATCH

IF @@TRANCOUNT>0 ROLLBACK TRANSACTION;

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

SELECT ERROR_MESSAGE() ErrorMessage,ERROR_LINE() ErrorLine;

END CATCH

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


GO

CREATE PROCEDURE [sWellness].[pConsultationAddOrUpdateProgramMHIScore]
@rConsultationId bigint,
@rParticipantSourceTypeId int,
@rOrgId int,
@rUserId bigint
AS
BEGIN
BEGIN TRY 
	DECLARE @rEmployeeId bigint;
	DECLARE @strBMI NVARCHAR(10), @strBPSys NVARCHAR(10), @strBPDia NVARCHAR(10), @strHBA1C NVARCHAR(10), @strLDL NVARCHAR(10);
	DECLARE @rBMI DECIMAL(10,2), @rBPSys DECIMAL(10,2), @rBPDia DECIMAL(10,2), @rHBA1C DECIMAL(10,2), @rLDL DECIMAL(10,2);
	DECLARE @rStress NUMERIC, @rLifestyle NUMERIC;

	set @rEmployeeId = (select ParticipantSourceId from sWellness.tWellnessConsultation where Id = @rConsultationId);
	select @rStress=Stress, @rLifestyle=Lifestyle from [sWellness].[tMHIScore] 
	where EmployeeId = @rEmployeeId and EmployeeSourceTypeId = @rParticipantSourceTypeId;

	set @strBMI = (select GTCD.ParameterValue from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 503)

	set @strBPSys = (select GTCD.ParameterValue from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 506)

	set @strBPDia = (select GTCD.ParameterValue from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 507)

	set @strHBA1C = (select CTRD.ServiceValue from sWellness.tConsultationTestRequest CTR 
	INNER JOIN sWellness.tConsultationTestRequestDetail CTRD ON CTRD.TestRequestId = CTR.Id
	INNER JOIN sOrderEntry.tTestDetail TD ON TD.Id = CTRD.TestDetailId
	INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
	where SourceId = @rConsultationId and TPM.StaticTestParameterId = 25)

	set @strLDL = (select CTRD.ServiceValue from sWellness.tConsultationTestRequest CTR 
	INNER JOIN sWellness.tConsultationTestRequestDetail CTRD ON CTRD.TestRequestId = CTR.Id
	INNER JOIN sOrderEntry.tTestDetail TD ON TD.Id = CTRD.TestDetailId
	INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
	where SourceId = @rConsultationId and TPM.StaticTestParameterId = 34)

	IF (@strBMI = '')
	BEGIN
		set @rBMI = (select BMI from [sWellness].[tMHIScore] where EmployeeId = @rEmployeeId and EmployeeSourceTypeId = @rParticipantSourceTypeId);
	END
	ELSE
	BEGIN
		set @rBMI = CAST(@strBMI AS DECIMAL(10,2))
	END
	IF (@strBPSys = '')
	BEGIN
		set @rBPSys = (select LEFT(BP, CHARINDEX('/', BP) - 1) from [sWellness].[tMHIScore] where EmployeeId = @rEmployeeId and EmployeeSourceTypeId = @rParticipantSourceTypeId);
	END
	ELSE
	BEGIN
		set @rBPSys = CAST(@strBPSys AS DECIMAL(10,2))
	END
	IF (@strBPDia = '')
	BEGIN
		set @rBPDia = (select SUBSTRING(BP, CHARINDEX('/', BP) + 1, LEN(BP)) from [sWellness].[tMHIScore] where EmployeeId = @rEmployeeId and EmployeeSourceTypeId = @rParticipantSourceTypeId);
	END
	ELSE
	BEGIN
		set @rBPDia = CAST(@strBPDia AS DECIMAL(10,2))
	END
	IF (@strHBA1C = '')
	BEGIN
		set @rHBA1C = (select HBA1C from [sWellness].[tMHIScore] where EmployeeId = @rEmployeeId and EmployeeSourceTypeId = @rParticipantSourceTypeId);
	END
	ELSE
	BEGIN
		set @rHBA1C = CAST(@strHBA1C AS DECIMAL(10,2))
	END
	IF (@strLDL = '')
	BEGIN
		set @rLDL = (select LDL from [sWellness].[tMHIScore] where EmployeeId = @rEmployeeId and EmployeeSourceTypeId = @rParticipantSourceTypeId);
	END
	ELSE
	BEGIN
		set @rLDL = CAST(@strLDL AS DECIMAL(10,2))
	END

	DECLARE @Result TABLE (Result NVARCHAR(20)); 
	DECLARE @Result2 TABLE (Result2 NVARCHAR(20));

	INSERT INTO @Result
	EXECUTE [sWellness].[pAddOrUpdateProgramMHIScoreNew] @rOrgId, @rEmployeeId, @rParticipantSourceTypeId, 1, 
			@rBMI, @rBPSys, @rBPDia, @rHBA1C, @rLDL, @rStress, @rLifestyle, @rUserId;

	IF EXISTS (SELECT 1 FROM @Result WHERE Result = '-1')
	BEGIN
		;THROW 50001, 'Error occurred in pAddOrUpdateProgramMHIScoreNew', 1
	END
	ELSE
	BEGIN
		INSERT INTO @Result2
		EXECUTE [sWellness].[pMHIScoreUpdationAddUpdate] 0, @rParticipantSourceTypeId, @rEmployeeId,
				@rBMI, @rHBA1C, @rLDL, @rBPSys, @rBPDia, @rStress, @rLifestyle, @rUserId;

		IF EXISTS (SELECT 1 FROM @Result2 WHERE Result2 = '-1')
		BEGIN
			;THROW 50002, 'Error occurred in pMHIScoreUpdationAddUpdate', 1
		END
		ELSE
		BEGIN
			SELECT 1 AS Result;
		END
	END
	
END TRY
BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION

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


GO

CREATE 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,'N/A') AS DepartmentName,
	EJD.OrganizationDepartmentId,
	ParticipantCode = EM.Code,
	ParticipantName = EM.FirstName + ' ' + isnull(EM.LastName,''),
	GenderId = PD.GenderId,
	Gender = ISNULL(GM.Title,'Not Known'),
	Isnull(CM.Id,0) As CauseId,
	isnull(CM.Title,'N/A') As CauseName,
	ISNULL(ETM.Title,'NA') AS ParticipantType,
	ParticipantSourceTypeId,
	CASE 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,
	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 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.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 sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId  
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM on ETM.Id = EJD.EmployeeTypeId
	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.DoctorEmployeeId = @rDoctorId) OR (@rDoctorId = 0))
	AND ((CM.Id = @rCauseId) OR (@rCauseId = -1))
	AND ((ED.StoreLocationId = @rStoreLocationId)OR @rStoreLocationId=0)
	AND
	(
		(EM.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 95)
		OR @rEmployeeCode = ''
	)
	AND (EJD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 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 * from #TempTable
	DROP TABLE #TempTable
END
GO
PRINT N'Creating Procedure [sWellness].[pGetConsultationFullViewDatas]...';


GO

CREATE PROCEDURE [sWellness].[pGetConsultationFullViewDatas] 
@rConsultationId bigint
as
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
	select EM.Code as EmployeeCode, ISNULL(EM.FirstName, '') + '' + ISNULL(EM.LastName, '') as EmployeeName, WC.ConsultationNumber 
	from sWellness.tWellnessConsultation WC
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = WC.ParticipantSourceId and WC.ParticipantSourceTypeId = 95
	where WC.Id = @rConsultationId

	declare @tbltmpview table(tid int identity(1,1),col1 varchar(max),col2 varchar(max))	
	insert into @tbltmpview
	select 'Height',Convert(varchar(50),GTCD.ParameterValue) + ' Cm'	
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 502
	OPTION (RECOMPILE)

	insert into @tbltmpview
	select 'Weight',Convert(varchar(50),GTCD.ParameterValue) + ' Cm'	
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 501
	OPTION (RECOMPILE)

	insert into @tbltmpview			
	select 'BMI',Convert(varchar(50),GTCD.ParameterValue) + ' kg/m2'
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 503
	OPTION (RECOMPILE)

	insert into @tbltmpview			
	select 'BPSys',Convert(varchar(50),GTCD.ParameterValue) + ' mmHg'
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 506
	OPTION (RECOMPILE)

	insert into @tbltmpview
	select 'BPDia',Convert(varchar(50),GTCD.ParameterValue) + ' mmHg'
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 507
	OPTION (RECOMPILE)

	select col1 as Parameter, col2 as [Value] from @tbltmpview
	OPTION (RECOMPILE)

	SELECT TP.Title as Parameter,TRD.ServiceValue as Result,TRD.Remark as Remark
	FROM sWellness.tConsultationTestRequestDetail TRD
	INNER JOIN sWellness.tConsultationTestRequest 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 = @rConsultationId AND TP.IsObsolete = 0
	OPTION (RECOMPILE)

	SELECT 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 [WeekNo],
	CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN 'Custom' ELSE 'Pre Define' END AS [Type],
	WAC.Title as [WellnessActivityCategory], WA.ActivityName as [WellnessActivity],
	CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN ISNULL(AA.WellnessActivityCustom,'') 
        ELSE ISNULL(WAT.[Name],'') END as [WellnessActivityTask],
		CAST(ISNULL(AA.TargetValue, 0) AS NVARCHAR(50)) AS [TargetValue],
 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 Frequency,
 CAST(AA.FrequencyCount AS NVARCHAR(50)) AS [FrequencyCount],
 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 ConsultationId = @rConsultationId
	OPTION (RECOMPILE)

	SELECT Isnull(INS.FieldRemark,'') as Questions,
			convert(varchar,ISNULL(AFF.AdditionalFieldResponse,'')) as Answers 
	from sExamination.tAdditionalFieldSetup InS
	LEFT JOIN [sWellness].[tConsultationAdditionalFieldDetails] AFF ON InS.Id= AFF.AdditionalFieldSetupId --and (@rSourceId <> 0 OR (@rSourceId = 0 and Isnull([AdditionalFieldId],0)=0))
	Where ISNULL(InS.SourceTypeId, 0) = 3 and ISNULL(InS.ExaminationTypeId, 0) = 17
	AND (Isnull([AdditionalFieldId],0) = (Select Top 1 Id from [sWellness].[tConsultationAdditionalFieldMaster] where ConsultationId = @rConsultationId))
	ORDER BY FieldOrder
	OPTION (RECOMPILE)

	SELECT Isnull(WC.ConsultationNotes,'') as ConsultationNotes,
			Isnull(WC.ConsultationRemarks,'') as ConsultationRemarks 
	from sWellness.tWellnessConsultation WC
	Where WC.Id = @rConsultationId

	OPTION (RECOMPILE)
	SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
END
GO
PRINT N'Creating Procedure [sWellness].[pGetMHIParameterGraph]...';


GO
CREATE PROCEDURE [sWellness].[pGetMHIParameterGraph]
(
    @rEmployeeId BIGINT,
    @rOrgId SMALLINT,
    @rParameterId SMALLINT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @FromDate DATETIME = DATEADD(YEAR, -1, GETDATE());

    ;WITH BaseData AS
    (
        SELECT 
            HistoryId,
            EmployeeId,
            OrgId,
            ActionDateTime,

            CASE 
                WHEN @rParameterId = 1 THEN CAST(BMI AS VARCHAR(20))
                WHEN @rParameterId = 2 THEN CAST(HBA1C AS VARCHAR(20))
                WHEN @rParameterId = 3 THEN CAST(LDL AS VARCHAR(20))
                WHEN @rParameterId IN (4,5) THEN BP
            END AS RawValue

        FROM [sWellness].[tMHIScore_History]
        WHERE EmployeeId = @rEmployeeId
            AND OrgId = @rOrgId
            AND ActionDateTime >= @FromDate
    ),

    ParsedData AS
    (
        SELECT 
            HistoryId,
            EmployeeId,
            OrgId,
            ActionDateTime,
            CASE 
                WHEN @rParameterId = 4 
                     AND CHARINDEX('/', RawValue) > 0 THEN 
                    TRY_CAST(
                        SUBSTRING(RawValue, CHARINDEX('/', RawValue) + 1, 10)
                    AS DECIMAL(10,2))
                WHEN @rParameterId = 5 
                     AND CHARINDEX('/', RawValue) > 0 THEN 
                    TRY_CAST(
                        LEFT(RawValue, CHARINDEX('/', RawValue) - 1)
                    AS DECIMAL(10,2))
                WHEN @rParameterId IN (1,2,3) THEN 
                    TRY_CAST(RawValue AS DECIMAL(10,2))
                ELSE NULL
            END AS Value
        FROM BaseData
        WHERE RawValue IS NOT NULL
    ),
    CleanData AS
    (
        SELECT *
        FROM ParsedData
        WHERE Value IS NOT NULL   -- remove invalid / bad data
    ),
    Deduplicated AS
    (
        SELECT *,
            ROW_NUMBER() OVER (PARTITION BY Value ORDER BY ActionDateTime DESC) AS rn
        FROM CleanData
    )
    SELECT
        '-' AS SetupName,
        Value,
        CONVERT(VARCHAR, ActionDateTime, 103) AS ExaminationDate,
        MIN(Value) OVER() AS Y1,
        MAX(Value) OVER() AS Y2,
        NULL AS NormalMinimum,
        NULL AS NormalMaximum,
        MIN(ActionDateTime) OVER() AS X1,
        MAX(ActionDateTime) OVER() AS X2,
        1 AS Xinterval,
        10 AS Yinterval,
        '' AS LowerLimitText,
        '' AS UpperLimitText
    FROM Deduplicated
    WHERE rn = 1   
    ORDER BY ActionDateTime ASC;
END
GO
PRINT N'Creating Procedure [sWellness].[pGetMHIProgramHistoryGraph]...';


GO
CREATE PROCEDURE [sWellness].[pGetMHIProgramHistoryGraph]
(
    @rEmployeeId BIGINT,
    @rOrgId SMALLINT
)
AS
BEGIN

	SET NOCOUNT ON;

	DECLARE @FromDate DATETIME = DATEADD(YEAR, -1, GETDATE());

	;WITH BaseData AS
	(
		SELECT 
			MHICategory,
			HistoryId,
			EmployeeId,
			OrgId,
			ActionDateTime,
			CAST(MHICategoryId AS DECIMAL(10,2)) AS Value
		FROM [sWellness].[tMHIScore_History]
		WHERE EmployeeId = @rEmployeeId
			AND OrgId = @rOrgId
			AND ActionDateTime >= @FromDate
			AND MHICategoryId IS NOT NULL
	),
	Deduplicated AS
	(
		SELECT *,
			ROW_NUMBER() OVER (
				PARTITION BY Value, ActionDateTime
				ORDER BY HistoryId DESC
			) AS rn
		FROM BaseData
	)

	SELECT
		MHICategory AS SetupName,
		Value,
		CONVERT(VARCHAR, ActionDateTime, 103) AS ExaminationDate,
		MIN(Value) OVER() AS Y1,
		MAX(Value) OVER() AS Y2,
		NULL AS NormalMinimum,
		NULL AS NormalMaximum,
		MIN(ActionDateTime) OVER() AS X1,
		MAX(ActionDateTime) OVER() AS X2,
		1 AS Xinterval,
		1 AS Yinterval,
		'' AS LowerLimitText,
		'' AS UpperLimitText
	FROM 
		Deduplicated
	WHERE 
		rn = 1
	ORDER BY 
		ActionDateTime 
	ASC;
END
GO
PRINT N'Creating Procedure [sWellness].[pGetWellnessCoachList]...';


GO
CREATE PROCEDURE [sWellness].[pGetWellnessCoachList]
(
	@rContextKey VARCHAR(500),
	@rf int,
	@rorgid int,
	@rStoreLocationId int
)
AS
BEGIN
	SELECT TOP 5 
		DM.Id,
		EM.FirstName +' '+ EM.LastName AS code
		FROM
		[sCwb].[tDoctorMaster] DM 
	INNER JOIN
		[sHrm].[tEmployeeMaster] EM
	ON
		EM.Id = DM.EmployeeId
	WHERE
		EM.OrgId = @rorgid 
	AND 
		((EM.FirstName like '%' + @rContextKey + '%') OR (EM.LastName like '%' + @rContextKey + '%') OR (EM.Code like '%' + @rContextKey + '%'))
	AND
		DM.IsWellness = 1
END
GO
PRINT N'Creating Procedure [sWellness].[pLastExaminationConsultationHeight]...';


GO

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

	 IF (ISNULL(@rHeight,'') = '')
	 BEGIN
		 set @rHeight = (select Top 1 CAST(ISNULL(V.Height,'') AS NVARCHAR(10)) AS Height FROM sExamination.tExamination E 
		 LEFT JOIN sExamination.tVital V ON V.SourceId = E.Id
		 where E.ParticipantSourceId = @rParticipantSourceId and E.ParticipantSourceTypeId = 95
		 and E.SetupId <> [sCommon].[fGetIntIdForOrg](8, @rOrgId)
		 and Isnull(Height,0) > 0
		 order by E.id desc)
	 END

	 select @rHeight as Height;
end
GO
PRINT N'Creating Procedure [sWellness].[pMobEmployeeConsultationListGet]...';


GO
CREATE   PROCEDURE [sWellness].[pMobEmployeeConsultationListGet]
@rEmployeeId bigint
AS
BEGIN
	select  E.Id as ConsultationId,E.SetupId as SetupId,convert(varchar,E.ConsultationDate,106) as ConsultationDate,
	        E.StoreLocationId, M.Code, ISNULL(M.FirstName, '') + ' ' + ISNULL(M.LastName, '') AS EmployeeName,
			ST.Id as  SubType ,Isnull(ConsultationNumber,'') as ConsultationNumber , STM.Title as StoreLocationTitle
			from sHrm.tEmployeeMaster  M
			inner join sWellness.tWellnessConsultation E
				  on M.Id = E.ParticipantSourceId AND ParticipantSourceTypeId = 95
			inner join sExamination.tSetupMaster S on E.SetupId = S.Id
			INNER JOIN sExamination.tSubTypeMaster ST ON S.SubTypeId = ST.Id 	
			inner join sIp.tStoreLocationMaster STM on E.StoreLocationId = STM.Id
			where M.Id = @rEmployeeId and ST.MainTypeId = 17
			AND IsNULL(E.IsCancel,0) = 0	
			order by  E.ConsultationDate  desc
END
GO
PRINT N'Creating Procedure [sWellness].[pMobGetEmployeeConsultationViewDatas]...';


GO

CREATE PROCEDURE [sWellness].[pMobGetEmployeeConsultationViewDatas]
@rConsultationId bigint
as
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
begin
	declare @lOrgId int
	declare @lVitalRes varchar(max)='',@lTestRes varchar(max)='',@lTaskRes varchar(max)='',
			@lAdditionalFieldRes varchar(max)='',@lNotesRes varchar(max)=''
	declare @lVitalHead varchar(max)='',@lTestHead varchar(max)='',@lTaskHead varchar(max)='',
			@lAdditionalFieldHead varchar(max)='',@lNotesHead varchar(max)=''

	select @lOrgId = OrgId from sWellness.tWellnessConsultation where Id = @rConsultationId	

	declare @tbltmpview table(tid int identity(1,1),col1 varchar(max),col2 varchar(max))	
	insert into @tbltmpview
	select 'Height',Convert(varchar(50),GTCD.ParameterValue) + ' Cm'	
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 502
	OPTION (RECOMPILE)

	insert into @tbltmpview
	select 'Weight',Convert(varchar(50),GTCD.ParameterValue) + ' Cm'	
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 501
	OPTION (RECOMPILE)

	insert into @tbltmpview			
	select 'BMI',Convert(varchar(50),GTCD.ParameterValue) + ' kg/m2'
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 503
	OPTION (RECOMPILE)

	insert into @tbltmpview			
	select 'BPSys',Convert(varchar(50),GTCD.ParameterValue) + ' mmHg'
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 506
	OPTION (RECOMPILE)

	insert into @tbltmpview
	select 'BPDia',Convert(varchar(50),GTCD.ParameterValue) + ' mmHg'
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 507
	OPTION (RECOMPILE)

	select @lVitalHead = @lVitalHead + '<div class="contentHolder box-body box-solid gridviewfont" style=" padding: 10px;background: #fff;border-radius: 5px;margin: 10px;">
	<div class="himsBoxHeader"><div class="leftdiv"> </div><div class="himsBoxTitle pTop5" style="padding: 10px 0px;">
    <div class="headerText"><div class="fLeft"> <span style="color:#7eacd3;font-weight:bold;font-size: 30px;">Vital</span> </div></div>
    <div class="fRight"></div></div></div><div class="himsBoxContent"><div>
    <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse; border: 0px solid; font-size: 30px;">
    <tbody><tr><th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Parameter</span></th>
	<th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"><span>Value</span></th></tr>'
	OPTION (RECOMPILE)

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

	select @lVitalRes = @lVitalRes + '</tbody></table></div></div></div>'
	select @lVitalRes = @lVitalHead + @lVitalRes
	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 sWellness.tConsultationTestRequestDetail TRD
	INNER JOIN sWellness.tConsultationTestRequest 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 = @rConsultationId AND TP.IsObsolete = 0
	OPTION (RECOMPILE)

	select @lTestHead = @lTestHead + '<div class="contentHolder box-body box-solid gridviewfont" style=" padding: 10px;background: #fff;border-radius: 5px;margin: 10px;">
    <div class="himsBoxHeader"><div class="leftdiv"> </div><div class="himsBoxTitle pTop5" style="padding: 10px 0px;">
    <div class="headerText"><div class="fLeft"> <span style="color:#7eacd3;font-weight:bold;font-size: 30px;">Test</span></div>
    </div><div class="fRight"></div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse; border: 0px solid; font-size: 30px;">
	<tbody><tr><th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Parameter</span></th>
	<th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"><span>Result</span></th>
	<th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"><span>Remark</span></th></tr>'
	OPTION (RECOMPILE)

	select @lTestRes = @lTestRes + '<tr>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col1,'') + '" class="boxEllips" style="display:inline-block;">' + isnull(col1,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col2,'') + '" class="boxEllips" style="display:inline-block;">' + isnull(col2,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col3,'') + '" class="boxEllips" style="display:inline-block;">' + isnull(col3,'') + '</span> </td>			
	</tr>' from @tbltmptest
	OPTION (RECOMPILE)

	select @lTestRes = @lTestRes + '</tbody></table></div></div></div>'
	select @lTestRes = @lTestHead + @lTestRes
	OPTION (RECOMPILE)

	declare @tbltmpTask table(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max)
									,col4 varchar(max),col5 varchar(max),col6 varchar(max),col7 varchar(max),col8 varchar(max)
									,col9 varchar(max),col10 varchar(max))
	insert into @tbltmpTask
	SELECT 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 WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN 'Custom' ELSE 'Pre Define' END AS TypeName,
	WAC.Title,WA.ActivityName,CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN ISNULL(AA.WellnessActivityCustom,'') 
        ELSE ISNULL(WAT.[Name],'') END as WellnessActivityTask,
		ISNULL(AA.TargetValue, 0) as TargetValue,
 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,
 AA.FrequencyCount,
 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 ConsultationId = @rConsultationId
	OPTION (RECOMPILE)

	select @lTaskHead = @lTaskHead + '<div class="contentHolder box-body box-solid gridviewfont" style=" padding: 10px;background: #fff;border-radius: 5px;margin: 10px;">
	<div class="himsBoxHeader"><div class="leftdiv"> </div><div class="himsBoxTitle pTop5" style="padding: 10px 0px;">
	<div class="headerText"><div class="fLeft"> <span style="color:#7eacd3;font-weight:bold;font-size: 30px;">Tasks</span> </div>
	</div><div class="fRight"></div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div>
   <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse; border: 0px solid; font-size: 30px;">
   <tbody><tr><th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Week No</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Type</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Wellness Activity Category</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Wellness Activity</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Wellness Activity Task</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Target Value</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Unit</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Frequency</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Frequency Count</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Status</span></th></tr>'
	OPTION (RECOMPILE)

	select @lTaskRes = @lTaskRes + '<tr>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col1,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col1,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col2,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col2,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col3,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col3,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col4,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col4,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col5,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col5,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col6,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col6,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col7,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col7,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col8,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col8,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col9,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col9,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col10,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col10,'') + '</span> </td>
	</tr>' from @tbltmpTask
	OPTION (RECOMPILE)

	select @lTaskRes = @lTaskRes + '</tbody></table></div></div></div>'
	select @lTaskRes = @lTaskHead + @lTaskRes
	OPTION (RECOMPILE)

	declare @tbltmpAdditionalField table(tid int identity(1,1),col1 varchar(max),col2 varchar(max))
	insert into @tbltmpAdditionalField
	SELECT Isnull(INS.FieldRemark,'') as FieldRemark,
			convert(varchar,ISNULL(AFF.AdditionalFieldResponse,'')) as AdditionalFieldResponse 
	from sExamination.tAdditionalFieldSetup InS
	LEFT JOIN [sWellness].[tConsultationAdditionalFieldDetails] AFF ON InS.Id= AFF.AdditionalFieldSetupId --and (@rSourceId <> 0 OR (@rSourceId = 0 and Isnull([AdditionalFieldId],0)=0))
	Where ISNULL(InS.SourceTypeId, 0) = 3 and ISNULL(InS.ExaminationTypeId, 0) = 17
	AND (Isnull([AdditionalFieldId],0) = (Select Top 1 Id from [sWellness].[tConsultationAdditionalFieldMaster] where ConsultationId = @rConsultationId))
	ORDER BY FieldOrder
	OPTION (RECOMPILE)

	select @lAdditionalFieldHead = @lAdditionalFieldHead + '<div class="contentHolder box-body box-solid gridviewfont" style=" padding: 10px;background: #fff;border-radius: 5px;margin: 10px;">
    <div class="himsBoxHeader"><div class="leftdiv"> </div><div class="himsBoxTitle pTop5" style="padding: 10px 0px;"><div class="headerText">
    <div class="fLeft"> <span style="color:#7eacd3;font-weight:bold;font-size: 30px;">Q & A</span> </div></div><div class="fRight"></div></div></div>
    <div class="himsBoxContent"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse; border: 0px solid; font-size: 30px;">
	<tbody><tr><th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Questions</span></th>
    <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Answers</span></th></tr>'
	OPTION (RECOMPILE)

	select @lAdditionalFieldRes = @lAdditionalFieldRes + '<tr>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col1,'') + '" class="boxEllips">' + isnull(col1,'') + '</span> </td>	
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col2,'') + '" class="boxEllips">' + isnull(col2,'') + '</span> </td>
	</tr>' from @tbltmpAdditionalField
	OPTION (RECOMPILE)

	select @lAdditionalFieldRes = @lAdditionalFieldRes + '</tbody></table></div></div></div>'
	select @lAdditionalFieldRes = @lAdditionalFieldHead + @lAdditionalFieldRes

	declare @tbltmpNotes table(tid int identity(1,1),col1 varchar(max),col2 varchar(max))
	insert into @tbltmpNotes
	SELECT Isnull(WC.ConsultationNotes,'') as ConsultationNotes,
			Isnull(WC.ConsultationRemarks,'') as ConsultationRemarks 
	from sWellness.tWellnessConsultation WC
	Where WC.Id = @rConsultationId
	OPTION (RECOMPILE)

	select @lNotesHead = @lNotesHead + '<div class="contentHolder box-body box-solid gridviewfont" style=" padding: 10px;background: #fff;border-radius: 5px;margin: 10px;">
    <div class="himsBoxHeader"><div class="leftdiv"> </div><div class="himsBoxTitle pTop5" style="padding: 10px 0px;"><div class="headerText">
    <div class="fLeft"> <span style="color:#7eacd3;font-weight:bold;font-size: 30px;">Notes</span> </div></div><div class="fRight"></div></div></div>
    <div class="himsBoxContent"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse; border: 0px solid; font-size: 30px;">
	<tbody><tr><th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Consultation Notes</span></th>
    <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Consultation Remarks</span></th></tr>'
	OPTION (RECOMPILE)

	select @lNotesRes = @lNotesRes + '<tr>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col1,'') + '" class="boxEllips">' + isnull(col1,'') + '</span> </td>	
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col2,'') + '" class="boxEllips">' + isnull(col2,'') + '</span> </td>
	</tr>' from @tbltmpNotes
	OPTION (RECOMPILE)

	select @lNotesRes = @lNotesRes + '</tbody></table></div></div></div>'
	select @lNotesRes = @lNotesHead + @lNotesRes
	OPTION (RECOMPILE)

	select '<HTML>
   <HEAD>
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <STYLE>
         @media (max-width: 767px) {
         /* .himsBoxContent{
         overflow-x: auto;
         } */
         .table {
         font-size: 10px !important;
         }
         .fLeft span {
         font-size: 12px !important;
         }
         .boxEllips {
         width: unset !important;
         white-space: normal;
         }
         .table th,
         .table td {
         padding: 5px !important;
         }
         }
      </STYLE>
   </HEAD><body style="font-family: sans-serif;background-color: #e9e9e9;">' + isnull(@lVitalRes,'') + isnull(@lTestRes,'') 
   + isnull(@lTaskRes,'') + isnull(@lAdditionalFieldRes,'') + isnull(@lNotesRes,'') + '</body></HTML>'as Res

	OPTION (RECOMPILE)
	SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
end
GO
PRINT N'Creating Procedure [sWellness].[pSaveRemarkConsultation]...';


GO

CREATE PROCEDURE [sWellness].[pSaveRemarkConsultation]
@rId bigint,
@rRemark nvarchar(500),
@rCreatedUserId bigint,
@rTypeId smallint
as
BEGIN
		IF(@rTypeId = 1)	
		BEGIN
				INSERT INTO [sWellness].[tConsultationRemarkLog]
				(
					ConsultationId,
					Remark,
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime
				)
				VALUES
				(
					@rId,                -- ConsultationId
					@rRemark,            -- Remark
					@rCreatedUserId,     -- CreatedUserId
					sCommon.fGetDate(),  -- CreatedDateTime
					NULL,                -- UpdatedUserId
					NULL                 -- UpdatedDateTime
				);
		END

		select ERL.Remark, ERL.CreatedDateTime, U.DisplayTitle 
		from [sWellness].[tConsultationRemarkLog] ERL 
		inner join sSecurity.tUser U on u.Id = ERL.CreatedUserId  
		where ConsultationId = @rId
END
GO
PRINT N'Refreshing Procedure [sExamination].[pOPDCustomSearchGenerateReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDCustomSearchGenerateReport]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetAdditionalFieldExaminationOPD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetAdditionalFieldExaminationOPD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindFeildList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindFeildList]';


GO
PRINT N'Refreshing Procedure [sWellness].[pActivityCategoryMasterDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pActivityCategoryMasterDelete]';


GO
PRINT N'Refreshing Procedure [sWellness].[pActivityCategoryMasterGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pActivityCategoryMasterGet]';


GO
PRINT N'Refreshing Procedure [sWellness].[pActivityCategoryMasterGetList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pActivityCategoryMasterGetList]';


GO
PRINT N'Refreshing Procedure [sWellness].[pActivityMasterGetList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pActivityMasterGetList]';


GO
PRINT N'Refreshing Procedure [sWellness].[pConsultationLoadAllDropDownLists]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pConsultationLoadAllDropDownLists]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetActivityCategoryList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetActivityCategoryList]';


GO
PRINT N'Refreshing Procedure [sWellness].[pListAssignedEmployeeTask]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pListAssignedEmployeeTask]';


GO
PRINT N'Refreshing Procedure [sWellness].[pActivityDashboardDetailGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pActivityDashboardDetailGet]';


GO
PRINT N'Refreshing Procedure [sWellness].[pActivityMasterDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pActivityMasterDelete]';


GO
PRINT N'Refreshing Procedure [sWellness].[pActivityMasterGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pActivityMasterGet]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetWellnessActivityDropdownList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetWellnessActivityDropdownList]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetWellnessActivityTaskMasterById]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetWellnessActivityTaskMasterById]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetWellnessActivityTaskMasterList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetWellnessActivityTaskMasterList]';


GO
PRINT N'Refreshing Procedure [sWellness].[pEmpDailyTaskDetailsGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pEmpDailyTaskDetailsGet]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetNonAdherenceTaskList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetNonAdherenceTaskList]';


GO
PRINT N'Refreshing Procedure [sWellness].[pWellnessActivityTaskMasterDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pWellnessActivityTaskMasterDelete]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetWellnessAppointmentSchedulingList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetWellnessAppointmentSchedulingList]';

GO

UPDATE sSecurity.tTask
SET ModuleId=197
WHERE Id=21069 ;
 
UPDATE sSecurity.tScreen
SET ScreenGroupId=220
WHERE Id=20921 ;

GO


ALTER PROCEDURE [sExamination].[pHealthAnalysisEmployeeParameterGetWithPagination]
	@rMaINTypeId INT,
	@rOrgId INT,
	@rSetupGroupId INT,
	@rSetupId INT,
	@rHealthIndicatorId INT,
	@rSectorId INT,
	@rVerticalId INT,
	@rCompanyGroupId INT,
	@rEmployeeCompanyId INT,
	@rLocationMainGroupId INT,
	@rLocationSubGroupId INT,
	@rLocationId INT,
	@rStoreLocationId INT,
	@rFunctionId INT,
	@rDepartmentGroupId INT,
	@rDepartmentId INT,
	@PageIndex INT,
	@rEmployeeCode VARCHAR(100),
	@rEmployeeFname VARCHAR(100),
	@rEmployeeLname VARCHAR(100),
	@rFromPercentage DEcimal(10,2),
	@rToPercentage DEcimal(10,2),
	@rHealthIndexParameterId NVARCHAR(MAX),
	@rUserId bigint,
	@rFromDate varchar(100) = '',
	@rToDate varchar(100) = '',
	@rGenderId int = 0,
	@rGradeId int = 0,
	@rEmployeeTypeGoupId int = 0,
	@rEmployeeTypeId int = 0,
	@rEmployeeSubTypeId int = 0,

	@SortColumnName NVARCHAR(MAX)= '',
	@IsAscendingOrder bit= 0,
	@PageNumber int = 1,
	@PageSize int = 20,
	@GlobalSearch NVARCHAR(MAX)= ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SET @rEmployeeFname = sCommon.fSearchStringGet(@rEmployeeFname)
	SET @rEmployeeLname = sCommon.fSearchStringGet(@rEmployeeLname)

	IF(@rToDate='')
	BEGIN
		SET @rToDate='01/06/2050'
	END
	select @rFromDate = CONVERT(VARCHAR(10), CONVERT(date, @rFromDate, 105), 23)
	select @rToDate = CONVERT(VARCHAR(10), CONVERT(date, @rToDate, 105), 23)

	DECLARE @EmployeeCode nVarchar(100)=''
	 
	Select Distinct EXM.ID,EXM.SetupId,EXM.ParticipantSourceId,EXM.EmployeeCompanyId,EXM.StoreLocationId,
	EXM.OrganizationDepartmentId,EXM.ParticipantSourceTypeId,EXM.OrgId,EXM.ExaminationDate,EXM.GradeId
	 INto #tmp 
	FROM sExamination.tExamination AS EXM
	INNER JOIN sExamination.tHealthIndex AS HI ON HI.ExaminationId=EXM.Id
	INNER JOIN [sExamination].[tHealthIndexParameterMaster] AS HIP ON HIP.ID = HI.HealthIndexParameterId	
	INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId
	INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId
	INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId
	INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID
	INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD on EMP.Id = EPD.EmployeeId	
	LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=EXM.EmployeeCompanyId
	LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId
	LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId
	LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId
	LEFT JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId
	LEFT JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId
	LEFT JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId
	LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId
	LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId
	LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId
	LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId
	LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId
	LEFT JOIN sHrm.tGradeMaster GRD on EJD.GradeId = GRD.Id
	INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	CROSS APPLY (
			SELECT TOP 1 HIM.Id
			FROM sExamination.tHealthIndicatorMaster AS HIM
			WHERE (HI.EarnedPoints * 100.0 / NULLIF(HI.TotalPoints,0)) > HIM.RangeFrom
			  AND (HI.EarnedPoints * 100.0 / NULLIF(HI.TotalPoints,0)) <= HIM.RangeTo
		) AS HIA
	WHERE EXM.ParticipantSourceTypeId=95 AND EXM.OrgId=@rOrgId
	AND HI.TotalPoints>0 AND SSM.MaINTypeId=@rMaINTypeId
	--AND (((SELECT Id FROM [sExamination].[tHealthIndicatorMaster] WHERE RangeTo >=CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))
	--AND CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))>RangeFrom) =@rHealthIndicatorId) OR (@rHealthIndicatorId=0))
	AND (HIA.Id = @rHealthIndicatorId OR @rHealthIndicatorId=0)
	AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))
	AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))
	AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))
	AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))
	AND ((HIP.ID in ((select Item from dbo.fSplitStr(@rHealthIndexParameterId,',') where Item <> ''))) OR (@rHealthIndexParameterId=''))
	AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))
	AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))
	AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))
	AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))
	AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))
	AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((EMP.Code = @rEmployeeCode) OR (@rEmployeeCode  = ''))
	AND ((EMP.FirstName LIKE @rEmployeeFname)  OR  (@rEmployeeFname = ''))
	AND ((EMP.LastName  LIKE @rEmployeeLname)  OR  (@rEmployeeLname = ''))
	AND ((CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints))) >= @rFromPercentage) OR (@rFromPercentage = -1))
	AND ((CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints))) <= @rToPercentage) OR (@rToPercentage = -1))
	AND ((LSG.Id=@rLocationSubGroupId ) OR (@rLocationSubGroupId  = 0 ))
	AND ((LMG.Id=@rLocationMainGroupId) OR (@rLocationMainGroupId = 0 ))
	AND UL.UserId = @rUserId 
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0 or @rFromDate = '')
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 or @rToDate ='')
	AND (EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0) -- Nidhi Pandey; Mantis id = 22911, DT - 16/01/2023
	--select * from #tmp
	select TR.ID As TestRequestId,TR.TestId,T.ID As ExaminationId
	into #tmp1
	From sExamination.tTestRequest TR
	    inner join #tmp as T On T.ID = TR.SourceID 		
		
	--mantis id 0047676
	select Distinct TRD.ServiceValue,T1.ExaminationId,   CASE 
        WHEN STPM.UCode = 'DIABETIC_FBS' THEN 'DIABETIC'
        ELSE STPM.UCode
    END AS UCode,TRD.Diagnosis
	into #tmp2
	from sExamination.tTestRequestDetail TRD
	inner join #tmp1 T1 On T1.TestRequestId=TRD.TestRequestId
	inner join sOrderEntry.tTestMaster TM on T1.TestId = TM.Id
	inner join sOrderEntry.tTestDetail TD on TM.Id = TD.TestId and TRD.TestDetailId = TD.Id
	inner join sOrderEntry.tTestParameterMaster TPM on TD.TestParameterId = TPM.Id
	inner join sOrderEntry.tStaticTestParameterMaster STPM on TPM.StaticTestParameterId = STPM.Id

	UNION ALL

	-- Mantis:51206, Dummy record if DIABETIC / DIABETIC_FBS not present
	SELECT 
    '' AS ServiceValue,
    X.ExaminationId,
    'DIABETIC' AS UCode,
    '' AS Diagnosis
	FROM (
		SELECT DISTINCT ExaminationId
		FROM #tmp1
	) X
	WHERE NOT EXISTS (
		SELECT 1
		FROM sExamination.tTestRequestDetail TRD
		INNER JOIN sExamination.tTestRequest TR 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
		INNER JOIN sOrderEntry.tStaticTestParameterMaster STPM ON TPM.StaticTestParameterId = STPM.Id
		WHERE TR.SourceId = X.ExaminationId
		  AND STPM.UCode IN ('DIABETIC_FBS','DIABETIC')
	);

	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
	print @configval
	-- changes as per mentis issue no:12021 - 2020-07-08 (Rahul,Raju sir,das sir) discussion
	if(@configval='Priority')
		begin
			update t set t.ServiceValue=(case when Isnull(t2.ServiceValue,'')!='' 
											--and Isnull(t3.ServiceValue,'')='' 
											then t2.ServiceValue
											when Isnull(t.ServiceValue,'')!='' then t.ServiceValue
											when Isnull(t3.ServiceValue,'')!='' then t3.ServiceValue
											 else t1.ServiceValue end)
			From #tmp2 as t
			left join #tmp2 as t1 on t1.ExaminationId=t.ExaminationId and t1.UCode='DIABETIC_RBS'
			left join #tmp2 as t2 on t2.ExaminationId=t.ExaminationId and t2.UCode='DIABETIC_HBA1C'
			left join #tmp2 as t3 on t3.ExaminationId=t.ExaminationId and t3.UCode='DIABETIC_PPBS'
			Where t.UCode='DIABETIC' --rand Isnull(t.ServiceValue,'')=''
		end
	else if(@configval='Priority Abnormal')
		begin
			update t set t.ServiceValue=(case when Isnull(t2.Diagnosis,'')='Diabetic' 											
											then t2.ServiceValue
											when Isnull(t.Diagnosis,'')='Diabetic' 
											then t.ServiceValue
											when Isnull(t3.Diagnosis,'')='Diabetic' 
											then t3.ServiceValue 
											when Isnull(t1.Diagnosis,'')='Diabetic' 
											then t1.ServiceValue
											
											when Isnull(t2.Diagnosis,'')='Pre Diabetic' 											
											then t2.ServiceValue
											when Isnull(t.Diagnosis,'')='Pre Diabetic' 
											then t.ServiceValue
											when Isnull(t3.Diagnosis,'')='Pre Diabetic' 
											then t3.ServiceValue
											when Isnull(t1.Diagnosis,'')='Pre Diabetic' 
											then t1.ServiceValue											
											 else t.ServiceValue end)
			From #tmp2 as t
			left join #tmp2 as t1 on t1.ExaminationId=t.ExaminationId and t1.UCode='DIABETIC_RBS'
			left join #tmp2 as t2 on t2.ExaminationId=t.ExaminationId and t2.UCode='DIABETIC_HBA1C'
			left join #tmp2 as t3 on t3.ExaminationId=t.ExaminationId and t3.UCode='DIABETIC_PPBS'
			Where t.UCode='DIABETIC' 

		end
	--select * from #tmp2 order by UCode

	DECLARE @TableOne TABLE
	(
		tid int identity(1,1),EmployeeCode NVARCHAR(250),EmployeeName NVARCHAR(250),TotalPoints NVARCHAR(100),
		EarnedPoints NVARCHAR(100),Percentage NVARCHAR(100),IndicatorName NVARCHAR(250),SetupName varchar(100),
		SubLocation varchar(50),HealthIndexParameter varchar(50),FromValue varchar(50),ToValue varchar(50),
		EarnedValue varchar(50),ParamterTypeId int,GradeTitle varchar(300),StorelocationId int, ColorCode nvarchar(50)
	)
	INSERT INTO @TableOne
	SELECT isnull(EMP.Code,''),
	UPPER(ISNULL(EMP.FirstName,'')+' '+ISNULL(EMP.LastName,'')),
	TotalPoints,
	EarnedPoints,
	CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints))) AS Percentage,
	(SELECT (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) FROM [sExamination].[tHealthIndicatorMaster] WHERE RangeTo >=CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))
	AND CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))>RangeFrom) AS IndicatorName,
	STM.Title,
	SLM.Title,
	HIP.Title,
	(select top 1 FromValue from [sExamination].[tHealthIndexParameterDetail] where HealthIndexParameterId = HIP.Id and EarnedPoints = HI.EarnedPoints
	and GenderId = EPD.GenderId and Points=10),
	(select top 1 ToValue from [sExamination].[tHealthIndexParameterDetail] where HealthIndexParameterId = HIP.Id and EarnedPoints = HI.EarnedPoints
	and GenderId = EPD.GenderId and Points=10),
	CASE WHEN HIP.HealthIndexParameterTypeId = 1 and HIP.Title = 'BMI' then
	(select convert(varchar,BMI) from sExamination.tVital where SourceId = EXM.Id)
	WHEN HIP.HealthIndexParameterTypeId = 1 and HIP.Title = 'Blood Pressure Systolic' then
	(select convert(varchar,BloodPressureSystolic) from sExamination.tVital where SourceId = EXM.Id)
	WHEN HIP.HealthIndexParameterTypeId = 1 and HIP.Title = 'Blood Pressure Diastolic' then
	(select convert(varchar,BloodPressureDiastolic) from sExamination.tVital where SourceId = EXM.Id)
	--WHEN HIP.HealthIndexParameterTypeId = 2 or HIP.HealthIndexParameterTypeId = 3 then (Select ISNULL(TRD.ServiceValue,'') From #tmp2 as TRD Where TRD.ExaminationId=EXM.Id and TRD.UCode=(Case WHEN HIP.Title = 'DIABETIC' THEN 'DIABETIC_FBS' ELSE HIP.Title END))
    WHEN HIP.HealthIndexParameterTypeId IN (2, 3) THEN     ISNULL(TRD.ServiceValue,'')
	WHEN HIP.HealthIndexParameterTypeId = 13 and HIP.Title = 'Audiometry' then
	(select convert(varchar,ARM.Title) from sExamination.tAudiometry AUD
	INNER JOIN sExamination.tAudiometryResultMaster ARM ON ARM.Id = CASE WHEN AUD.AudiometryAcResultLeftId > AUD.AudiometryAcResultRightId 
																   THEN AUD.AudiometryAcResultLeftId ELSE AUD.AudiometryAcResultRightId END
	where SourceId = EXM.Id)
	WHEN HIP.HealthIndexParameterTypeId = 14 and HIP.Title = 'Pulmonary' then
	(select LTRIM(RTRIM(ISNULL(PulmonaryResulIntensity,'') + ' ' + ISNULL(PulmonaryResult,''))) from sExamination.tPulmonary where SourceId = EXM.Id)
	else '' end,
	HIP.HealthIndexParameterTypeId,isnull(GRD.Title,''),
	SLM.Id,
	(SELECT ColorCode FROM [sExamination].[tHealthIndicatorMaster] WHERE RangeTo >=CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))
	AND CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))>RangeFrom) AS ColorCode
	FROM #tmp AS EXM
	--INNER JOin #tmp E On E.id=EXM.id
	INNER JOIN sExamination.tHealthIndex AS HI ON HI.ExaminationId=EXM.Id
	INNER JOIN [sExamination].[tHealthIndexParameterMaster] AS HIP ON HIP.ID = HI.HealthIndexParameterId	
	INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId
	INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId
	INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId
	INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID
	INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD on EMP.Id = EPD.EmployeeId	
	LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=EXM.EmployeeCompanyId
	LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId
	LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId
	LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId
	LEFT JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId
	LEFT JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId
	LEFT JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId
	LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId
	LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId
	LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId
	LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId
	LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId
	LEFT JOIN sHrm.tGradeMaster GRD on EJD.GradeId = GRD.Id
	LEFT JOIN #tmp2 TRD ON TRD.ExaminationId = EXM.Id AND TRD.UCode = HIP.Title
	INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId=95 AND EXM.OrgId=@rOrgId
	AND HI.TotalPoints>0 AND SSM.MaINTypeId=@rMaINTypeId
	AND (((SELECT Id FROM [sExamination].[tHealthIndicatorMaster] WHERE RangeTo >=CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))
	AND CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))>RangeFrom) =@rHealthIndicatorId) OR (@rHealthIndicatorId=0))
	AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))
	AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))
	AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))
	AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))
	AND ((HIP.ID in ((select Item from dbo.fSplitStr(@rHealthIndexParameterId,',') where Item <> ''))) OR (@rHealthIndexParameterId=''))
	AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))
	AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))
	AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))
	AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))
	AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))
	AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((EMP.Code = @rEmployeeCode) OR (@rEmployeeCode  = ''))
	AND ((EMP.FirstName LIKE @rEmployeeFname)  OR  (@rEmployeeFname = ''))
	AND ((EMP.LastName  LIKE @rEmployeeLname)  OR  (@rEmployeeLname = ''))
	AND ((CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints))) >= @rFromPercentage) OR (@rFromPercentage = -1))
	AND ((CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints))) <= @rToPercentage) OR (@rToPercentage = -1))
	AND ((LSG.Id=@rLocationSubGroupId ) OR (@rLocationSubGroupId  = 0 ))
	AND ((LMG.Id=@rLocationMainGroupId) OR (@rLocationMainGroupId = 0 ))
	AND ((EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)) -- Nidhi Pandey; Mantis id = 22911, DT - 16/01/2023
	AND UL.UserId = @rUserId
	--AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0 or @rFromDate = '')
	--AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 or @rToDate ='') 
	ORDER BY EMP.ID,HI.HealthIndexParameterId
	OPTION(RECOMPILE)


  
	
	;WITH PageNumbers AS(
	select 
	 ROW_NUMBER() OVER(
			ORDER BY CASE WHEN @SortColumnName = 'SrNo' AND @IsAscendingOrder = 0 THEN isnull(CONVERT(varchar,tid),'') END DESC,
					 CASE WHEN @SortColumnName = 'SrNo' AND @IsAscendingOrder = 1 THEN isnull(CONVERT(varchar,tid),'') END,
					 CASE WHEN @SortColumnName = 'Code' AND @IsAscendingOrder = 0 THEN isnull(EmployeeCode,'') END DESC,
					 CASE WHEN @SortColumnName = 'Code' AND @IsAscendingOrder = 1 THEN isnull(EmployeeCode,'') END,
					 CASE WHEN @SortColumnName = 'Employee' AND @IsAscendingOrder = 0 THEN isnull(EmployeeName,'') END DESC,
					 CASE WHEN @SortColumnName = 'Employee' AND @IsAscendingOrder = 1 THEN isnull(EmployeeName,'') END,
					 CASE WHEN @SortColumnName = 'Grade' AND @IsAscendingOrder = 0 THEN isnull(GradeTitle,'') END DESC,
					 CASE WHEN @SortColumnName = 'Grade' AND @IsAscendingOrder = 1 THEN isnull(GradeTitle,'') END,
					 CASE WHEN @SortColumnName = 'SetupName' AND @IsAscendingOrder = 0 THEN isnull(SetupName,'') END DESC,
					 CASE WHEN @SortColumnName = 'SetupName' AND @IsAscendingOrder = 1 THEN isnull(SetupName,'') END,
					 CASE WHEN @SortColumnName = 'SubLocation' AND @IsAscendingOrder = 0 THEN isnull(SubLocation,'') END DESC,
					 CASE WHEN @SortColumnName = 'SubLocation' AND @IsAscendingOrder = 1 THEN isnull(SubLocation,'') END,
					 CASE WHEN @SortColumnName = 'HealthIndexParameter' AND @IsAscendingOrder = 0 THEN isnull(HealthIndexParameter,'') END DESC,
					 CASE WHEN @SortColumnName = 'HealthIndexParameter' AND @IsAscendingOrder = 1 THEN isnull(HealthIndexParameter,'') END,
					 CASE WHEN @SortColumnName = 'TotalPoints' AND @IsAscendingOrder = 0 THEN ISNULL(TotalPoints,'') END DESC,
					 CASE WHEN @SortColumnName = 'TotalPoints' AND @IsAscendingOrder = 1 THEN ISNULL(TotalPoints,'') END,
					 CASE WHEN @SortColumnName = 'EarnedPoints' AND @IsAscendingOrder = 0 THEN ISNULL(EarnedPoints,'') END DESC,
					 CASE WHEN @SortColumnName = 'EarnedPoints' AND @IsAscendingOrder = 1 THEN ISNULL(EarnedPoints,'') END,
					 CASE WHEN @SortColumnName = 'Value' AND @IsAscendingOrder = 0 THEN ISNULL(EarnedValue,'') END DESC,
					 CASE WHEN @SortColumnName = 'Value' AND @IsAscendingOrder = 1 THEN ISNULL(EarnedValue,'') END,
					 CASE WHEN @SortColumnName = 'Range' AND @IsAscendingOrder = 0 THEN '(' + FromValue + ' - ' + ToValue + ')' END DESC,
					 CASE WHEN @SortColumnName = 'Range' AND @IsAscendingOrder = 1 THEN '(' + FromValue + ' - ' + ToValue + ')' END,
					 CASE WHEN @SortColumnName = 'Percentage' AND @IsAscendingOrder = 0 THEN ISNULL(Percentage,'') END DESC,
					 CASE WHEN @SortColumnName = 'Percentage' AND @IsAscendingOrder = 1 THEN ISNULL(Percentage,'') END,
					 CASE WHEN @SortColumnName = 'Indicator' AND @IsAscendingOrder = 0 THEN ISNULL(IndicatorName,'') END DESC,
					 CASE WHEN @SortColumnName = 'Indicator' AND @IsAscendingOrder = 1 THEN ISNULL(IndicatorName,'') END,
					 CASE WHEN @SortColumnName = '' THEN tid END
	  ) ID,
	 COUNT(*) OVER() 'RecordCount',
	 isnull(CONVERT(varchar,tid),'') 'SrNo',
	 isnull(EmployeeCode,'') 'Code',
	 isnull(EmployeeName,'') 'Employee',
	 isnull(GradeTitle,'') 'Grade',
	 isnull(SetupName,'') 'SetupName',
	 isnull(SubLocation,'') 'SubLocation',
	 isnull(HealthIndexParameter,'') 'HealthIndexParameter',
	 isnull(TotalPoints ,'') 'TotalPoints',
	 isnull(EarnedPoints,'') 'EarnedPoints',
	 isnull(EarnedValue,'') 'EarnedValue',
	 '(' + FromValue + ' - ' + ToValue + ')' 'Range',
	 isnull(Percentage,'') 'Percentage',
	 isnull(IndicatorName ,'') 'Indicator',
	 isnull(ColorCode, '') ColorCode
	from @TableOne 
	WHERE (ISNULL(@GlobalSearch,'') = '' OR isnull(CONVERT(varchar,tid),'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(EmployeeCode,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(EmployeeName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(GradeTitle,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(SetupName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(SubLocation,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(HealthIndexParameter,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(TotalPoints,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(EarnedPoints,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(EarnedValue,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR '(' + FromValue + ' - ' + ToValue + ')' LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(Percentage,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(IndicatorName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%')
	)
	SELECT  *
	FROM    PageNumbers
	WHERE  (@PageSize = -1 OR ID  BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize)) 
	OPTION(RECOMPILE)
	
	-------------------------

	Drop Table #tmp
	Drop Table #tmp1
	Drop Table #tmp2
END 

GO


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

GO


ALTER PROCEDURE [sHospitalization].[pGetDoctorsWithZeroCountAndOpenTickets]        
    @OrgId INT,        
    @HoursThreshold INT = 48,        
    @DaysLookback INT = 30        
AS        
BEGIN        
    SET NOCOUNT ON;        
      SELECT DISTINCT        
        --id.Id AS RecordId1s,
		 STUFF((
        SELECT DISTINCT ',' + Cast(id.Id as NVARCHAR(MAX))
        FROM sHospitalization.tIntimationDetails id	       
    INNER JOIN sHrm.tEmployeeMaster emp         
        ON id.AssignedDoctorId = emp.Id        
        AND emp.OrgId = @OrgId
    WHERE emp.Id = U.SourceId 
	and id.OrgId = @OrgId        
        AND id.IsObsolete = 0        
        AND id.TicketStatus IN ('Open')        
        AND id.CreatedDateTime <= DATEADD(HOUR, -@HoursThreshold, GETDATE()) 
		AND NOT EXISTS (  
		      SELECT 1
		      FROM sHospitalization.tIntimationDetails id2  
		      WHERE id2.AssignedDoctorId = id.AssignedDoctorId   
		      AND CAST(id2.UnattendedDate AS DATE) = CAST(GETDATE() AS DATE) 
		      AND id2.IsObsolete = 0)
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS RecordIds,
 
       -- iad.DoctorEmployeeId AS ParticipantSourceId ,      
     U.id AS ParticipantSourceId ,      
  id.orgid as orgId      
    FROM sHospitalization.tIntimationDetails id        
   -- INNER JOIN sHospitalization.tIntimationAssignedDoctor iad         
    --    ON id.AssignedDoctorId = iad.DoctorEmployeeId        
    INNER JOIN sHrm.tEmployeeMaster emp         
        ON id.AssignedDoctorId = emp.Id        
        AND emp.OrgId = @OrgId        
   INNER JOIN sSecurity.tUser U ON U.SourceId=id.AssignedDoctorId       
    LEFT JOIN sHrm.tEmployeeCommunications EC         
        ON emp.Id = EC.EmployeeId        
    WHERE         
        id.OrgId = @OrgId        
  And emp.OrgID =  @OrgId        
        AND id.IsObsolete = 0        
        AND id.TicketStatus IN ('Open')        
        AND id.CreatedDateTime <= DATEADD(HOUR, -@HoursThreshold, GETDATE()) 
		AND NOT EXISTS (  
		      SELECT 1
		      FROM sHospitalization.tIntimationDetails id2  
		      WHERE id2.AssignedDoctorId = id.AssignedDoctorId   
		      AND CAST(id2.UnattendedDate AS DATE) = CAST(GETDATE() AS DATE) 
		      AND id2.IsObsolete = 0     );  
END

GO


 CREATE or ALTER PROCEDURE [sExamination].[pSMSHistoryGetfordashboard]     
 @rEmployeeId Bigint, 
 @rOrgId smallint
 --@rAlertModeId tinyint

   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
  
BEGIN  
 SELECT   
   AL.Id AS Id,  
   AL.ContactId,  
    case when (AL.EventId = 34) then ISNULL(STUFF(AL.AlertMessage, CHARINDEX('Password', AL.AlertMessage)+9, LEN(AL.AlertMessage), '****'), AL.AlertMessage)   
    WHEN (AL.EventId = 35) then dbo.getNumericValue(AL.AlertMessage) 
    when (AL.EventId = 47) then dbo.getNumericValue(AL.AlertMessage) else AL.AlertMessage END AS 'AlertMessage',  -- change by Nidhi Pandey; mantis issue - 31722, DT - 01/03/2024  
   AL.AlertSubject,  
   AL.ResultMessage,  
   CASE WHEN AL.EventId>0 THEN EM.Title  
   ELSE AL.EventName  
   END AS EventName,  
   AL.SourceEvent,  
   U.DisplayTitle AS UserName,  
   AL.CreatedDateTime  
   --,  
   --OM.DisplayTitle AS Organization  
 FROM  
   sAlert.tAlertLog AL  
  LEFT JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId  
  INNER JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId  
 -- INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId   
 WHERE  
   ((AL.OrgId=@rOrgId) OR (@rOrgId=0))  
  ANd ((U.SourceId=@rEmployeeId) OR (@rEmployeeId=0))  
 ANd AL.AlertModeId=1
  ORDER BY AL.CreatedDateTime DESC  
END  

GO


ALTER PROCEDURE [sSecurity].[pMenuGet_Wellness]        
@rUserId [bigint],        
@rMenuId int = 0,        
@rResourceTypeId int= 0,        
@rOrgId int,        
@rflg bit = 0         
WITH EXECUTE AS CALLER        
AS        
SET NOCOUNT ON        
BEGIN        
declare @result varchar(15)='False'        
Select @result = [dbo].[fPHIPermissionUserwise](@rUserId,@rOrgId)        
if(@rflg=0)        
begin        
IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)        
  BEGIN        
   SELECT        
   MenuID,        
   ModuleId,        
   ParentMenuID,        
   MenuTitle,          
   ScreenTitle,           
   case when MenuID = 3314  then '~/Pages/Common/CommonMaster/CommonNavigationMaster.aspx' else         
   case when Menuid=1115 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   case when Menuid=3510 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   PageURL end end end PageURL,        
   ScreenId,        
   Permission,        
   OrderNumber,          
   TaskId,          
    PageURL  AS PagePath,        
    MenuIsObsolete          
  FROM        
    (SELECT Menu.Id AS MenuID,         
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
   Menu.Title AS MenuTitle,           
   ISNULL(Screen.Title, '') AS ScreenTitle,            
   ISNULL(Screen.Page, '') AS PageURL,        
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
   ISNULL(Menu.ScreenId, 0) AS ScreenId,        
   ISNULL(PermissionValue, 0) AS Permission,        
   ISNULL(OrderNumber, 0) AS OrderNumber,        
   ISNULL(Screen.TaskId,0) AS TaskId,        
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
   ISNULL(T.ModuleId,0) AS ModuleId,        
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete            
  FROM sSecurity.tMenu Menu         
  LEFT OUTER JOIN sSecurity.tScreen Screen        
   ON Menu.ScreenId = Screen.Id            
  LEFT OUTER JOIN (         
      SELECT         
       P.TaskId,         
       SUM(OT.AvailablePermission & 2) PermissionValue              
      FROM         
       sSecurity.tPermissionUser P        
       INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
       INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
       INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
       INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
      where p.userid= @rUserId 
	  AND T.Id not in (20834,20853)            
      GROUP BY         
       P.TaskId) TBL2        
      ON         
       Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId               
      WHERE         
      (Menu.IsObsolete = 0)         
      AND ISNULL(Screen.IsObsolete, 0) = 0 AND Menu.Id not in (40,191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368))         
      MenuTable          
  WHERE         
   MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
   AND         
   ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
   AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
   AND MenuIsObsolete = 0        
  ORDER BY         
   ParentMenuID          
  END        
ELSE         
  BEGIN        
   SELECT        
   MenuID,        
   ModuleId,        
   ParentMenuID,        
   MenuTitle,          
   ScreenTitle,           
   case when MenuID = 3314  then '~/Pages/Common/CommonMaster/CommonNavigationMaster.aspx' else        
   case when Menuid=1115 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
case when Menuid=3510 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   PageURL end end end PageURL,       
   ScreenId,        
   Permission,        
   OrderNumber,          
   TaskId,          
    PageURL  AS PagePath,        
    MenuIsObsolete          
  FROM        
    (SELECT Menu.Id AS MenuID,         
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
   Menu.Title AS MenuTitle,           
   ISNULL(Screen.Title, '') AS ScreenTitle,            
   ISNULL(Screen.Page, '') AS PageURL,        
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
   ISNULL(Menu.ScreenId, 0) AS ScreenId,        
   ISNULL(PermissionValue, 0) AS Permission,        
   ISNULL(OrderNumber, 0) AS OrderNumber,        
   ISNULL(Screen.TaskId,0) AS TaskId,        
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
   ISNULL(T.ModuleId,0) AS ModuleId,        
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete        

  FROM sSecurity.tMenu Menu         
  LEFT OUTER JOIN sSecurity.tScreen Screen        
   ON Menu.ScreenId = Screen.Id            
  LEFT OUTER JOIN (         
      SELECT         
       P.TaskId,         
       SUM(OT.AvailablePermission & 2) PermissionValue              
      FROM         
       sSecurity.tPermission P        
       INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
       INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
       INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
       INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
       INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId         
      --WHERE         
      -- RoleId  IN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) 
	  WHERE T.Id not in (20834,20853)        
      GROUP BY         
       P.TaskId) TBL2        
      ON         
       Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
      WHERE         
      (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
      AND ISNULL(Screen.IsObsolete, 0) = 0 AND Menu.Id not in (40,191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368))         
      MenuTable          
      --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
  WHERE         
   MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
   AND         
   ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
   AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
   AND MenuIsObsolete = 0        

  ORDER BY         
   ParentMenuID        
  END        
end        
else        
begin        
  IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)        
   begin        
    SELECT        
        MenuID,        
        ModuleId,        
        ParentMenuID,        
        MenuTitle,          
        ScreenTitle,           
        case when Menuid=1510 then '~/Pages/MaterialManagement/Procurement/ReportCriteria/Report' else  PageURL end PageURL,       
        ScreenId,        
        Permission,        
        OrderNumber,          
        TaskId,          
        PageURL  AS PagePath,        
        MenuIsObsolete,        
        Icon          
          FROM        
           (        
           SELECT Menu.Id AS MenuID,         
		  ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
          Menu.Title AS MenuTitle,           
          ISNULL(Screen.Title, '') AS ScreenTitle,            
          --case when Menu.Id=3023 then '' else ISNULL(Screen.Page, '') end AS PageURL,        
          ISNULL(Screen.Page, '') AS PageURL,        
          ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
          ISNULL(Menu.ScreenId, 0) AS ScreenId,        
          ISNULL(PermissionValue, 0) AS Permission,        
          ISNULL(OrderNumber, 0) AS OrderNumber,        
          ISNULL(Screen.TaskId,0) AS TaskId,        
          ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
          ISNULL(T.ModuleId,0) AS ModuleId,        
          ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
          case when Menu.Id=191810371 then 'fa fa-heart'
		 when Menu.Id=191810373 then 'fa fa-user-md'
		 when Menu.Id=191810378 then 'ft-user-plus'
		 when Menu.Id=35 then 'fa fa-support'
         else ISNULL(Screen.IconPath,'') end AS Icon        
         FROM sSecurity.tMenu Menu         
         LEFT OUTER JOIN sSecurity.tScreen Screen        
          ON Menu.ScreenId = Screen.Id            
         LEFT OUTER JOIN (         
          SELECT         
           P.TaskId,         
           SUM(OT.AvailablePermission & 2) PermissionValue              
          FROM         
           sSecurity.tPermissionUser P        
           INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
           INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
           INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
           INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          WHERE p.userid= @rUserId
		  AND T.Id not in (20834,20853)         
		  AND MM.Id IN (196,197,236,198)
          GROUP BY         
           P.TaskId) TBL2        
          ON         
           Screen.TaskId = TBL2.TaskId         
            LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
          WHERE         
          (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
          AND ISNULL(Screen.IsObsolete, 0) = 0     
          AND (Menu.Id in (191810371,191810373,191810378,191810337,35) Or ParentMenuID in (191810371,191810373,191810378,191810337,35))
          AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
         union        
          SELECT case when Menu.Id = 3023 then 1 else Menu.Id end AS MenuID,         
          ISNULL(Menu.Id, 0) AS ParentMenuID,         
          Screen1.Title AS MenuTitle,           
          ISNULL(Screen1.Title, '') AS ScreenTitle,            
          ISNULL(Screen1.Page, '')  AS PageURL,        
          ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,        
          ISNULL(Menu.ScreenId, 0) AS ScreenId,        
          ISNULL(PermissionValue, 0) AS Permission,        
          ISNULL(Screen1.OrderIndex, Screen.OrderIndex) AS OrderNumber,        
          ISNULL(Screen1.TaskId,0) AS TaskId,        
          ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
          ISNULL(T.ModuleId,0) AS ModuleId,        
          ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
          ISNULL(Screen1.IconPath,'') AS Icon        
         FROM sSecurity.tMenu Menu         
         LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id            
         LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId         
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId --AND ResourceTypeId = 0        
         LEFT OUTER JOIN (         
          SELECT         
         P.TaskId,         
           SUM(OT.AvailablePermission & 2) PermissionValue              
          FROM         
           sSecurity.tPermissionUser P        
           INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
           INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
           INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
           INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          WHERE p.userid= @rUserId
		  AND T.Id not in (20834,20853)    
		  AND MM.Id IN (196,197,236,198)
          GROUP BY         
           P.TaskId        
          ) TBL2        
          ON Screen1.TaskId = TBL2.TaskId         
         WHERE         
         (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
         AND ISNULL(Screen1.IsObsolete, 0) = 0        
         --AND (Menu.ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
         AND (Menu.ParentMenuID in (191810371,191810373,191810378,191810337,35))       
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen1.PHIAccessLevel,0)<>1))        
         )         
          MenuTable          
          --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
         WHERE         
       MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
          AND         
          ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
          AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
          AND MenuIsObsolete = 0        
          AND (1=(case when @rResourceTypeId=0 then 0 else 1 end) or (MenuTable.ResourceTypeId !=1))      
         ORDER BY         
          ParentMenuID        
   end        
  else        
   begin        
    SELECT        
         MenuID,        
         ModuleId,        
         ParentMenuID,        
         MenuTitle,          
         ScreenTitle,           
         case when Menuid=1510 then '~/Pages/MaterialManagement/Procurement/ReportCriteria/Report' else PageURL end PageURL,        
         ScreenId,        
         Permission,        
         OrderNumber,          
         TaskId,          
       PageURL  AS PagePath,        
       MenuIsObsolete,        
       Icon          
        FROM        
       (        
       SELECT Menu.Id AS MenuID,         
         ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
         Menu.Title AS MenuTitle,           
         ISNULL(Screen.Title, '') AS ScreenTitle,            
         --case when Menu.Id=3023 then '' else ISNULL(Screen.Page, '') end AS PageURL,        
         ISNULL(Screen.Page, '') AS PageURL,        
         ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
         ISNULL(Menu.ScreenId, 0) AS ScreenId,        
         ISNULL(PermissionValue, 0) AS Permission,        
         ISNULL(OrderNumber, 0) AS OrderNumber,        
         ISNULL(Screen.TaskId,0) AS TaskId,        
         ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
         ISNULL(T.ModuleId,0) AS ModuleId,        
         ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
         case when Menu.Id=191810371 then 'fa fa-heart'
		when Menu.Id=191810373 then 'fa fa-user-md'
		when Menu.Id=191810378 then 'ft-user-plus'
		when Menu.Id=35 then 'fa fa-support'
        else ISNULL(Screen.IconPath,'') end AS Icon        
        FROM sSecurity.tMenu Menu         
        LEFT OUTER JOIN sSecurity.tScreen Screen        
         ON Menu.ScreenId = Screen.Id            
        LEFT OUTER JOIN (         
         SELECT         
          P.TaskId,         
          SUM(OT.AvailablePermission & 2) PermissionValue              
         FROM         
          sSecurity.tPermission P        
          INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
          INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
          INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
          INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId
		 Where T.Id not in (20834,20853)   
		 AND MM.Id IN (196,197,236,198)
         GROUP BY         
          P.TaskId) TBL2        
         ON         
          Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
         WHERE         
         (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
         AND ISNULL(Screen.IsObsolete, 0) = 0
         AND (Menu.Id in (191810371,191810373,191810378,191810337,35) Or ParentMenuID in (191810371,191810373,191810378,191810337,35))
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
        union        
         SELECT case when Menu.Id = 3023 then 1 else Menu.Id end AS MenuID,         
         ISNULL(Menu.Id, 0) AS ParentMenuID,         
         Screen1.Title AS MenuTitle,           
         ISNULL(Screen1.Title, '') AS ScreenTitle,            
         ISNULL(Screen1.Page, '')  AS PageURL,        
         ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,        
         ISNULL(Menu.ScreenId, 0) AS ScreenId,        
         ISNULL(PermissionValue, 0) AS Permission,        
         ISNULL(Screen1.OrderIndex, Screen.OrderIndex) AS OrderNumber,        
         ISNULL(Screen1.TaskId,0) AS TaskId,        
         ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
         ISNULL(T.ModuleId,0) AS ModuleId,        
         ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
         ISNULL(Screen1.IconPath,'') AS Icon        
        FROM sSecurity.tMenu Menu         
        LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id            
        LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId --AND ResourceTypeId = 0        
        LEFT OUTER JOIN (         
         SELECT         
          P.TaskId,         
          SUM(OT.AvailablePermission & 2) PermissionValue              
         FROM         
       sSecurity.tPermission P        
          INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
          INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
          INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
          INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId               
         where T.Id not in (20834,20853) 
		 AND MM.Id IN (196,197,236,198)
		 GROUP BY         
          P.TaskId        
         ) TBL2        
         ON Screen1.TaskId = TBL2.TaskId         
        WHERE         
        (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
        AND ISNULL(Screen1.IsObsolete, 0) = 0       
        AND (Menu.ParentMenuID in (191810371,191810373,191810378,191810337,35))   
        AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
        AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen1.PHIAccessLevel,0)<>1))        
        )         
         MenuTable          
         --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
        WHERE         
         MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
         AND         
         ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
         AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
         AND MenuIsObsolete = 0        
         AND (1=(case when @rResourceTypeId=0 then 0 else 1 end) or (MenuTable.ResourceTypeId !=1))      
        ORDER BY         
         ParentMenuID        
   end        
end        
END

GO


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

GO


ALTER PROCEDURE [sSecurity].[pUserLocationAdd]
  
	@rOrgId [smallint],	
	@rUserId [bigint],	
	@rMapping [nvarchar](max),
	@rCreatedUserId [bigint]
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--DECLARE @loDoc INT
DECLARE @loXML XML
SET @loXML = CAST(@rMapping AS XML)
DECLARE @lCurrentDateTime DateTime
SET @lCurrentDateTime = sCommon.fGetDate()

--EXEC sp_xml_preparedocument @loDoc OUTPUT, @rMapping
BEGIN

DECLARE @DefaultStoreLocationId NVARCHAR(200), @DefaultStoreLocation NVARCHAR(200)

SELECT @DefaultStoreLocationId = UL.StoreLocationId, @DefaultStoreLocation = SLM.Title
FROM sSecurity.tUserLocation UL
INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = UL.StoreLocationId
WHERE UL.UserId = @rUserId
AND UL.IsPrimary = 1

IF @DefaultStoreLocationId IS NOT NULL
AND NOT EXISTS (
    SELECT 1
    FROM @loXML.nodes('/Items/Item') T(c)
    WHERE T.c.value('StoreLocationId[1]', 'NVARCHAR(200)') = @DefaultStoreLocationId
)
BEGIN
    SELECT -101 As Result, @DefaultStoreLocation as DefaultStoreLocation
    RETURN
END

DELETE FROM sSecurity.tUserLocation WHERE UserId = @rUserId


INSERT INTO sSecurity.tUserLocation (
							StoreLocationId, 
							UserId, 
							CreatedUserId,							 
							CreatedDateTime							 
							)		
			SELECT
			T.c.value('StoreLocationId[1]','NVARCHAR(200)') AS StoreLocationId,
			@rUserId,
			@rCreatedUserId,
			@lCurrentDateTime
			FROM
			@loXML.nodes('/Items/Item')T(c)
 
			Update sSecurity.tUserLocation set IsPrimary = 1 
			WHERE UserId = @rUserId and StoreLocationId = @DefaultStoreLocationId

			SELECT 1 As Result
END

GO

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

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

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

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

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

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

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

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

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

				SET @i_Row = @i_Row +1
			END


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


			SELECT * FROM #tbltmpSurveyResponseDetail

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


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

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

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

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

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

GO

ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramMHIScoreBulk]
(
      @rOrgId SMALLINT
    , @rUserId BIGINT
    , @rMHIScoreList [sWellness].[udt_MHIScoreUpdateBulk] READONLY
    , @InsertedCount INT OUTPUT
    , @UpdatedCount INT OUTPUT
    , @SkippedEmployeeCodeCount INT OUTPUT
    , @TotalProcessed INT OUTPUT
)
AS
BEGIN

SET NOCOUNT ON;

BEGIN TRY
BEGIN TRANSACTION;

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

------------------------------------------------
-- Parameter ranges
------------------------------------------------
SELECT
      HIPM.StaticHealthIndexParameterId
    , HIPD.FromValue
    , HIPD.ToValue
    , CASE
        WHEN HIPD.Points = 10 THEN 1
        WHEN HIPD.Points = 6 THEN 2
        WHEN HIPD.Points = 3 THEN 3
        ELSE HIPD.Points
      END Score
    , HIPD.DiagnosisRemark Category
    , HIPD.GenderId
INTO #TempParameterRange
FROM sExamination.tHealthIndexParameterMaster HIPM
JOIN sExamination.tHealthIndexParameterDetail HIPD
ON HIPD.HealthIndexParameterId = HIPM.Id
WHERE HIPM.StaticHealthIndexParameterId IN (1,2,5,17,23);

------------------------------------------------
-- Map EmployeeCode → EmployeeId
------------------------------------------------
SELECT
      EM.EmployeeId
    , EM.GenderId
    , S.BMI
    , S.SystolicBP
    , S.DiastolicBP
    , S.HBA1C
    , S.LDL
    , S.Stress
    , S.LifeStyle
INTO #InputData
FROM @rMHIScoreList S
JOIN sHrm.vExtEmployeeMaster EM
ON EM.Code = S.EmployeeCode;

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

------------------------------------------------
-- Score calculation
------------------------------------------------
SELECT
      I.*
    , BMI.Score BMIScore
    , BMI.Category BMICategory
    , HBA1C.Score HBA1CScore
    , HBA1C.Category HBA1CCategory
    , LDL.Score LDLScore
    , LDL.Category LDLCategory
    , CASE WHEN SYS.Score > DIA.Score THEN SYS.Score ELSE DIA.Score END BPScore
    , CASE WHEN I.Stress IS NULL THEN NULL WHEN I.Stress >= 90 THEN 1 WHEN I.Stress >= 75 THEN 2 ELSE 3 END StressScore
    , CASE  WHEN I.LifeStyle IS NULL THEN NULL WHEN I.LifeStyle <=49 THEN 3 WHEN I.LifeStyle <=70 THEN 2 ELSE 1 END LifestyleScore
INTO #Calculated
FROM #InputData I

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=1
AND I.BMI BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) BMI

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=2
AND I.HBA1C BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) HBA1C

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=5
AND I.LDL BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) LDL

OUTER APPLY
(
SELECT TOP 1 Score
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=23
AND I.SystolicBP BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) SYS

OUTER APPLY
(
SELECT TOP 1 Score
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=17
AND I.DiastolicBP BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) DIA;

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

UPDATE #Calculated
SET Biometrics =
(100.0*(ISNULL(BMIScore,0)+ISNULL(HBA1CScore,0)+ISNULL(LDLScore,0)+ISNULL(BPScore,0)))/4;

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

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

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

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

------------------------------------------------
-- Program assignment
------------------------------------------------
UPDATE C
SET ProgramId = PM.Id
FROM #Calculated C
JOIN sWellness.tStaticMHICategoryIndicator I
ON I.Id=C.MHICategoryId
JOIN sWellness.tProgramMaster PM
ON PM.MHIIndicatorId=I.Id
AND PM.CategoryId=1
AND PM.IsObsolete=0;

------------------------------------------------
-- UPDATE existing rows
------------------------------------------------
UPDATE T
SET
BMI=C.BMI,
BMIScore=C.BMIScore,
BMICategory=C.BMICategory,

HBA1C=C.HBA1C,
HBA1CScore=C.HBA1CScore,
HBA1CCategory=C.HBA1CCategory,

LDL=C.LDL,
LDLScore=C.LDLScore,
LDLCategory=C.LDLCategory,

BP=CAST(C.SystolicBP AS VARCHAR(10))+'/'+CAST(C.DiastolicBP AS VARCHAR(10)),
BPScore=C.BPScore,
BPCategory=CASE C.BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' ELSE 'Alert' END,

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

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

Biometrics=C.Biometrics,
BiometricsCategory=C.BiometricsCategory,

SurveyCategory=C.SurveyCategory,
MHICategory=C.MHICategory,
MHICategoryId=C.MHICategoryId,

ProgramId=C.ProgramId,

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

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

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

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

OPEN curInsert;
FETCH NEXT FROM curInsert INTO @EmployeeId;

WHILE @@FETCH_STATUS=0
BEGIN

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

INSERT INTO sWellness.tMHIScore
(
Id,OrgId,ProgramId,EmployeeId,EmployeeSourceTypeId,LastUpdateType,
HBA1C,HBA1CScore,HBA1CCategory,
LDL,LDLScore,LDLCategory,
BMI,BMIScore,BMICategory,
BP,BPScore,BPCategory,
Stress,StressScore,StressCategory,
Lifestyle,LifestyleScore,LifestyleCategory,
Biometrics,BiometricsCategory,
SurveyCategory,MHICategory,MHICategoryId,
CreatedUserId,CreatedDatetime
)
SELECT
@NextId,@rOrgId,C.ProgramId,C.EmployeeId,95,4,
C.HBA1C,C.HBA1CScore,C.HBA1CCategory,
C.LDL,C.LDLScore,C.LDLCategory,
C.BMI,C.BMIScore,C.BMICategory,
CAST(C.SystolicBP AS VARCHAR(10))+'/'+CAST(C.DiastolicBP AS VARCHAR(10)),
C.BPScore,
CASE C.BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' ELSE 'Alert' END,
C.Stress,C.StressScore,
CASE C.StressScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' ELSE 'Alert' END,
C.LifeStyle,C.LifestyleScore,
CASE C.LifestyleScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' ELSE 'Alert' END,
C.Biometrics,C.BiometricsCategory,
C.SurveyCategory,C.MHICategory,C.MHICategoryId,
@rUserId,sCommon.fGetDate()
FROM #Calculated C
WHERE C.EmployeeId=@EmployeeId;

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

FETCH NEXT FROM curInsert INTO @EmployeeId;
END

CLOSE curInsert;
DEALLOCATE curInsert;

------------------------------------------------
-- History
------------------------------------------------
DECLARE @EmpId BIGINT;

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

OPEN curHistory;
FETCH NEXT FROM curHistory INTO @EmpId;

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

FETCH NEXT FROM curHistory INTO @EmpId;
END

CLOSE curHistory;
DEALLOCATE curHistory;

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

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

COMMIT TRANSACTION;

END TRY
BEGIN CATCH

IF @@TRANCOUNT>0 ROLLBACK TRANSACTION;

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

SELECT ERROR_MESSAGE() ErrorMessage,ERROR_LINE() ErrorLine;

END CATCH

END

GO


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

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

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

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

   ISNULL(PM.Title, 'Not Assigned') AS ProgramName, AP.CauseId,
   CASE WHEN AP.ExaminationId IS NOT NULL THEN 
   'Completed'
   ELSE 
   'Pending'
   END AS Status,
   AP.ExaminationId as ConsultationId

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

ORDER BY AP.Id DESC;
		 
END

GO


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

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

SELECT
    Distinct
    AP.Id,
    AP.AppointmentNumber,
    AP.DoctorEmployeeId,
	ED.Code as EmployeeCode,
	AP.PatientSourceTypeId,
    ED.EmployeeName AS PatientName,
CASE 
    WHEN TRY_CAST(TM.FromTime AS TIME) IS NOT NULL
         AND TRY_CAST(TM.ToTime AS TIME) IS NOT NULL
         AND TRY_CAST(TM.FromTime AS TIME) <> '00:00:00'
         AND TRY_CAST(TM.ToTime AS TIME) <> '00:00:00'
    THEN 
        CONVERT(VARCHAR(8), TRY_CAST(TM.FromTime AS TIME), 100)
        + ' to ' +
        CONVERT(VARCHAR(8), TRY_CAST(TM.ToTime AS TIME), 100)
    ELSE '-'
END AS AppointmentTime,
	CONVERT(VARCHAR,AP.AppointmentDate,103) AS AppointmentDateFormatted,
  ISNULL(PM.Title, 'Not Assigned') AS ProgramName, AP.CauseId
FROM [sWellness].[tAppointment] AP
INNER JOIN [sHrm].[vEmployeeDetail] ED 
    ON AP.PatientSourceId = ED.EmployeeId
LEFT JOIN [sWellness].[tMHIScore] MH
    ON AP.PatientSourceId = MH.EmployeeId
LEFT JOIN [sWellness].[tProgramMaster] PM
    ON MH.ProgramId = PM.Id
LEFT JOIN sAppointment.tTimeSlotMaster TM
ON AP.TimeSlotId = TM.Id
WHERE 
    AP.DoctorEmployeeId = @rEmployeeId
    AND AP.OrgId = @rOrgId
    AND AP.AppointmentDate >= DATEADD(DAY,1,@Today)

ORDER BY AP.Id DESC;
		 
END

GO

ALTER PROCEDURE [sWellness].[PEmpDashboardDetailGet]  
@rEmpId bigint,  
@rOrgId int = 0  
as  
begin    
declare @lLatestVitalDisplayConfigVal varchar(5) = 'False';          
IF (@rOrgId > 0)  
BEGIN   
select @lLatestVitalDisplayConfigVal = sConfig.fConfigurationValueGet('Examination.LatestVitalDisplayOnDashboard',@rOrgId,0,0,0);  
END   

Declare @lHeight int =0,
        @lWeight decimal(8,2)=0,
		@lBMI decimal(8,2)=0,
		@lBloodPressureSystolic int=0,
		@lBloodPressureDiastolic int=0,
        @lHBA1C nvarchar(10)='0', 
		@lLDL nvarchar(10)='0',
		@lBMIDate nvarchar(20)='', 
		@lBPDate nvarchar(20)='', 
		@lHBA1CDate nvarchar(20)='', 
		@lLDLDate nvarchar(20)='',
		@MHIBiometricsCategory NVARCHAR(20) = 'Pending', @MHIStressCategory NVARCHAR(20) = 'Pending', @MHILifestyleCategory NVARCHAR(20) = 'Pending', @MHISurveyCategory NVARCHAR(20) = 'Pending', @MHICategory NVARCHAR(20),
	@MHIHBA1C NUMERIC(10,2)=0, @MHILDL NUMERIC(10,2)=0, @MHIBMI NUMERIC(10,2)=0,  @MHIBP NVARCHAR(20) = '';
		
IF (@rEmpId > 0)
BEGIN

Select Top 1 @lHeight=Height,@lWeight=BodyWeight,@lBMI=BMI,@lBMIDate=convert(varchar(20),ExaminationDate,103)   
from sExamination.tExamination E   
inner join sExamination.tVital V on V.SourceId=E.Id  
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId    
inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId  
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95  
and Isnull(V.Height,0)>0 and Isnull(V.BodyWeight,0)>0 and Isnull(V.BMI,0)>0  
and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))  
Order by E.ExaminationDate desc;    


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


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


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

END

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

SELECT    
     'Ht : ' + Convert(varchar(10),Isnull(@lHeight,0)) + 'cm' as Height,   
	 'Wt : ' + Convert(varchar(10),Isnull(@lWeight,0)) + 'kg' as Weight,   
	 ISNULL(@lHeight,0) as Height1,   
	 ISNULL(@lWeight,0) as Weight1,   
	 ISNULL(@MHIBMI,0) as BMI,   
	 ISNULL(@MHIBP,'') as BP,   
	 ISNULL(@MHIHBA1C,'0') as HBA1C,   
	 ISNULL(@MHILDL,'0') as LDL,   
	 @lBMIDate as BMIDate,   
	 @lBPDate as BPDate,   
	 @lHBA1CDate as HBA1CDate,   
	 @lLDLDate as LDLDate;    
	 
EXEC [sWellness].[pGetEmployeeHealthIndex] @rEmpId , @lBMI ,@lBMIDate, @lBloodPressureSystolic , @lBloodPressureDiastolic ,@lBPDate, @lHBA1C ,@lHBA1CDate,  @lLDL, @lLDLDate;  
	 
END

GO


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

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

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


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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

	   

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

GO


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

BEGIN		
			Select DISTINCT
			mhi.Id,
			mhi.ParticipantSourceTypeId,
			mhi.ParticipantSourceId,
			mhi.BMI,
			mhi.HBA1C,
			mhi.LDL,
			BPSystolic,
			BPDiastolic,
			mhi.Stress,
			mhi.LifeStyle,
			ED.Code as EmployeeCode,
			ED.EmployeeName
			FROM [sWellness].[tMHIScoreUpdation] mhi
			INNER JOIN [sHrm].[vEmployeeDetail] ED on mhi.ParticipantSourceId = ED.EmployeeId
			LEFT JOIN [sWellness].[tMHIScore] MHS on MHS.EmployeeId = ED.EmployeeId
			INNER JOIN [sIp].[tStoreLocationMaster] SLM	ON 	SLM.LocationId = ED.EmployeeLocationId
			INNER JOIN	sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id
			INNER JOIN	[sWellness].[tProgramMaster] PM	ON PM.Id = MHS.ProgramId
			WHERE
			((@rProgramId = 0) OR (MHS.ProgramId = @rProgramId))
		AND 
			((@rDepartmentId = 0) OR (ED.DepartmentId = @rDepartmentId))
		AND 
			((@rLocationId = 0) OR (ED.EmployeeLocationId = @rLocationId))
			AND 
			MHS.ProgramId > 0
		
		AND 
			MHS.OrgId = @rOrgId
		AND 
			UL.UserId = @rUserId
			ORDER BY mhi.Id DESC
END

GO


ALTER PROCEDURE [sWellness].[pGetMySurveylist]
	@rOrgId SMALLINT,
	@rLocationId BIGINT,
	@rEmployeeId BIGINT,
	@rAssignSurveyId INT = 0
AS
SET NOCOUNT ON
BEGIN
 
BEGIN TRY
	
	DECLARE @Age int=0

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

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

END TRY
BEGIN CATCH 
  --select '' as Result
END CATCH
END

GO


ALTER PROCEDURE [sWellness].[pSaveAllConsultationDatas]   
@rId BIGINT,
@rSourceTypeId int = 10173,
@rParticipantSourceTypeId int = 95,
@rParticipantSourceId bigint,
@rOrgId smallint,
@rVitals nvarchar(max),                
@rTests nvarchar(max),              
@rWellnessAppointments nvarchar(max),                
@rTasks nvarchar(max),                
@rAdditionalFields nvarchar(max),
@rUserId bigint
as                
begin                 
SET NOCOUNT ON                
--SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED                
--SET XACT_ABORT ON                
                
 --SELECT -1 AS RESULT                
 --return                
 declare @trancount int;                
                    
 declare @error int, @message varchar(4000), @xstate int,@errorCount int, @errorLine int;                
                
 declare @lNextNumber bigint,@lFromNextNumber bigint,@lCount int,@rStoreLocationId int               
 declare @lAppointmentid bigint,@rReferSourceId bigint,@i int,@lAppointmentType tinyint                
 declare @loNextNumber varchar(20),@lAppointmentDate varchar(50),@rConsultationDate varchar(50)               
                 
 declare @lxmlVital xml,@lxmlTests xml,@lxmlWellnessAppointment xml,@lxmlTasks xml,@lxmlAdditionalFields xml;
                 
 declare @exceptiondetail nvarchar(max),@username nvarchar(200);
 declare @cnt int;
 BEGIN TRY                       
 set @lxmlVital = CAST(@rVitals AS xml)           
 set @lxmlTests = CAST(@rTests AS xml) 
 set @lxmlWellnessAppointment = CAST(@rWellnessAppointments AS xml)                
 set @lxmlTasks = CAST(@rTasks AS xml)                
 set @lxmlAdditionalFields = CAST(@rAdditionalFields AS xml)
 
 set @username = (select Top 1 ISNULL(LoginTitle,'') from sSecurity.tUser where id=ISNULL(@rUserId,0));
 set @rConsultationDate = (select ConsultationDate from sWellness.tWellnessConsultation where Id = @rId);

BEGIN TRY
 declare @tblGeneralTemplates table(tid int identity(1,1),TestId int,ParamId int,
	GeneralTemplateConsultationId bigint,GeneralTemplateConsultationDetailId bigint,ServiceResult varchar(250),Remark varchar(250), GtgId smallint)
	insert into @tblGeneralTemplates
	select T.c.value('@GtId','Int') as TestId,
	T.c.value('@GtpId','Int') as ParamId,
	T.c.value('@GtExId','bigint') as GtExId,
	T.c.value('@GeneralTemplateConsultationDetailId','bigint') as GeneralTemplateConsultationDetailId,
	T.c.value('@ServiceResult','varchar(250)') as ServiceResult,
	T.c.value('@Remark','varchar(250)') as Remark,
	T.c.value('@GtgId','smallint') as GtgId
	from @lxmlVital.nodes('/GeneralTemplates/GeneralTemplate')T(c)

	select @cnt = count(*),@i = 1 from @tblGeneralTemplates

	delete w from sWellness.tGeneralTemplateConsultationDetail w
	inner join sWellness.tGeneralTemplateConsultation e
	on e.Id = w.GeneralTemplateConsultationId
	where e.GeneralTemplateId not in
	(
		select TestId from @tblGeneralTemplates
	)
	and w.GeneralTemplateParameterId not in
	(
		select ParamId from @tblGeneralTemplates
	) and e.SourceId = @rId and e.OrgId = @rOrgId
	and ((select distinct GtgId from @tblGeneralTemplates) = (select GeneralTemplateGroupId from sExamination.tGeneralTemplateMaster where Id = e.GeneralTemplateId))
		
	delete from sWellness.tGeneralTemplateConsultation where GeneralTemplateId not in
	(
		select TestId from @tblGeneralTemplates
	) and SourceId = @rId and OrgId = @rOrgId
	and ((select distinct GtgId from @tblGeneralTemplates) = (select GeneralTemplateGroupId from sExamination.tGeneralTemplateMaster where Id = GeneralTemplateId))

	while @i <= @cnt
	begin
		declare @TestId int,@ParamId int,@rServiceResult varchar(250)
		select @TestId = TestId,@ParamId = ParamId,@rServiceResult = ServiceResult from @tblGeneralTemplates where tid = @i
		select @TestId = isnull(@TestId,0),@ParamId = isnull(@ParamId,0),@rServiceResult = isnull(@rServiceResult,'')
		
		declare @detailid bigint
		select @detailid = GeneralTemplateConsultationDetailId from @tblGeneralTemplates where tid = @i
		
		declare @lParameterValueTypeId int,@lListValueTypeId int;
		select @lParameterValueTypeId = ParameterValueTypeId from sExamination.tGeneralTemplateParameter where Id = @ParamId
		
		if @TestId > 0
		begin
			if not exists(select * from sWellness.tGeneralTemplateConsultation where SourceId = @rId and SourceTypeId = @rSourceTypeId
			and GeneralTemplateId = @TestId and OrgId = @rOrgId)
			begin
				exec sCommon.pTableRowIdGet @rOrgId,'sWellness.tGeneralTemplateConsultation', 0, 1, 1,@outNextNumber = @lNextNumber output
				insert into sWellness.tGeneralTemplateConsultation
				(
					[Id],[SourceId],[GeneralTemplateId],[SourceTypeId],OrgId
				)
				values
				(
					@lNextNumber,@rId,@TestId,@rSourceTypeId,@rOrgId
				)
			end
			else
			begin
				select @lNextNumber = Id from sWellness.tGeneralTemplateConsultation where SourceId = @rId and SourceTypeId = @rSourceTypeId
				and GeneralTemplateId = @TestId and OrgId = @rOrgId
			end
			
			if @detailid > 0
			begin
				update sWellness.tGeneralTemplateConsultationDetail set ParameterValue = [sSetup].[fPortalXMLTagsReplaceReverse](@rServiceResult)
				where Id = @detailid
			end
			else if not exists(select * from sWellness.tGeneralTemplateConsultationDetail where GeneralTemplateConsultationId = @lNextNumber
			and GeneralTemplateParameterId = @ParamId)
			begin
				declare @GeneralTempExamiantionId bigint
				select @GeneralTempExamiantionId = @lNextNumber
				insert into sWellness.tGeneralTemplateConsultationDetail
				(
					[GeneralTemplateConsultationId],[GeneralTemplateParameterId],[ParameterValue],Remark,IsAbnormal
				)
				values
				(
					@GeneralTempExamiantionId,@ParamId,[sSetup].[fPortalXMLTagsReplaceReverse](@rServiceResult),'',0
				)
			end
			else
			begin
				update sWellness.tGeneralTemplateConsultationDetail set ParameterValue = [sSetup].[fPortalXMLTagsReplaceReverse](@rServiceResult)
				where [GeneralTemplateConsultationId] = @GeneralTempExamiantionId and [GeneralTemplateParameterId] = @ParamId
			end
		end
		select @i = @i + 1
	end  
 END TRY          
 BEGIN CATCH                 
  select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();

 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
  Select @rOrgId,'Consultation_Vital_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 1              
 END CATCH             
  
 declare @tblTests table(tid int identity(1,1),t_AreaId int,t_AreaTypeId int,t_ConsultationId bigint,                
 t_OrgId int,t_ParameterId int,t_ServiceValue nvarchar(500),t_Remark varchar(max),t_IsReferred bit,t_ClinicalId bigint,t_IsDone bit,                
 t_ParticipantAreaId bigint,t_TestRequestId bigint,t_TestDetailId int,t_TestRequestDetailId bigint,t_IsPackageValue varchar(10))                
 insert into @tblTests                
select T.c.value('@AreaId','int') as AreaId,                
 T.c.value('@AreaTypeId','int') as AreaTypeId,                
 T.c.value('@ConsultationId','bigint') as ConsultationId,                 
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@ParameterId','int') as ParameterId,            
 T.c.value('@ServiceValue','nvarchar(500)') as ServiceValue,      
 T.c.value('@Remark','varchar(max)') as Remark,                
 T.c.value('@IsReferred','bit') as IsReferred,                
 T.c.value('@ClinicalId','bigint') as ClinicalId,                
 T.c.value('@IsDone','bit') as IsDone,                 
 null,null,null,null,                
 T.c.value('@IsPackageValue','varchar(10)') as IsPackageValue                
 from @lxmlTests.nodes('/ExaminTest/Tests')T(c)                
                  
 update t set t.t_TestRequestId = p.Id from @tblTests t inner join sWellness.tConsultationTestRequest p                
 on t.t_AreaId = p.TestId and t.t_ConsultationId = p.SourceId                
                 
 update t set t.t_TestDetailId = p.Id from @tblTests t inner join sOrderEntry.tTestDetail p                
 on t.t_AreaId = p.TestId and t.t_ParameterId = p.TestParameterId                
                 
 declare @tblTestsNew table(tid int identity(1,1),tt_TestId int,tt_ConsultationId bigint,tt_OrgId int,                
 tt_ParticipantAreaId bigint,tt_TestRequestId bigint,tt_IsPackageValue varchar(10))                
 insert into @tblTestsNew                
 select distinct t_AreaId,t_ConsultationId,t_OrgId,t_ParticipantAreaId,t_TestRequestId,t_IsPackageValue from @tblTests                
 BEGIN TRY          
         
 begin                
 exec sCommon.pTableRowIdGet @rOrgId, 'sWellness.tConsultationTestRequest', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 SET @lFromNextNumber = @lNextNumber - 1                
 end                 
 MERGE sWellness.tConsultationTestRequest AS Target USING                 
 (                
  SELECT Id,tt_TestRequestId,tt_TestId,tt_OrgId,tt_ConsultationId,tid,tt_IsPackageValue                
  FROM @tblTestsNew TT LEFT JOIN sWellness.tConsultationTestRequest T with(NOLOCK) ON TT.tt_TestRequestId = T.Id                
 ) AS Source ON Target.Id = Source.tt_TestRequestId                 
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,SourceId,TestId,SourceTypeId,OrgId,IsObsolete,IsPackage                
  )                
  VALUES                
  (                
   @lFromNextNumber + tid,tt_ConsultationId,tt_TestId,@rSourceTypeId,tt_OrgId,0,case when upper(tt_IsPackageValue)='Y' then 1 else 0 end                
  );                
 begin                
 select @lCount = COUNT(1) FROM @tblTestsNew                 
 SET @lNextNumber  = @lCount + @lFromNextNumber                 
 exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sWellness.tConsultationTestRequest', @rCurrentNumber = @lNextNumber                
 end             
                 
 update t set t.t_TestRequestId = p.Id from @tblTests t inner join sWellness.tConsultationTestRequest p                
 on t.t_AreaId = p.TestId and t.t_ConsultationId = p.SourceId                
                 
 update t set t.t_TestRequestDetailId = p.Id from @tblTests t inner join sWellness.tConsultationTestRequestDetail p                
 on t.t_TestDetailId = p.TestDetailId and t.t_TestRequestId = p.TestRequestId
                 
 declare @tblTestsM table(tid int identity(1,1),t_AreaId int,t_AreaTypeId int,t_ConsultationId bigint,                
 t_OrgId int,t_ParameterId int,t_ServiceValue nvarchar(500),t_Remark varchar(400),t_IsReferred bit,t_ClinicalId bigint,t_IsDone bit,                
 t_ParticipantAreaId bigint,t_TestRequestId bigint,t_TestDetailId int,t_TestRequestDetailId bigint)                
 insert into @tblTestsM      
 select t_AreaId,t_AreaTypeId,t_ConsultationId,t_OrgId,t_ParameterId,t_ServiceValue,t_Remark,t_IsReferred,t_ClinicalId,t_IsDone,                
 t_ParticipantAreaId,t_TestRequestId,t_TestDetailId,t_TestRequestDetailId from @tblTests where t_TestDetailId is not null        
                
MERGE sWellness.tConsultationTestRequestDetail AS Target USING      
 (                
  SELECT Id,t_TestRequestId,t_TestDetailId,t_OrgId,t_ConsultationId,t_TestRequestDetailId,tid,t_ServiceValue,t_Remark      
  FROM @tblTestsM TT LEFT JOIN sWellness.tConsultationTestRequestDetail T with(NOLOCK) ON TT.t_TestRequestDetailId = T.Id                
 ) AS Source ON Target.Id = Source.t_TestRequestDetailId                
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   TestRequestId,TestDetailId,OrgId,ServiceValue,Remark           
  )                
  VALUES                
  (                
   t_TestRequestId,t_TestDetailId,t_OrgId,t_ServiceValue,t_Remark      
  )      
  WHEN MATCHED THEN UPDATE SET ServiceValue=t_ServiceValue, Remark=t_Remark;    
             
 END TRY                
 BEGIN CATCH                
  select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
  --set @trancount = @@trancount;                
  --if @xstate = -1                
  --          rollback;                
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --      if @xstate = 1 and @trancount > 0                
            --rollback tran;                
                    
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
  Select @rOrgId,'Consultation_TestRequestDetail_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 2              
 END CATCH

 declare @tblWellnessAppointments table(tid int identity(1,1),a_AppointmentId bigint,a_ExamId bigint,a_doctorId bigint,a_EmpId bigint,                
 a_obsolete bit,a_PatientSourceTypeId bigint,a_OrgId int,a_AppointmentDate varchar(50),a_StoreLocationId int,                
 a_FollowupRemark varchar(max),a_SetupId int,a_CauseId int,a_CreatedUserId bigint,a_SubTypeId int,                
 a_AppointNumber varchar(200),a_OtherName varchar(200),a_age int,a_VaccineId int,a_AppointmentType tinyint,a_genderId int)            
 insert into @tblWellnessAppointments                
 select T.c.value('@AppointmentId','bigint') as AppointmentId,                
 T.c.value('@ConsultationId','bigint') as ConsultationId,
 T.c.value('@DoctorEmployeeId','bigint') as DoctorEmployeeId,                
 T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,                
 T.c.value('@IsObsolete','bit') as IsObsolete,                
 T.c.value('@PatientSourceTypeId','int') as PatientSourceTypeId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@AppointmentDate','varchar(50)') as AppointmentDate,                
 T.c.value('@StoreLocationId','int') as StoreLocationId,   
 T.c.value('@FollowupRemark','varchar(max)') as FollowupRemark,                
 T.c.value('@SetupId','int') as SetupId,                
 T.c.value('@CauseId','int') as CauseId,                
 T.c.value('@CreatedUserId','bigint') as CreatedUserId,null,'',                
 T.c.value('@OtherName','varchar(200)') as OtherName,null as age,                
 T.c.value('@VaccineId','int') as VaccineId,                
 T.c.value('@AppointmentType','tinyint') as AppointmentType, null as genderId           
 from @lxmlWellnessAppointment.nodes('/Appointments/Appointment')T(c)         
            
 update w set w.a_SubTypeId = s.SubTypeId from @tblWellnessAppointments w inner join sExamination.tSetupMaster s on s.Id = w.a_SetupId                
              
 update a set a_age = case when a.a_PatientSourceTypeId = 1009 then                
 case when CS.DateOfBirth = '1900-01-01' then 0 else datediff(yy,CS.DateOfBirth,getdate()) end                
 when a.a_PatientSourceTypeId = 1001 then                
 case when EFD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EFD.DateOfBirth,getdate()) end else                
 case when EP.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EP.DateOfBirth,getdate()) end end                
 From @tblWellnessAppointments as a                
 left join sHrm.tEmployeeMaster EM on a.a_EmpId = EM.Id and a.a_PatientSourceTypeId = 95                
 left join sHrm.tEmployeePersonalDetail EP on a.a_EmpId = EP.EmployeeId and a.a_PatientSourceTypeId = 95                
 left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = a.a_EmpId and a.a_PatientSourceTypeId = 1001                
 left join sHrm.tCsrBenefiterMaster CS on a.a_EmpId = CS.Id and a.a_PatientSourceTypeId = 1009                
            
  update a set a_genderId = case when a.a_PatientSourceTypeId = 1009 then CS.GenderId                
 when a.a_PatientSourceTypeId = 1001 then EFD.GenderId else EP.GenderId end            
 From @tblWellnessAppointments as a                
 left join sHrm.tEmployeeMaster EM on a.a_EmpId = EM.Id and a.a_PatientSourceTypeId = 95                
 left join sHrm.tEmployeePersonalDetail EP on a.a_EmpId = EP.EmployeeId and a.a_PatientSourceTypeId = 95                
 left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = a.a_EmpId and a.a_PatientSourceTypeId = 1001                
 left join sHrm.tCsrBenefiterMaster CS on a.a_EmpId = CS.Id and a.a_PatientSourceTypeId = 1009                
                
  Declare @lExamid bigint = 0, @lFollowUpRemark varchar(max), @lEmpId bigint;            
  select @lAppointmentid = ISNULL(a_AppointmentId,0),@lAppointmentType = ISNULL(a_AppointmentType,0), @lExamid = ISNULL(a_ExamId,0),            
  @lFollowUpRemark = ISNULL(a_FollowupRemark,''), @lEmpId = ISNULL(a_EmpId,0) from @tblWellnessAppointments                    
            
  if(ISNULL(@lAppointmentid,0) > 0)            
  BEGIN
		update sWellness.tAppointment set ExaminationId = @lExamid where Id = ISNULL(@lAppointmentid,0)            
  END
                
  if(ISNULL(@lAppointmentid,0)>0)              
  begin               
  if exists (select 1 from  sWellness.tAppointment where Id = ISNULL(@lAppointmentid,0) and ISNULL(@lAppointmentType,0) <> 1 and ISNULL(@lExamid,0) <> ReferSourceId)                 
  begin   
  update sWellness.tAppointment set ApprovalStatusId = 550 where Id = ISNULL(@lAppointmentid,0) and ISNULL(@lAppointmentType,0) <> 1              
  end                
 end               
 set @lAppointmentid = 0                
 select @rStoreLocationId = a_StoreLocationId,@lAppointmentid = a_AppointmentId,                
 @lAppointmentDate = a_AppointmentDate,@rReferSourceId = a_ExamId from @tblWellnessAppointments 
       
 if @lAppointmentDate <> ''                
 begin                
   IF NOT EXISTS (SELECT 1 FROM sWellness.tAppointment WHERE ReferSourceId = @lExamid)
   BEGIN    
  exec sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId,@rPrefixFunctionalityId = 1022,@rStoreLocationId = 0,                
  @rNextNumber = @loNextNumber output         
                  
  update @tblWellnessAppointments set a_AppointNumber = @loNextNumber                
  begin try                
  --begin tran                
  begin                
                
  exec sCommon.pTableRowIdGet @rOrgId, 'sWellness.tAppointment', 0, 1, 1,@outNextNumber = @lNextNumber output                 
  SET @lFromNextNumber = @lNextNumber - 1                
  end                
    DECLARE @AppointmentFlag VARCHAR(50);
    SET @AppointmentFlag = 'Wellness Followup Appointment';

    INSERT INTO sWellness.tAppointment               
   (                
    Id,PatientSourceId,PatientSourceTypeId,AppointmentDate,                
    AppointmentNumber,DoctorEmployeeId,FromTime,ToTime,IsRegister,                
    IsObsolete,OrgId,StatusId,ReferSourceId,ReferSourceTypeId,                
    StoreLocationId,SetupId,CauseId,OtherName,FollowupRemark,age,ApprovalStatusId, GenderId,AppointmentFlag               
   )                
  SELECT                             
    @lFromNextNumber + tid,a_EmpId,a_PatientSourceTypeId,                
    case when len(a_AppointmentDate) = 10 then convert(Datetime, a_AppointmentDate, 104) else CONVERT(VARCHAR(11), a_AppointmentDate) end,                
    a_AppointNumber,case when a_doctorId > 0 then a_doctorId else null end,                
    null,null,0,a_obsolete,a_OrgId,1,a_ExamId,0,a_StoreLocationId,a_SetupId,a_CauseId,                
    case when a_OtherName <> '' then a_OtherName else null end,left(a_FollowupRemark,200),case when Isnull(a_age,0)=0 then null else a_age end,548, a_genderId,@AppointmentFlag            
   FROM @tblWellnessAppointments TT;     
  begin                
  select @lCount = COUNT(1) FROM @tblWellnessAppointments                 
  SET @lNextNumber  = @lCount + @lFromNextNumber                 
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sWellness.tAppointment', @rCurrentNumber = @lNextNumber                
  end                
  --commit tran;                
  end try                
  BEGIN CATCH                  
  select @error = ERROR_NUMBER(),                
      @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
  --set @trancount = @@trancount;                
  --if @xstate = -1                
  --          rollback;                
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --      if @xstate = 1 and @trancount > 0                
            --rollback tran ;                
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)             
  Select @rOrgId,'OPD_tAppointment_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 3          
 END CATCH     
 END
 end   
 
 DECLARE @tblTasks TABLE
(
    tid INT IDENTITY(1,1),
    r_ConsultationId BIGINT,
    r_Id BIGINT,
    r_WeekNoId INT,
    r_IsCustomActivityTask BIT,
    r_WellnessActivityCategoryId INT,
    r_WellnessActivityId INT,
    r_WellnessActivityTaskId INT,
    r_WellnessActivityCustomTask NVARCHAR(500),
    r_TargetValue NVARCHAR(100),
    r_UnitId INT,
    r_FrequencyTypeId INT,
    r_FrequencyCount INT,
    r_IsDelete BIT
)

INSERT INTO @tblTasks
SELECT
    T.c.value('@ConsultationId','bigint') AS ConsultationId,
    T.c.value('@Id','bigint') AS Id,
    T.c.value('@WeekNoId','int') AS WeekNoId,
    T.c.value('@IsCustomActivityTask','bit') AS IsCustomActivityTask,
    T.c.value('@WellnessActivityCategoryId','int') AS WellnessActivityCategoryId,
    T.c.value('@WellnessActivityId','int') AS WellnessActivityId,
    T.c.value('@WellnessActivityTaskId','int') AS WellnessActivityTaskId,
    T.c.value('@WellnessActivityCustomTask','nvarchar(500)') AS WellnessActivityCustomTask,
    T.c.value('@TargetValue','nvarchar(100)') AS TargetValue,
    T.c.value('@UnitId','int') AS UnitId,
    T.c.value('@FrequencyTypeId','int') AS FrequencyTypeId,
    T.c.value('@FrequencyCount','int') AS FrequencyCount,
    T.c.value('@IsDelete','bit') AS IsDelete
FROM @lxmlTasks.nodes('/WellnessTasks/Task') T(c)
         
 begin try
	DELETE A
	FROM sWellness.tAssignedActivity A
	INNER JOIN @tblTasks T 
		ON A.AssignedActivityId = T.r_Id
	WHERE T.r_IsDelete = 1

 DELETE FROM @tblTasks WHERE r_IsDelete = 1            
                 
 MERGE sWellness.tAssignedActivity AS Target
USING
(
 SELECT *
 FROM @tblTasks TT
 LEFT JOIN sWellness.tAssignedActivity T WITH(NOLOCK)
  ON TT.r_Id = T.AssignedActivityId
) AS Source
ON Target.AssignedActivityId = Source.r_Id
WHEN MATCHED THEN
 UPDATE SET
  WellnessActivityCategoryId = r_WellnessActivityCategoryId,
  WellnessActivityId = r_WellnessActivityId,
  WellnessActivityTaskId = r_WellnessActivityTaskId,
  IsCustomActivityTask = r_IsCustomActivityTask,
  WellnessActivityCustom = r_WellnessActivityCustomTask,
  TargetValue = r_TargetValue,
  UnitId = r_UnitId,
  FrequencyTypeId = r_FrequencyTypeId,
  FrequencyCount = r_FrequencyCount,
  WeekNo = r_WeekNoId,
  WeekStart = DATEADD(DAY, ((r_WeekNoId - 1) * 7) + 1, @rConsultationDate),
  WeekEnd = DATEADD(DAY, (r_WeekNoId * 7), @rConsultationDate),
  UpdatedUserId = @rUserId,
  UpdatedDateTime = sCommon.fGetDate()

WHEN NOT MATCHED THEN
 INSERT
 (
  ConsultationId,
  EmployeeId,
  WellnessActivityCategoryId,
  WellnessActivityId,
  WellnessActivityTaskId,
  IsCustomActivityTask,
  WellnessActivityCustom,
  TargetValue,
  UnitId,
  FrequencyTypeId,
  FrequencyCount,
  WeekNo,
  WeekStart,
  WeekEnd,
  CreatedUserId,
  CreatedDateTime
 )
 VALUES
 (
  @rId,
  @rParticipantSourceId,
  r_WellnessActivityCategoryId,
  r_WellnessActivityId,
  r_WellnessActivityTaskId,
  r_IsCustomActivityTask,
  r_WellnessActivityCustomTask,
  r_TargetValue,
  r_UnitId,
  r_FrequencyTypeId,
  r_FrequencyCount,
  r_WeekNoId,
  DATEADD(DAY, ((r_WeekNoId - 1) * 7) + 1, @rConsultationDate),
  DATEADD(DAY, (r_WeekNoId * 7), @rConsultationDate),
  @rUserId,
  sCommon.fGetDate()
 );  
                
 end try                
 BEGIN CATCH                
 select @error = ERROR_NUMBER(),                
  @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();
			   
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)         
  Select @rOrgId,'Consultation_Tasks_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 4              
END CATCH 

BEGIN TRY
	IF NOT EXISTS (select * from sWellness.tConsultationAdditionalFieldMaster where ConsultationId = @rId)
	begin    
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sWellness.tConsultationAdditionalFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output 
		
	INSERT INTO sWellness.tConsultationAdditionalFieldMaster
	(
		Id,ConsultationId,
		OrgId, IsObsolete, CreatedUserId, CreatedDateTime,
		UpdatedUserId, UpdatedDateTime
	)
	VALUES
	(
		@lNextNumber,@rId,
		@rOrgId, 0, @rUserId, sCommon.fGetDate(), 
		@rUserId, sCommon.fGetDate()
	)
	end
	else
	begin
		UPDATE sWellness.tConsultationAdditionalFieldMaster SET
		UpdatedUserId = @rUserId, UpdatedDateTime = sCommon.fGetDate()
		WHERE ConsultationId = @rId

		select @lNextNumber = Id from sWellness.tConsultationAdditionalFieldMaster where ConsultationId = @rId
	end

	DECLARE @loDoc INT
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAdditionalFields

	DELETE FROM sWellness.tConsultationAdditionalFieldDetails WHERE AdditionalFieldId=@lNextNumber
	
		INSERT INTO sWellness.tConsultationAdditionalFieldDetails
		(
			AdditionalFieldId,
			AdditionalFieldSetupId,
			AdditionalFieldResponse
		)
		SELECT
			@lNextNumber,AdditionalFieldSetupId,[sSetup].[fPortalXMLTagsReplaceReverse](AdditionalFieldResponse)
		FROM
			OPENXML (@loDoc, '/AdditionalFields/AdditionalField', 1)WITH
			(
				AdditionalFieldSetupId int,
				AdditionalFieldResponse nvarchar(1000)
			)
END TRY
BEGIN CATCH                  
  select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
                     
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)                
  Select @rOrgId,'Consultation_QA_Error',5000,@exceptiondetail,getdate(),@rUserId                  
  Set @errorCount=-1                
  SET @errorLine = 5              
 END CATCH
                
              
 END TRY                
  BEGIN CATCH                  
  select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
                     
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)                
  Select @rOrgId,'Consultation_DBError',5000,@exceptiondetail,getdate(),@rUserId                  
  Set @errorCount=-1                
  SET @errorLine = 6             
 END CATCH
 --COMMIT TRANSACTION                
 if (@errorCount=-1)                
 begin                
 SELECT -1 AS RESULT,  @message as Error, @errorLine as [LineNo]              
 end                
 else                
 begin                
 SELECT 1 AS RESULT  ,  @message as Error, @errorLine as [LineNo]              
 end                
 --SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off            
end 

GO

INSERT INTO sCommon.tModuleMaster (Id, Title, Remark, IsObsolete, ModuleTypeId)
VALUES (196, 'Wellness Employee Center', 'Wellness Employee Center', 0, 2);

INSERT INTO sSecurity.tMenu(Id, ParentMenuId, Title, TitleResourceKeyId, ScreenId, IsObsolete, OrderNumber, ShortcutKey)
VALUES (191810378, NULL, 'Wellness Employee Center', NULL, NULL, 0, 210, NULL);

update sSecurity.tTask set ModuleId = 196
where title in ('Wellness My Survey', 'Wellness Request Appointment', 'Wellness My Dashboard')

update sSecurity.tMenu set ParentMenuId = 191810378 where Id = 191810374

GO


CREATE PROCEDURE [sExamination].[pGetEmployeeDocumentsFromAPI]
@maintypeid int,    
@setupid int,    
@code varchar(300),    
@Name Varchar(300) = '',    
@orgid int,    
@readpermission bit = null,    
@deletepermission bit = null,    
@DocName varchar(300) = null,    
@StoreLocationId int = 0,
@ruserid bigint=0,  
@rConfigurationValue int = 0,
@rContractorId int = 0,
@rDepartmentId int = 0,
@FromDate date = '',
@ToDate date = '',
@RoundGroup int = 0,
@codelike varchar(300)
as    
begin    
 declare @empid bigint,@delmessage varchar(100)='''Are you sure to delete this item?'''   
     
 select @empid = Id from sHrm.tEmployeeMaster where Code = @code    
 if @code = ''    
 begin    
  select @empid = 0    
 end     
 select @empid = isnull(@empid,0)   
    
 declare @tbltmpHistory table(tid int identity(1,1),hid int)    
     
 if(@empid>0)    
   begin  
		if(@rConfigurationValue=1) -- for Different Drive  
		begin    
			insert into @tbltmpHistory  
			select distinct HD.Id from tbl_historydataoutside HD   
			inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
			inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
			inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
			inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
			inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
			inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id
			left join sProcurement.tVendorMaster VM on EJD.ContractorId = VM.Id 
			left join sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id
			where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
			and (HD.employeeid = @empid ) and EM.OrgID = @orgid
			and (HD.name like '%' + @DocName + '%' or @DocName = '')  
			and (EJD.OrganizationDepartmentId = @rDepartmentId or @rDepartmentId = 0)
			and ISNULL(EM.IsObsolete,0) = 0
			and (VM.Id = @rContractorId or @rContractorId = 0)
		and  (@MainTypeId <> 8 OR (e.ExaminationDate BETWEEN @FromDate AND @ToDate))
		and (@MainTypeId <> 1 OR ((SM.SetupGroupId = @RoundGroup) OR (@RoundGroup = 0)))
		AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@codelike, '') = ''
)
		end  
		if(@rConfigurationValue=2) -- for Azure  
		begin  
			insert into @tbltmpHistory  
			select distinct HD.Id from tbl_azurehistorydata HD   
			inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
			inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
			inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
			inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
			inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
			inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id   
			left join sProcurement.tVendorMaster VM on EJD.ContractorId = VM.Id --Nidhi Pandey dt- 24/01/2024 #30271 
			left join sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id
			where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
			and (HD.employeeid = @empid ) and EM.OrgID = @orgid 
			and (HD.name like '%' + @DocName + '%' or @DocName = '') 
			and (EJD.OrganizationDepartmentId = @rDepartmentId or @rDepartmentId = 0) 
			and ISNULL(EM.IsObsolete,0) = 0
			and (VM.Id = @rContractorId or @rContractorId = 0)
		and  (@MainTypeId <> 8 OR (e.ExaminationDate BETWEEN @FromDate AND @ToDate))
		and (@MainTypeId <> 1 OR ((SM.SetupGroupId = @RoundGroup) OR (@RoundGroup = 0)))
				AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@codelike, '') = ''
)
		end  
		else -- for Local or other  
		begin  
			insert into @tbltmpHistory    
			select distinct HD.Id from tbl_historydata HD  
			inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id    
			inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id    
			inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId    
			inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId    
			inner join sExamination.tSetupMaster SM on HD.setupid = SM.id    
			inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id     
			left join sProcurement.tVendorMaster VM on EJD.ContractorId = VM.Id
			left join sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id
			where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)    
			and (HD.employeeid = @empid ) and EM.OrgID = @orgid  
			and (HD.name like '%' + @DocName + '%' or @DocName = '')   
			and (EJD.OrganizationDepartmentId = @rDepartmentId or @rDepartmentId = 0)
			and ISNULL(EM.IsObsolete,0) = 0 
			and (VM.Id = @rContractorId or @rContractorId = 0)  
		and  (@MainTypeId <> 8 OR (e.ExaminationDate BETWEEN @FromDate AND @ToDate))
		and (@MainTypeId <> 1 OR ((SM.SetupGroupId = @RoundGroup) OR (@RoundGroup = 0)))
				AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@codelike, '') = ''
)
		end  
   end    
   else     
   begin    
		if(@rConfigurationValue=1) -- for Different Drive  
		begin    
			insert into @tbltmpHistory  
			select distinct HD.Id from tbl_historydataoutside HD   
			inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
			inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
			inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
			inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
			inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
			inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id   
			left join sProcurement.tVendorMaster VM on EJD.ContractorId = VM.Id --Nidhi Pandey dt- 24/01/2024 #30271
			left join sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id
			where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
			and (HD.employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
			and (((isnull(FirstName,'') + ' ' + isnull(LastName,'')) LIKE @Name) OR (ISNULL(@Name, '') = '') OR (ISNULL(FirstName, '') LIKE @Name+'%')) 
			and (HD.name like '%' + @DocName + '%' or @DocName = '')  
			and (1 = (case when @maintypeid = 1 then 0 else 1 end)or(SM.StoreLocationId = @StoreLocationId or @StoreLocationId = 0))   
			and (E.StorelocationId = @StoreLocationId or @StoreLocationId=0) 
			and (EJD.OrganizationDepartmentId = @rDepartmentId or @rDepartmentId = 0)  
			and ISNULL(EM.IsObsolete,0) = 0 
			and (VM.Id = @rContractorId or @rContractorId = 0)
		and  (@MainTypeId <> 8 OR (e.ExaminationDate BETWEEN @FromDate AND @ToDate))
		and (@MainTypeId <> 1 OR ((SM.SetupGroupId = @RoundGroup) OR (@RoundGroup = 0)))
				AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@codelike, '') = ''
)
		end  
		if(@rConfigurationValue=2) -- for Azure  
		begin  
			insert into @tbltmpHistory  
			select distinct HD.Id from tbl_azurehistorydata HD   
			inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
			inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
			inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
			inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
			inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
			inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id   
			left join sProcurement.tVendorMaster VM on EJD.ContractorId = VM.Id --Nidhi Pandey dt- 24/01/2024 #30271
			left join sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id
			where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
			and (HD.employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
			and (((isnull(FirstName,'') + ' ' + isnull(LastName,'')) LIKE @Name) OR (ISNULL(@Name, '') = '') OR (ISNULL(FirstName, '') LIKE @Name +'%'))      
			--and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid) --mantis id:0039446  
			and (HD.name like '%' + @DocName + '%' or @DocName = '')  
			and (EJD.OrganizationDepartmentId = @rDepartmentId or @rDepartmentId = 0)
			and (1 = (case when @maintypeid = 1 then 0 else 1 end)or(SM.StoreLocationId = @StoreLocationId or @StoreLocationId = 0))   
			and (E.StorelocationId = @StoreLocationId or @StoreLocationId=0)
			and ISNULL(EM.IsObsolete,0) = 0 --Nidhi Pandey dt- 22/05/2023  
			and (VM.Id = @rContractorId or @rContractorId = 0)  --Nidhi Pandey dt- 24/01/2024 #30271
		and  (@MainTypeId <> 8 OR (e.ExaminationDate BETWEEN @FromDate AND @ToDate))
		and (@MainTypeId <> 1 OR ((SM.SetupGroupId = @RoundGroup) OR (@RoundGroup = 0)))
				AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@codelike, '') = ''
)
		end  
		else -- for Local or other  
		begin  
			insert into @tbltmpHistory    
			select distinct HD.Id from tbl_historydata HD     
			inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id    
			inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id    
			inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId    
			inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId    
			inner join sExamination.tSetupMaster SM on HD.setupid = SM.id    
			inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id     
			left join sProcurement.tVendorMaster VM on EJD.ContractorId = VM.Id --Nidhi Pandey dt- 24/01/2024 #30271
			left join sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id
			where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)    
			and (HD.employeeid = @empid or @empid = 0) and EM.OrgID = @orgid    
			and (((isnull(FirstName,'') + ' ' + isnull(LastName,'')) LIKE @Name) OR (ISNULL(@Name, '') = '') OR (ISNULL(FirstName, '') LIKE @Name+'%'))        
			--and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid) --mantis id:0039446    
			and (HD.name like '%' + @DocName + '%' or @DocName = '')  
			and (EJD.OrganizationDepartmentId = @rDepartmentId or @rDepartmentId = 0)  
			and (1 = (case when @maintypeid = 1 then 0 else 1 end)or(SM.StoreLocationId = @StoreLocationId or @StoreLocationId = 0))    
			and (E.StorelocationId = @StoreLocationId or @StoreLocationId=0)     
			and ISNULL(EM.IsObsolete,0) = 0 --Nidhi Pandey dt- 22/05/2023 
			and (VM.Id = @rContractorId or @rContractorId = 0)  --Nidhi Pandey dt- 24/01/2024 #30271 
		and  (@MainTypeId <> 8 OR (e.ExaminationDate BETWEEN @FromDate AND @ToDate))
		and (@MainTypeId <> 1 OR ((SM.SetupGroupId = @RoundGroup) OR (@RoundGroup = 0)))
				AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@codelike, '') = ''
)
		end  
	end
   
   
if(@rConfigurationValue=1) -- for Different Drive  
begin    
       
     select   
   ISNULL(HD.Id,0) as HDId, ISNULL(SM.Id,0) as SMId  
  ,ISNULL(MT.Title,'') as MTTitle, ISNULL(SM.Title,'') as SMTitle  
  ,ISNULL(Code,'') as Code, ISNULL(name,'') as Name, isnull(FirstName,'') + ' ' + isnull(LastName,'') as EmployeeName  
  ,@readpermission as readpermission ,@deletepermission as deletepermission ,@delmessage as delmessage, @orgid as Orgid  
  ,ISNULL(ext,'') as ext,isnull(hd.OpdId,0)as OpdId  --mantis id: 46943; yogesh; Dt- 07/11/2025  
  from tbl_historydataoutside HD   
  inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
  inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
  inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
  inner join @tbltmpHistory on hid = HD.Id 
  where ISNULL(EM.IsObsolete,0) = 0 --Nidhi Pandey dt- 22/05/2023   
  order by tid  
    
end  
if(@rConfigurationValue=2) -- for Azure  
begin  
    
  select   
   ISNULL(HD.Id,0) as HDId, ISNULL(SM.Id,0) as SMId  
  ,ISNULL(MT.Title,'') as MTTitle, ISNULL(SM.Title,'') as SMTitle  
  ,ISNULL(Code,'') as Code, ISNULL(name,'') as Name, isnull(FirstName,'') + ' ' + isnull(LastName,'') as EmployeeName  
  ,@readpermission as readpermission ,@deletepermission as deletepermission ,@delmessage as delmessage, @orgid as Orgid,isnull(hd.OpdId,0)as OpdId  --mantis id: 46943; yogesh; Dt- 07/11/2025  
  from tbl_azurehistorydata HD   
  inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
  inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
  inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
  inner join @tbltmpHistory on hid = HD.Id   
  where ISNULL(EM.IsObsolete,0) = 0 --Nidhi Pandey dt- 22/05/2023   
  order by tid  
    
end  
else -- for Local or other  
begin   
    
  select   
   ISNULL(HD.Id,0) as HDId, ISNULL(SM.Id,0) as SMId  
  ,ISNULL(MT.Title,'') as MTTitle, ISNULL(SM.Title,'') as SMTitle  
  ,ISNULL(EM.Code,'') as Code, ISNULL(name,'') as Name, isnull(FirstName,'') + ' ' + isnull(LastName,'') as EmployeeName  
  ,@readpermission as readpermission ,@deletepermission as deletepermission ,@delmessage as delmessage, @orgid as Orgid,isnull(hd.OpdId,0)as OpdId  --mantis id: 46943; yogesh; Dt- 07/11/2025  
  ,ISNULL(OD.Title,'') as DepartmentName
  ,EJD.OrganizationDepartmentId as DepartmentId
  from tbl_historydata HD   
  inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id    
  inner join sExamination.tSetupMaster SM on HD.setupid = SM.id    
  inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
  inner join @tbltmpHistory on hid = HD.Id
  inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id
  left join sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id	
  where ISNULL(EM.IsObsolete,0) = 0 --Nidhi Pandey dt- 22/05/2023   
  order by tid    
    
end  
    
end

GO


CREATE or ALTER PROCEDURE [sExamination].[pGetEmployeeHealthIndex]  
(
	@rOrgId SMALLINT,
	@rEmployeeCode NVARCHAR(100)
)
AS  
BEGIN    
	DECLARE @lLatestVitalDisplayConfigVal VARCHAR(5) = 'False';
    DECLARE @EmployeeId BIGINT = 0;
	IF (@rOrgId > 0)
	BEGIN
		SELECT @lLatestVitalDisplayConfigVal = sConfig.fConfigurationValueGet('Examination.LatestVitalDisplayOnDashboard',@rOrgId,0,0,0);
	END

	IF (@rEmployeeCode IS NOT NULL AND LEN(@rEmployeeCode) > 0)
	BEGIN
		SET @EmployeeId = (SELECT Id FROM [sHrm].[tEmployeeMaster] WHERE Code = @rEmployeeCode)
	END

	DECLARE 
		@lHealthIndexScore DECIMAL(10,2),
		@lHeight INT,
		@lWeight DECIMAL(8,2),
		@lBMI DECIMAL(8,2),
		@lBloodPressureSystolic INT,
		@lBloodPressureDiastolic INT,
		@lFBS NVARCHAR(10),
		@lHB NVARCHAR(10),
		@lchol NVARCHAR(10),
		@lLastExaminationId BIGINT,
		@lLastExaminationdate nvarchar(20),
		@lHealthAnalysis NVARCHAR(1000),
		@lRBS NVARCHAR(10),
		@lHBA1C NVARCHAR(10),
		@lHealthScoreDate NVARCHAR(20),
		@lBMIDate NVARCHAR(20), 
		@lBPDate NVARCHAR(20),
		@lBloodSugarDate NVARCHAR(20), 
		@lCholesterolDate NVARCHAR(20),
		@lHBDate NVARCHAR(20),
		@lLDL NVARCHAR(10);

	SELECT @lHealthIndexScore = (SELECT TOP 1 CONVERT(DECIMAL(10,2),ROUND(ISNULL(D.HealthIndex,0),2)) 
	FROM sExamination.tExamination E 
	INNER JOIN sExamination.tDiagnosis D on D.SourceId=E.Id
	INNER JOIN sExamination.tSetupMaster SM on SM.id=E.SetupId
	INNER JOIN SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@EmployeeId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=1 and Isnull(D.HealthIndex,0)>0
	Order by E.ExaminationDate desc)

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

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

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

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

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

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

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


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

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

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


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

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

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

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

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

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


	SELECT 
		ISNULL(EM.Code,'-') AS EmployeeCode,
		ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') EmployeeName,
		convert(varchar(20),(DATEDIFF(yy,EPD.DateOfBirth,GETDATE()))) + ' Years' AS Age,
		Isnull(GM.Title,'') AS Gender,
		Isnull(BGM.Title,'') as BloodGroup,
		Isnull(@lHealthIndexScore,0) as HEALTHSCORE,
		@lHealthScoreDate as HealthScoreDate,
		Convert(varchar(10),Isnull(@lHeight,0)) + 'cm' as Height,
		Convert(varchar(10),Isnull(@lWeight,0)) + 'kg' as Weight,
		Isnull(@lBMI,0) as BMI,
		@lBMIDate as BMIDate,
		convert(varchar(10),@lBloodPressureSystolic) + '/' + Convert(varchar(10),@lBloodPressureDiastolic) as BP,
		@lBPDate as BPDate,
		Isnull(@lFBS,'0') as FBS,
		Isnull(@lHBA1C,'0') as HBA1C,
		Isnull(@lRBS,'0') as RBS,
		@lBloodSugarDate as BloodSugarDate,
		Isnull(@lchol,'0') as Cholesterol,
		@lCholesterolDate as CholesterolDate,
		Isnull(@lHB,'0') + ' g/dl' as Haemoglobin,
		@lHBDate as HBDate
	FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId 
		INNER JOIN sCommon.tLocationMaster LM on LM.ID = EJD.EmployeeLocationId
		LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId	 		     
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId	
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.Id = EC.EmployeeId 
		LEFT JOIN sHrm.tEmployeeJobTitleMaster EJTM ON EJTM.Id = EJD.EmployeeJobTitleId
		Left JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId
		Left JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = EPD.BloodGroupId
		LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM	ON EJD.OrganizationDepartmentId = ODM.Id
		LEFT JOIN sHrm.tEmployeeTypeMaster ETM on ETM.Id=EJD.EmployeeTypeId
		left join sHrm.tEmployeeImages EI on EI.EmployeeId=EM.id
		left join sExamination.tPrompt P on P.ParticipantId	=EM.id and P.ParticipantSourceTypeId=95
	Where EM.Id=@EmployeeId  
END

GO

ALTER TABLE [sWellness].[tWellnessConsultation]
ADD [OtherName] [nvarchar](250) NULL, [EmailAddress] [nvarchar](100) NULL

GO


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


ALTER PROCEDURE [sExamination].[pGetEmployeeDocumentsFromAPI]  
@maintypeid int,    
@setupid int,    
@code varchar(300),    
@Name Varchar(300) = '',    
@orgid int,    
@readpermission bit = null,    
@deletepermission bit = null,    
@DocName varchar(300) = null,    
@StoreLocationId int = 0,
@ruserid bigint=0,  
@rConfigurationValue int = 0,
@rContractorId int = 0,
@rDepartmentId int = 0,
@FromDate date = '',
@ToDate date = '',
@RoundGroup int = 0,
@codelike varchar(300)
as    
begin    
 declare @empid bigint,@delmessage varchar(100)='''Are you sure to delete this item?'''   
     
 select @empid = Id from sHrm.tEmployeeMaster where Code = @code    
 if @code = ''    
 begin    
  select @empid = 0    
 end     
 select @empid = isnull(@empid,0)   
    
 declare @tbltmpHistory table(tid int identity(1,1),hid int)    
     
 if(@empid>0)    
   begin  
		if(@rConfigurationValue=1) -- for Different Drive  
		begin    
			insert into @tbltmpHistory  
			select distinct HD.Id from tbl_historydataoutside HD   
			inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
			inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
			inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
			inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
			inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
			inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id
			left join sProcurement.tVendorMaster VM on EJD.ContractorId = VM.Id 
			left join sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id
			where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
			and (HD.employeeid = @empid ) and EM.OrgID = @orgid
			and (HD.name like '%' + @DocName + '%' or @DocName = '')  
			and (EJD.OrganizationDepartmentId = @rDepartmentId or @rDepartmentId = 0)
			and ISNULL(EM.IsObsolete,0) = 0
			and (VM.Id = @rContractorId or @rContractorId = 0)
		and  (@MainTypeId <> 8 OR (e.ExaminationDate BETWEEN @FromDate AND @ToDate))
		and (@MainTypeId <> 1 OR ((SM.SetupGroupId = @RoundGroup) OR (@RoundGroup = 0)))
		AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@codelike, '') = ''
)
		end  
		if(@rConfigurationValue=2) -- for Azure  
		begin  
			insert into @tbltmpHistory  
			select distinct HD.Id from tbl_azurehistorydata HD   
			inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
			inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
			inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
			inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
			inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
			inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id   
			left join sProcurement.tVendorMaster VM on EJD.ContractorId = VM.Id --Nidhi Pandey dt- 24/01/2024 #30271 
			left join sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id
			where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
			and (HD.employeeid = @empid ) and EM.OrgID = @orgid 
			and (HD.name like '%' + @DocName + '%' or @DocName = '') 
			and (EJD.OrganizationDepartmentId = @rDepartmentId or @rDepartmentId = 0) 
			and ISNULL(EM.IsObsolete,0) = 0
			and (VM.Id = @rContractorId or @rContractorId = 0)
		and  (@MainTypeId <> 8 OR (e.ExaminationDate BETWEEN @FromDate AND @ToDate))
		and (@MainTypeId <> 1 OR ((SM.SetupGroupId = @RoundGroup) OR (@RoundGroup = 0)))
				AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@codelike, '') = ''
)
		end  
		else -- for Local or other  
		begin  
			insert into @tbltmpHistory    
			select distinct HD.Id from tbl_historydata HD  
			inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id    
			inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id    
			inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId    
			inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId    
			inner join sExamination.tSetupMaster SM on HD.setupid = SM.id    
			inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id     
			left join sProcurement.tVendorMaster VM on EJD.ContractorId = VM.Id
			left join sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id
			where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)    
			and (HD.employeeid = @empid ) and EM.OrgID = @orgid  
			and (HD.name like '%' + @DocName + '%' or @DocName = '')   
			and (EJD.OrganizationDepartmentId = @rDepartmentId or @rDepartmentId = 0)
			and ISNULL(EM.IsObsolete,0) = 0 
			and (VM.Id = @rContractorId or @rContractorId = 0)  
		and  (@MainTypeId <> 8 OR (e.ExaminationDate BETWEEN @FromDate AND @ToDate))
		and (@MainTypeId <> 1 OR ((SM.SetupGroupId = @RoundGroup) OR (@RoundGroup = 0)))
				AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@codelike, '') = ''
)
		end  
   end    
   else     
   begin    
		if(@rConfigurationValue=1) -- for Different Drive  
		begin    
			insert into @tbltmpHistory  
			select distinct HD.Id from tbl_historydataoutside HD   
			inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
			inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
			inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
			inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
			inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
			inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id   
			left join sProcurement.tVendorMaster VM on EJD.ContractorId = VM.Id --Nidhi Pandey dt- 24/01/2024 #30271
			left join sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id
			where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
			and (HD.employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
			and (((isnull(FirstName,'') + ' ' + isnull(LastName,'')) LIKE @Name) OR (ISNULL(@Name, '') = '') OR (ISNULL(FirstName, '') LIKE @Name+'%')) 
			and (HD.name like '%' + @DocName + '%' or @DocName = '')  
			and (1 = (case when @maintypeid = 1 then 0 else 1 end)or(SM.StoreLocationId = @StoreLocationId or @StoreLocationId = 0))   
			and (E.StorelocationId = @StoreLocationId or @StoreLocationId=0) 
			and (EJD.OrganizationDepartmentId = @rDepartmentId or @rDepartmentId = 0)  
			and ISNULL(EM.IsObsolete,0) = 0 
			and (VM.Id = @rContractorId or @rContractorId = 0)
		and  (@MainTypeId <> 8 OR (e.ExaminationDate BETWEEN @FromDate AND @ToDate))
		and (@MainTypeId <> 1 OR ((SM.SetupGroupId = @RoundGroup) OR (@RoundGroup = 0)))
				AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@codelike, '') = ''
)
		end  
		if(@rConfigurationValue=2) -- for Azure  
		begin  
			insert into @tbltmpHistory  
			select distinct HD.Id from tbl_azurehistorydata HD   
			inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
			inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id  
			inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId  
			inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId  
			inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
			inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id   
			left join sProcurement.tVendorMaster VM on EJD.ContractorId = VM.Id --Nidhi Pandey dt- 24/01/2024 #30271
			left join sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id
			where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)  
			and (HD.employeeid = @empid or @empid = 0) and EM.OrgID = @orgid  
			and (((isnull(FirstName,'') + ' ' + isnull(LastName,'')) LIKE @Name) OR (ISNULL(@Name, '') = '') OR (ISNULL(FirstName, '') LIKE @Name +'%'))      
			--and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid) --mantis id:0039446  
			and (HD.name like '%' + @DocName + '%' or @DocName = '')  
			and (EJD.OrganizationDepartmentId = @rDepartmentId or @rDepartmentId = 0)
			and (1 = (case when @maintypeid = 1 then 0 else 1 end)or(SM.StoreLocationId = @StoreLocationId or @StoreLocationId = 0))   
			and (E.StorelocationId = @StoreLocationId or @StoreLocationId=0)
			and ISNULL(EM.IsObsolete,0) = 0 --Nidhi Pandey dt- 22/05/2023  
			and (VM.Id = @rContractorId or @rContractorId = 0)  --Nidhi Pandey dt- 24/01/2024 #30271
		and  (@MainTypeId <> 8 OR (e.ExaminationDate BETWEEN @FromDate AND @ToDate))
		and (@MainTypeId <> 1 OR ((SM.SetupGroupId = @RoundGroup) OR (@RoundGroup = 0)))
				AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@codelike, '') = ''
)
		end  
		else -- for Local or other  
		begin  
			insert into @tbltmpHistory    
			select distinct HD.Id from tbl_historydata HD     
			inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id    
			inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id    
			inner join sExamination.tExamination E on E.ParticipantSourceId=HD.employeeid and E.participantsourcetypeid=95 and E.setupId=Hd.SetupId    
			inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StorelocationId    
			inner join sExamination.tSetupMaster SM on HD.setupid = SM.id    
			inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id     
			left join sProcurement.tVendorMaster VM on EJD.ContractorId = VM.Id --Nidhi Pandey dt- 24/01/2024 #30271
			left join sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id
			where (HD.setupid = @setupid or @setupid = 0) and (maintypeid = @maintypeid or @maintypeid = 0)    
			and (HD.employeeid = @empid or @empid = 0) and EM.OrgID = @orgid    
			and (((isnull(FirstName,'') + ' ' + isnull(LastName,'')) LIKE @Name) OR (ISNULL(@Name, '') = '') OR (ISNULL(FirstName, '') LIKE @Name+'%'))        
			--and HD.setupid <> sCommon.fGetIntIdForOrg(8, @orgid) --mantis id:0039446    
			and (HD.name like '%' + @DocName + '%' or @DocName = '')  
			and (EJD.OrganizationDepartmentId = @rDepartmentId or @rDepartmentId = 0)  
			and (1 = (case when @maintypeid = 1 then 0 else 1 end)or(SM.StoreLocationId = @StoreLocationId or @StoreLocationId = 0))    
			and (E.StorelocationId = @StoreLocationId or @StoreLocationId=0)     
			and ISNULL(EM.IsObsolete,0) = 0 --Nidhi Pandey dt- 22/05/2023 
			and (VM.Id = @rContractorId or @rContractorId = 0)  --Nidhi Pandey dt- 24/01/2024 #30271 
		and  (@MainTypeId <> 8 OR (e.ExaminationDate BETWEEN @FromDate AND @ToDate))
		and (@MainTypeId <> 1 OR ((SM.SetupGroupId = @RoundGroup) OR (@RoundGroup = 0)))
				AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@codelike, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @codelike) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @codelike) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@codelike, '') = ''
)
		end  
	end
   
   
if(@rConfigurationValue=1) -- for Different Drive  
begin    
       
     select   
   ISNULL(HD.Id,0) as HDId, ISNULL(SM.Id,0) as SMId  
  ,ISNULL(MT.Title,'') as MTTitle, ISNULL(SM.Title,'') as SMTitle  
  ,ISNULL(Code,'') as Code, ISNULL(name,'') as Name, isnull(FirstName,'') + ' ' + isnull(LastName,'') as EmployeeName  
  ,@readpermission as readpermission ,@deletepermission as deletepermission ,@delmessage as delmessage, @orgid as Orgid  
  ,ISNULL(ext,'') as ext,isnull(hd.OpdId,0)as OpdId  --mantis id: 46943; yogesh; Dt- 07/11/2025  
  from tbl_historydataoutside HD   
  inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
  inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
  inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
  inner join @tbltmpHistory on hid = HD.Id 
  where ISNULL(EM.IsObsolete,0) = 0 --Nidhi Pandey dt- 22/05/2023   
  order by tid  
    
end  
if(@rConfigurationValue=2) -- for Azure  
begin  
    
  select   
   ISNULL(HD.Id,0) as HDId, ISNULL(SM.Id,0) as SMId  
  ,ISNULL(MT.Title,'') as MTTitle, ISNULL(SM.Title,'') as SMTitle  
  ,ISNULL(Code,'') as Code, ISNULL(name,'') as Name, isnull(FirstName,'') + ' ' + isnull(LastName,'') as EmployeeName  
  ,@readpermission as readpermission ,@deletepermission as deletepermission ,@delmessage as delmessage, @orgid as Orgid,isnull(hd.OpdId,0)as OpdId  --mantis id: 46943; yogesh; Dt- 07/11/2025  
  from tbl_azurehistorydata HD   
  inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id  
  inner join sExamination.tSetupMaster SM on HD.setupid = SM.id  
  inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
  inner join @tbltmpHistory on hid = HD.Id   
  where ISNULL(EM.IsObsolete,0) = 0 --Nidhi Pandey dt- 22/05/2023   
  order by tid  
    
end  
else -- for Local or other  
begin   
    
  select   
   ISNULL(HD.Id,0) as HDId, ISNULL(SM.Id,0) as SMId  
  ,ISNULL(MT.Title,'') as MTTitle, ISNULL(SM.Title,'') as SMTitle  
  ,ISNULL(EM.Code,'') as Code, ISNULL(name,'') as Name, isnull(FirstName,'') + ' ' + isnull(LastName,'') as EmployeeName  
  ,@readpermission as readpermission ,@deletepermission as deletepermission ,@delmessage as delmessage, @orgid as Orgid,isnull(hd.OpdId,0)as OpdId  --mantis id: 46943; yogesh; Dt- 07/11/2025  
  ,ISNULL(OD.Title,'') as DepartmentName
  ,EJD.OrganizationDepartmentId as DepartmentId
  from tbl_historydata HD   
  inner join sHrm.tEmployeeMaster EM on HD.employeeid = EM.id    
  inner join sExamination.tSetupMaster SM on HD.setupid = SM.id    
  inner join sExamination.tMainTypeMaster MT on HD.maintypeid = MT.Id  
  inner join @tbltmpHistory on hid = HD.Id
  inner join sHrm.temployeejobDetail EJD on EJD.Employeeid=EM.Id
  left join sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id	
  where ISNULL(EM.IsObsolete,0) = 0 --Nidhi Pandey dt- 22/05/2023   
  order by tid    
    
end  
    
end

GO


CREATE or ALTER PROCEDURE [sExamination].[pGetEmployeeHealthIndex]  
(
	@rOrgId SMALLINT,
	@rEmployeeCode NVARCHAR(100)
)
AS  
BEGIN    
	DECLARE @lLatestVitalDisplayConfigVal VARCHAR(5) = 'False';
    DECLARE @EmployeeId BIGINT = 0;
	IF (@rOrgId > 0)
	BEGIN
		SELECT @lLatestVitalDisplayConfigVal = sConfig.fConfigurationValueGet('Examination.LatestVitalDisplayOnDashboard',@rOrgId,0,0,0);
	END

	IF (@rEmployeeCode IS NOT NULL AND LEN(@rEmployeeCode) > 0)
	BEGIN
		SET @EmployeeId = (SELECT Id FROM [sHrm].[tEmployeeMaster] WHERE Code = @rEmployeeCode)
	END

	DECLARE 
		@lHealthIndexScore DECIMAL(10,2),
		@lHeight INT,
		@lWeight DECIMAL(8,2),
		@lBMI DECIMAL(8,2),
		@lBloodPressureSystolic INT,
		@lBloodPressureDiastolic INT,
		@lFBS NVARCHAR(10),
		@lHB NVARCHAR(10),
		@lchol NVARCHAR(10),
		@lLastExaminationId BIGINT,
		@lLastExaminationdate nvarchar(20),
		@lHealthAnalysis NVARCHAR(1000),
		@lRBS NVARCHAR(10),
		@lHBA1C NVARCHAR(10),
		@lHealthScoreDate NVARCHAR(20),
		@lBMIDate NVARCHAR(20), 
		@lBPDate NVARCHAR(20),
		@lBloodSugarDate NVARCHAR(20), 
		@lCholesterolDate NVARCHAR(20),
		@lHBDate NVARCHAR(20),
		@lLDL NVARCHAR(10);

	SELECT @lHealthIndexScore = (SELECT TOP 1 CONVERT(DECIMAL(10,2),ROUND(ISNULL(D.HealthIndex,0),2)) 
	FROM sExamination.tExamination E 
	INNER JOIN sExamination.tDiagnosis D on D.SourceId=E.Id
	INNER JOIN sExamination.tSetupMaster SM on SM.id=E.SetupId
	INNER JOIN SExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId
	Where E.ParticipantSourceId=@EmployeeId and E.ParticipantSourceTypeId=95
	and STM.MainTypeId=1 and Isnull(D.HealthIndex,0)>0
	Order by E.ExaminationDate desc)

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

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

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

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

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

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

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


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

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

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


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

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

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

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

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

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


	SELECT 
		ISNULL(EM.Code,'-') AS EmployeeCode,
		ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') EmployeeName,
		convert(varchar(20),(DATEDIFF(yy,EPD.DateOfBirth,GETDATE()))) + ' Years' AS Age,
		Isnull(GM.Title,'') AS Gender,
		Isnull(BGM.Title,'') as BloodGroup,
		Isnull(@lHealthIndexScore,0) as HEALTHSCORE,
		@lHealthScoreDate as HealthScoreDate,
		Convert(varchar(10),Isnull(@lHeight,0)) + 'cm' as Height,
		Convert(varchar(10),Isnull(@lWeight,0)) + 'kg' as Weight,
		Isnull(@lBMI,0) as BMI,
		@lBMIDate as BMIDate,
		convert(varchar(10),@lBloodPressureSystolic) + '/' + Convert(varchar(10),@lBloodPressureDiastolic) as BP,
		@lBPDate as BPDate,
		Isnull(@lFBS,'0') as FBS,
		Isnull(@lHBA1C,'0') as HBA1C,
		Isnull(@lRBS,'0') as RBS,
		@lBloodSugarDate as BloodSugarDate,
		Isnull(@lchol,'0') as Cholesterol,
		@lCholesterolDate as CholesterolDate,
		Isnull(@lHB,'0') + ' g/dl' as Haemoglobin,
		@lHBDate as HBDate
	FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId 
		INNER JOIN sCommon.tLocationMaster LM on LM.ID = EJD.EmployeeLocationId
		LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId	 		     
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId	
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.Id = EC.EmployeeId 
		LEFT JOIN sHrm.tEmployeeJobTitleMaster EJTM ON EJTM.Id = EJD.EmployeeJobTitleId
		Left JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId
		Left JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = EPD.BloodGroupId
		LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM	ON EJD.OrganizationDepartmentId = ODM.Id
		LEFT JOIN sHrm.tEmployeeTypeMaster ETM on ETM.Id=EJD.EmployeeTypeId
		left join sHrm.tEmployeeImages EI on EI.EmployeeId=EM.id
		left join sExamination.tPrompt P on P.ParticipantId	=EM.id and P.ParticipantSourceTypeId=95
	Where EM.Id=@EmployeeId  
END

GO


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

	WHERE 
		EM.IsObsolete = 0
		AND EM.OrgId = @rOrgId

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

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

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

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

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

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

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

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

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

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

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

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

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

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

GO


CREATE or ALTER proc [sSupport].[pAssignEmployeeExaminationGet]
@rSetupId [int] = 0,  
@rOrgId [int] = 0
as
begin
	SELECT EM.Id AS EmployeeId ,EM.Code AS EmployeeCode,  
 ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS EmployeeName
		FROM sExamination.tExamination E
		inner join sExamination.tSetupMaster SM1	on E.SetupId = SM1.Id
		inner join sExamination.tSubTypeMaster STM on SM1.SubTypeId = STM.Id
		inner join sHrm.tEmployeeMaster EM on EM.Id = E.ParticipantSourceId
		where e.setupid = @rSetupId
end

GO


ALTER PROCEDURE [sWellness].[pConsultationAdd]
@rId bigint,
@rOrgId smallint,
@rParticipantSourceTypeId smallint,
@rParticipantSourceId bigint,
@rSetupId bigint,
@rMainTypeId int,
@rConsultationDate date,
@rDoctorFlag int = null,
@rDoctorEmployeeId bigint  = NULL,
@rStatusId int,
@rStoreLocationId bigint,
@rCauseId int = null,
@rConsultationNotes nvarchar(2000) = '',
@rConsultationRemarks nvarchar(2000) = '',
@rConsultationTime nvarchar(50) = '',
@rConsultationOutTime nvarchar(50) = '',
@rOtherName nvarchar(250) = '',
@rOtherAge tinyint,
@rOtherMonth tinyint,
@rOtherGenderId tinyint,
@rEmailAddress nvarchar(100) = '',
@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
			)
			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
			)
			
			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
			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


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


ALTER PROCEDURE [sWellness].[pWellnessConsultationList]
(
	@rOrgId INT,  
	@rSetupId INT, 
	@rConsultationNo VARCHAR(300) = NULL,
	@rDoctorId BIGINT = 0,
	@rFromDate DATETIME = null,
	@rToDate DATETIME = null,
	@rCode NVARCHAR (20),  
	@rName NVARCHAR(50),
	@rCaseCauseId INT,
	@rEmployeeTypeId INT,
	@rStatusId int = 0,
	@rParticipantSourceTypeId int,
	@rStoreLocationId INT,	
	@rEmployeeId BIGINT = 0,
	@rProgramId BIGINT = 0,
	@SortColumnName NVARCHAR(MAX)= '',
	@IsAscendingOrder BIT= 0,
	@PageNumber INT = 1,
	@PageSize INT = 20,
	@GlobalSearch NVARCHAR(MAX)= ''
)
AS
SET NOCOUNT ON
BEGIN
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rName = sCommon.fSearchStringGet(@rName)
	
	SET @rFromDate = ISNULL (@rFromDate, '')
	SET @rToDate = ISNULL (@rToDate, '')

	
	;WITH PageNumbers AS(
	select 
	ROW_NUMBER() OVER(
			ORDER BY CASE WHEN @SortColumnName = 'ConsultationNumber' AND @IsAscendingOrder = 0 THEN t.ConsultationNumber END DESC,
					 CASE WHEN @SortColumnName = 'ConsultationNumber' AND @IsAscendingOrder = 1 THEN t.ConsultationNumber END,
					 CASE WHEN @SortColumnName = 'ParticipantCode' AND @IsAscendingOrder = 0 THEN t.ParticipantCode END DESC,
					 CASE WHEN @SortColumnName = 'ParticipantCode' AND @IsAscendingOrder = 1 THEN t.ParticipantCode END,
					 CASE WHEN @SortColumnName = 'ParticipantName' AND @IsAscendingOrder = 0 THEN t.ParticipantName END DESC,
					 CASE WHEN @SortColumnName = 'ParticipantName' AND @IsAscendingOrder = 1 THEN t.ParticipantName END,
					 CASE WHEN @SortColumnName = 'CreatedUserName' AND @IsAscendingOrder = 0 THEN t.CreatedUserName END DESC,
					 CASE WHEN @SortColumnName = 'CreatedUserName' AND @IsAscendingOrder = 1 THEN t.CreatedUserName END,
					 CASE WHEN @SortColumnName = 'Relation' AND @IsAscendingOrder = 0 THEN t.Relation END DESC,
					 CASE WHEN @SortColumnName = 'Relation' AND @IsAscendingOrder = 1 THEN t.Relation END,
					 CASE WHEN @SortColumnName = 'CauseName' AND @IsAscendingOrder = 0 THEN t.CauseName END DESC,
					 CASE WHEN @SortColumnName = 'CauseName' AND @IsAscendingOrder = 1 THEN t.CauseName END,
					 CASE WHEN @SortColumnName = '' THEN t.Id END DESC
	) PageId,
	COUNT(*) OVER() 'RecordCount',
	* from (
		SELECT 
			Cons.Id as Id,
			Cons.ConsultationNumber,
			Cons.ConsultationDate,
			CONVERT(VARCHAR,Cons.ConsultationDate,103) AS  ConsultationDateStr,
			ISNULL(PM.Title,'Not Applicable') AS ProgramName,
			Cons.CauseId,
			ISNULL(WVPM.Title,'-') AS CauseName,
			SM.RoundNumber,	
			SM.Title AS Setup,
			ParticipantCode = CASE Cons.ParticipantSourceTypeId WHEN 1009 THEN CSB.Code ELSE EM.Code END,
			[ParticipantName] = CASE Cons.ParticipantSourceTypeId WHEN 1009 THEN
			(CASE WHEN isnull(Cons.OtherName,'')='' THEN
			isnull(CSB.FirstName,'') + ' ' + isnull(CSB.LastName,'') ELSE Cons.OtherName END)
			ELSE EM.FirstName + ' ' + EM.LastName END,
			[Status] = SS.Title,
			ODP.Title AS Department,
			Relation = CASE Cons.ParticipantSourceTypeId WHEN 95 THEN 'Employee' WHEN 1009 THEN 'Other' END,
			StoreLocation = SLM.Title,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id = Cons.CreatedUserId) as CreatedUserName,
			ISNULL(EM1.FirstName,'') + ' ' + ISNULL( EM1.LastName,'') as DoctorName,
			ISNULL(ETM.Title,'-') AS EmployeeTypeName,
			ISNULL(PM.Id,-2) AS ProgramId
		FROM
			[sWellness].[tWellnessConsultation] Cons
		LEFT JOIN 
			[sHrm].[tEmployeeMaster] EM on Cons.ParticipantSourceId = EM.Id and Cons.ParticipantSourceTypeId = 95
		LEFT JOIN 
			sHrm.tCsrBenefiterMaster AS CSB ON CSB.Id = Cons.ParticipantSourceId AND Cons.ParticipantSourceTypeId = 1009
		LEFT JOIN 
			[sExamination].[tStatusMaster] SS on Cons.StatusId = SS.Id
		LEFT JOIN 
			[sHrm].[tEmployeeMaster] EM1 ON EM1.Id=Cons.DoctorEmployeeId
		LEFT JOIN 
			[sSecurity].[tUser] Users on Users.Id = Cons.CreatedUserId
		INNER JOIN 
			[sWellness].[tWellnessVisitPurposeMaster] WVPM on WVPM.Id = Cons.CauseId
		INNER JOIN 
			[sExamination].[tSetupMaster] SM on Cons.SetupId = SM.Id
		INNER JOIN 
			[sExamination].[tSubTypeMaster] ST on SM.SubTypeId = ST.Id
		INNER JOIN 
			[sIp].[tStoreLocationMaster] SLM on SLM.Id = Cons.StoreLocationId
		LEFT JOIN
			[sHrm].[tEmployeeJobDetail] EJD ON EJD.EmployeeId = EM.Id
		LEFT JOIN
			[sCommon].[tOrganizationDepartmentMaster] ODP ON ODP.Id = EJD.OrganizationDepartmentId
		LEFT JOIN
			[sHrm].[tEmployeeTypeMaster] ETM ON ETM.Id = EJD.EmployeeTypeId	
		LEFT JOIN	
			[sWellness].[tMHIScore] MHI  ON MHI.EmployeeId = Cons.ParticipantSourceId and Cons.ParticipantSourceTypeId = 95
		LEFT JOIN
			[sWellness].[tProgramMaster] PM ON PM.Id = MHI.ProgramId
		WHERE 
			Cons.OrgId = @rOrgId	
		AND 
			ISNULL(Cons.IsCancel,0) = 0
		AND (EM.Code LIKE @rCode + '%' OR @rCode = '' or CSB.Code LIKE @rCode + '%')    
		AND (EM.FirstName LIKE @rName + '%' or isnull(Cons.OtherName,'') LIKE @rName + '%' or CSB.FirstName LIKE Replace(@rName,' ','') + '%' OR @rName = '')			
		AND 
			((Cons.SetupId = @rSetupId) OR (@rSetupId = 0))
		AND 
			((EM.StatusId = @rStatusId) OR (@rStatusId = 0) OR (@rStatusId = -1))
		AND 
			(Cons.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)
		AND 
			((Cons.ConsultationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND 
			((Cons.ConsultationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))		
		AND
			((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = -1))
		AND 
			(Cons.CauseId = @rCaseCauseId OR @rCaseCauseId = 0 OR @rCaseCauseId = -1)
		AND 
			(Cons.DoctorEmployeeId = @rDoctorId OR @rDoctorId = 0)
		AND 
			((Cons.ParticipantSourceTypeId = @rParticipantSourceTypeId) OR (ISNULL(@rParticipantSourceTypeId,0)=0))
		AND 
			(Cons.ConsultationNumber LIKE '%' + @rConsultationNo OR ISNULL(@rConsultationNo,'')='')
	)
		t where ((t.ProgramId = @rProgramId) OR (@rProgramId = -1)) 
	AND
		(ISNULL(@GlobalSearch,'') = '' 
	OR 
		ISNULL(t.ConsultationDate,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
	OR 
		ISNULL(t.ParticipantCode,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
	OR 
		ISNULL(t.ParticipantName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
	OR 
		ISNULL(t.CreatedUserName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
	OR 
		ISNULL(t.CauseName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%')
	)
	SELECT  *
	FROM    PageNumbers
	WHERE  (@PageSize = -1 OR PageId  BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize))
END

GO


CREATE OR ALTER PROCEDURE [sWellness].[pWellnessConsultationList]
(
	@rOrgId INT,  
	@rSetupId INT, 
	@rConsultationNo VARCHAR(300) = NULL,
	@rDoctorId BIGINT = 0,
	@rFromDate DATETIME = null,
	@rToDate DATETIME = null,
	@rCode NVARCHAR (20),  
	@rName NVARCHAR(50),
	@rCaseCauseId INT,
	@rEmployeeTypeId INT,
	@rStatusId int = 0,
	@rParticipantSourceTypeId int,
	@rStoreLocationId INT,	
	@rEmployeeId BIGINT = 0,
	@rProgramId BIGINT = 0,
	@SortColumnName NVARCHAR(MAX)= '',
	@IsAscendingOrder BIT= 0,
	@PageNumber INT = 1,
	@PageSize INT = 20,
	@GlobalSearch NVARCHAR(MAX)= ''
)
AS
SET NOCOUNT ON
BEGIN
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rName = sCommon.fSearchStringGet(@rName)
	
	SET @rFromDate = ISNULL (@rFromDate, '')
	SET @rToDate = ISNULL (@rToDate, '')

	
	;WITH PageNumbers AS(
	select 
	ROW_NUMBER() OVER(
			ORDER BY CASE WHEN @SortColumnName = 'ConsultationNumber' AND @IsAscendingOrder = 0 THEN t.ConsultationNumber END DESC,
					 CASE WHEN @SortColumnName = 'ConsultationNumber' AND @IsAscendingOrder = 1 THEN t.ConsultationNumber END,
					 CASE WHEN @SortColumnName = 'ParticipantCode' AND @IsAscendingOrder = 0 THEN t.ParticipantCode END DESC,
					 CASE WHEN @SortColumnName = 'ParticipantCode' AND @IsAscendingOrder = 1 THEN t.ParticipantCode END,
					 CASE WHEN @SortColumnName = 'ParticipantName' AND @IsAscendingOrder = 0 THEN t.ParticipantName END DESC,
					 CASE WHEN @SortColumnName = 'ParticipantName' AND @IsAscendingOrder = 1 THEN t.ParticipantName END,
					 CASE WHEN @SortColumnName = 'CreatedUserName' AND @IsAscendingOrder = 0 THEN t.CreatedUserName END DESC,
					 CASE WHEN @SortColumnName = 'CreatedUserName' AND @IsAscendingOrder = 1 THEN t.CreatedUserName END,
					 CASE WHEN @SortColumnName = 'Relation' AND @IsAscendingOrder = 0 THEN t.Relation END DESC,
					 CASE WHEN @SortColumnName = 'Relation' AND @IsAscendingOrder = 1 THEN t.Relation END,
					 CASE WHEN @SortColumnName = 'CauseName' AND @IsAscendingOrder = 0 THEN t.CauseName END DESC,
					 CASE WHEN @SortColumnName = 'CauseName' AND @IsAscendingOrder = 1 THEN t.CauseName END,
					 CASE WHEN @SortColumnName = '' THEN t.Id END DESC
	) PageId,
	COUNT(*) OVER() 'RecordCount',
	* from (
		SELECT 
			Cons.Id as Id,
			Cons.ConsultationNumber,
			Cons.ConsultationDate,
			CONVERT(VARCHAR,Cons.ConsultationDate,103) AS  ConsultationDateStr,
			ISNULL(PM.Title,'Not Applicable') AS ProgramName,
			Cons.CauseId,
			ISNULL(WVPM.Title,'-') AS CauseName,
			SM.RoundNumber,	
			SM.Title AS Setup,
			ParticipantCode = CASE Cons.ParticipantSourceTypeId WHEN 1009 THEN CSB.Code ELSE EM.Code END,
			[ParticipantName] = CASE Cons.ParticipantSourceTypeId WHEN 1009 THEN
			(CASE WHEN isnull(Cons.OtherName,'')='' THEN
			isnull(CSB.FirstName,'') + ' ' + isnull(CSB.LastName,'') ELSE Cons.OtherName END)
			ELSE EM.FirstName + ' ' + EM.LastName END,
			[Status] = SS.Title,
			ODP.Title AS Department,
			Relation = CASE Cons.ParticipantSourceTypeId WHEN 95 THEN 'Employee' WHEN 1009 THEN 'Other' END,
			StoreLocation = SLM.Title,
			(SELECT DisplayTitle FROM sSecurity.tUser WHERE Id = Cons.CreatedUserId) as CreatedUserName,
			ISNULL(EM1.FirstName,'') + ' ' + ISNULL( EM1.LastName,'') as DoctorName,
			ISNULL(ETM.Title,'-') AS EmployeeTypeName,
			ISNULL(PM.Id,-2) AS ProgramId
		FROM
			[sWellness].[tWellnessConsultation] Cons
		LEFT JOIN 
			[sHrm].[tEmployeeMaster] EM on Cons.ParticipantSourceId = EM.Id and Cons.ParticipantSourceTypeId = 95
		LEFT JOIN 
			sHrm.tCsrBenefiterMaster AS CSB ON CSB.Id = Cons.ParticipantSourceId AND Cons.ParticipantSourceTypeId = 1009
		LEFT JOIN 
			[sExamination].[tStatusMaster] SS on Cons.StatusId = SS.Id
		LEFT JOIN 
			[sHrm].[tEmployeeMaster] EM1 ON EM1.Id=Cons.DoctorEmployeeId
		LEFT JOIN 
			[sSecurity].[tUser] Users on Users.Id = Cons.CreatedUserId
		INNER JOIN 
			[sWellness].[tWellnessVisitPurposeMaster] WVPM on WVPM.Id = Cons.CauseId
		INNER JOIN 
			[sExamination].[tSetupMaster] SM on Cons.SetupId = SM.Id
		INNER JOIN 
			[sExamination].[tSubTypeMaster] ST on SM.SubTypeId = ST.Id
		INNER JOIN 
			[sIp].[tStoreLocationMaster] SLM on SLM.Id = Cons.StoreLocationId
		LEFT JOIN
			[sHrm].[tEmployeeJobDetail] EJD ON EJD.EmployeeId = EM.Id
		LEFT JOIN
			[sCommon].[tOrganizationDepartmentMaster] ODP ON ODP.Id = EJD.OrganizationDepartmentId
		LEFT JOIN
			[sHrm].[tEmployeeTypeMaster] ETM ON ETM.Id = EJD.EmployeeTypeId	
		LEFT JOIN	
			[sWellness].[tMHIScore] MHI  ON MHI.EmployeeId = Cons.ParticipantSourceId and Cons.ParticipantSourceTypeId = 95
		LEFT JOIN
			[sWellness].[tProgramMaster] PM ON PM.Id = MHI.ProgramId
		WHERE 
			Cons.OrgId = @rOrgId	
		AND 
			ISNULL(Cons.IsCancel,0) = 0
		AND (EM.Code LIKE @rCode + '%' OR @rCode = '' or CSB.Code LIKE @rCode + '%')    
		AND (EM.FirstName LIKE @rName + '%' or isnull(Cons.OtherName,'') LIKE @rName + '%' or CSB.FirstName LIKE Replace(@rName,' ','') + '%' OR @rName = '')			
		AND 
			((Cons.SetupId = @rSetupId) OR (@rSetupId = 0))
		AND 
			((EM.StatusId = @rStatusId) OR (@rStatusId = 0) OR (@rStatusId = -1))
		AND 
			(Cons.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)
		AND 
			((Cons.ConsultationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND 
			((Cons.ConsultationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))		
		AND
			((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = -1))
		AND 
			(Cons.CauseId = @rCaseCauseId OR @rCaseCauseId = 0 OR @rCaseCauseId = -1)
		AND 
			(Cons.DoctorEmployeeId = @rDoctorId OR @rDoctorId = 0)
		AND 
			((Cons.ParticipantSourceTypeId = @rParticipantSourceTypeId) OR (ISNULL(@rParticipantSourceTypeId,0)=0))
		AND 
			(Cons.ConsultationNumber LIKE '%' + @rConsultationNo OR ISNULL(@rConsultationNo,'')='')
	)
		t where ((t.ProgramId = @rProgramId) OR (@rProgramId = -1)) 
	AND
		(ISNULL(@GlobalSearch,'') = '' 
	OR 
		ISNULL(t.ConsultationDate,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
	OR 
		ISNULL(t.ParticipantCode,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
	OR 
		ISNULL(t.ParticipantName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
	OR 
		ISNULL(t.CreatedUserName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
	OR 
		ISNULL(t.CauseName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%')
	)
	SELECT  *
	FROM    PageNumbers
	WHERE  (@PageSize = -1 OR PageId  BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize))
END
GO

/****** Object:  StoredProcedure [sWellness].[pEmployeeMHIScoreList]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


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

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

/****** Object:  StoredProcedure [sWellness].[pGetWellnessEmployeeProgramDetailsById]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetWellnessEmployeeProgramDetailsById](
	@rId INT,
	@rOrgId INT
)
AS		
BEGIN		--  [sWellness].[pGetWellnessEmployeeProgramDetailsById]1,9999
SET NOCOUNT ON;	

		SELECT MS.[Id] AS Id
			  ,MS.[ProgramId] AS ProgramId
			  ,PM.Title AS ProgramName
			  ,MS.[EmployeeId] AS EmployeeId
			  ,ED.Code As EmployeeCode
			  ,ED.EmployeeName AS EmployeeName
			  ,ED.EmployeeLocationId AS LocationId
			  ,ISNULL(ED.CompanyEmail,'') AS EmployeeEmail
			  ,LM.Title AS LocationName
			  ,[ED].[DepartmentId] AS DepartmentId
			  ,[ED].[DepartmentName] AS DepartmentName
			  ,[SurveyCategory] AS SurveyCategory
			  ,[MHICategory] AS MHICategory
		  FROM 
			  [sWellness].[tMHIScore] MS
		  LEFT JOIN
		      [sWellness].[tProgramMaster] PM 
		  ON 
			  MS.ProgramId = PM.Id
		  INNER JOIN 
			  [sHrm].[vExtEmployeeMaster] ED
		  ON 
			  MS.EmployeeId = ED.EmployeeId
		  LEFT JOIN
			  [sCommon].[tLocationMaster] LM
		  ON 
			 LM.Id = ED.EmployeeLocationId
		  WHERE
			 MS.OrgId = @rOrgId AND MS.Id = @rId;
END
GO

/****** Object:  StoredProcedure [sWellness].[pLastExaminationConsultationParameter]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


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

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

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

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

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

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

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

/****** Object:  StoredProcedure [sWellness].[pGetMHIScoreUpdationList]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

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

BEGIN		
			Select DISTINCT
			mhi.Id,
			mhi.ParticipantSourceTypeId,
			mhi.ParticipantSourceId,
			mhi.BMI,
			mhi.HBA1C,
			mhi.LDL,
			BPSystolic,
			BPDiastolic,
			mhi.Stress,
			mhi.LifeStyle,
			ED.Code as EmployeeCode,
			ED.EmployeeName
			FROM [sWellness].[tMHIScoreUpdation] mhi
			INNER JOIN [sHrm].[vEmployeeDetail] ED on mhi.ParticipantSourceId = ED.EmployeeId
			LEFT JOIN [sWellness].[tMHIScore] MHS on MHS.EmployeeId = ED.EmployeeId
			INNER JOIN [sIp].[tStoreLocationMaster] SLM	ON 	SLM.LocationId = ED.EmployeeLocationId
			INNER JOIN	sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id
			LEFT JOIN	[sWellness].[tProgramMaster] PM	ON PM.Id = MHS.ProgramId
			WHERE
			(
				@rProgramId = 0
				OR ((@rProgramId = 999) AND (MHS.ProgramId = 0 OR MHS.ProgramId IS NULL))
				OR (@rProgramId <> 0 AND @rProgramId <> 999 AND MHS.ProgramId = @rProgramId)
			)
		AND 
			(
				(@rDepartmentId = 0)
			OR 
				(ED.DepartmentId = @rDepartmentId)
			)
		AND 
			(
				(@rLocationId = 0)
			OR 
				(ED.EmployeeLocationId = @rLocationId)
			)
		AND 
			MHS.OrgId = @rOrgId
		AND 
			UL.UserId = @rUserId
			ORDER BY mhi.Id DESC
END

GO

/****** Object:  StoredProcedure [sWellness].[PEmpDashboardDetailGet]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sWellness].[PEmpDashboardDetailGet]
@rEmpId bigint,  
@rOrgId int = 0  
as  
begin    
declare @lLatestVitalDisplayConfigVal varchar(5) = 'False';          
IF (@rOrgId > 0)  
BEGIN   
select @lLatestVitalDisplayConfigVal = sConfig.fConfigurationValueGet('Examination.LatestVitalDisplayOnDashboard',@rOrgId,0,0,0);  
END   

Declare @lHeight int =0,
        @lWeight decimal(8,2)=0,
		@lBMI decimal(8,2)=0,
		@lBloodPressureSystolic int=0,
		@lBloodPressureDiastolic int=0,
        @lHBA1C nvarchar(10)='0', 
		@lLDL nvarchar(10)='0',
		@lBMIDate nvarchar(20)='', 
		@lBPDate nvarchar(20)='', 
		@lHBA1CDate nvarchar(20)='', 
		@lLDLDate nvarchar(20)='',
		@MHIBiometricsCategory NVARCHAR(20) = 'Pending', @MHIStressCategory NVARCHAR(20) = 'Pending', @MHILifestyleCategory NVARCHAR(20) = 'Pending', @MHISurveyCategory NVARCHAR(20) = 'Pending', @MHICategory NVARCHAR(20),
	@MHIHBA1C NUMERIC(10,2)=0, @MHILDL NUMERIC(10,2)=0, @MHIBMI NUMERIC(10,2)=0,  @MHIBP NVARCHAR(20) = '', @AssignedProgram NVARCHAR(200)= 'Not Assigned',
	@MHISysBp NUMERIC(10,0), @MHIDiaBp NUMERIC(10,0);
		
IF (@rEmpId > 0)
BEGIN

 set @lHeight = (select Top 1 GTCD.ParameterValue AS Height from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tGeneralTemplateConsultation GTC ON GTC.SourceId = WC.Id
	 INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	 INNER JOIN sExamination.tGeneralTemplateParameter GTM ON GTM.Id = GTCD.GeneralTemplateParameterId
	 WHERE WC.ParticipantSourceId = @rEmpId and WC.ParticipantSourceTypeId = 95
	 and GTM.StaticGeneralTemplateParameterId = 502 and Isnull(CAST(GTCD.ParameterValue as float),0) > 0
	 order by WC.Id desc);

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




IF (ISNULL(@lHeight, 0) = 0 AND ISNULL(@lWeight, 0) = 0)
BEGIN
Select Top 1 @lHeight=Height,@lWeight=BodyWeight,@lBMI=BMI,@lBMIDate=convert(varchar(20),ExaminationDate,103)   
from sExamination.tExamination E   
inner join sExamination.tVital V on V.SourceId=E.Id  
inner join sExamination.tSetupMaster SM on SM.id=E.SetupId    
inner join sExamination.tSubTypeMaster STM on STM.id=SM.SubTypeId  
Where E.ParticipantSourceId=@rEmpId and E.ParticipantSourceTypeId=95  
and Isnull(V.Height,0)>0 and Isnull(V.BodyWeight,0)>0 and Isnull(V.BMI,0)>0  
and ((@lLatestVitalDisplayConfigVal = 'True') or (@lLatestVitalDisplayConfigVal = 'False' and STM.MainTypeId!=8))  
Order by E.ExaminationDate desc;    
END   


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


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


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

SELECT TOP 1 @AssignedProgram = Title 
	FROM 
		[sWellness].[tProgramMaster] PM 
	INNER JOIN 
		[sWellness].[tMHIScore] MHI
	ON 
		MHI.ProgramId = PM.Id 
	WHERE 
		MHI.EmployeeId = @rEmpId;

END

SELECT TOP 1 @MHIBiometricsCategory = BiometricsCategory, @MHIStressCategory = StressCategory, @MHILifestyleCategory = LifestyleCategory, @MHISurveyCategory = SurveyCategory, @MHICategory = MHICategory , 
				 @MHIHBA1C = HBA1C, @MHILDL = LDL , @MHIBMI = BMI, @MHIBP = BP,
    @MHISysBp = TRY_CAST(
                    CASE 
                        WHEN BP IS NOT NULL 
                             AND LTRIM(RTRIM(BP)) <> ''
                             AND CHARINDEX('/', BP) > 1
                        THEN LTRIM(RTRIM(LEFT(BP, CHARINDEX('/', BP) - 1)))
                    END
                 AS INT),
    @MHIDiaBp = TRY_CAST(
                    CASE 
                        WHEN BP IS NOT NULL 
                             AND LTRIM(RTRIM(BP)) <> ''
                             AND CHARINDEX('/', BP) > 0
                             AND CHARINDEX('/', BP) < LEN(BP)
                        THEN LTRIM(RTRIM(
                                SUBSTRING(BP, CHARINDEX('/', BP) + 1, LEN(BP))
                             ))
                    END
                 AS INT)
		   FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmpId;



SELECT    
     'Ht : ' + Convert(varchar(10),Isnull(@lHeight,0)) + 'cm' as Height,   
	 'Wt : ' + Convert(varchar(10),Isnull(@lWeight,0)) + 'kg' as Weight,   
	 ISNULL(@lHeight,0) as Height1,   
	 ISNULL(@lWeight,0) as Weight1,   
	 ISNULL(@MHIBMI,0) as BMI,   
	 ISNULL(@MHIBP,'') as BP,   
	 ISNULL(@MHIHBA1C,'0') as HBA1C,   
	 ISNULL(@MHILDL,'0') as LDL,   
	 @lBMIDate as BMIDate,   
	 @lBPDate as BPDate,   
	 @lHBA1CDate as HBA1CDate,   
	 @lLDLDate as LDLDate,
	 @AssignedProgram AS AssignedProgram;
	 
EXEC [sWellness].[pGetEmployeeHealthIndex] @rEmpId , @MHIBMI ,@lBMIDate, @MHISysBp , @MHIDiaBp ,@lBPDate, @MHIHBA1C ,@lHBA1CDate,  @MHILDL, @lLDLDate;  
	 
END
GO

/****** Object:  StoredProcedure [sWellness].[pGetEmployeeHealthIndex]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



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

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

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

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


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

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

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

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

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

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

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


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

		DROP TABLE #TempParameterRange;

		SELECT TOP 1 @AssignedProgram = Title, @AssignedProgramDate =  CONVERT(VARCHAR(20),MHI.UpdatedDatetime,103) 
		FROM 
			[sWellness].[tProgramMaster] PM 
		INNER JOIN 
			[sWellness].[tMHIScore] MHI
		ON 
			MHI.ProgramId = PM.Id 
		WHERE 
			MHI.EmployeeId = @rEmployeeID;


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

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


		SELECT * FROM #TempMHIScore

		DROP TABLE #TempMHIScore
END
GO

/****** Object:  StoredProcedure [sWellness].[pAddOrUpdateProgramMHIScore]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramMHIScore]
(
	@rOrgId SMALLINT,	
    @rEmployeeId BIGINT,
	@rEmployeeSourceTypeId INT,
    @rSubmitFrom SMALLINT,
    @rBMI NUMERIC(10,2) = NULL,
    @rSystolicBP NUMERIC(10,0)=NULL,
    @rDiastolicBP NUMERIC(10,0)=NULL,
    @rHBA1C NUMERIC(10,2)=NULL,
    @rLDL NUMERIC(10,2)=NULL,
    @rStress NUMERIC(10,2)=NULL,
    @rLifeStyle NUMERIC(10,2)=NULL,
    @rUserId BIGINT
)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE @lNextNumber BIGINT = 0;
	BEGIN TRY
        BEGIN TRANSACTION
			CREATE TABLE #TempParameterRange
			(
				StaticHIPId INT, ParameterName VARCHAR(100), MinimumRange NUMERIC(10,5), MaximumRange NUMERIC(10,5), Score SMALLINT, Category NVARCHAR(100), GenderId SMALLINT
			)

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


			DECLARE @DepartmentId INT, @GenderId SMALLINT,
					@BMICategory NVARCHAR(30) = NULL, @BMIScore SMALLINT,
					@HBA1CCategory NVARCHAR(30) = NULL, @HBA1CScore SMALLINT,
					@LDLCategory NVARCHAR(30) = NULL, @LDLScore SMALLINT,
					@SystolicCategory NVARCHAR(30) = NULL, @SystolicScore SMALLINT,
					@DiastolicCategory NVARCHAR(30) = NULL, @DiastolicScore SMALLINT,
					@BPCategory NVARCHAR(30) = NULL, @BPScore SMALLINT = NULL,
					@BiometricsCategory VARCHAR(30) = NULL, @BiometricsCategoryIndex SMALLINT = NULL,
					@LifeStyleCategory VARCHAR(30) = NULL, @LifeStyleIndex SMALLINT = NULL,
					@StressCategory VARCHAR(30) = NULL, @StressIndex SMALLINT = NULL,
					@SurveyCategory VARCHAR(30) = NULL, @SurveyIndex SMALLINT = NULL,
					@MHICategory VARCHAR(30) = NULL, @MHIIndex SMALLINT = NULL,
					@TotalBiometrics INT = NULL, @BiometricScore DECIMAL(10,2) = NULL

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

			-- Add OR UPDATE Biometric parameter not included biometric category & survey & mhi category
			IF (@rSubmitFrom = 1 OR @rSubmitFrom = 2)
			BEGIN
				-- BMI
				IF(@rBMI IS NOT NULL AND @rBMI > 0 )
				BEGIN
					SELECT TOP 1 @BMICategory = Category, @BMIScore = Score FROM #TempParameterRange WHERE StaticHIPId = 1 AND @rBMI >= MinimumRange AND @rBMI <= MaximumRange AND GenderId = @GenderId
				END

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

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

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

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

				IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId)
				BEGIN
					
					EXEC sCommon.pTableRowIdGet @rOrgId,'sWellness.tMHIScore', 0,1,1, @outNextNumber = @lNextNumber OUTPUT

					INSERT INTO [sWellness].[tMHIScore] 
					(
						Id,OrgId,ProgramId, EmployeeId, EmployeeSourceTypeId, LastUpdateType,
						HBA1C,HBA1CScore, HBA1CCategory, LDL, LDLScore, LDLCategory, BMI, BMIScore, BMICategory,
						BP, BPScore, BPCategory,
						CreatedUserId, CreatedDatetime
					) 
					VALUES
					(
						@lNextNumber, @rOrgId, 0, @rEmployeeId, @rEmployeeSourceTypeId, @rSubmitFrom,
						@rHBA1C, @HBA1CScore, @HBA1CCategory, @rLDL, @LDLScore, @LDLCategory, @rBMI, @BMIScore, @BMICategory,
						CAST(@rSystolicBP AS VARCHAR(10)) + '/' + CAST(@rDiastolicBP AS VARCHAR(10)), @BPScore, @BPCategory,
						@rUserId, sCommon.fGetDate()
					)
				END
				ELSE
				BEGIN
					UPDATE 
						[sWellness].[tMHIScore]
					SET
						HBA1C = @rHBA1C,
						HBA1CScore = @HBA1CScore,
						HBA1CCategory = @HBA1CCategory,
						LDL = @rLDL,
						LDLScore = @LDLScore,
						LDLCategory = @LDLCategory,
						BMI = @rBMI,
						BMIScore = @BMIScore,
						BMICategory = @BMICategory,
						BP = CAST(@rSystolicBP AS VARCHAR(10)) + '/' + CAST(@rDiastolicBP AS VARCHAR(10)),
						BPScore = @BPScore,
						BPCategory = @BPCategory,
						UpdatedUserId = @rUserId,
						UpdatedDatetime = sCommon.fGetDate()
					WHERE
						EmployeeId = @rEmployeeId;

					 SET @lNextNumber =@@ROWCOUNT;
				END
			END
			-- Add OR UPDATE survey parameter not included bio metric category & biometric parameter & mhi category
			ELSE IF (@rSubmitFrom = 3)
			BEGIN				
				IF(@rStress IS NOT NULL)
				BEGIN
					SET @StressIndex = CASE WHEN @rStress IS NULL THEN NULL WHEN @rStress <= 13 THEN 1 WHEN @rStress <= 26 THEN 2 ELSE 3 END;
					SET @StressCategory = CASE @StressIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
				END
				IF(@rLifeStyle IS NOT NULL)
				BEGIN
					SET @LifestyleIndex = CASE WHEN @rLifeStyle IS NULL THEN NULL WHEN @rLifeStyle <= 49 THEN 3 WHEN @rLifeStyle <= 70 THEN 2 ELSE 1 END;
					SET @LifeStyleCategory = CASE @LifestyleIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
				END

				IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId)
				BEGIN		
				
					EXEC sCommon.pTableRowIdGet @rOrgId,'sWellness.tMHIScore', 0,1,1, @outNextNumber = @lNextNumber OUTPUT

					INSERT INTO [sWellness].[tMHIScore] 
					(
						Id,OrgId,ProgramId, EmployeeId, EmployeeSourceTypeId, LastUpdateType,
						Stress, StressScore, StressCategory, Lifestyle, LifestyleScore, LifestyleCategory,
						CreatedUserId, CreatedDatetime
					) 
					VALUES
					(
						@lNextNumber, @rOrgId, 0, @rEmployeeId, @rEmployeeSourceTypeId, @rSubmitFrom,
						@rStress, @StressIndex, @StressCategory, @rLifeStyle, @LifestyleIndex, @LifeStyleCategory,
						@rUserId, sCommon.fGetDate()
					)
				END
				ELSE
				BEGIN
					UPDATE 
						[sWellness].[tMHIScore]
					SET
						Stress = @rStress,
						StressScore = @StressIndex,
						StressCategory = @StressCategory,
						Lifestyle = @rLifeStyle,
						LifestyleScore = @LifestyleIndex,
						LifestyleCategory = @LifeStyleCategory,
						UpdatedUserId = @rUserId,
						UpdatedDatetime = sCommon.fGetDate()
					WHERE
						EmployeeId = @rEmployeeId;

					 SET @lNextNumber = @@ROWCOUNT;

				END
			END

			-- Calculate Biometric Score,  Biometric Category, Survey Category, MHI Category Start
			IF EXISTS(SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId AND BMIScore IS NOT NULL AND HBA1CScore IS NOT NULL AND LDLScore IS NOT NULL AND  BPScore IS NOT NULL)
			BEGIN
				SELECT @TotalBiometrics = ISNULL(BMIScore, 0) + ISNULL(HBA1CScore, 0) + ISNULL(LDLScore, 0) + ISNULL(BPScore, 0) FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId
				SET @BiometricScore = (100.0 * @TotalBiometrics) / NULLIF(4, 0);			
				SET @BiometricsCategoryIndex = CASE WHEN @BiometricScore IS NULL THEN NULL WHEN @BiometricScore <= 100 THEN 1 WHEN @BiometricScore < 150 THEN 2 ELSE 3 END;
				SET @BiometricsCategory = CASE @BiometricsCategoryIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
			END
			IF EXISTS(SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId AND StressScore IS NOT NULL AND LifestyleScore IS NOT NULL)
			BEGIN
				SELECT TOP 1 @SurveyCategory = CASE WHEN StressScore = 3 OR LifestyleScore = 3 THEN 'Alert' WHEN StressScore = 2 OR LifestyleScore = 2 THEN 'SubOptimal' ELSE 'Optimal' END FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId;
			END
			IF(@BiometricsCategory IS NOT NULL AND @SurveyCategory IS NOT NULL)
			BEGIN
				SET @MHICategory =  CASE WHEN @BiometricsCategory = 'Alert' OR @SurveyCategory = 'Alert' THEN 'Alert' 
									WHEN @BiometricsCategory = 'SubOptimal' OR @SurveyCategory = 'SubOptimal' THEN 'SubOptimal' 
									ELSE 'Optimal' END;
			END

			UPDATE 
				[sWellness].[tMHIScore]
			SET
				Biometrics = @BiometricScore,
				BiometricsCategory = @BiometricsCategory,
				SurveyCategory = @SurveyCategory,
				MHICategory =  @MHICategory,
				UpdatedUserId = @rUserId,
				UpdatedDatetime = sCommon.fGetDate()
			WHERE
				EmployeeId = @rEmployeeId;

			SET @lNextNumber = @@ROWCOUNT;

			IF (@lNextNumber > 0)
			BEGIN
				 EXEC sWellness.pInsertMHIScoreHistoryIfChanged
						@rEmployeeId = @rEmployeeId,
						@rUserId     = @rUserId;
			END
 
		COMMIT TRANSACTION
        SELECT CAST(@lNextNumber AS NVARCHAR(20)) AS Result
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION

        SELECT CAST(-1 AS NVARCHAR(10)) AS Result
        SELECT ERROR_MESSAGE()
    END CATCH
END
GO

/****** Object:  StoredProcedure [sWellness].[pAddOrUpdateProgramMHIScoreNew]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramMHIScoreNew]
(
	@rOrgId SMALLINT,	
    @rEmployeeId BIGINT,
	@rEmployeeSourceTypeId INT,
    @rSubmitFrom SMALLINT,
    @rBMI NUMERIC(10,2) = NULL,
    @rSystolicBP NUMERIC(10,0)=NULL,
    @rDiastolicBP NUMERIC(10,0)=NULL,
    @rHBA1C NUMERIC(10,2)=NULL,
    @rLDL NUMERIC(10,2)=NULL,
    @rStress NUMERIC(10,2)=NULL,
    @rLifeStyle NUMERIC(10,2)=NULL,
    @rUserId BIGINT
)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE @lNextNumber BIGINT = 0;
	BEGIN TRY
        BEGIN TRANSACTION
			CREATE TABLE #TempParameterRange
			(
				StaticHIPId INT, ParameterName VARCHAR(100), MinimumRange NUMERIC(10,5), MaximumRange NUMERIC(10,5), Score SMALLINT, Category NVARCHAR(100), GenderId SMALLINT
			)

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

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

			DECLARE @DepartmentId INT, @GenderId SMALLINT,
					@BMICategory NVARCHAR(30) = NULL, @BMIScore SMALLINT,
					@HBA1CCategory NVARCHAR(30) = NULL, @HBA1CScore SMALLINT,
					@LDLCategory NVARCHAR(30) = NULL, @LDLScore SMALLINT,
					@SystolicCategory NVARCHAR(30) = NULL, @SystolicScore SMALLINT,
					@DiastolicCategory NVARCHAR(30) = NULL, @DiastolicScore SMALLINT,
					@BPCategory NVARCHAR(30) = NULL, @BPScore SMALLINT = NULL,
					@BiometricsCategory VARCHAR(30) = NULL, @BiometricsCategoryIndex SMALLINT = NULL,
					@LifeStyleCategory VARCHAR(30) = NULL, @LifeStyleIndex SMALLINT = NULL,
					@StressCategory VARCHAR(30) = NULL, @StressIndex SMALLINT = NULL,
					@SurveyCategory VARCHAR(30) = NULL, @SurveyIndex SMALLINT = NULL,
					@MHICategory VARCHAR(30) = NULL, @MHICategoryId SMALLINT = NULL,
					@TotalBiometrics INT = NULL, @BiometricScore DECIMAL(10,2) = NULL,
					@AssignedMHIIndicatorId INT = 0, @AssignedProgramId INT = 0

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

			-- Add OR UPDATE Biometric parameter not included biometric category & survey & mhi category
			
				-- BMI
			IF(@rBMI IS NOT NULL AND @rBMI > 0 )
			BEGIN
				SELECT TOP 1 @BMICategory = Category, @BMIScore = Score FROM #TempParameterRange WHERE StaticHIPId = 1 AND @rBMI >= MinimumRange AND @rBMI <= MaximumRange AND GenderId = @GenderId
			END

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

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

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

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

			IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId)
			BEGIN
					
				EXEC sCommon.pTableRowIdGet @rOrgId,'sWellness.tMHIScore', 0,1,1, @outNextNumber = @lNextNumber OUTPUT

				INSERT INTO [sWellness].[tMHIScore] 
				(
					Id,OrgId,ProgramId, EmployeeId, EmployeeSourceTypeId, LastUpdateType,
					HBA1C,HBA1CScore, HBA1CCategory, LDL, LDLScore, LDLCategory, BMI, BMIScore, BMICategory,
					BP, BPScore, BPCategory,
					CreatedUserId, CreatedDatetime
				) 
				VALUES
				(
					@lNextNumber, @rOrgId, 0, @rEmployeeId, @rEmployeeSourceTypeId, @rSubmitFrom,
					@rHBA1C, @HBA1CScore, @HBA1CCategory, @rLDL, @LDLScore, @LDLCategory, @rBMI, @BMIScore, @BMICategory,
					CAST(@rSystolicBP AS VARCHAR(10)) + '/' + CAST(@rDiastolicBP AS VARCHAR(10)), @BPScore, @BPCategory,
					@rUserId, sCommon.fGetDate()
				)
			END
			ELSE
			BEGIN
				UPDATE 
					[sWellness].[tMHIScore]
				SET
					HBA1C = @rHBA1C,
					HBA1CScore = @HBA1CScore,
					HBA1CCategory = @HBA1CCategory,
					LDL = @rLDL,
					LDLScore = @LDLScore,
					LDLCategory = @LDLCategory,
					BMI = @rBMI,
					BMIScore = @BMIScore,
					BMICategory = @BMICategory,
					BP = CAST(@rSystolicBP AS VARCHAR(10)) + '/' + CAST(@rDiastolicBP AS VARCHAR(10)),
					BPScore = @BPScore,
					BPCategory = @BPCategory,
					UpdatedUserId = @rUserId,
					UpdatedDatetime = sCommon.fGetDate()
				WHERE
					EmployeeId = @rEmployeeId;

					SET @lNextNumber =@@ROWCOUNT;
			END
			
			-- Add OR UPDATE survey parameter not included bio metric category & biometric parameter & mhi category
			IF(@rStress IS NOT NULL)
			BEGIN
				--SET @StressIndex = CASE WHEN @rStress IS NULL THEN NULL WHEN @rStress <= 13 THEN 1 WHEN @rStress <= 26 THEN 2 ELSE 3 END;
				SET @StressIndex = CASE WHEN @rStress IS NULL THEN NULL WHEN @rStress >= 90 THEN 1 WHEN @rStress >= 75 THEN 2 ELSE 3 END;
				SET @StressCategory = CASE @StressIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
			END
			--IF(@rLifeStyle IS NOT NULL AND @rLifeStyle > 0 )
			IF(@rLifeStyle IS NOT NULL)
			BEGIN
				SET @LifestyleIndex = CASE WHEN @rLifeStyle IS NULL THEN NULL WHEN @rLifeStyle <= 49 THEN 3 WHEN @rLifeStyle <= 70 THEN 2 ELSE 1 END;
				SET @LifeStyleCategory = CASE @LifestyleIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
			END

			IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId)
			BEGIN		
				
				EXEC sCommon.pTableRowIdGet @rOrgId,'sWellness.tMHIScore', 0,1,1, @outNextNumber = @lNextNumber OUTPUT

				INSERT INTO [sWellness].[tMHIScore] 
				(
					Id,OrgId,ProgramId, EmployeeId, EmployeeSourceTypeId, LastUpdateType,
					Stress, StressScore, StressCategory, Lifestyle, LifestyleScore, LifestyleCategory,
					CreatedUserId, CreatedDatetime
				) 
				VALUES
				(
					@lNextNumber, @rOrgId, 0, @rEmployeeId, @rEmployeeSourceTypeId, @rSubmitFrom,
					@rStress, @StressIndex, @StressCategory, @rLifeStyle, @LifestyleIndex, @LifeStyleCategory,
					@rUserId, sCommon.fGetDate()
				)
			END
			ELSE
			BEGIN
				UPDATE 
					[sWellness].[tMHIScore]
				SET
					Stress = @rStress,
					StressScore = @StressIndex,
					StressCategory = @StressCategory,
					Lifestyle = @rLifeStyle,
					LifestyleScore = @LifestyleIndex,
					LifestyleCategory = @LifeStyleCategory,
					UpdatedUserId = @rUserId,
					UpdatedDatetime = sCommon.fGetDate()
				WHERE
					EmployeeId = @rEmployeeId;

					SET @lNextNumber = @@ROWCOUNT;

			END

			-- Calculate Biometric Score,  Biometric Category, Survey Category, MHI Category Start
			IF EXISTS(SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId AND BMIScore IS NOT NULL AND HBA1CScore IS NOT NULL AND LDLScore IS NOT NULL AND  BPScore IS NOT NULL)
			BEGIN
				SELECT @TotalBiometrics = ISNULL(BMIScore, 0) + ISNULL(HBA1CScore, 0) + ISNULL(LDLScore, 0) + ISNULL(BPScore, 0) FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId
				SET @BiometricScore = (100.0 * @TotalBiometrics) / NULLIF(4, 0);			
				SET @BiometricsCategoryIndex = CASE WHEN @BiometricScore IS NULL THEN NULL WHEN @BiometricScore <= 100 THEN 1 WHEN @BiometricScore < 150 THEN 2 ELSE 3 END;
				SET @BiometricsCategory = CASE @BiometricsCategoryIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
			END
			IF EXISTS(SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId AND StressScore IS NOT NULL AND LifestyleScore IS NOT NULL)
			BEGIN
				SELECT TOP 1 @SurveyCategory = CASE WHEN StressScore = 3 OR LifestyleScore = 3 THEN 'Alert' WHEN StressScore = 2 OR LifestyleScore = 2 THEN 'SubOptimal' ELSE 'Optimal' END FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId;
			END
			IF(@BiometricsCategory IS NOT NULL AND @SurveyCategory IS NOT NULL)
			BEGIN
				SET @MHICategory =  CASE WHEN @BiometricsCategory = 'Alert' OR @SurveyCategory = 'Alert' THEN 'Alert' 
									WHEN @BiometricsCategory = 'SubOptimal' OR @SurveyCategory = 'SubOptimal' THEN 'SubOptimal' 
									ELSE 'Optimal' END;

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

				IF(@MHICategoryId > 0)
				BEGIN
					SET @AssignedMHIIndicatorId = (SELECT TOP 1 Id FROM [sWellness].[tStaticMHICategoryIndicator] WHERE Id = @MHICategoryId)
					IF(@AssignedMHIIndicatorId > 0)
					BEGIN
						SET @AssignedProgramId = (SELECT TOP 1 Id FROM [sWellness].[tProgramMaster] WHERE MHIIndicatorId = @AssignedMHIIndicatorId AND CategoryId = 1 AND IsObsolete = 0)
					END
				END
			END
			ELSE
			BEGIN
				SET @MHICategory = 'NotApplicable';
				SET @MHICategoryId = 0;
				SET @AssignedProgramId = 0;
			END

			UPDATE 
				[sWellness].[tMHIScore]
			SET
				ProgramId = @AssignedProgramId,
				Biometrics = @BiometricScore,
				BiometricsCategory = @BiometricsCategory,
				SurveyCategory = @SurveyCategory,
				MHICategory =  @MHICategory,
				MHICategoryId =  @MHICategoryId,
				UpdatedUserId = @rUserId,
				UpdatedDatetime = sCommon.fGetDate()
			WHERE
				EmployeeId = @rEmployeeId;

			SET @lNextNumber = @@ROWCOUNT;

			IF (@lNextNumber > 0)
			BEGIN
				 EXEC sWellness.pInsertMHIScoreHistoryIfChanged
						@rEmployeeId = @rEmployeeId,
						@rUserId     = @rUserId;
			END
 
		COMMIT TRANSACTION
        SELECT CAST(@lNextNumber AS NVARCHAR(20)) AS Result
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION

        SELECT CAST(-1 AS NVARCHAR(10)) AS Result
        SELECT ERROR_MESSAGE()
    END CATCH
END
GO

/****** Object:  StoredProcedure [sWellness].[pGetWellnessAppointmentSchedulingList]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
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
    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

/****** Object:  StoredProcedure [sWellness].[pGetAllConsultationDetails]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
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,
 Age = case when EP.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EP.DateOfBirth,getdate()) end,    
 isnull(SA.Id,'') as WellnessAppointmentId,    
 isnull(convert(varchar,SA.AppointmentDate,103),'') as AppointmentDate,    
 isnull(SA.FollowupRemark,'') as FollowupRemark,
 isnull(EE.ConsultationNotes,'') as ConsultationNotes,
 isnull(EE.ConsultationRemarks,'') as ConsultationRemarks,  
 EM2.FirstName + ' ' + isnull(EM2.LastName,'') as DoctorName, 
 isnull(EE.ConsultationTime,'') as ConsultationTime,    
 isnull(EE.ConsultationOutTime,'') as ConsultationOutTime,
 EJD.EmployeeLocationId as EmployeeLocationId,
 ISNULL(EE.OtherName,'') as OtherName, EE.Age as OtherAge, EE.Months as OtherMonth, EE.GenderId as OtherGenderId,
 ISNULL(EE.EmailAddress,'') as EmailAddress,
 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
 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

/****** Object:  StoredProcedure [sWellness].[pConsultationAdd]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE OR ALTER PROCEDURE [sWellness].[pConsultationAdd]
@rId bigint,
@rOrgId smallint,
@rParticipantSourceTypeId smallint,
@rParticipantSourceId bigint,
@rSetupId bigint,
@rMainTypeId int,
@rConsultationDate date,
@rDoctorFlag int = null,
@rDoctorEmployeeId bigint  = NULL,
@rStatusId int,
@rStoreLocationId bigint,
@rCauseId int = null,
@rConsultationNotes nvarchar(2000) = '',
@rConsultationRemarks nvarchar(2000) = '',
@rConsultationTime nvarchar(50) = '',
@rConsultationOutTime nvarchar(50) = '',
@rOtherName nvarchar(250) = '',
@rOtherAge tinyint,
@rOtherMonth tinyint,
@rOtherGenderId tinyint,
@rEmailAddress nvarchar(100) = '',
@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
			)
			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
			)
			
			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
			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

/****** Object:  StoredProcedure [sWellness].[pGetMySurveylist]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

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

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

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

/****** Object:  StoredProcedure [sWellness].[pGetWellnessActivityTaskMasterList]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetWellnessActivityTaskMasterList]
	@rActivityId INT = 0,
	@rFrequencyTypeId INT = 0
AS
BEGIN		
		SELECT [Id]
			  ,WATM.[ActivityId] AS ActivityId
			  ,WAM.ActivityName AS ActivityName
			  ,WATM.Name as TaskName
			  ,[TargetValue]
			  ,WAM.DefaultUnitId
			  ,CASE WHEN WAM.DefaultUnitId = 1 THEN 'Steps' 
					WHEN WAM.DefaultUnitId = 2 THEN 'Min' 
					WHEN WAM.DefaultUnitId = 3 THEN 'ML'
					WHEN WAM.DefaultUnitId = 4 THEN 'Times' 
					WHEN WAM.DefaultUnitId = 5 THEN 'Glass' 
					WHEN WAM.DefaultUnitId = 6 THEN 'Hours' 
					WHEN WAM.DefaultUnitId = 7 THEN 'GM'
					WHEN WAM.DefaultUnitId = 8 THEN 'hh_mm' 
					WHEN WAM.DefaultUnitId = 9 THEN 'MG' 
					WHEN WAM.DefaultUnitId = 10 THEN 'Number' 					
				END AS UnitName
			  ,[FrequencyTypeId]
			  ,CASE WHEN [FrequencyTypeId] = 1 THEN 'Daily'
					WHEN [FrequencyTypeId] = 2 THEN 'Weekly'
				END AS FrequencyType
			  ,[FrequencyCount]
			  ,[DurationDays]
		 FROM 
			[sWellness].[tWellnessActivityTaskMaster] WATM
		 LEFT JOIN 
			[sWellness].[tWellnessActivityMaster] WAM
		 ON 
			WAM.ActivityId = WATM.ActivityId
		 WHERE 
			(WAM.[ActivityId] = @rActivityId OR ISNULL(@rActivityId,0) = 0)
		 AND
			([FrequencyTypeId] = @rFrequencyTypeId OR ISNULL(@rFrequencyTypeId,0) = 0)
END
GO

/****** Object:  StoredProcedure [sWellness].[pGetWellnessActivityTaskMasterById]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetWellnessActivityTaskMasterById]
	@rId INT = 0
AS
BEGIN		
		SELECT [Id]
			  ,WATM.[ActivityId] AS ActivityId
			  ,WAM.ActivityName AS ActivityName
			  ,WATM.Name as TaskName
			  ,[TargetValue]
			  ,WAM.DefaultUnitId AS UnitId
			  ,CASE WHEN WAM.DefaultUnitId = 1 THEN 'Steps' 
					WHEN WAM.DefaultUnitId = 2 THEN 'Min' 
					WHEN WAM.DefaultUnitId = 3 THEN 'ML'
					WHEN WAM.DefaultUnitId = 4 THEN 'Times'
					WHEN WAM.DefaultUnitId = 5 THEN 'Glass' 
					WHEN WAM.DefaultUnitId = 6 THEN 'Hours' 
					WHEN WAM.DefaultUnitId = 7 THEN 'GM'
					WHEN WAM.DefaultUnitId = 8 THEN 'hh_mm' 
					WHEN WAM.DefaultUnitId = 9 THEN 'MG' 
					WHEN WAM.DefaultUnitId = 10 THEN 'Number' 	
				END AS UnitName
			  ,[FrequencyTypeId]
			  ,CASE WHEN [FrequencyTypeId] = 1 THEN 'Daily'
					WHEN [FrequencyTypeId] = 2 THEN 'Weekly'
				END AS FrequencyType
			  ,[FrequencyCount]
			  ,[DurationDays]
		 FROM 
			[sWellness].[tWellnessActivityTaskMaster] WATM
		 LEFT JOIN 
			[sWellness].[tWellnessActivityMaster] WAM
		 ON 
			WAM.ActivityId = WATM.ActivityId
		 WHERE 
			WATM.Id = @rId
END
GO

/****** Object:  StoredProcedure [sWellness].[pActivityMasterGetList]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

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

BEGIN		
			Select AM.ActivityId,AM.ActivityName,
			ACM.Title as ActivityCategoryName,AM.Description,
			CASE WHEN AM.IsObsolete = 0 THEN 'Active'
			ELSE 'InActive'
			end as Status,
			AM.IsObsolete,
			CASE WHEN [DefaultUnitId] = 1 THEN 'Steps' 
					WHEN [DefaultUnitId] = 2 THEN 'Min' 
					WHEN [DefaultUnitId] = 3 THEN 'ML'
					WHEN [DefaultUnitId] = 4 THEN 'Times' 
					WHEN [DefaultUnitId] = 5 THEN 'Glass' 
					WHEN [DefaultUnitId] = 6 THEN 'Hours' 
					WHEN [DefaultUnitId] = 7 THEN 'GM'
					WHEN [DefaultUnitId] = 8 THEN 'hh_mm' 
					WHEN [DefaultUnitId] = 9 THEN 'MG' 
					WHEN [DefaultUnitId] = 10 THEN 'Number'
				END AS UnitName,
			DefaultUnitId,
			ACM.Code as ActivityCode
			FROM 
			[sWellness].[tWellnessActivityMaster] AM
			INNER JOIN [sWellness].[tWellnessActivityCategoryMaster] ACM ON AM.WellnessActivityCategoryId = ACM.Id
			Where 
			(ActivityName like '%'+@rActivityName+'%' or ISNULL(@rActivityName,'')='')
			and (WellnessActivityCategoryId = @rActivityCategoryId OR (@rActivityCategoryId = 0 OR @rActivityCategoryId is null))
			ORDER BY AM.ActivityId DESC
END
GO

/****** Object:  StoredProcedure [sWellness].[pAddOrUpdateProgramMHIScoreBulk]    Script Date: 06-04-2026 19:19:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


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

SET NOCOUNT ON;

BEGIN TRY
BEGIN TRANSACTION;

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

------------------------------------------------
-- Parameter ranges
------------------------------------------------
SELECT
      HIPM.StaticHealthIndexParameterId
    , HIPD.FromValue
    , HIPD.ToValue
    , CASE
        WHEN HIPD.Points = 10 THEN 1
        WHEN HIPD.Points = 6 THEN 2
        WHEN HIPD.Points = 3 THEN 3
        ELSE HIPD.Points
      END Score
    , HIPD.DiagnosisRemark Category
    , HIPD.GenderId
INTO #TempParameterRange
FROM sExamination.tHealthIndexParameterMaster HIPM
JOIN sExamination.tHealthIndexParameterDetail HIPD
ON HIPD.HealthIndexParameterId = HIPM.Id
WHERE HIPM.StaticHealthIndexParameterId IN (1,2,5,17,23);

------------------------------------------------
-- Map EmployeeCode → EmployeeId
------------------------------------------------
SELECT
      EM.EmployeeId
    , EM.GenderId
    , S.BMI
    , S.SystolicBP
    , S.DiastolicBP
    , S.HBA1C
    , S.LDL
    , S.Stress
    , S.LifeStyle
INTO #InputData
FROM @rMHIScoreList S
JOIN sHrm.vExtEmployeeMaster EM
ON EM.Code = S.EmployeeCode;

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

------------------------------------------------
-- Score calculation
------------------------------------------------
SELECT
      I.*
    , BMI.Score BMIScore
    , BMI.Category BMICategory
    , HBA1C.Score HBA1CScore
    , HBA1C.Category HBA1CCategory
    , LDL.Score LDLScore
    , LDL.Category LDLCategory
    , CASE WHEN SYS.Score > DIA.Score THEN SYS.Score ELSE DIA.Score END BPScore
    , CASE WHEN I.Stress IS NULL THEN NULL WHEN I.Stress >= 90 THEN 1 WHEN I.Stress >= 75 THEN 2 ELSE 3 END StressScore
    , CASE  WHEN I.LifeStyle IS NULL THEN NULL WHEN I.LifeStyle <=49 THEN 3 WHEN I.LifeStyle <=70 THEN 2 ELSE 1 END LifestyleScore
INTO #Calculated
FROM #InputData I

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=1
AND I.BMI BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) BMI

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=2
AND I.HBA1C BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) HBA1C

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=5
AND I.LDL BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) LDL

OUTER APPLY
(
SELECT TOP 1 Score
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=23
AND I.SystolicBP BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) SYS

OUTER APPLY
(
SELECT TOP 1 Score
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=17
AND I.DiastolicBP BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) DIA;

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

UPDATE #Calculated
SET Biometrics =
(100.0*(ISNULL(BMIScore,0)+ISNULL(HBA1CScore,0)+ISNULL(LDLScore,0)+ISNULL(BPScore,0)))/4;

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

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

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

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

------------------------------------------------
-- Program assignment
------------------------------------------------
UPDATE C
SET ProgramId = PM.Id
FROM #Calculated C
JOIN sWellness.tStaticMHICategoryIndicator I
ON I.Id=C.MHICategoryId
JOIN sWellness.tProgramMaster PM
ON PM.MHIIndicatorId=I.Id
AND PM.CategoryId=1
AND PM.IsObsolete=0;

------------------------------------------------
-- UPDATE existing rows
------------------------------------------------
UPDATE T
SET
BMI=C.BMI,
BMIScore=C.BMIScore,
BMICategory=C.BMICategory,

HBA1C=C.HBA1C,
HBA1CScore=C.HBA1CScore,
HBA1CCategory=C.HBA1CCategory,

LDL=C.LDL,
LDLScore=C.LDLScore,
LDLCategory=C.LDLCategory,

BP=CAST(C.SystolicBP AS VARCHAR(10))+'/'+CAST(C.DiastolicBP AS VARCHAR(10)),
BPScore=C.BPScore,
BPCategory=CASE C.BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' ELSE 'Alert' END,

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

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

Biometrics=C.Biometrics,
BiometricsCategory=C.BiometricsCategory,

SurveyCategory=C.SurveyCategory,
MHICategory=C.MHICategory,
MHICategoryId=C.MHICategoryId,

ProgramId=C.ProgramId,

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

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

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

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

OPEN curInsert;
FETCH NEXT FROM curInsert INTO @EmployeeId;

WHILE @@FETCH_STATUS=0
BEGIN

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

INSERT INTO sWellness.tMHIScore
(
Id,OrgId,ProgramId,EmployeeId,EmployeeSourceTypeId,LastUpdateType,
HBA1C,HBA1CScore,HBA1CCategory,
LDL,LDLScore,LDLCategory,
BMI,BMIScore,BMICategory,
BP,BPScore,BPCategory,
Stress,StressScore,StressCategory,
Lifestyle,LifestyleScore,LifestyleCategory,
Biometrics,BiometricsCategory,
SurveyCategory,MHICategory,MHICategoryId,
CreatedUserId,CreatedDatetime
)
SELECT
@NextId,@rOrgId,C.ProgramId,C.EmployeeId,95,4,
C.HBA1C,C.HBA1CScore,C.HBA1CCategory,
C.LDL,C.LDLScore,C.LDLCategory,
C.BMI,C.BMIScore,C.BMICategory,
CAST(C.SystolicBP AS VARCHAR(10))+'/'+CAST(C.DiastolicBP AS VARCHAR(10)),
C.BPScore,
CASE C.BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' ELSE 'Alert' END,
C.Stress,C.StressScore,
CASE C.StressScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' ELSE 'Alert' END,
C.LifeStyle,C.LifestyleScore,
CASE C.LifestyleScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' ELSE 'Alert' END,
C.Biometrics,C.BiometricsCategory,
C.SurveyCategory,C.MHICategory,C.MHICategoryId,
@rUserId,sCommon.fGetDate()
FROM #Calculated C
WHERE C.EmployeeId=@EmployeeId;

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

FETCH NEXT FROM curInsert INTO @EmployeeId;
END

CLOSE curInsert;
DEALLOCATE curInsert;

------------------------------------------------
-- History
------------------------------------------------
DECLARE @EmpId BIGINT;

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

OPEN curHistory;
FETCH NEXT FROM curHistory INTO @EmpId;

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

FETCH NEXT FROM curHistory INTO @EmpId;
END

CLOSE curHistory;
DEALLOCATE curHistory;

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

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

COMMIT TRANSACTION;

END TRY
BEGIN CATCH

IF @@TRANCOUNT>0 ROLLBACK TRANSACTION;

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

SELECT ERROR_MESSAGE() ErrorMessage,ERROR_LINE() ErrorLine;

END CATCH

END

GO


ALTER PROCEDURE [sExamination].[pGetInjuryFormFields]
@rId [bigint] = 0
AS  
SET NOCOUNT ON  
BEGIN
	DECLARE @CauseId int = 0,@ExaminationId bigint;
	SET @CauseId = (SELECT ISNULL(CauseId, 0) FROM sExamination.tExamination EXM
	INNER JOIN [sExamination].[tCustomIncident] CI ON CI.ExaminationId = EXM.Id
	WHERE CI.Id = @rId)

	SET @ExaminationId = (SELECT ExaminationId from [sExamination].[tCustomIncident] where Id = @rId)

	IF EXISTS(SELECT 1 FROM [sInjury].[vIncidentInformation] WHERE ExaminationId = @ExaminationId)
	BEGIN
	SELECT 
	InS.Id,
	FieldRemark,
	FieldTypeId,
	FieldList,
	IsFieldMandatory,
	FieldGroup,FieldOrder,
	CASE WHEN FieldRemark = 'Process Name' THEN ISNULL(II.ProcessName,'')
	WHEN FieldRemark = 'Equipment name' THEN ISNULL(II.EquipmentName,'')
	WHEN FieldRemark = 'Injury phenomena Basic Details' THEN ISNULL(II.InjuryPhenomenaBasicDetails,'')
	WHEN FieldRemark = 'Shift' THEN 
	CASE WHEN II.ShiftId = 1 THEN 'A'
	WHEN II.ShiftId = 2 THEN 'B'
	WHEN II.ShiftId = 3 THEN 'C'
	WHEN II.ShiftId = 4 THEN 'G'
	END
	ELSE '' END AS IncidentFieldResponse
    FROM sSafety.tIncidentSetup InS
	LEFT JOIN [sExamination].[tCustomIncidentField] CIF ON CIF.IncidentSetupId = InS.Id and IncidentId = @rId 
	LEFT JOIN [sExamination].[tCustomIncident] CI ON CI.Id = CIF.IncidentId
	LEFT JOIN [sInjury].[vIncidentInformation] II ON CI.ExaminationId = II.ExaminationId
    Where Isnull(InS.CauseId, 0) = @CauseId and @CauseId > 0
    ORDER BY FieldOrder
	END

	ELSE 
	BEGIN
	SELECT InS.Id, FieldRemark,FieldTypeId,FieldList,IsFieldMandatory,FieldGroup,FieldOrder,ISNULL(IncidentFieldResponse,'') AS IncidentFieldResponse
    FROM sSafety.tIncidentSetup InS
	LEFT JOIN [sExamination].[tCustomIncidentField] CIF ON CIF.IncidentSetupId = InS.Id and IncidentId = @rId
    Where Isnull(InS.CauseId, 0) = @CauseId and @CauseId > 0
    ORDER BY FieldOrder
	END
END

GO


ALTER PROCEDURE [sExamination].[pGetInjuryListingFields]
@rId [bigint] = 0
AS  
SET NOCOUNT ON  
BEGIN
	DECLARE @CauseId int = 0,@ExaminationId bigint;
	SET @CauseId = (SELECT ISNULL(CauseId, 0) FROM sExamination.tExamination EXM
	INNER JOIN [sExamination].[tCustomIncident] CI ON CI.ExaminationId = EXM.Id
	WHERE CI.Id = @rId)

	SET @ExaminationId = (SELECT ExaminationId from [sExamination].[tCustomIncident] where Id = @rId)

	IF EXISTS(SELECT 1 FROM [sInjury].[vIncidentInformation] WHERE ExaminationId = @ExaminationId)
	BEGIN
	SELECT 
	InS.Id,
	FieldRemark,
	FieldTypeId,
	FieldList,
	IsFieldMandatory,
	FieldGroup,FieldOrder,
	CASE WHEN FieldRemark = 'Process Name' THEN ISNULL(II.ProcessName,'')
	WHEN FieldRemark = 'Equipment name' THEN ISNULL(II.EquipmentName,'')
	WHEN FieldRemark = 'Injury phenomena Basic Details' THEN ISNULL(II.InjuryPhenomenaBasicDetails,'')
	WHEN FieldRemark = 'Shift' THEN 
	CASE WHEN II.ShiftId = 1 THEN 'A'
	WHEN II.ShiftId = 2 THEN 'B'
	WHEN II.ShiftId = 3 THEN 'C'
	WHEN II.ShiftId = 4 THEN 'G'
	END
	ELSE ISNULL(IncidentFieldResponse,'') END AS IncidentFieldResponse
    FROM sSafety.tIncidentSetup InS
	LEFT JOIN [sExamination].[tCustomIncidentField] CIF ON CIF.IncidentSetupId = InS.Id and IncidentId = @rId 
	LEFT JOIN [sExamination].[tCustomIncident] CI ON CI.Id = CIF.IncidentId
	LEFT JOIN [sInjury].[vIncidentInformation] II ON CI.ExaminationId = II.ExaminationId
    Where Isnull(InS.CauseId, 0) = @CauseId and @CauseId > 0
    ORDER BY FieldOrder
	END

	ELSE 
	BEGIN
	SELECT InS.Id, FieldRemark,FieldTypeId,FieldList,IsFieldMandatory,FieldGroup,FieldOrder,ISNULL(IncidentFieldResponse,'') AS IncidentFieldResponse
    FROM sSafety.tIncidentSetup InS
	LEFT JOIN [sExamination].[tCustomIncidentField] CIF ON CIF.IncidentSetupId = InS.Id and IncidentId = @rId
    Where Isnull(InS.CauseId, 0) = @CauseId and @CauseId > 0
    ORDER BY FieldOrder
	END
END

GO


ALTER PROCEDURE [sExamination].[pInjuryListingGet]  
@rId [bigint] = 0,
@rEmployeeCode[nvarchar](20),
@rStoreLocationId [int],
@rUserId [bigint] = 0
AS  
SET NOCOUNT ON  
BEGIN  
 SET @rEmployeeCode=sCommon.fSearchStringGet(@rEmployeeCode);  
   
 WITH InjuredPersons AS (
    SELECT 
        II.Id AS IncidentId,

        -- InjuredPersonNames
        STUFF((
            SELECT ', ' + ED.EmployeeDetails
            FROM (
                SELECT DISTINCT
                    vd.ReportId,
                    LTRIM(RTRIM(
                        CASE
                            WHEN eem.FirstName IS NOT NULL AND eem.FirstName <> '' AND eem.FirstName <> '--'
                                 AND vd.VisitorName IS NOT NULL AND vd.VisitorName <> '' AND vd.VisitorName <> '--'
                            THEN (eem.FirstName + ' ' + eem.LastName) + ', ' + vd.VisitorName
                            WHEN eem.FirstName IS NOT NULL AND eem.FirstName <> '' AND eem.FirstName <> '--'
                            THEN (eem.FirstName + ' ' + eem.LastName)
                            WHEN vd.VisitorName IS NOT NULL AND vd.VisitorName <> '' AND vd.VisitorName <> '--'
                            THEN vd.VisitorName
                            ELSE ''
                        END
                    )) AS EmployeeDetails
                FROM [sInjury].[vVictimDetails] vd
                LEFT JOIN sHrm.tEmployeeMaster eem ON eem.Id = vd.EmployeeId
            ) ED
            WHERE ED.ReportId = II.Id
            FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS InjuredPersonNames,

        -- EmployeeCode
        STUFF((
            SELECT ', ' + ED.EmployeeCodes
            FROM (
                SELECT DISTINCT
                    vd.ReportId,
                    LTRIM(RTRIM(
                        CASE
                            WHEN eem.Code IS NOT NULL AND eem.Code <> '' AND eem.Code <> '--'
                            THEN eem.Code
                            ELSE ''
                        END
                    )) AS EmployeeCodes
                FROM [sInjury].[vVictimDetails] vd
                LEFT JOIN sHrm.tEmployeeMaster eem ON eem.Id = vd.EmployeeId
            ) ED
            WHERE ED.ReportId = II.Id
            FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS EmployeeCode

    FROM [sInjury].[vIncidentInformation] II
),
InjuredPerson2 AS(
SELECT CI.ExaminationId,EE.ExaminationNumber,
                 case ISNULL(EE.ParticipantSourceTypeId,95)
		             when  95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
                 else 
		             case 
		             when isnull(OP.OtherName,'') <> '' then OP.OtherName 
		             else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') 
		             end 
		         end 
		AS EmployeeName ,
		case isnull(EE.ParticipantSourceTypeId,95) 
		when 95 then isnull(EM.Code,'') 
		else isnull(CS.Code,'') end AS EmployeeCode
		FROM
[sExamination].[tCustomIncident] CI   
 LEFT join sExamination.tCustomIncidentStatus CIS ON CIS.Id = CI.StatusId
 INNER JOIN sExamination.tExamination EE ON CI.ExaminationId=EE.Id
 LEFT JOIN sHrm.tEmployeeMaster EM ON EE.ParticipantSourceId=EM.Id AND isnull(EE.ParticipantSourceTypeId,95) = 95 
 LEFT JOIN sHrm.tCsrBenefiterMaster CS ON EE.ParticipantSourceId=CS.Id AND EE.ParticipantSourceTypeId = 1009 
 LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId  
 LEFT JOIN sExamination.tOPD OP on OP.ExaminationId = EE.Id
 UNION 
  SELECT CI.ExaminationId,EE.ExaminationNumber,case ISNULL(EE.ParticipantSourceTypeId,95)
		             when  95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
                 else 
		             case 
		             when isnull(OP.OtherName,'') <> '' then OP.OtherName 
		             else 
					 
					 isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') 
		             end 
		         end 
		AS EmployeeName,
		case isnull(EE.ParticipantSourceTypeId,95) 
		when 95 then isnull(EM.Code,'') 
		else isnull(CS.Code,'') end AS EmployeeCode
		FROM
[sExamination].[tCustomIncident] CI   
 INNER join sExamination.tCustomIncidentStatus CIS ON CIS.Id = CI.StatusId
 INNER JOIN sExamination.tArchieveExamination EE ON CI.ExaminationId=EE.Id
 LEFT JOIN sHrm.tEmployeeMaster EM ON EE.ParticipantSourceId=EM.Id AND isnull(EE.ParticipantSourceTypeId,95) = 95 
 LEFT JOIN sHrm.tCsrBenefiterMaster CS ON EE.ParticipantSourceId=CS.Id AND EE.ParticipantSourceTypeId = 1009 
 LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId  
 LEFT JOIN sExamination.tOPD OP on OP.ExaminationId = EE.Id
)
SELECT * FROM( SELECT CI.Id,CI.ExaminationId,
        CASE WHEN  CI.ExaminationId IS NULL THEN IP.InjuredPersonNames
		     ELSE
                IP2.EmployeeName
		END
		AS EmployeeName,  
		CASE WHEN  CI.ExaminationId IS NULL THEN IP.EmployeeCode
		     ELSE
                IP2.EmployeeCode
		END
		AS EmployeeCode,
        case isnull(EE.ParticipantSourceTypeId,95) when 95 then EM.Id else CS.Id end AS EmployeeId,  
        isnull(EE.ParticipantSourceTypeId,95) as ParticipantSourceTypeId,
        case isnull(EE.ParticipantSourceTypeId,95) when 95 then 'Employee' ELSE 'Other' end AS ParticipantType, 
        CI.IsFit, 
		isnull(IP2.ExaminationNumber, '') as ExaminationNumber, CIS.Id as LogStatusId, 
        isnull(CIS.Title, '') as LogStatus, isnull(C.Title, '') as VisitPurpose, 
        isnull(CI.PlantId, 0) as PlantId, 
		CASE WHEN  CI.ExaminationId IS NULL THEN II.IncidentDateTime
		     ELSE
                CI.IncidentDateTime
		END
		AS IncidentDateTime,
        case when II.Id is not null then 1 else 0 end as IsFIRCreated,
        isnull(II.ReportCode, '') as ReportCode,

CASE 
    WHEN LatestLog.Status = 2 THEN 2  -- Completed
    WHEN LatestLog.Status = 4 THEN 4
    WHEN LatestLog.Status = 5 THEN 5
    WHEN LatestLog.Status IS NULL
         AND NOT EXISTS (
             SELECT 1 
             FROM [sInjury].[vIncidentInformation] 
             WHERE ExaminationId = CI.ExaminationId
         )
    THEN 0
    ELSE 1  -- Pending
END AS RestAdviseStatus,

		CASE 
	      WHEN NOT EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformation] WHERE ExaminationId = CI.ExaminationId)
			AND NOT EXISTS(SELECT 1 FROM [sInjury].[vIncidentInformationLog] WHERE ReportId=II.Id)
            THEN 0
		  WHEN NOT EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformationLog] RAD WHERE RAD.ReportId=II.Id)
            THEN 0
			WHEN EXISTS (
					SELECT 1 
					FROM [sInjury].[vRestAdvisedByDoctor] RAD 
					WHERE RAD.ReportId = II.Id 
					  --AND RAD.InDraft = 0 
					  AND RAD.RevisitStatus =2
				) THEN 2 -- 2= Complete
		  WHEN EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformationLog] IIL
                         WHERE IIL.ReportId = II.Id AND IIL.Status = 2 AND IIL.PartialViewId=5)
            THEN 1 -- 1= Pending
				ELSE 0 
	    END as RevisitStatus,

        CASE 
	        WHEN 
	        EXISTS (SELECT  1 FROM [sInjury].[vOccupationalReportLog] ORL
                  LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
                  LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
	        LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
                  WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId) 
	        THEN 
	        (SELECT TOP 1 ORL.Id FROM [sInjury].[vOccupationalReportLog] ORL
                  LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
                  LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
	        LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
                  WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId)
	        ELSE
                  (SELECT top 1 IL.Id FROM [sInjury].[vIncidentInformationLog] IL
	        LEFT JOIN [sInjury].[vIncidentInformation] IR on IR.Id=IL.ReportId
	        where IR.[InDraft]=0 and IL.RoleId = 32 and IL.ReportId = II.Id order by IL.Id desc) 
	    END as LogId,

	    CASE 
	        WHEN 
	        EXISTS (SELECT  1 FROM [sInjury].[vOccupationalReportLog] ORL
                  LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
                  LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
	        LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
                  WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId) 
	        THEN 
	        (SELECT TOP 1 ORL.ReportId FROM [sInjury].[vOccupationalReportLog] ORL
                  LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
                  LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
	        LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
                  WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId)
	        ELSE
                  (SELECT top 1 IL.ReportId FROM [sInjury].[vIncidentInformationLog] IL
	        LEFT JOIN [sInjury].[vIncidentInformation] IR on IR.Id=IL.ReportId
	        where IR.[InDraft]=0 and IL.RoleId = 32 and IL.ReportId = II.Id order by IL.Id desc) 
	    END as ReportId,

		CASE 
		    WHEN 
		    EXISTS (SELECT  1 FROM [sInjury].[vOccupationalReportLog] ORL
               LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
               LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
		    LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
               WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId) 
		    THEN 
		    (SELECT TOP 1 PM.Id FROM [sInjury].[vOccupationalReportLog] ORL
               LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
               LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
		    LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
               WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId)
		    ELSE
               (SELECT top 1 IL.PartialViewId FROM [sInjury].[vIncidentInformationLog] IL
		    LEFT JOIN [sInjury].[vIncidentInformation] IR on IR.Id=IL.ReportId
		    where IR.[InDraft]=0 and IL.RoleId = 32 and IL.ReportId = II.Id order by IL.Id desc)
		END as PartialViewId, 

		CASE 
		    WHEN 
		    EXISTS (SELECT  1 FROM [sInjury].[vOccupationalReportLog] ORL
               LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
               LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
		    LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
               WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId) 
		    THEN 
		    (SELECT TOP 1 PM.PartialViewName FROM [sInjury].[vOccupationalReportLog] ORL
               LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
               LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
		    LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
               WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId)
		    ELSE
               (SELECT top 1 (select PartialViewName from [sInjury].[vPartialViewMaster] where Id=IL.PartialViewId)
		    FROM [sInjury].[vIncidentInformationLog] IL
		    LEFT JOIN [sInjury].[vIncidentInformation] IR on IR.Id=IL.ReportId
		    where IR.[InDraft]=0 and IL.RoleId = 32 and IL.ReportId = II.Id order by IL.Id desc) 
		END as PartialViewName, 

		CASE 
		    WHEN 
		    EXISTS (SELECT  1 FROM [sInjury].[vOccupationalReportLog] ORL
               LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
               LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
		    LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
               WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId) 
		    THEN 
		    (SELECT TOP 1 ORL.Status FROM [sInjury].[vOccupationalReportLog] ORL
               LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
               LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
		    LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
               WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId)
		    ELSE
               (SELECT top 1 IL.Status FROM [sInjury].[vIncidentInformationLog] IL
		    LEFT JOIN [sInjury].[vIncidentInformation] IR on IR.Id=IL.ReportId
		    where IR.[InDraft]=0 and IL.RoleId = 32 and IL.ReportId = II.Id order by IL.Id desc) 
		END as Status, 

        (SELECT top 1 IL.RoleId FROM [sInjury].[vIncidentInformationLog] IL
		        LEFT JOIN [sInjury].[vIncidentInformation] IR on IR.Id=IL.ReportId
		        where IR.[InDraft]=0 and IL.RoleId = 32 and IL.ReportId = II.Id order by IL.Id desc) as RoleId,

		CASE 
		    WHEN NOT EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformation] WHERE ExaminationId = CI.ExaminationId)
			AND NOT EXISTS(SELECT 1 FROM [sInjury].[vIncidentInformationLog] WHERE ReportId=II.Id)
            THEN 'FIR Generation'

	        --WHEN EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformation] WHERE Id = II.Id and InDraft = 1)
         --   THEN 'Incident Log Information'
            -- Check in IncidentInformationLog
            WHEN EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformationLog] IIL
                         WHERE IIL.ReportId = II.Id AND IIL.Status in (1,4,5))
            THEN 
                (SELECT TOP 1 PM.PartialViewName FROM [sInjury].[vIncidentInformationLog] IIL
                 LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id = IIL.PartialViewId
                 WHERE IIL.ReportId = II.Id AND IIL.Status in (1,4,5) AND IIL.Id in (SELECT MAX(Id)
                  FROM [sInjury].[vIncidentInformationLog]
                  WHERE ReportId = II.Id
                    AND PartialViewId = IIL.PartialViewId))
            -- Check in ReportPreparation
            WHEN EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformation] WHERE Id = II.Id and IsGenbaDone = 1 and Id Not in(select ReportId from [sInjury].[vReportPreparation]))
            THEN 'Report Preparation'
		    
	        WHEN EXISTS (SELECT 1 FROM [sInjury].[vReportPreparation] RP
            WHERE RP.ReportId = II.Id AND RP.Status IN (1, 3))
            THEN 'Report Preparation'
            -- Check in OccupationalReportLog
            WHEN EXISTS (SELECT 1 FROM [sInjury].[vOccupationalReportLog] ORL
                         WHERE ORL.ReportId = II.Id AND ORL.Status = 1)
            THEN
                (SELECT TOP 1 ST.StageName FROM [sInjury].[vOccupationalReportLog] ORL
                 LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
                 LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
                 WHERE ORL.ReportId = II.Id AND ORL.Status = 1)
            ELSE 'Completed'
	    END AS CurrentStageName,

		CASE 
	    WHEN EXISTS (SELECT 1 FROM [sInjury].[vReportPreparation] RP
        WHERE RP.ReportId = II.Id AND RP.Status>1)
		THEN 1
		ELSE 0
		END AS IsReportPrepDone,
		isnull(OP.ReferenceEmployeeId, '') as ReferenceOtherId, isnull(EM2.Code, '') as ReferenceCode, 
		isnull(EM2.FirstName,'') + ' ' + isnull(EM2.LastName,'') as ReferenceName,
		isnull(CI.InjuryConfirmedById, 0) as InjuryConfirmedById, isnull(EM3.FirstName,'') + ' ' + isnull(EM3.LastName,'') as InjuryConfirmedByName,
		isnull(ECOM.CompanyEmail, '') as InjuryConfirmedMailId
 From [sInjury].[vIncidentInformation] II
 FULL OUTER join [sExamination].[tCustomIncident] CI ON II.ExaminationId = CI.ExaminationId 
 LEFT join sExamination.tCustomIncidentStatus CIS ON CIS.Id = CI.StatusId
 LEFT JOIN sExamination.tExamination EE ON CI.ExaminationId=EE.Id
 LEFT JOIN sHrm.tEmployeeMaster EM ON EE.ParticipantSourceId=EM.Id AND isnull(EE.ParticipantSourceTypeId,95) = 95 
 LEFT JOIN sHrm.tCsrBenefiterMaster CS ON EE.ParticipantSourceId=CS.Id AND EE.ParticipantSourceTypeId = 1009 
 LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId  
 LEFT JOIN sExamination.tOPD OP on OP.ExaminationId = EE.Id
 LEFT JOIN sHrm.tEmployeeMaster EM2 ON EM2.Id = OP.ReferenceEmployeeId
 LEFT JOIN sExamination.tCauseMaster C on C.Id = EE.CauseId
 LEFT JOIN sExamination.tCauseTypeMaster CTM on CTM.Id = C.CauseTypeId
 LEFT JOIN InjuredPersons IP ON IP.IncidentId = II.Id AND CI.ExaminationId IS NULL
 LEFT JOIN InjuredPerson2 IP2 ON IP2.ExaminationId=CI.ExaminationId
 LEFT JOIN sHrm.tEmployeeMaster EM3 ON EM3.Id = CI.InjuryConfirmedById
 LEFT JOIN sHrm.tEmployeeCommunications ECOM ON ECOM.EmployeeId = EM3.Id
 OUTER APPLY (
    SELECT TOP 1 IIL.Status
    FROM [sInjury].[vIncidentInformationLog] IIL
    WHERE IIL.ReportId = II.Id 
      AND IIL.PartialViewId = 5
    ORDER BY IIL.Id DESC  
) LatestLog
 WHERE 
 (II.InDraft IS NULL OR II.InDraft <> 1)
 AND (
        ( II.InDraft = 0 AND II.LocationId = (SELECT LocationId FROM sIp.tStoreLocationMaster WHERE Id = @rStoreLocationId))
        OR
        (II.InDraft IS NULL AND EE.StoreLocationId = @rStoreLocationId)
    )
AND (
(II.InDraft = 0 AND II.IsActive=1)
OR 
(II.InDraft IS NULL)
)
AND ( 
(II.InDraft IS NULL AND CI.StatusId = 2 )
OR
(II.InDraft = 0)
)
AND ISNULL(EE.IsCancel,0)=0
)S
 WHERE ((S.EmployeeCode like @rEmployeeCode)  OR (ISNULL(@rEmployeeCode,'')=''))
 AND ((S.Id = @rId) OR (@rId = 0))
 ORDER BY S.Id DESC;
END  

GO











