-- (select ID from sCommon.tCompanyInformation Where id > 100);


CREATE OR ALTER PROCEDURE[dbo].[prc_AutoImportEmployees_Honda]
@rOrgId int,                  
@rStrXML nvarchar(max),                  
@rCreatedUserId bigint,                  
@rTemplateId int                  
as                  
begin                  
 declare @loXML xml,@res varchar(50) ,@rEmployeeTypeId int,@rEmployeeSubTypeId int,@rEmployeeTypeGroupId int         
 BEGIN TRY            
  set @rStrXML = Replace(@rStrXML,'&nbsp;','')                  
  set @loXML = CAST(@rStrXML as xml)                  
 END TRY                  
 BEGIN CATCH                  
  update	[sHrm].[tWebApiImportEmployee]  set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
  select @res = 0                  
  return                  
 END CATCH                  
 DECLARE @tblinsertedlocationid TABLE(autoid int identity(1,1),Id int,Title nvarchar(200),Code nvarchar(50));                 
 BEGIN TRY                  
      
  declare @tblEmployee table                  
  (                  
   tid int identity(1,1),t_EmpCode varchar(300),t_UserName varchar(300),t_Status varchar(100),t_FirstName varchar(300),                  
   t_MiddleName varchar(300),t_LastName varchar(300),t_Business varchar(500),t_BusinessId int,                  
   t_SubBusiness varchar(500),t_VerticalId int,t_CompanyGroup varchar(500),t_CompanyGroupId int,t_CompanyName varchar(500),t_CompanyId int,                  
   t_DateOfBirth varchar(100),t_DateOfJoining varchar(100),t_Designation varchar(500),t_DesignationId int,                  
   t_Grade varchar(100),t_GradeId int,t_Location nvarchar(300),t_LocationId int,t_SubLocation nvarchar(300),t_SubLocationId int,
   t_Department varchar(500),t_DepartmentId int,                  
   t_BloodGroupId int,t_ReportingManager varchar(500),t_MaritalStatusId int,t_GenderId int,                  
   t_Address1 varchar(1000),t_Address2 varchar(1000),t_Address3 varchar(1000),t_City varchar(500),                  
   t_State varchar(500),t_Country varchar(500),t_CorporateMob varchar(100),t_CorporateEmail varchar(200),                  
   t_DateOfLeaving varchar(100),t_EmployeeId bigint,t_FunctionId int,                  
   t_DepartmentGroupId int,t_TargetGroupId int,t_StatusId int,t_ReportingManagerId bigint,t_CompanyIdNew int ,                
   --t_DateofMarriage varchar(100),t_GroupDateOfJoining varchar(100), t_LocationCode varchar(100),
   t_PanNo varchar(100), t_PFUANNo varchar(100),t_AdharNo varchar(100) ,t_EmployeeGroup varchar(500)    
   ,t_EmployeeTypeGroup varchar(500), t_EmployeeType varchar(500) ,t_EmployeeSubType varchar(500),t_ProcessTypeId int,t_ProcessType varchar(500),    
   t_EmployeeGroupId int ,t_EmployeeTypeId int ,t_EmployeeSubTypeId int, t_EmployeeTypeGroupId int,t_JobTitle varchar(500)
   ,t_JobTitleId int, t_CompanyHead varchar(500), t_CompanyHeadId bigint, t_CompanyGroupHead varchar(500), t_CompanyGroupHeadId bigint, 
   t_SubBussinesHead varchar(500), t_SubBussinesHeadId bigint, t_BussinesHead varchar(500), t_BussinesHeadId bigint,
   t_Coordinator varchar(500), t_CoordinatorId bigint, t_ExeCoordinator varchar(500), t_ExeCoordinatorId bigint, 
   t_Director varchar(500), t_DirectorId bigint, t_IsUserValid bit
  )                  
  insert into @tblEmployee                  
  select T.c.value('@EmpCode','varchar(300)') as EmpCode,
  T.c.value('@UserName','varchar(300)') as UserName,
  T.c.value('@EmployementStatus','varchar(100)') as EmployementStatus,                  
  T.c.value('@FirstName','varchar(300)') as FirstName,                  
  T.c.value('@MiddleName','varchar(300)') as MiddleName,                  
  T.c.value('@LastName','varchar(300)') as LastName,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Business','varchar(500)')) as Business,                  
  T.c.value('@BusinessId','int') as BusinessId,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@SubBusiness','varchar(500)')) as SubBusiness,                  
  T.c.value('@VerticalId','int') as VerticalId,    
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@CompanyGroup','varchar(500)')) as CompanyGroup,          
   T.c.value('@CompanyGroupId','int') as CompanyGroupId,                     
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@CompanyName','varchar(500)')) as CompanyName,                  
  T.c.value('@CompanyId','int') as CompanyId,                  
  T.c.value('@DateOfBirth','varchar(100)') as DateOfBirth,                  
  T.c.value('@DateOfJoining','varchar(100)') as DateOfJoining,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Designation','varchar(500)')) as Designation,                  
  T.c.value('@DesignationId','int') as DesignationId,              
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Grade','varchar(100)')) as Grade,         
  T.c.value('@GradeId','int') as GradeId,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Location','nvarchar(300)')) as Location,                  
  Isnull(T.c.value('@LocationId','int'),0) as LocationId,  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@SubLocation','nvarchar(300)')) as SubLocation,          
   Isnull(T.c.value('@SubLocationId','int'),0) as SubLocationId,                 
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Department','varchar(500)')) as Department,                  
  T.c.value('@DepartmentId','int') as DepartmentId,                  
  T.c.value('@BloodGroupId','int') as BloodGroupId,                  
  T.c.value('@ReportingManager','varchar(500)') as ReportingManager,                  
T.c.value('@MaritalStatusId','int') as MaritalStatusId,                  
  T.c.value('@GenderId','int') as GenderId,                  
[sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Address1','varchar(1000)')) as Address1,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Address2','varchar(1000)')) as Address2,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Address3','varchar(1000)')) as Address3,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@City','varchar(500)')) as City,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@State','varchar(500)')) as State,                  
  T.c.value('@Country','varchar(500)') as Country,                  
  T.c.value('@CorporateMobile','varchar(100)') as CorporateMobile,                  
  T.c.value('@CorporateEmail','varchar(200)') as CorporateEmail,                  
  T.c.value('@LeavingDate','varchar(100)') as LeavingDate,                  
  null,null,null,null,null,null,null,                
  --T.c.value('@DateofMarriage','varchar(100)') as DateofMarriage,                  
  --T.c.value('@GroupDateOfJoining','varchar(100)') as GroupDateOfJoining,                 
  --T.c.value('@LocationCode','varchar(500)') as LocationCode,                
  T.c.value('@PanNo','varchar(500)') as PanNo,                
  T.c.value('@PFUANNo','varchar(500)') as PFUANNo,                
  T.c.value('@AdharNo','varchar(500)') as AdharNo,    
  T.c.value('@EmployeeGroup','varchar(500)') as EmployeeGroup,    
  T.c.value('@EmployeeTypeGroup','varchar(500)') as EmployeeTypeGroup, 
  T.c.value('@EmployeeType','varchar(500)') as EmployeeType,    
     
  T.c.value('@EmployeeSubType','varchar(500)') as EmployeeSubType,    
  null,    
  T.c.value('@ProcessType','varchar(500)') as ProcessType,null,null,null, null,  
  T.c.value('@JobTitle','varchar(500)') as JobTitle,null,
  T.c.value('@CompanyHead','varchar(500)') as CompanyHead,null,
  T.c.value('@CompanyGroupHead','varchar(500)') as CompanyGroupHead,null,
  T.c.value('@SubBussinesHead','varchar(500)') as SubBussinesHead,null,
  T.c.value('@BussinesHead','varchar(500)') as BussinesHead,null,
  T.c.value('@Coordinator','varchar(500)') as Coordinator,null,
  T.c.value('@ExeCoordinator','varchar(500)') as ExeCoordinator,null,
  T.c.value('@Director','varchar(500)') as Director,null,0
  from @loXML.nodes('/Employees/Employee')T(c) 

  ;WITH CTE AS
	(
		SELECT tid, t_EmpCode, 
			   ROW_NUMBER() OVER (PARTITION BY LTRIM(RTRIM(t_EmpCode)) ORDER BY tid) AS rn
			   FROM @tblEmployee
	)
	DELETE FROM CTE
	WHERE rn > 1;

  --select * from @tblEmployee    
      
 --  DELETE FROM @tblEmployee    
 --WHERE t_EmpCode IN (    
 --   SELECT t_EmpCode    
 --   FROM @tblEmployee    
 --   GROUP BY t_EmpCode    
 --   HAVING COUNT(*) > 1    
 --)     
 --Limit 1;    
     
 --;WITH CTE AS (    
 --   SELECT *,    
 --          ROW_NUMBER() OVER (PARTITION BY t_EmpCode ORDER BY (SELECT NULL)) AS RowNum    
 --   FROM @tblEmployee    
 --)    
 --DELETE FROM CTE    
 --WHERE RowNum > 1;
               
  update @tblEmployee set t_EmployeeId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_EmpCode,0) = ISNULL(Code,0) and OrgId = @rOrgId                  
  update @tblEmployee set t_TargetGroupId = Id from sHrm.tTargetGroupMaster where Title = '-' and OrgId = @rOrgId                  
  update @tblEmployee set t_StatusId = case t_Status when 'Working' then 7 when 'Left' then 9 when 'Pre Join' then 10 else 7 end                  
  update @tblEmployee set t_ReportingManagerId = Id from sHrm.tEmployeeMaster where code = t_ReportingManager      
  update @tblEmployee set t_DepartmentId = Id from sCommon.tOrganizationDepartmentMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_Department,'')))) and OrgId = @rOrgId      
  update @tblEmployee set t_DepartmentGroupId = Id from sCommon.tDepartmentGroupMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_Department,'')))) and OrgId = @rOrgId      
  update @tblEmployee set t_FunctionId = Id from sCommon.tFunctionMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_Department,'')))) and OrgId = @rOrgId      
      
  update @tblEmployee set t_EmployeeGroup = '-' where ISNULL(t_EmployeeGroup,'') = ''    
  update @tblEmployee set t_EmployeeType = 'Regular' where ISNULL(t_EmployeeType,'') = ''    
  update @tblEmployee set t_EmployeeSubType = 'Regular' where ISNULL(t_EmployeeSubType,'') = ''    
  update @tblEmployee set t_ProcessType = 'Non Hazard' , t_ProcessTypeId = 2   where ISNULL(t_ProcessTypeId,0) = 0 
  update @tblEmployee set t_EmployeeTypeGroup = 'Regular' where ISNULL(t_EmployeeTypeGroup,'') = ''   
  
  update @tblEmployee set t_SubBusiness = t_Business where ISNULL(t_SubBusiness,'-') = '-' and t_Business != '-'
  update @tblEmployee set t_CompanyGroup = t_SubBusiness where ISNULL(t_CompanyGroup,'-') = '-' and ISNULL(t_SubBusiness,'-') != '-'
  update @tblEmployee set t_CompanyGroup = t_Business where ISNULL(t_CompanyGroup,'-') = '-' and ISNULL(t_SubBusiness,'-') = '-' 
  update @tblEmployee set t_CompanyName = t_CompanyGroup where ISNULL(t_CompanyName,'-') = '-' and ISNULL(t_CompanyGroup,'-') != '-' 
  update @tblEmployee set t_CompanyName = t_SubBusiness where ISNULL(t_CompanyName,'-') = '-' and ISNULL(t_CompanyGroup,'-') = '-' and ISNULL(t_SubBusiness,'-') != '-'    
  update @tblEmployee set t_CompanyName = t_Business where ISNULL(t_CompanyName,'-') = '-' and ISNULL(t_CompanyGroup,'-') = '-' and ISNULL(t_SubBusiness,'-') = '-'
  
  --select * from @tblEmployee
    
  update @tblEmployee set t_EmployeeGroupId = Id from sHrm.tEmployeeGroupMaster where UPPER(RTRIM(LTRIM(Title))) =  UPPER(RTRIM(LTRIM(t_EmployeeGroup))) and OrgId = @rOrgId    
      
  --SELECT Top 1 @rEmployeeTypeGroupId = Id FROM sHrm.tEmployeeTypeGroupMaster WHERE UPPER(RTRIM(LTRIM(Code))) = 'EMPLOYEE' and OrgId = @rOrgId    
      
  update @tblEmployee set t_EmployeeTypeGroupId = Id FROM sHrm.tEmployeeTypeGroupMaster WHERE UPPER(RTRIM(LTRIM(Title))) = UPPER(RTRIM(LTRIM(t_EmployeeTypeGroup)))  and OrgId = @rOrgId    
      
  update @tblEmployee set t_EmployeeTypeId = Id from sHrm.tEmployeeTypeMaster WHERE UPPER(RTRIM(LTRIM(Title))) = UPPER(RTRIM(LTRIM(t_EmployeeType))) and OrgId = @rOrgId and EmployeeTypeGroupId = t_EmployeeTypeGroupId    
      
  --SELECT Top 1 @rEmployeeTypeId = Id FROM sHrm.tEmployeeTypeMaster WHERE UPPER(RTRIM(LTRIM(Code))) = (Case when IsNULL(t_EmployeeType,'') = '' then 'REGULAR' else t_EmployeeType end) and OrgId = @rOrgId and EmployeeTypeGroupId = @rEmployeeTypeGroupId  
  
   update @tblEmployee set t_EmployeeSubTypeId =Id FROM sHrm.tEmployeeSubTypeMaster WHERE UPPER(RTRIM(LTRIM(Title))) = UPPER(RTRIM(LTRIM(t_EmployeeSubType))) and OrgId = @rOrgId and EmployeeTypeId = t_EmployeeTypeId                    
   
   update @tblEmployee set t_JobTitleId =Id FROM sHrm.tEmployeeJobTitleMaster WHERE UPPER(RTRIM(LTRIM(Title))) = UPPER(RTRIM(LTRIM(t_JobTitle))) and OrgId = @rOrgId                    
    
	-- update date format if it is not in "yyyy-mm-dd" format by MS - 2024-06-21 start changes
	UPDATE @tblEmployee
		SET
		  t_DateOfJoining = 
			CASE WHEN t_DateOfJoining LIKE '____-__-__' THEN t_DateOfJoining
				 ELSE CONVERT(varchar(10), CONVERT(date, t_DateOfJoining, 103), 23)
			END,
		  t_DateOfBirth = 
			CASE WHEN t_DateOfBirth LIKE '____-__-__' THEN t_DateOfBirth
				 ELSE CONVERT(varchar(10), CONVERT(date, t_DateOfBirth, 103), 23)
			END;

	-- changes end
	
	update @tblEmployee set t_CompanyHeadId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_CompanyHead,0) = ISNULL(Code,0) and OrgId = @rOrgId
	update @tblEmployee set t_CompanyGroupHeadId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_CompanyGroupHead,0) = ISNULL(Code,0) and OrgId = @rOrgId
	update @tblEmployee set t_SubBussinesHeadId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_SubBussinesHead,0) = ISNULL(Code,0) and OrgId = @rOrgId
	update @tblEmployee set t_BussinesHeadId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_BussinesHead,0) = ISNULL(Code,0) and OrgId = @rOrgId
	update @tblEmployee set t_CoordinatorId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_Coordinator,0) = ISNULL(Code,0) and OrgId = @rOrgId
	update @tblEmployee set t_ExeCoordinatorId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_ExeCoordinator,0) = ISNULL(Code,0) and OrgId = @rOrgId
	update @tblEmployee set t_DirectorId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_Director,0) = ISNULL(Code,0) and OrgId = @rOrgId

  select @res = 1
 END TRY     
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
  return                  
 END CATCH                  
                   
 declare @lNextNumber bigint,@lFromNextNumber bigint,@lCount int                  
                   
 BEGIN TRY                  
  update @tblEmployee set t_BusinessId = Id from sHrm.tSectorMaster where upper(Title) = RTrim(LTrim(upper(t_Business))) and OrgId = @rOrgId                  
  create table #tblTable                  
  (                  
   tid int identity(1,1),t_Title varchar(300),t_Id int,t_MainId int                  
  )                  
  insert into #tblTable                  
  select distinct t_Business,t_BusinessId,0 from @tblEmployee                  
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tSectorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                     
  MERGE sHrm.tSectorMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title                  
   FROM #tblTable TT LEFT JOIN sHrm.tSectorMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id        
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tSectorMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_BusinessId = Id from sHrm.tSectorMaster where Title = t_Business and OrgId = @rOrgId                  
               
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
               
  select @res = 0                  
 END CATCH                  
                   
BEGIN TRY                  
  update @tblEmployee set t_VerticalId = Id from sHrm.tVerticalMaster where upper(Title) = Rtrim(LTrim(upper(t_SubBusiness)))  and OrgId = @rOrgId                  
  truncate table #tblTable                  
  insert into #tblTable 
           
select distinct t_SubBusiness,t_VerticalId,t_BusinessId from @tblEmployee                  
  -- select * from @tblEmployee
  --select * from #tblTable            
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tVerticalMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tVerticalMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title,t_MainId                  
   FROM #tblTable TT LEFT JOIN sHrm.tVerticalMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                  
  --WHEN MATCHED THEN                    
  -- UPDATE SET SectorId = t_MainId,UpdatedUserId=@rCreatedUserId,UpdatedDateTime=getdate()                     
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,SectorId                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),t_MainId                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tVerticalMaster', @rCurrentNumber = @lNextNumber                  
                
                 
  update @tblEmployee set t_VerticalId = Id from sHrm.tVerticalMaster where Title = t_SubBusiness  and OrgId = @rOrgId                  
   --select * from @tblEmployee            
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 --BEGIN TRY                    
 -- truncate table #tblTable                  
 -- insert into #tblTable                  
 -- select distinct t_SubBusiness,t_VerticalId,t_VerticalId from @tblEmployee                  
                    
 -- exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tCompanyGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
 -- SET @lFromNextNumber = @lNextNumber - 1                  
                    
 -- MERGE sHrm.tCompanyGroupMaster AS Target USING                   
 -- (                  
 --  SELECT tid,Id,t_Id,t_Title,t_MainId                  
 --  FROM #tblTable TT LEFT JOIN sHrm.tCompanyGroupMaster T ON TT.t_Id = T.VerticalId                  
 -- ) AS Source ON Target.VerticalId = Source.t_Id                  
 -- --WHEN MATCHED THEN                    
 -- -- UPDATE SET VerticalId = t_MainId,UpdatedUserId=@rCreatedUserId,UpdatedDateTime=getdate()                   
 -- WHEN NOT MATCHED THEN                  
 --  INSERT                  
 --  (                  
 --   Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,VerticalId                  
 --  )                  
 --  VALUES                  
 --  (                  
 --   @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),t_MainId                  
 --  );                  
                    
 -- select @lCount = COUNT(1) FROM #tblTable                  
 -- SET @lNextNumber  = @lCount + @lFromNextNumber                   
 -- exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tCompanyGroupMaster', @rCurrentNumber = @lNextNumber                  
                    
 -- update @tblEmployee set t_CompanyGroupId = Id from sHrm.tCompanyGroupMaster where Title = t_SubBusiness and VerticalId = t_VerticalId and OrgId = @rOrgId                  
                    
 -- select @res = 1           
 --END TRY         
 --BEGIN CATCH                  
 -- update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
 -- where Id = @rTemplateId                  
                    
 -- select @res = 0                  
 --END CATCH  
 
 BEGIN TRY 
 
 update @tblEmployee set t_CompanyGroupId = Id from sHrm.tCompanyGroupMaster where upper(Title) = Rtrim(LTrim(upper(t_CompanyGroup))) and VerticalId = t_VerticalId and OrgId = @rOrgId                             
  truncate table #tblTable          
  insert into #tblTable          
  select distinct t_CompanyGroup,t_CompanyGroupId,t_VerticalId from @tblEmployee          
    
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tCompanyGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output           
  SET @lFromNextNumber = @lNextNumber - 1          
            
  MERGE sHrm.tCompanyGroupMaster AS Target USING           
  (          
   SELECT tid,Id,t_Id,t_Title,t_MainId          
   FROM #tblTable TT LEFT JOIN sHrm.tCompanyGroupMaster T ON TT.t_Id = T.Id          
  ) AS Source ON Target.Id = Source.t_Id                 
  WHEN NOT MATCHED THEN          
   INSERT          
   (          
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,VerticalId          
   )          
   VALUES          
   (          
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),t_MainId          
   );          
            
  select @lCount = COUNT(1) FROM #tblTable          
  SET @lNextNumber  = @lCount + @lFromNextNumber           
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tCompanyGroupMaster', @rCurrentNumber = @lNextNumber          
      
  update @tblEmployee set t_CompanyGroupId = Id from sHrm.tCompanyGroupMaster where Title = t_CompanyGroup and VerticalId = t_VerticalId and OrgId = @rOrgId          
         
  select @res = 1          
 END TRY          
 BEGIN CATCH          
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3          
  where Id = @rTemplateId          
            
  select @res = 0          
 END CATCH                   
                   
 BEGIN TRY                  
  update @tblEmployee set t_CompanyId = Id from sHrm.tEmployeeCompanyMaster where Upper(Title) = RTrim(LTrim(Upper(t_CompanyName))) and CompanyGroupId = t_CompanyGroupId and OrgId = @rOrgId                  
  truncate table #tblTable                  
  insert into #tblTable                  
  select distinct t_CompanyName,Isnull(t_CompanyId,0),t_CompanyGroupId from @tblEmployee                  
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCompanyMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tEmployeeCompanyMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title,t_MainId                  
   FROM #tblTable TT LEFT JOIN sHrm.tEmployeeCompanyMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                  
  --WHEN MATCHED THEN                    
  -- UPDATE SET CompanyGroupId = t_MainId,UpdatedUserId=@rCreatedUserId,UpdatedDateTime=getdate()                   
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,CompanyGroupId                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),t_MainId                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeCompanyMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_CompanyId = Id from sHrm.tEmployeeCompanyMaster where Title = t_CompanyName and CompanyGroupId = t_CompanyGroupId and OrgId = @rOrgId                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 --BEGIN TRY                  
 -- update @tblEmployee set t_CompanyId = Id from sHrm.tEmployeeLegalEntitymaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_CompanyName,'')))) and OrgId = @rOrgId                    
 -- truncate table #tblTable                  
 -- insert into #tblTable                  
 -- select distinct t_CompanyName,Isnull(t_CompanyId,0),0 from @tblEmployee                   
                    
 -- exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeLegalEntitymaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
 -- SET @lFromNextNumber = @lNextNumber - 1                  
                    
 -- MERGE sHrm.tEmployeeLegalEntitymaster AS Target USING                   
 -- (                  
 --  SELECT tid,Id,t_Id,t_Title,t_MainId   
 --  FROM #tblTable TT LEFT JOIN sHrm.tEmployeeLegalEntitymaster T ON TT.t_Id = T.Id                  
 -- ) AS Source ON Target.Id = Source.t_Id                  
 -- --WHEN MATCHED THEN                    
 -- -- UPDATE SET CompanyGroupId = t_MainId,UpdatedUserId=@rCreatedUserId,UpdatedDateTime=getdate()                   
 -- WHEN NOT MATCHED THEN                  
 --  INSERT                  
 --  (                  
 --   Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
 --  )                  
 --  VALUES                  
 --  (                  
 --   @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
 --  );                  
                    
 -- select @lCount = COUNT(1) FROM #tblTable                  
 -- SET @lNextNumber  = @lCount + @lFromNextNumber                   
 -- exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeLegalEntitymaster', @rCurrentNumber = @lNextNumber                  
                    
 -- update @tblEmployee set t_CompanyId = Id from sHrm.tEmployeeLegalEntitymaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_CompanyName,'')))) and OrgId = @rOrgId                  
                    
 -- select @res = 1                  
 --END TRY                  
 --BEGIN CATCH                  
 -- update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
 -- where Id = @rTemplateId                  
                    
 -- select @res = 0                  
 --END CATCH                  
                   
 BEGIN TRY                  
 update @tblEmployee set t_DesignationId = Id from sHrm.tEmployeeDesignationMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_Designation,'')))) and OrgId = @rOrgId                  
  truncate table #tblTable      
                  
  insert into #tblTable                  
  select distinct t_Designation,t_DesignationId,0 from @tblEmployee                  
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeDesignationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tEmployeeDesignationMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title                  
   FROM #tblTable TT LEFT JOIN sHrm.tEmployeeDesignationMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id               
 WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeDesignationMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_DesignationId = Id from sHrm.tEmployeeDesignationMaster where Title = t_Designation and OrgId = @rOrgId                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 BEGIN TRY                  
  truncate table #tblTable                  
  insert into #tblTable                  
  select distinct t_Grade,t_GradeId,0 from @tblEmployee                  
                 
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tGradeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tGradeMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title                  
   FROM #tblTable TT LEFT JOIN sHrm.tGradeMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                   
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,GradeNumber                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),1                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tGradeMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_GradeId = Id from sHrm.tGradeMaster where Title = t_Grade and OrgId = @rOrgId                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0               
 END CATCH                  
                   
 BEGIN TRY        
  truncate table #tblTable                  
  insert into #tblTable                  
  select distinct t_Department,t_DepartmentId,0 from @tblEmployee                  
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sCommon.tFunctionMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sCommon.tFunctionMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title                  
   FROM #tblTable TT LEFT JOIN sCommon.tFunctionMaster T ON TT.t_Title collate SQL_Latin1_General_CP1_CI_AS = T.Title                  
  ) AS Source ON upper(Target.Title) = upper(Source.t_Title) collate SQL_Latin1_General_CP1_CI_AS                   
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sCommon.tFunctionMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_FunctionId = Id from sCommon.tFunctionMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_Department,'')))) and OrgId = @rOrgId                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 BEGIN TRY                  
  truncate table #tblTable                  
  insert into #tblTable                  
  select distinct t_Department,t_DepartmentId,ISNULL(t_FunctionId,0) from @tblEmployee                  
      
  exec sCommon.pTableRowIdGet @rOrgId, 'sCommon.tDepartmentGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sCommon.tDepartmentGroupMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title,t_MainId                  
   FROM #tblTable TT LEFT JOIN sCommon.tDepartmentGroupMaster T ON TT.t_Title collate SQL_Latin1_General_CP1_CI_AS = T.Title                  
  ) AS Source ON upper(Target.Title) = upper(Source.t_Title) collate SQL_Latin1_General_CP1_CI_AS                  
  --WHEN MATCHED THEN                  
  --UPDATE set FunctionId=t_MainId                  
                     
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,FunctionId       
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),t_MainId                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sCommon.tDepartmentGroupMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_DepartmentGroupId = Id from sCommon.tDepartmentGroupMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_Department,'')))) and OrgId = @rOrgId                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 BEGIN TRY                  
  truncate table #tblTable                  
  insert into #tblTable                  
  select distinct t_Department,t_DepartmentId,ISNULL(t_DepartmentGroupId,0) from @tblEmployee                  
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sCommon.tOrganizationDepartmentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sCommon.tOrganizationDepartmentMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title,t_MainId                  
   FROM #tblTable TT LEFT JOIN sCommon.tOrganizationDepartmentMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                  
  --WHEN MATCHED THEN                  
  --UPDATE set DepartmentGroupId=t_MainId                  
                       
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,DepartmentGroupId                  
   )                  
   VALUES                
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),t_MainId                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sCommon.tOrganizationDepartmentMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_DepartmentId = Id from sCommon.tOrganizationDepartmentMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_Department,'')))) and OrgId = @rOrgId                  
                    
                    
  select @res = 1                   
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
 -- Location Auto Insert Starts here                  
 BEGIN TRY                  
  Declare @orgid int,@userid bigint,@maxcityid int                  
  set @orgid=@rOrgId                  
  set @userid=(select Top 1 CreatedUserid from scommon.tStatemaster where OrgId=@orgid)                  
   if not exists(Select 1 from scommon.tStatemaster where Title='-' and OrgId=@orgid)                  
    begin                  
     insert into scommon.tStatemaster                  
     select @orgid,[sCommon].[fGetIntIdForOrg](100,@orgid),'-',@userid,GetDate(),@userid,GetDate(),0,[sCommon].[fGetIntIdForOrg](1,@orgid),1              
     --print 'Insert State'                  
    end                  
                  
  --set @maxcityid=(select Right(Max(id),3)+100 from sCommon.tCityMaster where orgid=@orgid)      
  -- if not exists(Select 1 from scommon.tCitymaster where Title='-' and OrgId=@orgid)                  
  --  begin                  
  --   insert into scommon.tCitymaster                  
  --   select @orgid,[sCommon].[fGetIntIdForOrg](1,@orgid),'-',@userid,GetDate(),@userid,GetDate(),0,[sCommon].[fGetIntIdForOrg](@maxcityid,@orgid),1                  
  --   --print 'Insert City'                  
  --  end                  
                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                  
 --BEGIN TRY                  
 ---- change by MS 03/05/2022 for adani data issue            
 -- update @tblEmployee set t_LocationId = Id from sCommon.tLocationMaster where upper(Title) = Rtrim(LTrim(upper(t_Location))) and OrgId = @rOrgId             
 -- and upper(LocationCode) = Rtrim(LTrim(upper(t_LocationCode)))            
 -- and Isnull(t_LocationCode,'')<>''            
            
 -- update @tblEmployee set t_LocationId = Id from sCommon.tLocationMaster where upper(Title) = Rtrim(LTrim(upper(t_Location))) and OrgId = @rOrgId             
 -- --and upper(LocationCode) = Rtrim(LTrim(upper(t_LocationCode)))            
 -- and Isnull(t_LocationCode,'')=''            
                    
 -- truncate table #tblTable                    
 -- insert into #tblTable                  
 -- select distinct t_Location,t_LocationId,0 from @tblEmployee where Isnull(t_LocationId,0)=0             
                    
                    
 -- exec sCommon.pTableRowIdGet @rOrgId, 'sIp.tStoreLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
 -- SET @lFromNextNumber = @lNextNumber - 1               
            
            
                     
 -- MERGE sIp.tStoreLocationMaster AS Target USING                   
 -- (                  
 --  SELECT tid,Id,t_Id,t_Title                  
 --  FROM #tblTable TT LEFT JOIN sIp.tStoreLocationMaster T ON TT.t_Id = T.Id                  
 -- ) AS Source ON Target.Id = Source.t_Id                   
 -- WHEN NOT MATCHED THEN                  
 --  INSERT                  
 --  (                  
 --   Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
 --  )                  
 --  VALUES                  
 --  (                  
 --   @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
 --  )          
 --  OUTPUT          
 --  inserted.Id,inserted.Title,inserted.Code          
 --  into @tblinsertedlocationid;          
                  
 -- select @lCount = COUNT(1) FROM #tblTable                  
 -- SET @lNextNumber  = @lCount + @lFromNextNumber                   
 -- exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sIp.tStoreLocationMaster', @rCurrentNumber = @lNextNumber                    
            
 -- select @res = 1                  
 --END TRY                  
 --BEGIN CATCH                  
 -- update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
 -- where Id = @rTemplateId                  
                    
 -- select @res = 0                  
 --END CATCH                  
                  
 --BEGIN TRY                  
 -- truncate table #tblTable                  
 -- insert into #tblTable                  
 -- select distinct t_Location,t_LocationId,0 from @tblEmployee                  
                    
 -- exec sCommon.pTableRowIdGet @rOrgId, 'sCommon.tLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
 -- SET @lFromNextNumber = @lNextNumber - 1                  
                     
 -- MERGE sCommon.tLocationMaster AS Target USING                   
 -- (                  
 --  SELECT tid,Id,t_Id,t_Title                  
 --  FROM #tblTable TT LEFT JOIN sCommon.tLocationMaster T ON TT.t_Id = T.Id                  
 -- ) AS Source ON Target.Id = Source.t_Id                   
 -- WHEN NOT MATCHED THEN                  
 --  INSERT                  
 --  (                  
 --   Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,CountryId,StateId                  
 --  )                  
 --  VALUES                  
 --  (                  
 --   @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),[sCommon].[fGetIntIdForOrg](100,@orgid),[sCommon].[fGetIntIdForOrg](1,@orgid)                  
 --  );                  
                    
 -- select @lCount = COUNT(1) FROM #tblTable                  
 -- SET @lNextNumber  = @lCount + @lFromNextNumber                   
 -- exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sCommon.tLocationMaster', @rCurrentNumber = @lNextNumber                  
                    
 -- update @tblEmployee set t_LocationId = Id from sCommon.tLocationMaster where Upper(Title) = Upper(t_Location) and OrgId = @rOrgId                  
 -- update sCommon.tLocationMaster set LocationCode = t_LocationCode from @tblEmployee where t_LocationId = Id            
                    
 -- update SLM Set SLM.LocationId = LM.id From sIp.tStoreLocationMaster SLM                  
 -- inner join sCommon.tLocationMaster LM on Upper(LM.Title)=Upper(SLM.Title) and LM.OrgId = @rOrgId                  
 -- Where Isnull(SLM.LocationId,0) = 0          
            
 -- -- Mentis id (0021441 jignesh)           
 -- Declare @i int = 1;          
          
 -- while (@i <= (select count(*) from @tblinsertedlocationid))          
 -- begin          
 --Declare @Title_ nvarchar(200), @Code_ nvarchar(50),@LocationId_ int,@id_ int;          
 --select @Title_ = isnull(Title,''),@code_= isnull(code,''),@id_=Id from @tblinsertedlocationid where autoid = @i          
 --select @LocationId_ = SLM.LocationId from sIp.tStoreLocationMaster SLM where SLM.Id = @id_          
 --exec [sIp].[pStoreLocationMasterAdd_sap] @rTitle = @Title_,          
 --@rCreatedUserId = @rCreatedUserId,@rIsObsolete=0,@rCode=@code_,@rLocationId=@LocationId_,@rOrgId=@rOrgId,@rStartTime=null,          
 --@rEndTime=null,@rIsActiveHealth=1,@rIsOPDSetup=0          
          
 --set @i = @i+1;          
 -- end          
 -- ----------------------------------          
                    
                 
                  
 -- select @res = 1                  
 --END TRY                  
 --BEGIN CATCH                  
 -- update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
 -- where Id = @rTemplateId                  
                    
 -- select @res = 0                  
 --END CATCH    
 
 BEGIN TRY          
  update @tblEmployee set t_SubLocationId = 0, t_LocationId = 0  
  update @tblEmployee set t_SubLocationId = Id, t_LocationId = LocationId from sIp.tStoreLocationMaster     
 where upper(Title) = Rtrim(Ltrim(upper(t_SubLocation))) and OrgId = @rOrgId --and t_SubLocationId = 0    
            
 truncate table #tblTable            
 insert into #tblTable          
 select distinct t_SubLocation,t_SubLocationId,0 from @tblEmployee where Isnull(t_SubLocationId,0) = 0          
            
        
 exec sCommon.pTableRowIdGet @rOrgId, 'sIp.tStoreLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output           
 SET @lFromNextNumber = @lNextNumber - 1          
             
 MERGE sIp.tStoreLocationMaster AS Target USING           
 (          
 SELECT tid,Id,t_Id,t_Title          
 FROM #tblTable TT LEFT JOIN sIp.tStoreLocationMaster T ON TT.t_Id = T.Id          
 ) AS Source ON Target.Id = Source.t_Id           
 WHEN NOT MATCHED THEN          
 INSERT          
 (          
 Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime          
 )          
 VALUES          
 (          
 @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()          
 );          
            
 select @lCount = COUNT(1) FROM #tblTable          
 SET @lNextNumber  = @lCount + @lFromNextNumber           
 exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sIp.tStoreLocationMaster', @rCurrentNumber = @lNextNumber            
      
 update @tblEmployee set t_SubLocationId = Id, t_LocationId = ISNULL(LocationId,0) from sIp.tStoreLocationMaster     
 where Upper(Title) = Upper(t_SubLocation) and OrgId = @rOrgId    
    
    
  select @res = 1          
 END TRY          
 BEGIN CATCH          
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3          
  where Id = @rTemplateId          
            
  select @res = 0          
 END CATCH          
          
 BEGIN TRY         
     
  update @tblEmployee set t_Location = t_SubLocation from sCommon.tLocationMaster where t_LocationId = 0    
    
 truncate table #tblTable          
 insert into #tblTable          
 select distinct t_Location,t_LocationId,0 from @tblEmployee where t_LocationId = 0    
            
 exec sCommon.pTableRowIdGet @rOrgId, 'sCommon.tLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output           
 SET @lFromNextNumber = @lNextNumber - 1          
             
 MERGE sCommon.tLocationMaster AS Target USING           
 (          
 SELECT tid,Id,t_Id,t_Title          
 FROM #tblTable TT LEFT JOIN sCommon.tLocationMaster T ON TT.t_Id = T.Id          
 ) AS Source ON Target.Id = Source.t_Id           
 WHEN NOT MATCHED THEN          
 INSERT          
 (          
 Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,CountryId,StateId          
 )          
 VALUES          
 (          
 @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),[sCommon].[fGetIntIdForOrg](100,@rorgId),[sCommon].[fGetIntIdForOrg](1,@rorgId)          
 );          
            
 select @lCount = COUNT(1) FROM #tblTable          
 SET @lNextNumber  = @lCount + @lFromNextNumber           
 exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sCommon.tLocationMaster', @rCurrentNumber = @lNextNumber          
            
 update @tblEmployee set t_LocationId = Id  from sCommon.tLocationMaster where Upper(Title) = Upper(t_Location) and OrgId = @rOrgId       
            
 update SLM Set SLM.LocationId = LM.id From sIp.tStoreLocationMaster SLM          
 inner join sCommon.tLocationMaster LM on Upper(LM.Title)=Upper(SLM.Title) and LM.OrgId = @rOrgId          
 Where Isnull(SLM.LocationId,0) = 0      
               
 --   IF OBJECT_ID(N'tempdb..#tblTable') IS NOT NULL    
 --BEGIN    
 -- drop table #tblTable    
 --END     
    
  select @res = 1          
 END TRY          
 BEGIN CATCH          
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3          
  where Id = @rTemplateId          
            
  select @res = 0          
 END CATCH          
         
 -- Location Auto Insert ends here                
                   
 -- Location Auto Insert ends here                  
    
--- employeegroup insert start    
    
--BEGIN TRY      
               
--  truncate table #tblTable             
--  insert into #tblTable                  
--  select distinct t_EmployeeGroup,ISNULL(t_EmployeeGroupId,0),0 from @tblEmployee                  
                
--  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
--  SET @lFromNextNumber = @lNextNumber - 1                  
                    
--  MERGE sHrm.tEmployeeGroupMaster AS Target USING                   
--  (                  
--   SELECT tid,Id,t_Id,t_Title                 
--   FROM #tblTable TT LEFT JOIN sHrm.tEmployeeGroupMaster T ON TT.t_Id = T.Id                  
--  ) AS Source ON Target.Id = Source.t_Id                  
--  --WHEN MATCHED THEN                  
--  --UPDATE set DepartmentGroupId=t_MainId                  
                       
--  WHEN NOT MATCHED THEN                  
--   INSERT                  
--   (                  
--    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
--   )                  
--   VALUES                
--   (                  
--    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
--   );                  
                  
--  select @lCount = COUNT(1) FROM #tblTable                  
--  SET @lNextNumber  = @lCount + @lFromNextNumber                   
--  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeGroupMaster', @rCurrentNumber = @lNextNumber                  
       
--  update @tblEmployee set t_EmployeeGroupId = Id from sHrm.tEmployeeGroupMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_EmployeeGroup,'')))) and OrgId = @rOrgId                  
                    
                   
--  select @res = 1                   
-- END TRY                  
-- BEGIN CATCH                  
--  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
--  where Id = @rTemplateId                  
                    
--  select @res = 0                  
-- END CATCH      
    
--- employeegroup insert end 

--- employeetypegroup insert start    
    
BEGIN TRY      
               
  truncate table #tblTable             
  insert into #tblTable                  
  select distinct t_EmployeeTypeGroup,ISNULL(t_EmployeeTypeGroupId,0),0 from @tblEmployee                  
               
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeTypeGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tEmployeeTypeGroupMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title                 
   FROM #tblTable TT LEFT JOIN sHrm.tEmployeeTypeGroupMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                  
  --WHEN MATCHED THEN                  
  --UPDATE set DepartmentGroupId=t_MainId                  
                       
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
   )                  
   VALUES                
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
   );                  
                  
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeTypeGroupMaster', @rCurrentNumber = @lNextNumber                  
       
  update @tblEmployee set t_EmployeeTypeGroupId = Id from sHrm.tEmployeeTypeGroupMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_EmployeeTypeGroup,'')))) and OrgId = @rOrgId                  
                    
                   
  select @res = 1                   
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH      
   -- select * from @tblEmployee
--- employeeTypegroup insert end    
    
    
--- employeeType insert start    
    
BEGIN TRY     
                
  truncate table #tblTable     
              
  insert into #tblTable                  
  select distinct t_EmployeeType,ISNULL(t_EmployeeTypeId,0),ISNULL(t_EmployeeTypeGroupId,0) from @tblEmployee                  
     
            
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tEmployeeTypeMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title,t_MainId                
   FROM #tblTable TT LEFT JOIN sHrm.tEmployeeTypeMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                  
  --WHEN MATCHED THEN                  
  --UPDATE set DepartmentGroupId=t_MainId                  
                       
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,EmployeeTypeGroupId                  
   )                  
   VALUES                
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate() ,t_MainId                
   );                  
                  
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeTypeMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_EmployeeTypeId = Id from sHrm.tEmployeeTypeMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_EmployeeType,'')))) and EmployeeTypeGroupId = t_EmployeeTypeGroupId  and OrgId = @rOrgId                  
                  
                    
  select @res = 1                   
 END TRY                  
 BEGIN CATCH      
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH      
    --select * from @tblEmployee
--- employeetype insert end    
    
    
    
--- employeeSubType insert start    
    
BEGIN TRY    
                 
  truncate table #tblTable     
                   
  insert into #tblTable                  
  select distinct t_EmployeeSubType,ISNULL(t_EmployeeSubTypeId,0),ISNULL(t_EmployeeTypeId,0) from @tblEmployee                  
             
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeSubTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tEmployeeSubTypeMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title,t_MainId                
   FROM #tblTable TT LEFT JOIN sHrm.tEmployeeSubTypeMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                  
  --WHEN MATCHED THEN                  
  --UPDATE set DepartmentGroupId=t_MainId                  
                       
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,EmployeeTypeId                  
   )                  
   VALUES                
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate() ,t_MainId                
   );                  
  print 3                   
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeSubTypeMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_EmployeeSubTypeId = Id from sHrm.tEmployeeSubTypeMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_EmployeeSubType,'')))) and EmployeeTypeId = t_EmployeeTypeId  and OrgId = @rOrgId                  
         
              
                    
  select @res = 1                   
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH      
  IF OBJECT_ID(N'tempdb..#tblTable') IS NOT NULL    
 BEGIN    
  drop table #tblTable    
 END  
 --select * from @tblEmployee       
--- employeeSubType insert end    
    
    
    
                  
 BEGIN TRY                  
                   
  update @tblEmployee set t_StatusId = Id from sCommon.tStatusMaster where Title = t_Status and StatusTypeId = 4                  
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tEmployeeMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_EmployeeId,t_EmpCode,t_StatusId,t_FirstName,t_MiddleName,t_LastName,                  
   t_TargetGroupId,t_LocationId                  
   FROM @tblEmployee TT LEFT JOIN sHrm.tEmployeeMaster T ON ISNULL(TT.t_EmployeeId,0) = T.Id                  
  ) AS Source ON Target.Id = ISNULL(Source.t_EmployeeId,0)                  
  WHEN MATCHED THEN                  
   UPDATE SET FirstName = t_FirstName,MiddleName = t_MiddleName,LastName = t_LastName,                  
   StatusId = t_StatusId,WorkLocationId = t_LocationId,UpdatedDateTime=getDate(),ImportReferenceId=@rTemplateId,IsObsolete=0                  
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,FirstName,MiddleName,LastName,StatusId,IsObsolete,CreatedUserId,CreatedDateTime,                  
    UpdatedUserId,UpdatedDateTime,IsTemporary,TargetGroupId,WorkLocationId,ImportReferenceId                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_EmpCode,t_FirstName,t_MiddleName,t_LastName,t_StatusId,0,                  
    @rCreatedUserId,getdate(),@rCreatedUserId,getdate(),0,t_TargetGroupId,t_LocationId,@rTemplateId                  
   );                  
                   
  select @lCount = COUNT(1) FROM @tblEmployee                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_EmployeeId = Id from sHrm.tEmployeeMaster where Code = t_EmpCode and OrgId = @rOrgId                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 update @tblEmployee set t_DateOfLeaving='1900-01-01' where ISNULL(t_DateOfLeaving,'')=''                   
 
 BEGIN TRY                  
  MERGE sHrm.tEmployeeJobDetail AS Target USING                   
  (                  
   SELECT tid,t_EmployeeId,t_DesignationId,t_LocationId,t_DepartmentId,t_DateOfJoining,t_CompanyId,                  
   ISNULL(t_DateOfLeaving,'1900-01-01')t_DateOfLeaving,t_GradeId,t_ReportingManagerId,t_EmployeeGroupId,t_EmployeeTypeId,t_EmployeeSubTypeId,t_ProcessTypeId,t_JobTitleId               
   FROM @tblEmployee TT LEFT JOIN sHrm.tEmployeeJobDetail T ON TT.t_EmployeeId = T.EmployeeId                  
  ) AS Source ON Target.EmployeeId = Source.t_EmployeeId                  
  WHEN MATCHED THEN                  
   UPDATE SET EmployeeDesignationId = t_DesignationId,EmployeeLocationId = ISNULL(t_LocationId,0),                  
   OrganizationDepartmentId = t_DepartmentId,DateOfJoining = t_DateOfJoining,EmployeeCompanyId = t_CompanyId,                  
   DateOfLeaving = ISNULL(t_DateOfLeaving,'1900-01-01'),GradeId = t_GradeId,ReportingMangerEmployeeId = ISNULL(t_ReportingManagerId,0),                  
   IsSkilled = 1,UpdatedUserId = @rCreatedUserId,UpdatedDateTime = getdate(),LegalEntityId=null,    
   EmployeeGroupId=t_EmployeeGroupId,             
   EmployeeTypeId=t_EmployeeTypeId,EmployeeSubTypeId=t_EmployeeSubTypeId, ProcessTypeId = t_ProcessTypeId, EmployeeJobTitleId = ISNULL(t_JobTitleId  ,0)        
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    EmployeeId,OrgId,EmployeeDesignationId,EmployeeLocationId,OrganizationDepartmentId,DateOfJoining,                  
    EmployeeCompanyId,DateOfLeaving,GradeId,ReportingMangerEmployeeId,IsSkilled,UpdatedUserId,                  
    UpdatedDateTime,ProcessTypeId,EmployeeTypeId,EmployeeSubTypeId,EmployeeGroupCode,EmployeeGroupId,LegalEntityId,EmployeeJobTitleId 
   )              
   VALUES                  
   (              
    t_EmployeeId,@rOrgId,ISNULL(t_DesignationId,0),ISNULL(t_LocationId,0),ISNULL(t_DepartmentId,0),ISNULL(t_DateOfJoining,'1900-01-01'),ISNULL(t_CompanyId,0),--t_CompanyIdNew,                  
    ISNULL(t_DateOfLeaving,'1900-01-01'),ISNULL(t_GradeId,0),ISNULL(t_ReportingManagerId,0),1,              
    @rCreatedUserId,getdate(),ISNULL(t_ProcessTypeId,0),ISNULL(t_EmployeeTypeId,0),ISNULL(t_EmployeeSubTypeId,0),'-',ISNULL(t_EmployeeGroupId,0) ,null,ISNULL(t_JobTitleId  ,0)
   );                  
                     
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
  
  
 BEGIN TRY                  
  MERGE sHrm.tEmployeePersonalDetail AS Target USING                   
  (                  
   SELECT tid,t_EmployeeId,t_DateOfBirth,t_GenderId,t_BloodGroupId,t_MaritalStatusId,                
   t_AdharNo ,--t_DateofMarriage,
   t_PanNo,t_PFUANNo                
   FROM @tblEmployee TT LEFT JOIN sHrm.tEmployeePersonalDetail T ON TT.t_EmployeeId = T.EmployeeId                  
  ) AS Source ON Target.EmployeeId = Source.t_EmployeeId                  
  WHEN MATCHED THEN              
   UPDATE SET DateOfBirth = t_DateOfBirth,GenderId = t_GenderId,BloodGroupId = ISNULL(t_BloodGroupId,0),                  
   --IsDisability = 0,IsDisabilityCertified = 0,IsFireTraining = 0,IsFirstAidTraining = 0,                
   UidNumber = t_AdharNo,--DateofMarriage = t_DateofMarriage,                
   PanNo = t_PanNo,PFUANNo  = t_PFUANNo,                  
   UpdatedUserId = @rCreatedUserId,MaritalStatusId=t_MaritalStatusId                  
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    EmployeeId,OrgId,DateOfBirth,GenderId,BloodGroupId,IsDisability,IsDisabilityCertified,                  
    IsFireTraining,IsFirstAidTraining,UpdatedUserId,UpdatedDateTime,MaritalStatusId,                
 UidNumber,--DateofMarriage,
 PanNo,PFUANNo                
   )                  
   VALUES                  
   (                  
    t_EmployeeId,@rOrgId,t_DateOfBirth,t_GenderId,ISNULL(t_BloodGroupId,0),0,0,0,0,@rCreatedUserId,                  
    getdate(),t_MaritalStatusId, t_AdharNo, --t_DateofMarriage,                
 t_PanNo,t_PFUANNo                
   );                  
                     
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 BEGIN TRY                  
  MERGE sHrm.tEmployeeCommunications AS Target USING                   
  (                  
   SELECT tid,t_EmployeeId,t_Address1,t_Address2,t_Address3,t_City,t_State,t_Country,replace(Rtrim(Ltrim(t_CorporateMob)),' ','')t_CorporateMob,t_CorporateEmail                  
   FROM @tblEmployee TT LEFT JOIN sHrm.tEmployeeCommunications T ON TT.t_EmployeeId = T.EmployeeId                  
  ) AS Source ON Target.EmployeeId = Source.t_EmployeeId                  
  WHEN MATCHED THEN                  
   UPDATE SET PresentStreetOne = t_Address1,PresentStreetTwo = t_Address2,PresentStreetThree = t_Address3,                  
   PresentCountry = t_Country,PresentState = t_State,PresentCity = t_City,                  
   PresentContactNo = case when len(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''))>10                   
         then left(replace(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''),'+91',''),50)                  
         else replace(Rtrim(Ltrim(t_CorporateMob)),' ','') end ,                  
   --PhoneNoCompany = t_CorporateMob,                  
   CompanyEmail = t_CorporateEmail,                  
   --PersonalEmail = t_CorporateEmail,                  
   MobileNumber = case when len(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''))>10                   
         then left(replace(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''),'+91',''),10)                  
         else replace(Rtrim(Ltrim(t_CorporateMob)),' ','') end ,                  
   CreatedUserId = @rCreatedUserId,                  
   CreatedDateTime = getdate(),UpdatedUserId = @rCreatedUserId,UpdatedDateTime = getdate()                  
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    EmployeeId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,PresentState,PresentCity,                  
    PresentContactNo,CompanyEmail,MobileNumber,CreatedUserId,CreatedDateTime,                  
    UpdatedUserId,UpdatedDateTime                  
   )                  
   VALUES                  
   (                  
    t_EmployeeId,t_Address1,t_Address2,t_Address3,t_Country,t_State,t_City,case when len(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''))>10                   
    then left(replace(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''),'+91',''),50) else replace(Rtrim(Ltrim(t_CorporateMob)),' ','') end,                  
    t_CorporateEmail,case when len(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''))>10 then left(replace(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''),'+91',''),10)                  
    else replace(Rtrim(Ltrim(t_CorporateMob)),' ','') end,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
   );                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH       
 
 BEGIN TRY                  
  MERGE sHrm.tApprovalAuthority AS Target USING                   
  (                  
   SELECT tid,t_EmployeeId,t_CompanyHeadId, t_CompanyGroupHeadId, t_SubBussinesHeadId, t_BussinesHeadId,
   t_CoordinatorId, t_ExeCoordinatorId, t_DirectorId
   FROM @tblEmployee TT LEFT JOIN sHrm.tApprovalAuthority T ON TT.t_EmployeeId = T.EmployeeId                  
  ) AS Source ON Target.EmployeeId = Source.t_EmployeeId                  
  WHEN MATCHED THEN                  
   UPDATE SET CompanyHeadId = ISNULL(t_CompanyHeadId, 0), 
       CompanyGroupHeadId = ISNULL(t_CompanyGroupHeadId, 0), 
       SubBussinesHeadId = ISNULL(t_SubBussinesHeadId, 0),                  
       BussinesHeadId = ISNULL(t_BussinesHeadId, 0), 
       CoordinatorId = ISNULL(t_CoordinatorId, 0), 
       ExeCoordinatorId = ISNULL(t_ExeCoordinatorId, 0), 
       DirectorId = ISNULL(t_DirectorId, 0),                  
	   UpdatedUserId = @rCreatedUserId,
	   UpdatedDateTime = getdate()
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    EmployeeId,CompanyHeadId,CompanyGroupHeadId,SubBussinesHeadId,BussinesHeadId,CoordinatorId,ExeCoordinatorId,DirectorId,       
    CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
   )
   VALUES
   (                  
    t_EmployeeId, ISNULL(t_CompanyHeadId, 0), ISNULL(t_CompanyGroupHeadId, 0), ISNULL(t_SubBussinesHeadId, 0), ISNULL(t_BussinesHeadId, 0), 
    ISNULL(t_CoordinatorId, 0), ISNULL(t_ExeCoordinatorId, 0), ISNULL(t_DirectorId, 0),
	@rCreatedUserId,getdate(), @rCreatedUserId, getdate()
   );

  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH

 --User Add
 BEGIN TRY           
    -- Mantis: 0037352
	 ;WITH CTE AS
	 (
	 	SELECT tid, t_IsUserValid, t_UserName, ROW_NUMBER() OVER (PARTITION BY LTRIM(RTRIM(t_UserName)) ORDER BY tid) AS rn
	 	FROM @tblEmployee
	 )
	 update cte set t_IsUserValid = 1 from cte WHERE rn = 1;
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1
                    
  MERGE sSecurity.tUser AS Target USING         
  (                  
   SELECT tid,Id,t_FirstName,t_LastName,t_UserName,t_EmployeeId,t_EmpCode,t_StatusId,t_LocationId
   FROM @tblEmployee TT LEFT JOIN sSecurity.tUser T ON ISNULL(TT.t_EmployeeId,0) = T.Id
   Where TT.t_StatusId = 7 and ISNULL(TT.t_UserName, '') <> '' and t_IsUserValid = 1
  ) AS Source ON Target.SourceId = ISNULL(Source.t_EmployeeId,0) and SourceTypeId = 95
  WHEN NOT MATCHED THEN
   INSERT
   (                  
    Id,	DisplayTitle, LoginTitle, LoginPassword, LastLockOutDate, NumberOfLogonAttempt, IsObsolete,
    CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, OrgId,
	SourceId, SourceTypeId
   )
   VALUES
   (                  
    @lFromNextNumber + tid,(t_FirstName + ' ' + t_LastName), t_EmpCode, LEFT(REPLACE(CONVERT(VARCHAR(40), NEWID()) + CONVERT(VARCHAR(40), NEWID()), '-', ''), 40), 
	sCommon.fGetDate(), 0, 0, @rCreatedUserId, sCommon.fGetDate(), @rCreatedUserId, sCommon.fGetDate(), 
	@rOrgId, t_EmployeeId, 95
   );

  select @lCount = COUNT(1) FROM @tblEmployee                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sSecurity.tUser', @rCurrentNumber = @lNextNumber

  INSERT INTO sSecurity.tUserLocation (StoreLocationId, UserId, CreatedUserId, CreatedDateTime)
	SELECT t_SubLocationId, USR.Id, @rCreatedUserId, sCommon.fGetDate()
	FROM @tblEmployee e
	INNER JOIN sSecurity.tUser USR ON USR.SourceId = ISNULL(e.t_EmployeeId, 0) AND USR.SourceTypeId = 95
	WHERE e.t_StatusId = 7
	AND NOT EXISTS (
		SELECT 1
		FROM sSecurity.tUserLocation ul
		WHERE ul.UserId = USR.Id and ul.StoreLocationId = t_SubLocationId
	);

	INSERT INTO sSecurity.tUserRole (RoleId, UserId, IsObsolete, IsPrimary, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime)
	SELECT [sCommon].[fGetIntIdForOrg](10, @rOrgId), USR.Id, 0, 1, @rCreatedUserId, sCommon.fGetDate(), @rCreatedUserId, sCommon.fGetDate()
	FROM @tblEmployee e
	INNER JOIN sSecurity.tUser USR ON USR.SourceId = ISNULL(e.t_EmployeeId, 0) AND USR.SourceTypeId = 95
	WHERE e.t_StatusId = 7
	AND NOT EXISTS (
		SELECT 1
		FROM sSecurity.tUserRole ur
		WHERE ur.UserId = USR.Id
	);

  select @res = 1  
 END TRY
 BEGIN CATCH
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH
                  
 if(@res=1)       
 begin                  
 delete from sHrm.tVerticalMaster where id not in(select distinct VerticalId From sHrm.tCompanyGroupMaster)                  
 update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = 'Success',StatusCode=4 where Id = @rTemplateId                  
 end                  
 select @res as res                 
end 

GO




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

GO


ALTER FUNCTION [dbo].[fGetShift](@OPDTime time,@orgid int)  
RETURNS NVARCHAR(MAX)
AS  
BEGIN 
  DECLARE @Title NVARCHAR(MAX) = ''
  SELECT @Title = Title FROM sCommon.tCompanyShiftMaster 
  WHERE OrgId=@orgid and IsObsolete=0 AND
  (
    (
        FromTime <= ToTime
        AND @OPDTime BETWEEN FromTime AND ToTime
    )
    OR
    (
        FromTime > ToTime
        AND
        (
            @OPDTime >= FromTime
            OR @OPDTime <= ToTime
        )
    )
  )
  
  IF (@Title='')
  BEGIN
     SELECT @Title = 'Blank Shift'
  END  
  RETURN @Title
END


GO


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


						 GO


CREATE OR ALTER PROCEDURE[dbo].[CommanMisOpdDashboard]  
 @rStoreLocationId int = 0,  
 @rParticipantTypeId int = 0 ,  
 @rCaseCauseId int = 0, 
 @rVisitTypeId int,
 @rShiftId int,
 @rLocationId int = 0,  
 @rFunctionId int = 0,  
 @rDepartmentGroupId int = 0,  
 @rDepartmentId int = 0,  
 @rGradeId int = 0,  
 @rDesignationId int = 0,  
 @rJobTitleId int=0,  
 @rEmployeeTypeId int=0,  
 @rCompanyId int=0,  
 @rContractorId int = 0,  
 @rGenderId smallint,  
 @rStatusId int,  
 @rAgeFrom int,  
 @rAgeTo int=100,  
 @rFromDate datetime = null,  
 @rToDate datetime = null,  
 @rOrgId int,  
 @rEmployeeCode nvarchar(50)='',  
 @rUserId bigint = 0,  
 @rSectorId bigint = 0,  
 @rVerticalId bigint = 0,  
 @rCompnayGroupId bigint = 0  ,
 @rTargetGroupIds Nvarchar(Max) = ''
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON BEGIN  

DECLARE @ShiftTitle nvarchar(100) = '';
IF (@rShiftId > 0)
BEGIN
     set @ShiftTitle = (select Title from sCommon.tCompanyShiftMaster where Id = @rShiftId)
END

 SELECT SLM.Title,(select isnull(convert(decimal(18,2),Sum(Amount)),0) as 'Other Expance'  
 from sAccounting.tExpense SA where SA.StoreLocationId = SLM.Id  And  ((SA.ExpenseDate >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))  
 AND ((SA.ExpenseDate <= (@rToDate) ) OR (ISNULL(@rToDate, '') = ''))) as 'Other Expance',  
 (select isnull(convert(decimal(18,2),Sum(Amount)),0) as TotalVehicleExpance  
 from sSupport.tVehicleMaintenance Vm  
 inner join sSupport.tVehicleMaintenanceDetail vmd on vmd.VehicleMaintenanceId = vm.id  
 where vm.StoreLocationId = SLM.Id And ((Vm.MaintenanceDate >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))  
 AND ((Vm.MaintenanceDate <= (@rToDate) ) OR (ISNULL(@rToDate, '') = ''))) as 'Vehicle Expance',  
 (select isnull(convert(decimal(18,2),Sum(Amount)),0) as BioMedicalExpance  
 from sSupport.tBioMedicalWaste SB where SB.StoreLocationId = SLM.Id  And ((SB.CollectionDate >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))  
 AND ((SB.CollectionDate <= (@rToDate) ) OR (ISNULL(@rToDate, '') = ''))) as 'Bio-Medical Expance',  
 (select isnull(convert(decimal(18,2),Sum(MaintenenceCost)),0) as 'MaintenenceExpance'  
   
   
 from sAssetManagement.tMaintenence AM where AM.StoreLocationId = SLM.ID  And ((AM.MaintenenceDate >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))  
 AND ((AM.MaintenenceDate <= (@rToDate) ) OR (ISNULL(@rToDate, '') = ''))) as MaintenenceExpance,  
 (select isnull(convert(decimal(18,2),Sum(( isnull(SIB.Quantity,0) - isnull(innercount.RetQty,0 ) ) * isnull(WeightedAverageCost,1))),0) as 'First Aid Expance'  
 from sProcurement.tStockIssue SI   
 inner join sProcurement.tStockIssueDetail SIDT on SIDT.StockIssueId = SI.Id  
 left join sProcurement.tStockIssueBatch SIB on SIB.StockIssueDetailId = SIDT.Id  
 left join sIp.tStockItemPlanning SIP on SIP.StockItemId = SIDT.StockItemId and SIP.StoreLocationId = SI.FromStoreLocationId  
 left join (   
   
 select sum(isnull(SRB.ReturnQuantity,0)) as 'RetQty',SRB.StockIssueBatchId    
 from  sProcurement.tStockIssueReturn SIR   
 inner join  sProcurement.tStockIssueReturnBatch  SRB on SRB.StockIssueReturnId = SIR.Id    
 group by  SRB.StockIssueBatchId ) as innercount on innercount.StockIssueBatchId = SIB.Id  
 where SI.FromStoreLocationId = SLM.Id And ((convert(date,SI.CreatedDateTime) >= convert(Date,@rFromDate) ) OR (ISNULL(@rFromDate, '') = ''))  
 AND ((convert(date,SI.CreatedDateTime) <= convert(Date,@rToDate) ) OR (ISNULL(@rToDate, '') = ''))  
 and OtherLocationSourceTypeId is not null and OtherLocationSourceTypeId  in (120) and OtherLocationSourceTypeId not in(0)) as 'First Aid Expance',
   
 (select isnull(convert(decimal(18,2),Sum(( isnull(SIB.Quantity,0) - isnull(innercount.RetQty,0 ) ) * isnull(WeightedAverageCost,1))),0) as 'Ambulance Medicine'  
 from sProcurement.tStockIssue SI   
 inner join sProcurement.tStockIssueDetail SIDT on SIDT.StockIssueId = SI.Id  
 left join sProcurement.tStockIssueBatch SIB on SIB.StockIssueDetailId = SIDT.Id  
 left join sIp.tStockItemPlanning SIP on SIP.StockItemId = SIDT.StockItemId and SIP.StoreLocationId = SI.FromStoreLocationId  
 left join ( select sum(isnull(SRB.ReturnQuantity,0)) as 'RetQty',SRB.StockIssueBatchId    
 from  sProcurement.tStockIssueReturn SIR   
 inner join  sProcurement.tStockIssueReturnBatch  SRB on SRB.StockIssueReturnId = SIR.Id    
 group by  SRB.StockIssueBatchId ) as innercount on innercount.StockIssueBatchId = SIB.Id  
 where SI.FromStoreLocationId = SLM.Id And ((convert(date,SI.CreatedDateTime) >= convert(Date,@rFromDate) ) OR (ISNULL(@rFromDate, '') = ''))  
 AND ((convert(date,SI.CreatedDateTime) <= convert(Date,@rToDate) ) OR (ISNULL(@rToDate, '') = ''))  
 and OtherLocationSourceTypeId is not null and OtherLocationSourceTypeId  in (121) and OtherLocationSourceTypeId not in(0)) as 'Ambulance Medicine',  
   
   
 (select isnull(convert(decimal(18,2),Sum(( isnull(SIB.Quantity,0) - isnull(innercount.RetQty,0 ) ) * isnull(WeightedAverageCost,1))),0)   
 as 'Other Stock Issue'  
 from sProcurement.tStockIssue SI   
 inner join sProcurement.tStockIssueDetail SIDT on SIDT.StockIssueId = SI.Id  
 left join sProcurement.tStockIssueBatch SIB on SIB.StockIssueDetailId = SIDT.Id  
 --inner join  (  
 -- Select isnull(WeightedAverageCost,1) as 'WeightedAverageCost',SIB.Id from sIp.tWeightedAverageCostLog SIPD   
 -- inner join sProcurement.tStockIssueBatch SIB  ON SIPD.SourceId = SIB.Id and SIPD.SourceTypeId = 51  
 -- )  as ABC on   ABC.Id = SIB.Id  
 left join sIp.tStockItemPlanning SIP on SIP.StockItemId = SIDT.StockItemId   and SIP.StoreLocationId = SI.FromStoreLocationId  
 left join ( select sum(isnull(SRB.ReturnQuantity,0)) as 'RetQty',SRB.StockIssueBatchId    
 from  sProcurement.tStockIssueReturn SIR   
 inner join  sProcurement.tStockIssueReturnBatch  SRB on SRB.StockIssueReturnId = SIR.Id    
 group by  SRB.StockIssueBatchId ) as innercount on innercount.StockIssueBatchId = SIB.Id  
 where SI.FromStoreLocationId = SLM.Id   
 And ((convert(date,SI.CreatedDateTime) >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))  
 AND ((convert(date,SI.CreatedDateTime) <= (@rToDate) ) OR (ISNULL(@rToDate, '') = ''))  
 and OtherLocationSourceTypeId is not null and OtherLocationSourceTypeId  in (122) and OtherLocationSourceTypeId not in(0)) as 'Other Stock Issue'  
   
 ,  
 (SELECT ISNULL(convert(decimal(18,2),SUM((DB.Quantity - DB.ReturnQuantity) * DB.UnitCost)),0) as 'MedicineExpance'  
 FROM sExamination.tPrescription P INNER JOIN sExamination.tPrescriptionDetail PD ON PD.PrescriptionId = P.Id  
 INNER JOIN sPharmacy.tDispense D ON D.PrescriptionDetailId=PD.Id INNER JOIN sPharmacy.tDispenseBatch DB ON DB.DispenseId = D.Id  
 INNER JOIN sExamination.tExamination EAED ON P.SourceId=EAED.Id  
 INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = EAED.StoreLocationId AND UL.UserId = @rUserId  
 INNER JOIN sSecurity.tUser U ON U.Id = EAED.CreatedUserId where EAED.StoreLocationId = SLM.Id  
 and ISNULL(convert(decimal(18,2),(DB.Quantity - DB.ReturnQuantity) * DB.UnitCost),0) > 0 --Shivam DT-13/06/23; id - 25595
 and ((EAED.ExaminationDate >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))  
 and ((EAED.ExaminationDate <= (@rToDate) ) OR (ISNULL(@rToDate, '') = ''))) as 'Medicine Expance'  
 
 from sIp.tStoreLocationMaster SLM  
 INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id  
 WHERE  
  UL.UserId =@rUserId   
 AND SLM.OrgId=@rOrgId And ((SLM.Id  = @rStoreLocationId ) OR (ISNULL(@rStoreLocationId, '') = ''))  
 And SLM.IsActiveHealth='1'   AND SLM.IsOPDSetup = 1 AND   SLM.IsObsolete=0   order by SLM.Title asc    
 
 CREATE TABLE #TempTable  
 (  
  ExaminationId  bigint,DepartmentName nvarchar(150),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,Disease varchar(200),DiseseSystem varchar(200),DiseaseId bigint  
 )  
 INSERT INTO #TempTable  
 (  
  ExaminationId,DepartmentName,OrganizationDepartmentId,ParticipantCode,ParticipantName,GenderId,Gender,  
  CauseId,CauseName,ParticipantType,ParticipantSourceTypeId,EMPType,LoginTitle,UserId,LocationId,Disease,DiseseSystem,DiseaseId  
 )  
 SELECT ED.Id AS ExaminationId,  
 ODM.Title AS DepartmentName,  
 ED.OrganizationDepartmentId,  
 ParticipantCode = CASE ED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,  
 ParticipantName = CASE ED.ParticipantSourceTypeId WHEN 95 THEN EM.FirstName + ' ' + isnull(EM.LastName,'')  
 WHEN 1001 THEN EFD.Name WHEN 1009 THEN  
  CASE WHEN isnull(O.OtherName,'') <> '' THEN O.OtherName   
  ELSE BM.FirstName + ' ' + isnull(BM.LastName,'') END END,  
 GenderId = CASE ED.ParticipantSourceTypeId  
 WHEN 95 THEN EPD.GenderId  
 WHEN 1001 THEN ISNULL([sCommon].[fGenderIdFromRelationIdGet](EFD.RelationshipId),'')  
 WHEN 1009 THEN BM.GenderId END,  
 Gender = CASE ED.ParticipantSourceTypeId  
 WHEN 95 THEN GM1.Title  
 WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')  
 WHEN 1009 THEN GM2.Title END,  
 CM.Id As CauseId,  
 CM.Title As CauseName,  
 ParticipantType = CASE ED.ParticipantSourceTypeId WHEN 95 THEN ETM.Title WHEN 1001 THEN 'Dep' WHEN 1009 THEN BTM.Code END,  
 ParticipantSourceTypeId,  
 CASE ParticipantSourceTypeId WHEN 95 THEN 'Employee' WHEN 1001 THEN 'Dep' WHEN 1009 THEN 'Oth' END AS EMPType,  
 U.LoginTitle,  
 UL.UserId,  
 ED.StoreLocationId,  
 DM.Title AS Disease,  
 ISNULL(DS.Title,'Blank') AS DiseseSystem,  
 DM.Id AS DiseaseId  
 FROM sExamination.tExamination ED   
 INNER JOIN sExamination.tExaminDisease ED1 ON ED1.SourceId=ED.Id  
 INNER JOIN sExamination.tExaminDiseaseDetail EDD ON EDD.ExaminDiseaseId = ED1.Id  
 INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id=EDD.DiseaseId   
 INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = ED.StoreLocationId  
 INNER JOIN sSecurity.tUser U ON U.Id = ED.CreatedUserId  
 INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = ED.SetupId  
 INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id  
 INNER JOIN sIp.tStoreLocationMaster SLM on ED.StoreLocationId = SLM.Id  
   
 LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = ED.CauseId and CM.OrgId = @rOrgId  
 LEFT JOIN sHrm.tEmployeeCompanyMaster ECM on ED.EmployeeCompanyId = ECM.Id  
 LEFT JOIN sHrm.tCompanyGroupMaster CG on ECM.CompanyGroupId = CG.Id  
 LEFT JOIN sHrm.tVerticalMaster VM on CG.VerticalId = VM.Id   
 LEFT JOIN sHrm.tEmployeeMaster EM on ED.ParticipantSourceId = EM.Id and ED.ParticipantSourceTypeId = 95  
 LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId  
 LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on ED.ParticipantSourceId = EFD.Id and ED.ParticipantSourceTypeId = 1001  
 LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id   
 LEFT JOIN sHrm.tCsrBenefiterMaster BM on ED.ParticipantSourceId = BM.Id and ED.ParticipantSourceTypeId = 1009  
 LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CsrBenefiterTypeId = BTM.Id  
 LEFT JOIN sHrm.tEmployeeJobDetail EJD on EM.Id = EJD.EmployeeId  
 LEFT JOIN sHrm.tEmployeeJobDetail EJD2 on EM2.Id = EJD2.EmployeeId  
 LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM on ED.OrganizationDepartmentId = ODM.Id  
 LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON ODM.DepartmentGroupId = DGM.Id   
 LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id  
 LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId  
 LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId   
 LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId  
 LEFT JOIN sExamination.tDiseaseSystemMaster DS ON DS.Id = DM.DiseaseSystemId  
 LEFT JOIN sExamination.tOPD O ON O.ExaminationId = ED.Id  
     
 WHERE STM.MainTypeId = 8 and isnull(IsCancel,0) = 0 -- 7 for caselist  
 AND ED1.IsObsolete = 0  
 AND EDD.IsObsolete = 0  
 AND ((ED.StoreLocationId = @rStoreLocationId)OR @rStoreLocationId=0)  
 AND  
 (  
  (EM.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EM2.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (BM.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  @rEmployeeCode = ''  
 )  
 AND (ED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)  
 AND(ED.GradeId=@rGradeId OR @rGradeId=0)  
 AND(ED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)  
 AND  
 (  
  (EJD.EmployeeJobTitleId = @rJobTitleId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EJD2.EmployeeJobTitleId = @rJobTitleId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (0 = 0 AND ED.ParticipantSourceTypeId = 1009)  
  OR @rJobTitleId = 0  
 )  
 AND  
 (  
  (EJD.EmployeeTypeId = @rEmployeeTypeId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EJD2.EmployeeTypeId = @rEmployeeTypeId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (0 = 0 AND ED.ParticipantSourceTypeId = 1009)  
  OR @rEmployeeTypeId = 0  
 )   
 AND  
 (     
  (EJD.ContractorId = @rContractorId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EJD2.ContractorId = @rContractorId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (0 = 0 AND ED.ParticipantSourceTypeId = 1009)  
  OR @rContractorId=0  
 )  
 AND(ED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)  
 AND  
 (  
  (EPD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EFD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (BM.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1009)  
  OR @rGenderId=0  
 )  
 AND(ED.EmployeeStatusId=@rStatusId OR @rStatusId=0)  
 AND  
 (  
  (isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND ED.ParticipantSourceTypeId = 1009)  
  OR ISNULL(@rAgeTo,0)=0  
 )  
 AND  
 (  
  (isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND ED.ParticipantSourceTypeId = 1009)     
  OR ISNULL(@rAgeFrom,0)=0  
 )  
 AND ((ED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((ED.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))  
 --AND (SLM.LocationId = @rLocationId or @rLocationId = 0)  
 AND (ED.OrgId =  @rOrgId)  
 AND ((ED.CauseId=@rCaseCauseId ) or (@rCaseCauseId=0))  
 AND (@rVisitTypeId = 0 OR ISNULL(O.VisitTypeId, 1) = @rVisitTypeId)
 AND (@ShiftTitle = '' OR @ShiftTitle = [dbo].[fGetShift](O.OPDTime,@rOrgId))
 AND ((ED.ParticipantSourceTypeId=@rParticipantTypeId) or (@rParticipantTypeId=0))  
 AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)  
 AND (FM.Id = @rFunctionId OR @rFunctionId = 0)  
 and (ECM.CompanyGroupId = @rCompnayGroupId or @rCompnayGroupId = 0)  
 and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)  
 and (VM.SectorId = @rSectorId or @rSectorId = 0)  
 AND UL.UserId = @rUserId  
 AND ((ED.TargetGroupId IN (SELECT item FROM  sCommon.fnsplit(@rTargetGroupIds,',') )) or @rTargetGroupIds='') --Nidhi DT-17/01/23; id - 22910
  
   CREATE TABLE #TempTableNew  
 (  
  ExaminationId  bigint,DepartmentName nvarchar(150),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,VisitType nvarchar(100),Shifts nvarchar(100),FurtherAction nvarchar(100)  
 )  
 INSERT INTO #TempTableNew
 (  
  ExaminationId,DepartmentName,OrganizationDepartmentId,ParticipantCode,ParticipantName,GenderId,Gender,  
  CauseId,CauseName,ParticipantType,ParticipantSourceTypeId,EMPType,LoginTitle,UserId,LocationId,VisitType,
  Shifts, FurtherAction
 )  
   
 SELECT ED.Id AS ExaminationId,  
 ODM.Title AS DepartmentName,  
 ED.OrganizationDepartmentId,  
 ParticipantCode = CASE ED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,  
 ParticipantName = CASE ED.ParticipantSourceTypeId WHEN 95 THEN EM.FirstName + ' ' + isnull(EM.LastName,'')  
 WHEN 1001 THEN EFD.Name WHEN 1009 THEN  
  CASE WHEN isnull(O.OtherName,'') <> '' THEN O.OtherName   
  ELSE BM.FirstName + ' ' + isnull(BM.LastName,'') END END,  
 GenderId = CASE ED.ParticipantSourceTypeId  
 WHEN 95 THEN EPD.GenderId  
 WHEN 1001 THEN ISNULL([sCommon].[fGenderIdFromRelationIdGet](EFD.RelationshipId),'')  
 WHEN 1009 THEN BM.GenderId END,  
 Gender = CASE ED.ParticipantSourceTypeId  
 WHEN 95 THEN GM1.Title  
 WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')  
 WHEN 1009 THEN GM2.Title END,  
 CM.Id As CauseId,  
 CM.Title As CauseName,  
 ParticipantType = CASE ED.ParticipantSourceTypeId WHEN 95 THEN ETM.Title WHEN 1001 THEN 'Dep' WHEN 1009 THEN 'Oth' END,  
 ParticipantSourceTypeId,  
 CASE ParticipantSourceTypeId WHEN 95 THEN 'Employee' WHEN 1001 THEN 'Dep' WHEN 1009 THEN 'Oth' END AS EMPType,  
 U.LoginTitle,  
 UL.UserId,  
 ED.StoreLocationId, 
 ISNULL(VTM.Title, 'Direct Consultation') as VisitType, [dbo].[fGetShift](O.OPDTime,@rOrgId) as Shifts,
 FAM.Title as FurtherAction
 FROM sExamination.tExamination ED   
 INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = ED.StoreLocationId  
 INNER JOIN sSecurity.tUser U ON U.Id = ED.CreatedUserId  
 INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = ED.SetupId  
 INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id 
 INNER JOIN sIp.tStoreLocationMaster SLM on ED.StoreLocationId = SLM.Id   
 INNER JOIN sExamination.tCauseMaster CM ON CM.Id = ED.CauseId and CM.OrgId = @rOrgId  
 LEFT JOIN sHrm.tEmployeeCompanyMaster ECM on ED.EmployeeCompanyId = ECM.Id  
 LEFT JOIN sHrm.tCompanyGroupMaster CG on ECM.CompanyGroupId = CG.Id  
 LEFT JOIN sHrm.tVerticalMaster VM on CG.VerticalId = VM.Id   
 LEFT JOIN sHrm.tEmployeeMaster EM on ED.ParticipantSourceId = EM.Id and ED.ParticipantSourceTypeId = 95  
 LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId  
 LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on ED.ParticipantSourceId = EFD.Id and ED.ParticipantSourceTypeId = 1001  
 LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id   
 LEFT JOIN sHrm.tCsrBenefiterMaster BM on ED.ParticipantSourceId = BM.Id and ED.ParticipantSourceTypeId = 1009  
 LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CsrBenefiterTypeId = BTM.Id  
 LEFT JOIN sHrm.tEmployeeJobDetail EJD on EM.Id = EJD.EmployeeId  
 LEFT JOIN sHrm.tEmployeeJobDetail EJD2 on EM2.Id = EJD2.EmployeeId  
 LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM on ED.OrganizationDepartmentId = ODM.Id  
 LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON ODM.DepartmentGroupId = DGM.Id   
 LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id  
 LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId  
 LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId   
 LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId  
 LEFT JOIN sExamination.tOPD O ON O.ExaminationId = ED.Id
 LEFT JOIN sExamination.tVisitTypeMaster VTM ON VTM.Id = O.VisitTypeId
 LEFT JOIN sSafety.tFurtherActionMaster FAM ON FAM.Id = O.FurtherActionId     
 WHERE STM.MainTypeId = 8 and isnull(IsCancel,0) = 0 -- 7 for caselist   
 AND ((ED.StoreLocationId = @rStoreLocationId)OR @rStoreLocationId=0)  
 AND   
 (  
  (EM.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EM2.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (BM.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  @rEmployeeCode = ''  
 )  
 AND (ED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)  
 AND(ED.GradeId=@rGradeId OR @rGradeId=0)  
 AND(ED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)  
 AND  
 (  
  (EJD.EmployeeJobTitleId = @rJobTitleId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EJD2.EmployeeJobTitleId = @rJobTitleId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (0 = 0 AND ED.ParticipantSourceTypeId = 1009)  
  OR @rJobTitleId = 0  
 )  
 AND  
 (  
  (EJD.EmployeeTypeId = @rEmployeeTypeId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EJD2.EmployeeTypeId = @rEmployeeTypeId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (0 = 0 AND ED.ParticipantSourceTypeId = 1009)  
  OR @rEmployeeTypeId = 0  
 )   
 AND  
 (     
  (EJD.ContractorId = @rContractorId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EJD2.ContractorId = @rContractorId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (0 = 0 AND ED.ParticipantSourceTypeId = 1009)  
  OR @rContractorId=0  
 )  
 AND(ED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)  
 AND  
 (  
  (EPD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EFD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (BM.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1009)  
  OR @rGenderId=0  
 )  
 AND(ED.EmployeeStatusId=@rStatusId OR @rStatusId=0)  
 AND  
 (  
  (isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND ED.ParticipantSourceTypeId = 1009)  
  OR ISNULL(@rAgeTo,0)=0  
 )  
 AND  
 (  
  (isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND ED.ParticipantSourceTypeId = 1009)     
  OR ISNULL(@rAgeFrom,0)=0  
 )  
 AND ((ED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((ED.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))  
 --AND (SLM.LocationId = @rLocationId or @rLocationId = 0)  
 AND (ED.OrgId =  @rOrgId)  
 AND ((ED.CauseId=@rCaseCauseId )or (@rCaseCauseId=0))  
 AND (@rVisitTypeId = 0 OR ISNULL(O.VisitTypeId, 1) = @rVisitTypeId)
 AND (@ShiftTitle = '' OR @ShiftTitle = [dbo].[fGetShift](O.OPDTime,@rOrgId))
 AND ((ED.ParticipantSourceTypeId=@rParticipantTypeId) or (@rParticipantTypeId=0))  
 AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)  
 AND (FM.Id = @rFunctionId OR @rFunctionId = 0)  
 and (ECM.CompanyGroupId = @rCompnayGroupId or @rCompnayGroupId = 0)  
 and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)  
 and (VM.SectorId = @rSectorId or @rSectorId = 0)  
 AND UL.UserId = @rUserId 
 AND ((ED.TargetGroupId IN (SELECT item FROM  sCommon.fnsplit(@rTargetGroupIds,',') )) or @rTargetGroupIds='') --Nidhi DT-17/01/23; id - 22910
  
   
 SELECT SLM.Title,(select Count(*) as 'Oth' from #TempTableNew T where T.EMPType='Oth'  
 and t.LocationId = SLM.id And SLM.IsActiveHealth='1' AND SLM.IsOpdSetup = 1 and T.ParticipantType is not null ) as 'Oth',  
 (select Count(*) as 'Employee' from #TempTableNew T where T.EMPType='Employee' and T.LocationId = SLM.id  
 And SLM.IsActiveHealth='1' AND SLM.IsOpdSetup = 1 and T.ParticipantType is not null ) as 'Employee',  
 (select Count(*) as 'Dep' from #TempTableNew T where T.EMPType='Dep' and T.LocationId = SLM.id And SLM.IsActiveHealth='1'  
 AND SLM.IsOpdSetup = 1 and T.ParticipantType is not null ) as 'Dep'   
 from sIp.tStoreLocationMaster SLM  
 INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id  
  WHERE UL.UserId =@rUserId AND SLM.OrgId=@rOrgId  
 And ((SLM.Id  = @rStoreLocationId ) OR (ISNULL(@rStoreLocationId, '') = '')) And SLM.IsActiveHealth='1' AND SLM.IsOpdSetup = 1  
 order by SLM.Title asc
  
 declare @query varchar(max)='',@cols varchar(max)  
      
 select @cols = STUFF((SELECT Distinct ',' + QUOTENAME(CASE ParticipantSourceTypeId WHEN 95 THEN T.Title WHEN 1001 THEN 'Dep' WHEN 1009 THEN 'Oth' end)   
    from sExamination.tExamination E  
    left join sHrm.tEmployeeMaster M on E.ParticipantSourceId = M.Id and E.ParticipantSourceTypeId = 95  
    inner join sExamination.tSetupMaster SM on E.SetupId = SM.Id  
    inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id  
    left join sHrm.tEmployeeJobDetail J on J.EmployeeId = M.Id  
    left join sHrm.tEmployeeTypeMaster T on J.EmployeeTypeId = T.Id   
    where E.OrgId = @rOrgId and MainTypeId = 8 and isnull(IsCancel,0) = 0 group by T.Title,  
    ParticipantSourceTypeId FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')    
   
 if @cols <> ''  
 begin   
  select @query = @query + 'SELECT * FROM  
  (  
   SELECT L.Title,ParticipantType AS ''ParticipantType'',COUNT(Isnull(ParticipantType,0)) AS Cnt  
   FROM #TempTableNew TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY ParticipantType,TM.LocationId,L.Title  
  ) as s  
  PIVOT  
  (  
   max(Cnt) FOR ParticipantType IN (' + @cols + ')  
  )AS pvt'  
  exec (@query)  
 end
 ELSE
 BEGIN
	select 0 as Result
 END
   
 declare @query11 varchar(max)='',@cols11 varchar(max)  
       
    select @cols11 = STUFF((SELECT Distinct ',' + QUOTENAME(CauseName) from #TempTableNew FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')  
  
    if @cols11 <> ''  
 begin   
  select @query11 = @query11 + 'SELECT * FROM  
  (  
   SELECT  L.Title ,CauseName AS CauseName,COUNT(Isnull(CauseId,0)) AS CauseCnt  
   FROM #TempTableNew TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where CauseName is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY CauseName,L.Title  
  ) as s  
  PIVOT  
  (  
   max(CauseCnt) FOR CauseName IN (' + @cols11 + ')  
  )AS pvt'  
  exec (@query11)  
 end 
 ELSE
 BEGIN
	select 0 as Result
 END
   
 declare @query2 varchar(max)='',@cols2 varchar(max)  
      
    select @cols2 = STUFF((SELECT Distinct ',' + QUOTENAME(CauseName) from #TempTableNew where CauseName is not null  
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    if @cols2 <> ''  
 begin   
  select @query2 = @query2 + 'SELECT * FROM  
  (  
   SELECT  L.Title ,CauseName AS CauseName,CauseId  
   FROM #TempTableNew TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where CauseName is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY CauseName,L.Title,CauseId  
  ) as s  
  PIVOT  
  (  
   max(CauseId) FOR CauseName IN (' + @cols2 + ')  
  )AS pvt'  
  exec (@query2)  
 end
 ELSE
 BEGIN
	select 0 as Result
 END
   
 declare @query3 varchar(max)='',@cols3 varchar(max)  
      
    select @cols3 = STUFF((SELECT Distinct ',' + QUOTENAME(DiseseSystem) from #TempTable where DiseseSystem is not null  
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
 if @cols3 <> ''  
 begin   
  select @query3 = @query3 + 'SELECT * FROM  
  (  
   SELECT  L.Title ,DiseseSystem AS DiseseSystem,COUNT(Isnull(DiseaseId,0)) AS DiseaseCnt  
   FROM #TempTable TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where DiseseSystem is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY DiseseSystem,L.Title  
  ) as s  
  PIVOT  
  (  
   max(DiseaseCnt) FOR DiseseSystem IN (' + @cols3 + ')  
  )AS pvt'  
  exec (@query3)  
 end
 ELSE
 BEGIN
	select 0 as Result
 END
    
 declare @query4 varchar(max)='',@cols4 varchar(max)  
      
    select @cols4 = STUFF((SELECT Distinct ',' + QUOTENAME(DiseseSystem) from #TempTable where DiseseSystem is not null  
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
 if @cols4 <> ''  
 begin   
  select @query4 = @query4 + 'SELECT * FROM  
  (  
   SELECT  L.Title ,DiseseSystem AS DiseseSystem,DiseaseId  
   FROM #TempTable TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where DiseseSystem is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY DiseseSystem,L.Title,DiseaseId  
  ) as s  
  PIVOT  
  (  
   max(DiseaseId) FOR DiseseSystem IN (' + @cols4 + ')  
  )AS pvt'  
  exec (@query4)  
 end
 ELSE
 BEGIN
	select 0 as Result
 END
   
 SELECT SLM.Title,(select Count(*) as 'High Risk' from #TempTableNew T
					Inner Join sExamination.tExamination EXM on EXM.Id = T.ExaminationId
  where ISNULL(EXM.RiskCategoryId, 0) = 1 and t.LocationId = SLM.id) as 'High Risk',
 (select Count(*) as 'Pediatric' from #TempTableNew T
	Inner Join sExamination.tOPD OPD on OPD.ExaminationId = T.ExaminationId
  where ISNULL(OPD.IsPediatric, 0) = 1 and t.LocationId = SLM.id) as 'Pediatric'
 from sIp.tStoreLocationMaster SLM  
 INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id  
  WHERE UL.UserId =@rUserId AND SLM.OrgId=@rOrgId  
 And ((SLM.Id  = @rStoreLocationId ) OR (ISNULL(@rStoreLocationId, '') = '')) And SLM.IsActiveHealth='1' AND SLM.IsOpdSetup = 1  
 order by SLM.Title asc
   
declare @query5 varchar(max)='',@cols5 varchar(max)  
      
    select @cols5 = STUFF((SELECT Distinct ',' + QUOTENAME(VisitType) from #TempTableNew where VisitType is not null  
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
 if @cols5 <> ''  
 begin   
  select @query5 = @query5 + 'SELECT * FROM  
  (  
   SELECT L.Title, VisitType AS VisitType,COUNT(VisitType) AS VisitTypeCnt  
   FROM #TempTableNew TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where VisitType is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY VisitType,L.Title  
  ) as s
  PIVOT  
  (  
   max(VisitTypeCnt) FOR VisitType IN (' + @cols5 + ')  
  )AS pvt'
  exec (@query5)
 end
 ELSE
 BEGIN
	select 0 as Result
 END

 declare @query6 varchar(max)='',@cols6 varchar(max)  
      
    select @cols6 = STUFF((SELECT Distinct ',' + QUOTENAME(Shifts) from #TempTableNew where Shifts is not null  
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
 if @cols6 <> ''  
 begin   
  select @query6 = @query6 + 'SELECT * FROM  
  (  
   SELECT L.Title, Shifts AS Shifts,COUNT(Shifts) AS ShiftsCnt  
   FROM #TempTableNew TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where Shifts is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY Shifts,L.Title  
  ) as s
  PIVOT  
  (  
   max(ShiftsCnt) FOR Shifts IN (' + @cols6 + ')  
  )AS pvt'
  exec (@query6)
 end
 ELSE
 BEGIN
	select 0 as Result
 END

  declare @query7 varchar(max)='',@cols7 varchar(max)  
      
    select @cols7 = STUFF((SELECT Distinct ',' + QUOTENAME(FurtherAction) from #TempTableNew where FurtherAction is not null  
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
 if @cols7 <> ''  
 begin   
  select @query7 = @query7 + 'SELECT * FROM  
  (  
   SELECT L.Title, FurtherAction AS FurtherAction,COUNT(FurtherAction) AS FurtherActionCnt  
   FROM #TempTableNew TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where FurtherAction is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY FurtherAction,L.Title  
  ) as s
  PIVOT  
  (  
   max(FurtherActionCnt) FOR FurtherAction IN (' + @cols7 + ')
  )AS pvt'
  exec (@query7)
 end
 ELSE
 BEGIN
	select 0 as Result
 END

  declare @query8 varchar(max)='', @cols8 varchar(max)  
       
  select @cols8 = STUFF((SELECT Distinct ',' + QUOTENAME(ISNULL(EM.Firstname,'') + ' ' + ISNULL(EM.Lastname,'')) from sAppointment.tAppointment AP
							inner join shrm.tEmployeemaster EM on EM.Id = AP.DoctorEmployeeId
							inner join sIp.tStoreLocationMaster L on AP.StoreLocationId = L.Id
                         where DoctorEmployeeId is not null
						 AND ((AP.AppointmentDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
						 AND ((AP.AppointmentDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
						 AND (AP.StoreLocationId=@rStoreLocationId OR @rStoreLocationId=0)
  FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
      
 if @cols8 <> ''  
 begin  
  select @query8 = @query8 + 'SELECT * FROM  
  (  
   SELECT L.Title, ISNULL(EM.Firstname,'''') + '' '' + ISNULL(EM.Lastname,'''') AS DoctorName,
   COUNT(AP.DoctorEmployeeId) AS DoctorCnt
   FROM sAppointment.tAppointment AP
   inner join shrm.tEmployeemaster EM on EM.Id = AP.DoctorEmployeeId
   inner join sIp.tStoreLocationMaster L on AP.StoreLocationId = L.Id
   where DoctorEmployeeId is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1
   AND ((AP.AppointmentDate >= ''' + CAST(@rFromDate AS NVARCHAR(12)) + ''') OR (ISNULL(''' + CAST(@rFromDate AS NVARCHAR(12)) + ''','''') = ''''))  
   AND ((AP.AppointmentDate <= ''' + CAST(@rToDate AS NVARCHAR(12)) + ''') OR (ISNULL(''' + CAST(@rToDate AS NVARCHAR(12)) + ''','''') = ''''))
   AND (AP.StoreLocationId=' + CAST(@rStoreLocationId AS NVARCHAR(12)) + ' or ' + CAST(@rStoreLocationId AS NVARCHAR(12)) + ' = 0)
   GROUP BY EM.Firstname,EM.Lastname,L.Title
  ) as s
  PIVOT
  (  
   max(DoctorCnt) FOR DoctorName IN (' + @cols8 + ')
  )AS pvt'
  exec (@query8)
 end
 ELSE
 BEGIN
	select 0 as Result
 END

   declare @query9 varchar(max)='', @cols9 varchar(max)  
       
  select @cols9 = STUFF((SELECT Distinct ',' + QUOTENAME(ISNULL(EM.Firstname,'') + ' ' + ISNULL(EM.Lastname,'')) from sExamination.tRegistration REG
							inner join shrm.tEmployeemaster EM on EM.Id = REG.DoctorEmployeeId
							inner join sIp.tStoreLocationMaster L on REG.StoreLocationId = L.Id
                         where DoctorEmployeeId is not null
						 AND ((REG.RegistrationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
						 AND ((REG.RegistrationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
						 AND (REG.StoreLocationId=@rStoreLocationId OR @rStoreLocationId=0)
  FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
      
 if @cols9 <> ''  
 begin  
  select @query9 = @query9 + 'SELECT * FROM  
  (  
   SELECT L.Title, ISNULL(EM.Firstname,'''') + '' '' + ISNULL(EM.Lastname,'''') AS DoctorName,
   COUNT(REG.DoctorEmployeeId) AS DoctorCnt
   FROM sExamination.tRegistration REG
   inner join shrm.tEmployeemaster EM on EM.Id = REG.DoctorEmployeeId
   inner join sIp.tStoreLocationMaster L on REG.StoreLocationId = L.Id
   where DoctorEmployeeId is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1
   AND ((REG.RegistrationDate >= ''' + CAST(@rFromDate AS NVARCHAR(12)) + ''') OR (ISNULL(''' + CAST(@rFromDate AS NVARCHAR(12)) + ''','''') = ''''))  
   AND ((REG.RegistrationDate <= ''' + CAST(@rToDate AS NVARCHAR(12)) + ''') OR (ISNULL(''' + CAST(@rToDate AS NVARCHAR(12)) + ''','''') = ''''))
   AND (REG.StoreLocationId=' + CAST(@rStoreLocationId AS NVARCHAR(12)) + ' or ' + CAST(@rStoreLocationId AS NVARCHAR(12)) + ' = 0)
   GROUP BY EM.Firstname,EM.Lastname,L.Title
  ) as s
  PIVOT
  (  
   max(DoctorCnt) FOR DoctorName IN (' + @cols9 + ')
  )AS pvt'
  exec (@query9)
 end
 ELSE
 BEGIN
	select 0 as Result
 END

 DROP TABLE #TempTable  
 DROP TABLE #TempTableNew       

END

GO


CREATE OR ALTER PROCEDURE[sAlert].[pAlertLogAdd]   
 @rXML nvarchar(max),  
 @rOrgId smallint  
   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
--BEGIN TRY  
   
 --BEGIN TRANSACTION  
 DECLARE @loXML XML;  
  
  SET @rXML=REPLACE(@rXML,'&','AND');  
 SET @loXML = CAST(@rXML AS XML);  
  
 DECLARE @lCount INT  
 DECLARE @lInterrorCode INT  
 --  @intDoc INT  
 --EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXML  
   
 DECLARE @lNextNumber BIGINT    
 DECLARE @lFromNextNumber BIGINT
 DECLARE @lMaxId BIGINT
 
 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAlert.tAlertLog', 0, 1, 1,@outNextNumber = @lNextNumber output

 SELECT @lMaxId = ISNULL(MAX(Id),0) FROM sAlert.tAlertLog WHERE OrgId = @rOrgId
 
 IF @lNextNumber <= @lMaxId
 BEGIN
     SET @lFromNextNumber = @lMaxId
 END
 ELSE
 BEGIN
     SET @lFromNextNumber = @lNextNumber - 1
 END
 
 INSERT INTO sAlert.tAlertLog  
  (  
   Id,  
   ContactId,  
   AlertMessage,  
   AlertSubject,  
   StatusId,  
   ResultMessage,  
   SMSType,  
   SourceEvent,  
   EventId,  
   EventName,  
   AlertModeId,  
   OrgId,  
   CreatedUserId,  
   CreatedDateTime,  
   UserId,  
   IsDaily,  
   IsWeekly,  
   IsMonthly,  
   ProviderAppointmentId , 
   ClaimIntimationDetailId
  )  
 SELECT  
   @lFromNextNumber + ROW_NUMBER() OVER(ORDER BY T.c.value('ContactId[1]','nvarchar(50)')),  
   T.c.value('ContactId[1]','nvarchar(500)') AS ContactId,  
   [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('AlertMessage[1]','nvarchar(max)')) AS AlertMessage,  
   [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('AlertSubject[1]','nvarchar(255)')) AS AlertSubject,  
   T.c.value('StatusId[1]','int') AS StatusId,  
   [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('ResultMessage[1]','nvarchar(255)')) AS ResultMessage,  
   T.c.value('SMSType[1]','nvarchar(50)') AS SMSType,  
   T.c.value('SourceEvent[1]','nvarchar(50)') AS SourceEvent,  
   T.c.value('EventId[1]','int') AS EventId,   
   [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('EventName[1]','nvarchar(100)')) AS EventName,  
   T.c.value('AlertModeId[1]','tinyint') AS AlertModeId,  
   @rOrgId,  
   CASE WHEN T.c.value('CreatedUserId[1]','bigint') = 1 THEN sCommon.fGetBigIntIdForOrg(T.c.value('CreatedUserId[1]','bigint'),@rOrgId) ELSE T.c.value('CreatedUserId[1]','bigint') END,  
     
   sCommon.fGetDate(),  
   T.c.value('UserId[1]','bigint') AS UserId,  
   case when T.c.value('Flag[1]','int') = 1 then 1 ENd,  
   case when T.c.value('Flag[1]','int') = 2 then 1 ENd,  
   case when T.c.value('Flag[1]','int') = 3 then 1 ENd,  
     T.c.value('ProviderAppointmentId[1]','bigint') AS ProviderAppointmentId  ,
	  T.c.value('ClaimIntimationDetailId[1]','bigint') AS ClaimIntimationDetailId  

    
 FROM  
  @loXML.nodes('/Table/AlertLog')T(c)  
 -- OPENXML (@intDoc, '/Table/AlertLog', 1)  
 --WITH  
 --(  
 -- ContactId nvarchar(50) 'ContactId',  
 -- AlertMessage nvarchar(255) 'AlertMessage',  
 -- AlertSubject nvarchar(255) 'AlertSubject',  
 -- StatusId int 'StatusId',  
 -- ResultMessage nvarchar(255) 'ResultMessage',  
 -- SMSType nvarchar(50) 'SMSType',  
 -- SourceEvent nvarchar(50) 'SourceEvent',  
 -- EventId int 'EventId',  
 -- AlertModeId tinyint 'AlertModeId',  
 -- CreatedUserId bigint 'CreatedUserId'  
 --)  
  
 SELECT @lCount = COUNT(1)  
  FROM   
  @loXML.nodes('/Table/AlertLog')T(c)  
  --OPENXML (@intDoc, '/Table/AlertLog', 1)  
  --   WITH ( ContactId nvarchar(50))  
  SET @lNextNumber  = @lCount + @lFromNextNumber   
    
  EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAlert.tAlertLog', @rCurrentNumber = @lNextNumber   
    
  --EXEC sp_xml_removedocument @intDoc  
    
  SELECT 1 AS Result,@lFromNextNumber+1 AS FromId,@lNextNumber AS ToId  
   
 -- COMMIT TRANSACTION  
    
 --END TRY  
   
 --BEGIN CATCH   
 -- ROLLBACK TRANSACTION  
 -- SELECT -1 AS Result  
 --END CATCH  
END  

GO


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

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

IF(@rId = 0)
BEGIN

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


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

	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sExamination.tHealthIndexParameterDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	SELECT @lMaxId = ISNULL(MAX(Id), 0) FROM sExamination.tHealthIndexParameterDetail WHERE OrgId = @rOrgId

	IF @lNextNumber <= @lMaxId
	BEGIN
		SET @lNextNumber = @lMaxId + 1
	END

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

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

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


GO


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

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

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

 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrDiseaseXML,5,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >      
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>      
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>        <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  declare @tbltmpHistory table       
  (      
   tid int identity(1,1),h_ParticipantSourceId bigint,h_Self nvarchar(2000),h_Mother nvarchar(200),      
   h_Father nvarchar(200),h_Brother nvarchar(200),h_Sister nvarchar(200),h_Surgery nvarchar(2000),h_ExaminationId bigint,h_OrgId int,      
   h_ParticipantAreaId bigint,h_AreaId int,AreaName nvarchar(200),h_HistoryId bigint, h_TreatmentHistoryRemark nvarchar(2000),h_PastHistoryRemark nvarchar(2000),  
   h_PastMedicalHistorySelf nvarchar(2000),h_HistoryMother nvarchar(2000),h_HistoryFather nvarchar(2000)  
  )      
  insert into @tbltmpHistory      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  replace(T.c.value('@PastHistorySelf','nvarchar(2000)'),'+',',') as PastHistorySelf,      
  replace(T.c.value('@PastHistoryMother','nvarchar(200)'),'+',',') as PastHistoryMother,      
  replace(T.c.value('@PastHistoryFather','nvarchar(200)'),'+',',') as PastHistoryFather,      
  replace(T.c.value('@PastHistoryBrother','nvarchar(200)'),'+',',') as PastHistoryBrother,      
  replace(T.c.value('@PastHistorySister','nvarchar(200)'),'+',',') as PastHistorySister,      
  T.c.value('@PastSurgicalHistorySelf','nvarchar(2000)') as Surgery,0,0,null,null,'Past History',null,T.c.value('@TreatmentHistoryRemark','nvarchar(2000)') as TreatmentHistoryRemark      
  ,T.c.value('@PastHistoryRemark','nvarchar(2000)') as PastHistoryRemark,  
  T.c.value('@PastMedicalHistorySelf','nvarchar(2000)') as PastMedicalHistorySelf,  --mantis:0033673 by shivam(15/05/2024)  
  T.c.value('@HistoryMother','nvarchar(2000)') as HistoryMother, --Mantis: 0032861, Date: 13/04/2024 by Deval  
  T.c.value('@HistoryFather','nvarchar(2000)') as HistoryFather --Mantis: 0032861, Date: 13/04/2024 by Deval  
  from @loXMLHistory.nodes('/Historys/History')T(c)
        
  update t  set h_ExaminationId = e_examinationid,h_OrgId = e_OrgId  
  from @tbltmpHistory as t      
  inner join #tbltmpExamination e on t.h_ParticipantSourceId=e.e_ParticipantSourceId --and t.tid=e.tid      
  --where e_ParticipantSourceId = h_ParticipantSourceId         

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

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

  select @lCount = max(tid) FROM #tblPulmonary      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tPulmonary', @rCurrentNumber = @lNextNumber      
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrPulmonary,9,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >      
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>      
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>      
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tbltmpAudiometry') IS NOT NULL      
  DROP TABLE #tbltmpAudiometry      
      
  create table #tbltmpAudiometry      
  (      
   tid int identity(1,1),a_ParticipantSourceId bigint,a_LocationId int,a_SetupId int,      
   a_LeftAcRemarkId int,a_RightAcRemarkId int,a_By_Rule int,a_AudioLeftACIds nvarchar(max),a_AudioRightACIds nvarchar(max),      
   a_AudioLeftBCIds nvarchar(max),a_AudioRightBCIds nvarchar(max),a_ExaminationId bigint,a_ParticipantAreaId bigint,      
   a_AudiometryId bigint,a_OrgId int,a_SetupGroupId int,a_LeftManualRemark nvarchar(2000),a_RightManualRemark nvarchar(2000),
   a_LeftAcResultId int, a_LeftBcResultId int, a_RightAcResultId int, a_RightBcResultId int
  )
         
  insert into #tbltmpAudiometry      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@LocationId','int') as LocationId,      
  T.c.value('@SetupId','int') as SetupId,      
  T.c.value('@LeftAcRemarkId','int') as LeftAcRemarkId,      
  T.c.value('@RightAcRemarkId','int') as RightAcRemarkId,      
  case when T.c.value('@By_Rule','nvarchar(10)') = 'y' or T.c.value('@By_Rule','nvarchar(10)') = 'yes' or T.c.value('@By_Rule','nvarchar(10)') = '1' then 1 else 0 end as By_Rule,      
  T.c.value('@AudioLeftACIds','nvarchar(max)') as e_AudioLeftACIds,      
  T.c.value('@AudioRightACIds','nvarchar(max)') as AudioRightACIds,      
  T.c.value('@AudioLeftBCIds','nvarchar(max)') as AudioLeftBCIds,      
  T.c.value('@AudioRightBCIds','nvarchar(max)') as AudioRightBCIds,      
  null,null,null,null,null,
  T.c.value('@LeftManualRemark','nvarchar(2000)') as LeftManualRemark,
  T.c.value('@RightManualRemark','nvarchar(2000)') as RightManualRemark,
  T.c.value('@LeftAcResultId','int') as LeftAcResultId,
  T.c.value('@LeftBcResultId','int') as LeftBcResultId,
  T.c.value('@RightAcResultId','int') as RightAcResultId,
  T.c.value('@RightBcResultId','int') as RightBcResultId
  from @loXMLAudiometry.nodes('/Examinations/Examination')T(c)      
        
  Delete From #tbltmpAudiometry Where Isnull(a_LeftAcRemarkId,'')='' and Isnull(a_RightAcRemarkId,'')='' and Isnull(a_By_Rule,'')='' and      
  Isnull(a_AudioLeftACIds,'')='' and Isnull(a_AudioRightACIds,'')='' and Isnull(a_AudioLeftBCIds,'')='' and Isnull(a_AudioRightBCIds,'')=''
  and Isnull(a_LeftManualRemark,'')='' and Isnull(a_RightManualRemark,'')='' and Isnull(a_LeftAcResultId,'0')='0' and Isnull(a_LeftBcResultId,'0')='0'
  and Isnull(a_RightAcResultId,'0')='0' and Isnull(a_RightBcResultId,'0')='0'

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

  Declare @lAudiometryResultRemarkManualConf nvarchar(10);

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

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

   select @i = @i + 1      
  end      
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrAudiometry,10,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >      
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>      
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>      
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
 select distinct e_type, case       
    when e_type=0 then 'Error In XML Generation'      
    when e_type=1 then 'Error In Importing Examination Data'      
    when e_type=2 then 'Error In Importing Vital Data'      
    when e_type=3 then 'Error In Importing Diagnosis Data'      
    when e_type=4 then 'Error In Importing Habit Data'      
    when e_type=5 then 'Error In Importing Disease Data'      
    when e_type=6 then 'Error In Importing History Data'      
    when e_type=7 then 'Error In Importing Test Data'      
    when e_type=8 then 'Error In Importing General Data'      
    when e_type=9 then 'Error In Importing Pulmonary Data'      
    when e_type=10 then 'Error In Importing Audiometry Data'      
    else 'Error In Importing Data'      
    end as e_Message      
  from tbl_ImportExaminationErrorLog where e_UserId =@rUserId and (DATEDIFF(minute,e_CreatedDate,getdate())<=5)      
      
IF OBJECT_ID('tempdb..#tbltmpExamination') IS NOT NULL DROP TABLE #tbltmpExamination;  
IF OBJECT_ID('tempdb..#tbltmpExaminationNull') IS NOT NULL DROP TABLE #tbltmpExaminationNull;  
IF OBJECT_ID('tempdb..#tbltmpVitals') IS NOT NULL DROP TABLE #tbltmpVitals;  
IF OBJECT_ID('tempdb..#tbltmpDiagnosis') IS NOT NULL DROP TABLE #tbltmpDiagnosis;  
IF OBJECT_ID('tempdb..#tbltmpHabitsNull') IS NOT NULL DROP TABLE #tbltmpHabitsNull;  
IF OBJECT_ID('tempdb..#tbltmpHabitss') IS NOT NULL DROP TABLE #tbltmpHabitss;  
IF OBJECT_ID('tempdb..#tbltmpDisease') IS NOT NULL DROP TABLE #tbltmpDisease;  
IF OBJECT_ID('tempdb..#tbltmpDiseaseNull') IS NOT NULL DROP TABLE #tbltmpDiseaseNull;  
IF OBJECT_ID('tempdb..#tbltmpDiseaseDetailsNull') IS NOT NULL DROP TABLE #tbltmpDiseaseDetailsNull;  
IF OBJECT_ID('tempdb..#tbltmpTests') IS NOT NULL DROP TABLE #tbltmpTests;  
IF OBJECT_ID('tempdb..#tblGeneral') IS NOT NULL DROP TABLE #tblGeneral;  
IF OBJECT_ID('tempdb..#tblGeneralN') IS NOT NULL DROP TABLE #tblGeneralN;  
IF OBJECT_ID('tempdb..#tblExaminationGeneral') IS NOT NULL DROP TABLE #tblExaminationGeneral;  
IF OBJECT_ID('tempdb..#tblGeneralTests') IS NOT NULL DROP TABLE #tblGeneralTests;  
IF OBJECT_ID('tempdb..#tblPulmonary') IS NOT NULL DROP TABLE #tblPulmonary;  
IF OBJECT_ID('tempdb..#tbltmpAudiometry') IS NOT NULL DROP TABLE #tbltmpAudiometry;  
IF OBJECT_ID('tempdb..#tbltmpExaminationN') IS NOT NULL DROP TABLE #tbltmpExaminationN;  
IF OBJECT_ID('tempdb..#tbltmpAudiometryN') IS NOT NULL DROP TABLE #tbltmpAudiometryN;  
IF OBJECT_ID('tempdb..#tbltmpHabitDetailsNull') IS NOT NULL DROP TABLE #tbltmpHabitDetailsNull;  
IF OBJECT_ID('tempdb..#tbltmpDiseaseN') IS NOT NULL DROP TABLE #tbltmpDiseaseN;  
IF OBJECT_ID('tempdb..#tbltmpHistorySelf') IS NOT NULL DROP TABLE #tbltmpHistorySelf;  
IF OBJECT_ID('tempdb..#tbltmpHistoryMother') IS NOT NULL DROP TABLE #tbltmpHistoryMother;  
IF OBJECT_ID('tempdb..#tbltmpHistoryFather') IS NOT NULL DROP TABLE #tbltmpHistoryFather;  
IF OBJECT_ID('tempdb..#tbltmpHistoryBrother') IS NOT NULL DROP TABLE #tbltmpHistoryBrother;  
IF OBJECT_ID('tempdb..#tbltmpHistorySister') IS NOT NULL DROP TABLE #tbltmpHistorySister;  
IF OBJECT_ID('tempdb..#tbltmpHistorySelfN') IS NOT NULL DROP TABLE #tbltmpHistorySelfN;  
IF OBJECT_ID('tempdb..#tbltmpHistoryMotherN') IS NOT NULL DROP TABLE #tbltmpHistoryMotherN;  
IF OBJECT_ID('tempdb..#tbltmpHistoryFatherN') IS NOT NULL DROP TABLE #tbltmpHistoryFatherN;  
IF OBJECT_ID('tempdb..#tbltmpHistoryBrotherN') IS NOT NULL DROP TABLE #tbltmpHistoryBrotherN;  
IF OBJECT_ID('tempdb..#tbltmpHistorySisterN') IS NOT NULL DROP TABLE #tbltmpHistorySisterN;  
  
--Drop Table #tbltmpExamination  
--Drop Table #tbltmpExaminationNull      
--Drop Table #tbltmpVitals      
--Drop Table #tbltmpDiagnosis      
--Drop Table #tbltmpHabitsNull      
--Drop Table #tbltmpHabitss      
--Drop Table #tbltmpDisease      
--Drop Table #tbltmpDiseaseNull      
--Drop Table #tbltmpDiseaseDetailsNull      
--Drop Table #tbltmpTests      
----Drop table #tbltmpTestsN      
----Drop table #tbltmpRatioN      
----Drop table #tbltmpRatio      
--Drop table #tblGeneral      
--Drop table #tblGeneralN      
--Drop table #tblExaminationGeneral      
--Drop table #tblGeneralTests      
----Drop table #tblGeneralParameters      
--Drop table #tblPulmonary      
--Drop table #tbltmpAudiometry      
--Drop table #tbltmpExaminationN      
--Drop table #tbltmpAudiometryN      
--Drop table #tbltmpHabitDetailsNull      
--Drop table #tbltmpDiseaseN      
--Drop table #tbltmpHistorySelf      
--Drop table #tbltmpHistoryMother      
--Drop table #tbltmpHistoryFather      
--Drop table #tbltmpHistoryBrother      
--Drop table #tbltmpHistorySister      
--Drop table #tbltmpHistorySelfN      
--Drop table #tbltmpHistoryMotherN      
--Drop table #tbltmpHistoryFatherN      
--Drop table #tbltmpHistoryBrotherN      
--Drop table #tbltmpHistorySisterN      
end  

GO


ALTER proc [sExamination].[pImportALLOPDExamination]
@rstrExamination nvarchar(max),
@rstrPrescription nvarchar(max),
@rCreatedUserId bigint,
@rOrgId int,
@rStoreLocationId int,
@rUserSourceId bigint = 0 ---[Developer:Nidhi, Mantis:26061, Date:13/07/2023]

as
begin
	declare @lNextNumber bigint,@lFromNextNumber bigint,@cntExam int,@incExam int,@lCount int,@i int	
	declare @lxmlExamination xml,@lxmlPrescription xml
	
	set @lxmlExamination = CAST(@rstrExamination AS xml)
	set @lxmlPrescription = CAST(@rstrPrescription AS xml)
	
	declare @tblExamination table
	(
		tid int identity(1,1),e_ParticipantSourceId bigint,e_ParticipantSourceTypeId int,
		e_ExaminationDate nvarchar(200),e_CauseId int,e_SetupId int,e_DeptId int,e_MainTypeId int,
		e_DiseaseAll nvarchar(max),e_Name nvarchar(300)
		,e_InTime nvarchar(20), e_OutTime nvarchar(20),e_ComplaintRemark nvarchar(1000),e_VitalRemark nvarchar(300),
		e_FurtherActionId int,e_SubLocationId int,e_ExaminationId bigint,e_ProcessTypeId int,e_CriteriaGroupId int,
		e_CompanyId int,e_TargetGroupId int,e_DesignationId int,e_GradeId int,e_ExamNumber nvarchar(500),e_Height int,e_BodyWeight decimal(10,2),
        e_Temperature decimal(5,2),e_SPO2 decimal(5,2),e_Pulse smallint,e_BloodPressureSystolic int,e_BloodPressureDiastolic smallint ,e_Pediatric bit,e_HighRisk bit
	)
	insert into @tblExamination
	select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,
	T.c.value('@ParticipantSourceTypeId','int') as ParticipantSourceTypeId,
	T.c.value('@ExaminationDate','nvarchar(200)') as ExaminationDate,
	T.c.value('@CauseId','int') as CauseId,
	T.c.value('@SetupId','int') as SetupId,
	T.c.value('@DeptId','int') as DeptId,
	T.c.value('@MainTypeId','int') as MainTypeId,
	T.c.value('@Disease','nvarchar(max)') as Disease,
	T.c.value('@Name','nvarchar(300)') as Name,
	T.c.value('@InTime','nvarchar(20)') as InTime,
	T.c.value('@OutTime','nvarchar(20)') as OutTime,
	T.c.value('@ComplaintRemark','nvarchar(1000)') as ComplaintRemark,
	T.c.value('@VitalRemark','nvarchar(300)') as VitalRemark,
	T.c.value('@FurtherActionId','int') as FurtherActionId,
    T.c.value('@SubLocationId','int') as SubLocationId,--[Mantis:0039663 by Shivam on 23/01/2025]
	0,null,null,null,null,null,null,null,  
	T.c.value('@Height','int') as Height,--[0042109] all below Added by Shiv Thapa on 24/07/2025
    T.c.value('@Weight','decimal(10,2)') as BodyWeight,
    T.c.value('@Temperature','decimal(5,2)') as Temperature,
    T.c.value('@SPO2','decimal(5,2)') as SPO2,
    T.c.value('@Pulse','smallint') as Pulse,
	T.c.value('@BPSys','int') as BloodPressureSystolic,
	T.c.value('@BPDia','smallint') as BloodPressureDiastolic,
    T.c.value('@Pediatric','bit') as Pediatric,
	T.c.value('@HighRisk','bit') as HighRisk
	from @lxmlExamination.nodes('/Examinations/Examination')T(c)
	
	update @tblExamination set e_ProcessTypeId = JD.ProcessTypeId,e_TargetGroupId = EM.TargetGroupId,
	e_CompanyId = JD.EmployeeCompanyId,e_DesignationId = JD.EmployeeDesignationId,e_GradeId = JD.GradeId	
	from @tblExamination inner join sHrm.tEmployeeMaster EM on e_ParticipantSourceId = EM.Id
	inner join sHrm.tEmployeeJobDetail JD on e_ParticipantSourceId = JD.EmployeeId
	
	select @incExam = count(*) from sExamination.tExamination where isnull(Examinationnumber,'') <> ''
	and DATEDIFF(day,CreatedDateTime,getdate())>=0 and SetupId = sCommon.fGetIntIdForOrg(8,@rOrgId)
	and StoreLocationId = @rStoreLocationId 
	
	update @tblExamination set e_examinationid = Id from sExamination.tExamination where ParticipantSourceId = e_ParticipantSourceId
	and ParticipantSourceTypeId = e_ParticipantSourceTypeId and  SetupId = e_SetupId and Convert(nvarchar(200),ExaminationDate,103) = Convert(nvarchar(200),e_ExaminationDate,103)
	and   ISNULL(e_Name,'') = ISNULL(OPDOtherName,'') and isnull(IsCancel,0) = 0 -- othername issue in importopd medicine by Nidhi Pandey

	--select * from @tblExamination
	--exec sCommon.pTableRowIdGet @rOrgId, 'sExamination.tExamination', 0, 1, 1,@outNextNumber = @lNextNumber output	
	--SET @lFromNextNumber = @lNextNumber - 1

 ---- othername issue in importopd medicine by Nidhi Pandey
	--declare @countExam int = (select Count(*) from @tblExamination)
	--Declare @tempExmId bigint = 0, @tempothername nvarchar(300) = ''
	--while(@countExam != 0)
	--BEGIN
	--set @tempExmId = 0 set @tempothername= ''
	--	if Exists(Select 1 from @tblExamination where e_examinationid != 0 and e_ParticipantSourceTypeId = 1009 and tid = @countExam)
	--	BEGIN
	--		select @tempExmId =e_examinationid ,@tempothername = e_Name  from @tblExamination where e_examinationid != 0 and e_ParticipantSourceTypeId = 1009 and tid = @countExam
	--		if not Exists(Select 1 from sExamination.tOPD where ExaminationId = @tempExmId and OtherName = @tempothername)
	--		BEGIN
	--			update @tblExamination set e_examinationid = 0 where tid = @countExam
	--		END
	--	END
	--	set @countExam = @countExam - 1
	--END
	
	---- othername issue in importopd medicine by Nidhi Pandey
	
	MERGE sExamination.tExamination AS Target USING 
	(
		SELECT Id,e_ParticipantSourceId,e_SetupId,e_ExaminationDate,e_ProcessTypeId,e_CriteriaGroupId,
		e_CompanyId,e_TargetGroupId,e_DesignationId,e_GradeId,e_DeptId,e_ParticipantSourceTypeId,		
		e_examinationid,e_CauseId,tid,e_Name,e_SubLocationId
		FROM @tblExamination TT LEFT JOIN sExamination.tExamination T ON TT.e_examinationid = T.Id
	) AS Source ON Target.Id = Source.e_examinationid	
	--WHEN MATCHED THEN
	--	UPDATE SET IsCancel = 0   --- Nidhi Pandey; Import again after IsCancel issue ; 24/04/2024
	WHEN NOT MATCHED THEN
		INSERT
		(
			OrgId,ParticipantSourceTypeId,ParticipantSourceId,OrganizationDepartmentId,SetupId,
			RoundNumber,StatusId,ExaminationDate,CreatedUserId,CreatedDateTime,
			UpdatedUserId,UpdatedDateTime,ParentExaminationId,StoreLocationId,CauseId,ProcessTypeId,
			EmployeeCompanyId,TargetGroupId,EmployeeDesignationId,CriteiraGroupId,GradeId,DoctorEmployeeId,  --Nidhi Pandey; as suggested by Manthan Sir, dt - 3/07/2023
			ExaminationNumber,OPDOtherName
		)
		VALUES
		(
			@rOrgId,e_ParticipantSourceTypeId,e_ParticipantSourceId,e_DeptId,e_SetupId,0,1,
			case when len(e_ExaminationDate) = 10 then convert(Datetime, e_ExaminationDate, 104) else CONVERT(nvarchar(11), e_ExaminationDate) end,
			@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),0,e_SubLocationId,e_CauseId,
			e_ProcessTypeId,e_CompanyId,e_TargetGroupId,e_DesignationId,e_CriteriaGroupId,e_GradeId,@rUserSourceId,
			'OPD-' + sCommon.fGetFormattedDate()  + RIGHT(100000 + (@incExam + tid) ,5),e_Name
		);
	

	
	select @lFromNextNumber = SCOPE_IDENTITY(),@lNextNumber=SCOPE_IDENTITY()

	update @tblExamination set e_examinationid = Id from sExamination.tExamination where ParticipantSourceId = e_ParticipantSourceId
	and ParticipantSourceTypeId = e_ParticipantSourceTypeId and  SetupId = e_SetupId and Convert(nvarchar(200),ExaminationDate,103) = Convert(nvarchar(200),e_ExaminationDate,103)	
	and OPDOtherName = e_Name and isnull(IsCancel,0) = 0 -- othername issue in importopd medicine by Nidhi Pandey
	
	
	
	--select * from @tblExamination



	-- update @tblExamination set e_examinationid = final.Id 
	-- from (
	-- select top 1 *
	-- From(
	-- select  Id,ParticipantSourceId,ParticipantSourceTypeId,SetupId 
	--  From sExamination.tExamination as b
	--  inner join @tblExamination as t 
	--  on b.ParticipantSourceId=t.e_ParticipantSourceId and b.ParticipantSourceTypeId = t.e_ParticipantSourceTypeId and  b.SetupId = t.e_SetupId 
	--  order by b.id desc
	--  ) as temp
	--) as final
	--where final.ParticipantSourceId = e_ParticipantSourceId
	--and final.ParticipantSourceTypeId = e_ParticipantSourceTypeId and  final.SetupId = e_SetupId

	--select @lCount = COUNT(1) FROM @tblExamination 
	--SET @lNextNumber  = @lCount + @lFromNextNumber	
	--exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sExamination.tExamination', @rCurrentNumber = @lNextNumber
	
	--exec sCommon.pTableRowIdGet @rOrgId, 'sExamination.tExaminDisease', 0, 1, 1,@outNextNumber = @lNextNumber output	
	--SET @lFromNextNumber = @lNextNumber - 1
	--select * from @tblExamination
	--return
	MERGE sExamination.tExaminDisease AS Target USING 
	(
		SELECT Id,e_examinationid,tid
		FROM @tblExamination TT LEFT JOIN sExamination.tExaminDisease T ON TT.e_examinationid = T.SourceId
	) AS Source ON Target.SourceId = Source.e_examinationid	
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,SourceTypeId,SourceId,Remark,OrgId,IsObsolete
		)
		VALUES
		(
			e_examinationid,1002,e_examinationid,'',@rOrgId,0
		);
	
	--select @lCount = COUNT(1) FROM @tblExamination 
	--SET @lNextNumber  = @lCount + @lFromNextNumber	
	--exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sExamination.tExaminDisease', @rCurrentNumber = @lNextNumber
	
	declare @tblDisease table
	(
		tid int identity(1,1),d_DisaeseId int,d_ParticipantSoruceId bigint,d_ParticipantSourceTypeId int,d_ExaminationId bigint,
		d_ExaminDiseaseId bigint,d_Name nvarchar(200)
	)
	insert into @tblDisease
	select null,e_ParticipantSourceId,e_ParticipantSourceTypeId,e_examinationid,null,Item
	from @tblExamination cross apply dbo.fSplitStr(replace(e_DiseaseAll,'+',','),',') where Item <> ''
	
	update @tblDisease set d_DisaeseId = Id from sExamination.tDiseaseMaster where OrgId = @rOrgId and d_Name = Title
	update @tblDisease set d_ExaminDiseaseId = Id from sExamination.tExaminDisease where SourceId = d_ExaminationId
	
	declare @tblDiseaseN table
	(
		tid int identity(1,1),d_DisaeseId int,d_ParticipantSoruceId bigint,d_ParticipantSourceTypeId int,d_ExaminationId bigint,
		d_ExaminDiseaseId bigint,d_Name nvarchar(200)
	)
	insert into @tblDiseaseN
	select distinct d_DisaeseId,d_ParticipantSoruceId,d_ParticipantSourceTypeId,d_ExaminationId,d_ExaminDiseaseId,d_Name
	from @tblDisease
	
	--exec sCommon.pTableRowIdGet @rOrgId, 'sExamination.tExaminDiseaseDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
	--SET @lFromNextNumber = @lNextNumber - 1
	
	MERGE sExamination.tExaminDiseaseDetail AS Target USING 
	(
		SELECT Id,d_ExaminDiseaseId,d_ExaminationId,d_DisaeseId,tid
		FROM @tblDiseaseN TT LEFT JOIN sExamination.tExaminDiseaseDetail T ON TT.d_DisaeseId = T.DiseaseId
		and TT.d_ExaminDiseaseId = T.ExaminDiseaseId
	) AS Source ON Target.ExaminDiseaseId = Source.d_ExaminDiseaseId and Target.DiseaseId = Source.d_DisaeseId	
	WHEN NOT MATCHED THEN
		INSERT
		(
			ExaminDiseaseId,DiseaseId,Remark,OrgId,IsObsolete
		)
		VALUES
		(
			d_ExaminDiseaseId,d_DisaeseId,'',@rOrgId,0
		);
	
	--select @lCount = COUNT(1) FROM @tblDiseaseN 
	--SET @lNextNumber  = @lCount + @lFromNextNumber	
	--exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sExamination.tExaminDiseaseDetail', @rCurrentNumber = @lNextNumber
	
	declare @tblPrescription table
	(
		tid int identity(1,1),p_ParticipantSourceId bigint,p_ParticipantSourceTypeId int,p_StockId int,
		p_Quantity nvarchar(100),p_IsNotStore bit,p_IsBatchWise bit,p_IsDispense bit,p_FrequencyId int,
		p_Dose nvarchar(100),p_DrugQty nvarchar(100),p_DrugFrequecyText nvarchar(300),p_DrugInstruction nvarchar(300),
		p_DrugScheduleId int,p_SourceTypeId int,p_QueueTypeId int,p_StoreLocationId int,p_IsAutoDispense bit,
		p_LocationId int,p_IsDirect bit,p_Duration nvarchar(50),p_IsAllowDirectIssue bit,
		p_OtherName nvarchar(300),p_ExaminationDate nvarchar(200) -- Nidhi Pandey; Mantis - 27787; DT - 04/10/2023
		,p_ExaminationId bigint,p_PrescriptionId bigint,p_StockBatchId int,p_PrescriptionDetailId bigint,p_DispenseId bigint,
		pp_RemainQty decimal(12,2),pp_AverageCost decimal(12,2),pp_InwardValue decimal(12,2),pp_DispenseBatchId bigint
	)
	insert into @tblPrescription
	select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,
	T.c.value('@ParticipantSourceTypeId','int') as ParticipantSourceTypeId,
	T.c.value('@StockId','int') as StockId,
	T.c.value('@StockQty','nvarchar(100)') as StockQty,
	T.c.value('@IsNotInStore','bit') as IsNotInStore,
	T.c.value('@IsBatchWise','bit') as IsBatchWise,
	T.c.value('@IsDispense','bit') as IsDispense,
	T.c.value('@DrugFrequencyId','int') as DrugFrequencyId,
	T.c.value('@Dosage','nvarchar(100)') as Dosage,
	T.c.value('@DrugQuantity','nvarchar(100)') as DrugQuantity,
	T.c.value('@DrugFrequencyText','nvarchar(300)') as DrugFrequencyText,
	T.c.value('@DrugInstruction','nvarchar(300)') as DrugInstruction,
	T.c.value('@DrugScheduleId','int') as DrugScheduleId,
	T.c.value('@SourceTypeId','int') as SourceTypeId,
	T.c.value('@QueueTypeId','int') as QueueTypeId,
	T.c.value('@StoreLocationId','int') as StoreLocationId,
	T.c.value('@IsAutoDispense','bit') as IsAutoDispense,
	T.c.value('@LocationId','int') as LocationId,
	T.c.value('@IsDirect','bit') as IsDirect,
	T.c.value('@Duration','nvarchar(50)') as Duration,
	T.c.value('@IsAllowDirectIssue','bit') as IsAllowDirectIssue,
	T.c.value('@OtherName','nvarchar(300)') as OtherName,
	T.c.value('@ExaminationDate','nvarchar(200)') as ExaminationDate, -- Nidhi Pandey; Mantis - 27787; DT - 04/10/2023
	null,null,null,null,null,null,null,null,null
	from @lxmlPrescription.nodes('/Examinations/Prescription')T(c)
	
	update w set p_ExaminationId = e_examinationid from @tblPrescription w
	inner join @tblExamination on e_ParticipantSourceId = p_ParticipantSourceId and e_ParticipantSourceTypeId = p_ParticipantSourceTypeId and e_Name = p_OtherName
	and e_ExaminationDate = p_ExaminationDate  -- Nidhi Pandey; Mantis - 27787; DT - 04/10/2023
	
	update w set w.p_StockBatchId = p.Id from @tblPrescription w inner join sProcurement.tStockBatch p
	on w.p_StockId = p.StockItemId and p.StoreLocationId = w.p_StoreLocationId and p.OrgId = @rOrgId
	and isnull(p.Number,'') = ''
	
	--select * from @tblPrescription

	declare @tblPrescriptionN table
	(
		tid int identity(1,1),p_ParticipantSourceId bigint,p_ParticipantSourceTypeId int,p_ExaminationId bigint
	)
	insert into @tblPrescriptionN
	select e_ParticipantSourceId,e_ParticipantSourceTypeId,e_examinationid from @tblExamination
	where e_ParticipantSourceId in (select p_ParticipantSourceId from @tblPrescription)
	and e_ParticipantSourceTypeId in (select p_ParticipantSourceTypeId from @tblPrescription)
	
	declare @lAutoDispense bit,@lDirect bit
	
	select top 1 @lAutoDispense = p_IsAutoDispense,@lDirect = p_IsDirect from @tblPrescription
	
	exec sCommon.pTableRowIdGet @rOrgId, 'sExamination.tPrescription', 0, 1, 1,@outNextNumber = @lNextNumber output	
	SET @lFromNextNumber = @lNextNumber - 1
	
	MERGE sExamination.tPrescription AS Target USING 
	(
		SELECT Id,p_ExaminationId,tid
		FROM @tblPrescriptionN TT LEFT JOIN sExamination.tPrescription T ON TT.p_ExaminationId = T.SourceId
	) AS Source ON Target.SourceId = Source.p_ExaminationId	
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,SourceTypeId,SourceId,Number,IsObsolete,CreatedUserId,CreatedDateTime,DoctorEmployeeId, --Nidhi Pandey; as suggested by Manthan Sir, dt - 3/07/2023
			IsDispensed,UpdatedDateTime,UpdatedUserId,Remark,OrgId,IsDirect
		)
		VALUES
		(
			@lFromNextNumber + tid,1002,p_ExaminationId,@lFromNextNumber + tid,
			0,@rCreatedUserId,sCommon.fGetDate(),@rUserSourceId,0,sCommon.fGetDate(),@rCreatedUserId,'',@rOrgId,@lDirect
		);
	
	update @tblPrescription set p_PrescriptionId = Id from sExamination.tPrescription where p_ExaminationId = SourceId
	
	select @lCount = COUNT(1) FROM @tblPrescriptionN
	SET @lNextNumber  = @lCount + @lFromNextNumber	
	exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sExamination.tPrescription', @rCurrentNumber = @lNextNumber
	
	exec sCommon.pTableRowIdGet @rOrgId, 'sExamination.tPrescriptionDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
	SET @lFromNextNumber = @lNextNumber - 1
	
	MERGE sExamination.tPrescriptionDetail AS Target USING 
	(
		SELECT Id,p_PrescriptionId,p_StockId,p_FrequencyId,p_DrugQty,p_Dose,p_DrugFrequecyText,
		p_DrugInstruction,p_DrugScheduleId,p_ExaminationId,p_Duration,p_Quantity,p_IsAllowDirectIssue,
		p_IsNotStore,p_StoreLocationId,p_SourceTypeId,p_QueueTypeId,tid
		FROM @tblPrescription TT LEFT JOIN sExamination.tPrescriptionDetail T ON TT.p_PrescriptionId = T.PrescriptionId
		and TT.p_StockId = T.StockItemId
	) AS Source ON Target.PrescriptionId = Source.p_PrescriptionId and Target.StockItemId = Source.p_StockId	
	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
		)
		VALUES
		(
			@lFromNextNumber + tid,p_PrescriptionId,p_StockId,p_DrugInstruction,1,'',
			p_Quantity,p_IsAllowDirectIssue,0,@rCreatedUserId,@rCreatedUserId,
			0,sCommon.fGetDate(),@rOrgId,0,p_IsNotStore,p_Dose,
			p_Dose,p_FrequencyId,p_DrugScheduleId
		);
	
	select @lCount = COUNT(1) FROM @tblPrescription 
	SET @lNextNumber  = @lCount + @lFromNextNumber	
	exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sExamination.tPrescriptionDetail', @rCurrentNumber = @lNextNumber
	
	update w set w.p_PrescriptionDetailId = p.Id from @tblPrescription w inner join sExamination.tPrescriptionDetail p
	on w.p_PrescriptionId = p.PrescriptionId and w.p_StockId = p.StockItemId
	
	if @lAutoDispense <> '0'
	begin
		--UPDATE PD SET PD.DispensedQuantity = p_Quantity
		--FROM sExamination.tPrescriptionDetail PD inner join @tblPrescription w ON PD.Id = w.p_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 @tblPrescription w ON PD.Id = w.p_PrescriptionDetailId
		where p_QueueTypeId = 2
		
		UPDATE e SET e.StatusId = 4 from sExamination.tExamination e inner join
		@tblPrescriptionN w on w.p_ExaminationId = e.Id
		
		update w set w.p_DispenseId = p.Id from @tblPrescription w inner join sPharmacy.tDispense p
		on w.p_PrescriptionDetailId = p.PrescriptionDetailId
		
		exec sCommon.pTableRowIdGet @rOrgId, 'sPharmacy.tDispense', 0, 1, 1,@outNextNumber = @lNextNumber output	
		SET @lFromNextNumber = @lNextNumber - 1
		
		MERGE sPharmacy.tDispense AS Target USING 
		(
			SELECT Id,p_PrescriptionDetailId,tid
			FROM @tblPrescription TT LEFT JOIN sPharmacy.tDispense T ON TT.p_PrescriptionDetailId = T.Id
		) AS Source ON Target.Id = Source.p_PrescriptionDetailId
		WHEN MATCHED THEN
			UPDATE SET PrescriptionDetailId = p_PrescriptionDetailId
		WHEN NOT MATCHED THEN
			INSERT
			(
				Id,PrescriptionDetailId,CreatedUserId,CreatedDateTime,OrgId
			)
			VALUES
			(
				@lFromNextNumber + tid,p_PrescriptionDetailId,@rCreatedUserId,sCommon.fGetDate(),@rOrgId
			);
			
		select @lCount = COUNT(1) FROM @tblPrescription
		SET @lNextNumber  = @lCount + @lFromNextNumber	
		exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sPharmacy.tDispense', @rCurrentNumber = @lNextNumber
		
		update w set w.p_DispenseId = p.Id from @tblPrescription w inner join sPharmacy.tDispense p
		on w.p_PrescriptionDetailId = p.PrescriptionDetailId
		
		update w set w.pp_RemainQty = (p.PrescribedQuantity - p.DispensedQuantity)
		from @tblPrescription w inner join sExamination.tPrescriptionDetail p on w.p_PrescriptionDetailId = p.Id
		
		update w set w.pp_AverageCost = WeightedAverageCost from @tblPrescription w
		inner join sIp.tStockItemPlanning p on w.p_StockId = p.StockItemId and w.p_StoreLocationId = p.StoreLocationId
		
		update @tblPrescription set pp_InwardValue = (pp_AverageCost * pp_RemainQty)
		
		update w set w.pp_DispenseBatchId = p.Id from @tblPrescription w inner join sPharmacy.tDispenseBatch p
		on w.p_DispenseId = p.DispenseId
		
		exec sCommon.pTableRowIdGet @rOrgId, 'sPharmacy.tDispenseBatch', 0, 1, 1,@outNextNumber = @lNextNumber output	
		SET @lFromNextNumber = @lNextNumber - 1
		
		MERGE sPharmacy.tDispenseBatch AS Target USING 
		(
			SELECT Id,p_StockBatchId,p_DispenseId,pp_RemainQty,pp_AverageCost,p_IsNotStore,tid
			FROM @tblPrescription TT LEFT JOIN sPharmacy.tDispenseBatch T ON TT.p_DispenseId = T.Id			
		) AS Source ON Target.Id = Source.p_DispenseId		
		WHEN NOT MATCHED THEN
			INSERT
			(
				Id,DispenseId,StockBatchId,Quantity,UnitCost,OrgId,ReturnQuantity
			)
			VALUES
			(
				@lFromNextNumber + tid,p_DispenseId,p_StockBatchId,
				pp_RemainQty,pp_AverageCost,@rOrgId,0
			);
			
		select @lCount = COUNT(1),@i = 1 FROM @tblPrescription
		SET @lNextNumber  = @lCount + @lFromNextNumber	
		exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sPharmacy.tDispenseBatch', @rCurrentNumber = @lNextNumber
		
		update w set w.pp_DispenseBatchId = p.Id from @tblPrescription w inner join sPharmacy.tDispenseBatch p
		on w.p_DispenseId = p.DispenseId
		
		while @i <= @lCount
		begin
			declare @rSourceTypeId int,@rSourceId bigint,@rItemSourceTypeId int,@rItemSourceId int,
			@rQuantity decimal(12,2),@rValue decimal(12,2),@rLocationId int,@rItemBatchId int,
			@rIsNotInStore bit			
			
			select @rSourceTypeId = 48,@rSourceId = pp_DispenseBatchId,@rItemSourceId = p_StockId,
			@rItemSourceTypeId = 34,@rQuantity = pp_RemainQty,@rValue = pp_InwardValue,@rStoreLocationId = p_StoreLocationId,
			@rLocationId = p_LocationId,@rItemBatchId = p_StockBatchId,@rIsNotInStore = p_IsNotStore
			from @tblPrescription where tid = @i
						
			if @rIsNotInStore = 0
			begin			
				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 inner join @tblPrescription w on P.Id = w.p_PrescriptionId
			end
			select @i = @i + 1
		end
	end
	
	declare @tblExaminationOPD table
	(
		tid int identity(1,1),e_ParticipantSourceId bigint,e_ParticipantSourceTypeId int,
		e_Name nvarchar(300),e_ExaminationId bigint,e_InTime nvarchar(20),e_OutTime nvarchar(20),e_FurtherActionId int,e_Pediatric bit
	)
	insert into @tblExaminationOPD
	select e_ParticipantSourceId,e_ParticipantSourceTypeId,e_Name,e_ExaminationId,e_InTime,e_OutTime,e_FurtherActionId,e_Pediatric from @tblExamination where e_ParticipantSourceTypeId = 1009
	--select * from @tblExaminationOPD
	MERGE sExamination.tOPD AS Target USING 
	(
		SELECT e_Name,e_ExaminationId,tid,e_InTime,e_OutTime,e_FurtherActionId,e_Pediatric
		FROM @tblExaminationOPD TT LEFT JOIN sExamination.tOPD T ON TT.e_examinationid = T.ExaminationId
	) AS Source ON Target.ExaminationId = Source.e_examinationid
	when Matched Then
	Update set 	OPDTime = e_InTime,OPDOutTime = e_OutTime,FurtherActionId = e_FurtherActionId , IsPediatric=e_Pediatric  
	WHEN NOT MATCHED THEN
		INSERT
		(
			ExaminationId,OtherName,OPDTime,OPDOutTime,FurtherActionId,IsPediatric
		)
		VALUES
		(
			e_ExaminationId,e_Name,e_InTime,e_OutTime,e_FurtherActionId,e_Pediatric
		);
	
	insert into @tblExaminationOPD
	select e_ParticipantSourceId,e_ParticipantSourceTypeId,e_Name,e_ExaminationId,e_InTime,e_OutTime,e_FurtherActionId,e_Pediatric from @tblExamination where e_ParticipantSourceTypeId != 1009
--	select * from @tblExaminationOPD
	MERGE sExamination.tOPD AS Target USING 
	(
		SELECT e_Name,e_ExaminationId,tid,e_InTime,e_OutTime,e_FurtherActionId,e_Pediatric
		FROM @tblExaminationOPD TT LEFT JOIN sExamination.tOPD T ON TT.e_examinationid = T.ExaminationId where TT.e_ParticipantSourceTypeId != 1009
	) AS Source ON Target.ExaminationId = Source.e_examinationid
	when Matched Then
	Update set 	OPDTime = e_InTime,OPDOutTime = e_OutTime,FurtherActionId = e_FurtherActionId, IsPediatric=e_Pediatric,FitnessStatus='-1'--0042109
	WHEN NOT MATCHED THEN
		INSERT
		(
			ExaminationId,OtherName,OPDTime,OPDOutTime,FurtherActionId,IsPediatric,FitnessStatus
		)
		VALUES
		(
			e_ExaminationId,'',e_InTime,e_OutTime,e_FurtherActionId,e_Pediatric,'-1'
		);
	---MGMotor req
	

	

	MERGE sExamination.tVital AS Target USING 
	(
		SELECT Id,e_examinationid,tid,e_VitalRemark,e_Height,e_BodyWeight,e_Pulse,e_Temperature,e_SPO2,e_BloodPressureSystolic,e_BloodPressureDiastolic
		FROM @tblExamination TT LEFT JOIN sExamination.tVital T ON TT.e_examinationid = T.SourceId
	) AS Source ON Target.SourceId = Source.e_examinationid
	When MATCHED THEN
		UPDATE SET Remark = e_VitalRemark,
				Height = e_Height,
                BodyWeight = e_BodyWeight,
                Pulse = e_Pulse,
                Temperature = e_Temperature,
                SPo2 = e_SPO2,
				BloodPressureSystolic =e_BloodPressureSystolic,  
				BloodPressureDiastolic =e_BloodPressureDiastolic,
                BMI = CASE 
                 WHEN Source.e_Height IS NOT NULL AND Source.e_Height > 0
                      AND Source.e_BodyWeight IS NOT NULL AND Source.e_BodyWeight > 0
                 THEN CAST(
                         CASE 
                             WHEN (CAST(Source.e_BodyWeight AS DECIMAL(18,6)) /
                                   POWER(CAST(Source.e_Height AS DECIMAL(18,6)) / 100.0, 2)
                                  ) > 999.99
                             THEN 999.99
                             ELSE ROUND(
                                    CAST(Source.e_BodyWeight AS DECIMAL(18,6)) /
                                    POWER(CAST(Source.e_Height AS DECIMAL(18,6)) / 100.0, 2),
                                    2
                                  )
                         END AS DECIMAL(5,2)
                      )
                 ELSE BMI
              END

	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,SourceTypeId,SourceId,Remark,Height,BodyWeight,Pulse,Temperature,SPo2,BloodPressureSystolic,BloodPressureDiastolic,OrgId,IsObsolete,CreatedUserId,CreatedDateTime,BMI
		)
		VALUES
		(
			e_examinationid,1002,e_examinationid,e_VitalRemark,e_Height,e_BodyWeight,e_Pulse,e_Temperature,e_SPO2,e_BloodPressureSystolic,e_BloodPressureDiastolic,@rOrgId,0,@rCreatedUserId,sCommon.fGetDate()
			,  CASE 
            WHEN e_Height IS NOT NULL AND e_Height > 0
                 AND e_BodyWeight IS NOT NULL AND e_BodyWeight > 0
            THEN CAST(
                    CASE 
                        WHEN (CAST(e_BodyWeight AS DECIMAL(18,6)) /
                              POWER(CAST(e_Height AS DECIMAL(18,6)) / 100.0, 2)
                             ) > 999.99
                        THEN 999.99
                        ELSE ROUND(
                               CAST(e_BodyWeight AS DECIMAL(18,6)) /
                               POWER(CAST(e_Height AS DECIMAL(18,6)) / 100.0, 2),
                               2
                             )
                    END AS DECIMAL(5,2)
                 )
            ELSE 0
        END	);

	--exec sCommon.pTableRowIdGet @rOrgId, 'sExamination.tComplaint', 0, 1, 1,@outNextNumber = @lComplaintNextNumber output	
	
	MERGE sExamination.tComplaint AS Target USING 
	(
		SELECT Id,e_examinationid,tid,e_ComplaintRemark
		FROM @tblExamination TT LEFT JOIN sExamination.tComplaint T ON TT.e_examinationid = T.SourceId
	) AS Source ON Target.SourceId = Source.e_examinationid
	When MATCHED THEN
		UPDATE SET Remark = e_ComplaintRemark	
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,SourceTypeId,SourceId,Remark,OrgId,IsObsolete
		)
		VALUES
		(
			e_examinationid,1002,e_examinationid,e_ComplaintRemark,@rOrgId,0
		);
	
		 

	--MGmotor req end


	select '' as res
	select * from @tblExamination
	select * from @tblExaminationOPD	
end

GO


ALTER proc [sExamination].[pMobImproveDeteriorateCountGet]
@rSectorId nvarchar(max)= '',    
@rVerticalId nvarchar(max)= '',  
@rStateId nvarchar(max) = '',   
@rSetup1Id int,  
@rSetup2Id int,  
@rFlag int = 0,   -- Flag 0 for up down count, 1 for up employee list, 2 for down employee list
@rIsCurrent int = 1
as
begin  
 declare @tbl1Setup table
 (
  tid int identity(1,1),t_ParticipantSourceId bigint,t_HealthIndex decimal(12,2),t_ParticipantName varchar(300)  
 )
 insert into @tbl1Setup  
 select E.ParticipantSourceId,D.HealthIndex,EM.FirstName + ' ' + EM.LastName  
 from sExamination.tExamination E
 inner join shrm.temployeejobdetail ejd on ejd.employeeid=E.participantSourceid    
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=(case when @rIsCurrent=0 then E.EmployeeCompanyId else EJD.EmployeeCompanyId end)
 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 [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id=EJD.EmployeeTypeId    
 INNER join sCommon.tOrganizationDepartmentMaster ODM on ODM.Id=(case when @rIsCurrent=0 then E.OrganizationDepartmentId else EJD.OrganizationDepartmentId end)   
 INNER join sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id    
 inner join sCommon.tFunctionMaster FM on FM.id=FunctionId    
 INNER join sCommon.tLocationMaster LM on Ejd.EmployeeLocationId=LM.Id  
 inner join sCommon.tStateMaster tSM on tSM.Id=LM.StateId   
 inner join sExamination.tDiagnosis D on E.Id = D.SourceId  
 inner join sHrm.tEmployeeMaster EM on EM.Id = E.ParticipantSourceId 
  
 where E.SetupId = @rSetup1Id and E.ParticipantSourceTypeId = 95
 AND (ISNULL(SCT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rSectorId,''),','))OR ISNULL(@rSectorId,'')='')    
 AND (ISNULL(VTM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')       
 AND (ISNULL(tSM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rStateId,''),','))OR ISNULL(@rStateId,'')='')    
 and D.HealthIndex > 0  
   
 declare @tbl2Setup table  
 (  
  tid int identity(1,1),t_ParticipantSourceId bigint,t_HealthIndex decimal(12,2)  
 )  
 insert into @tbl2Setup  
 select E.ParticipantSourceId,D.HealthIndex 
 from sExamination.tExamination E  
 inner join shrm.temployeejobdetail ejd on ejd.employeeid=E.participantSourceid    
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=(case when @rIsCurrent=0 then E.EmployeeCompanyId else EJD.EmployeeCompanyId end)
 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 [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id=EJD.EmployeeTypeId    
 INNER join sCommon.tOrganizationDepartmentMaster ODM on ODM.Id=(case when @rIsCurrent=0 then E.OrganizationDepartmentId else EJD.OrganizationDepartmentId end)
 INNER join sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id    
 inner join sCommon.tFunctionMaster FM on FM.id=FunctionId    
 INNER join sCommon.tLocationMaster LM on Ejd.EmployeeLocationId=LM.Id  
 inner join sCommon.tStateMaster tSM on tSM.Id=LM.StateId   
 inner join sExamination.tDiagnosis D on E.Id = D.SourceId  
 inner join sHrm.tEmployeeMaster EM on EM.Id = E.ParticipantSourceId  
 where E.SetupId = @rSetup2Id and E.ParticipantSourceTypeId = 95    
 and D.HealthIndex > 0  
   
 declare @lImporoved int,@lDeteriorate int  
   
 select @lImporoved = count(1) from @tbl2Setup t2,@tbl1Setup t1 where t2.t_ParticipantSourceId = t1.t_ParticipantSourceId  
 and t2.t_HealthIndex > t1.t_HealthIndex  
   
 select @lDeteriorate = count(1) from @tbl2Setup t2,@tbl1Setup t1 where t2.t_ParticipantSourceId = t1.t_ParticipantSourceId  
 and t2.t_HealthIndex < t1.t_HealthIndex  
   
 if @rFlag = 0  
 begin  
  select @lImporoved as UP,@lDeteriorate as Down  
 end  
   
 if @rFlag = 1  
 begin   
  select t1.t_ParticipantSourceId as EmployeeId,t1.t_ParticipantName as EmployeeName,t1.t_HealthIndex as Setup1,t2.t_HealthIndex as Setup2  
  from @tbl2Setup t2,@tbl1Setup t1 where t2.t_ParticipantSourceId = t1.t_ParticipantSourceId  
  and t2.t_HealthIndex > t1.t_HealthIndex 
  ORDER BY t1.t_ParticipantName ASC
 end  
 else if @rFlag = 2  
 begin  
  select t1.t_ParticipantSourceId as EmployeeId,t1.t_ParticipantName as EmployeeName,t1.t_HealthIndex as Setup1,t2.t_HealthIndex as Setup2  
  from @tbl2Setup t2,@tbl1Setup t1 where t2.t_ParticipantSourceId = t1.t_ParticipantSourceId  
  and t2.t_HealthIndex < t1.t_HealthIndex 
  ORDER BY t1.t_ParticipantName ASC
 end
end


GO


CREATE OR ALTER PROCEDURE[sExamination].[pOPDDashboard]
(
	@rStoreLocationId int,
	@rParticipantTypeId int,
	@rCaseCauseId int,
	@rVisitTypeId int,
	@rShiftId int,
	@rLocationId int,
	@rFunctionId int,
	@rDepartmentGroupId int,
	@rDepartmentId int,
	@rGradeId int,
	@rDesignationId int,
	@rJobTitleId int=0,
	@rEmployeeTypeId int=0,
	@rCompanyId int=0,
	@rContractorId int,
	@rGenderId smallint,
	@rStatusId smallint,
	@rAgeFrom int,
	@rAgeTo int=100,
	@rFromDate datetime = null,
	@rToDate datetime = null,
	@rOrgId int,
	@rEmployeeCode nvarchar(50)='',
	@rUserId bigint
)
AS
BEGIN
SET NOCOUNT ON;

DECLARE @CurrentDate DATETIME = GETDATE();
DECLARE @ShiftTitle nvarchar(100) = '';
IF (@rShiftId > 0)
BEGIN
     set @ShiftTitle = (select Title from sCommon.tCompanyShiftMaster where Id = @rShiftId)
END

SELECT
	ED.Id AS ExaminationId,
	ED.StoreLocationId AS LocationId,
	ED.OrganizationDepartmentId,
	ISNULL(OD.Title,'N/A') AS DepartmentName,
	CM.Id AS CauseId,
	ISNULL(CM.Title,'N/A') AS CauseName,
	UL.UserId,
	U.DisplayTitle AS LoginTitle,
	ED.ParticipantSourceTypeId,
	CASE 
		WHEN ED.ParticipantSourceTypeId = 95 THEN PD.GenderId
		WHEN ED.ParticipantSourceTypeId = 1001 THEN EFD.GenderId
		ELSE BM.GenderId
	END AS GenderId,
	CASE 
		WHEN ED.ParticipantSourceTypeId = 95 THEN ISNULL(GM.Title,'Not Known')
		WHEN ED.ParticipantSourceTypeId = 1001 THEN 
			(SELECT ISNULL(Title,'Not Known') FROM sCommon.tGenderMaster WHERE Id = EFD.GenderId)
		ELSE (CASE WHEN OP.GenderId > 0 THEN (select ISNULL(Title,'Not Known') from sCommon.tGenderMaster where Id = OP.GenderId) ELSE ISNULL(GM2.Title,'Not Known') END)
	END AS Gender,
	CASE ED.ParticipantSourceTypeId
		WHEN 95 THEN ISNULL(ETM.Title,'NA')
		WHEN 1001 THEN 'Dependent'
		WHEN 1009 THEN ISNULL(BTM.Title,'NA')
	END AS ParticipantType,
	CASE ED.ParticipantSourceTypeId
		WHEN 95 THEN 'Employee'
		WHEN 1001 THEN 'Dependent'
		WHEN 1009 THEN 'Other'
	END AS EMPType,
	NM.Title AS Nationality,
	ISNULL(VTM.Title, 'Direct Consultation') as VisitType,
	[dbo].[fGetShift](OP.OPDTime,@rOrgId) as Shifts
INTO #BaseData
FROM sExamination.tExamination ED
LEFT JOIN sHrm.tEmployeeMaster EM ON ED.ParticipantSourceId = EM.Id AND ED.ParticipantSourceTypeId = 95
LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON ED.ParticipantSourceId = EFD.Id AND ED.ParticipantSourceTypeId = 1001
LEFT JOIN sHrm.tCsrBenefiterMaster BM ON BM.Id = ED.ParticipantSourceId AND ED.ParticipantSourceTypeId = 1009
LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
LEFT JOIN sHrm.tEmployeePersonalDetail PD ON EM.Id = PD.EmployeeId
LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = PD.GenderId
LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId

LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
LEFT JOIN sHrm.tEmployeeJobDetail EJD2 ON EFD.EmployeeId = EJD2.EmployeeId

LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM ON BM.CSRBenefiterTypeId = BTM.Id

LEFT JOIN sCommon.tOrganizationDepartmentMaster OD ON ED.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 sExamination.tCauseMaster CM ON CM.Id = ED.CauseId
LEFT JOIN sExamination.tOPD OP on ED.Id = OP.ExaminationId
LEFT JOIN sExamination.tVisitTypeMaster VTM on VTM.Id = OP.VisitTypeId
LEFT JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = ED.StoreLocationId
LEFT JOIN sSecurity.tUser U ON U.Id = ED.CreatedUserId
LEFT JOIN sHrm.tNationalityMaster NM ON PD.NationalityId = NM.Id

INNER JOIN sExamination.tSetupMaster SSM ON ED.SetupId = SSM.Id
INNER JOIN sExamination.tSubTypeMaster ST ON SSM.SubTypeId = ST.Id

WHERE 
	ST.MainTypeId = 8
	AND ISNULL(ED.IsCancel,0) = 0
	AND ED.OrgId = @rOrgId
	AND (
	@rEmployeeCode = '' OR
		(
			(ED.ParticipantSourceTypeId = 95 AND EM.Code = @rEmployeeCode)
			OR (ED.ParticipantSourceTypeId = 1001 AND EM2.Code = @rEmployeeCode)
			OR (ED.ParticipantSourceTypeId = 1009 AND BM.Code = @rEmployeeCode)
		)
	)
	AND (
	@rJobTitleId = 0 OR
		(
			(ED.ParticipantSourceTypeId = 95 AND EJD.EmployeeJobTitleId = @rJobTitleId)
			OR (ED.ParticipantSourceTypeId = 1001 AND EJD2.EmployeeJobTitleId = @rJobTitleId)
			OR (ED.ParticipantSourceTypeId = 1009)
		)
	)
	AND
	(
		(EJD.EmployeeTypeId = @rEmployeeTypeId and ED.ParticipantSourceTypeId = 95)
		OR (EJD2.ContractorId = @rEmployeeTypeId and ED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND ED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeId = 0
	)	
	AND
	(
		(EJD.ContractorId = @rContractorId and ED.ParticipantSourceTypeId = 95)
		OR (EJD2.ContractorId = @rContractorId and ED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND ED.ParticipantSourceTypeId = 1009)
		OR @rContractorId = 0
	)	
	AND (ED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)
	AND
	(
		(PD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 95)
		OR (EFD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1001)
		OR (BM.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1009)
		OR @rGenderId = 0
	)
	AND (EM.StatusId=@rStatusId OR @rStatusId=0)
	AND (@rDesignationId = 0 OR ED.EmployeeDesignationId = @rDesignationId)
	AND (@rDepartmentId = 0 OR ED.OrganizationDepartmentId = @rDepartmentId)
	AND (@rGradeId = 0 OR ED.GradeId = @rGradeId)
	AND (
		@rAgeTo = 0 OR
		(
			(ED.ParticipantSourceTypeId = 95 AND PD.DateOfBirth >= DATEADD(YEAR, -@rAgeTo, @CurrentDate))
			OR (ED.ParticipantSourceTypeId = 1001 AND EFD.DateOfBirth >= DATEADD(YEAR, -@rAgeTo, @CurrentDate))
			OR (ED.ParticipantSourceTypeId = 1009 AND BM.DateOfBirth >= DATEADD(YEAR, -@rAgeTo, @CurrentDate))
		)
	)
	AND (
		@rAgeFrom = 0 OR
		(
			(ED.ParticipantSourceTypeId = 95 AND PD.DateOfBirth <= DATEADD(YEAR, -@rAgeFrom, @CurrentDate))
			OR (ED.ParticipantSourceTypeId = 1001 AND EFD.DateOfBirth <= DATEADD(YEAR, -@rAgeFrom, @CurrentDate))
			OR (ED.ParticipantSourceTypeId = 1009 AND BM.DateOfBirth <= DATEADD(YEAR, -@rAgeFrom, @CurrentDate))
		)
	)
	AND (@rStoreLocationId = 0 OR ED.StoreLocationId = @rStoreLocationId)
	AND (@rDepartmentId = 0 OR ED.OrganizationDepartmentId = @rDepartmentId)
	AND (@rCaseCauseId = 0 OR ED.CauseId = @rCaseCauseId)
	AND (@rVisitTypeId = 0 OR ISNULL(OP.VisitTypeId, 1) = @rVisitTypeId)
	AND (@ShiftTitle = '' OR @ShiftTitle = [dbo].[fGetShift](OP.OPDTime,@rOrgId))
	AND (@rParticipantTypeId = 0 OR ED.ParticipantSourceTypeId = @rParticipantTypeId)
	AND (@rFunctionId = 0 OR FM.Id = @rFunctionId)
	AND (@rDepartmentGroupId = 0 OR DGM.Id = @rDepartmentGroupId)

	AND (@rFromDate IS NULL OR ED.ExaminationDate >= @rFromDate)
	AND (@rToDate IS NULL OR ED.ExaminationDate <= @rToDate)

	AND UL.UserId = @rUserId;

SELECT 
	B.LocationId,
	DSM.Title AS Disease,
	DSM.Id AS DiseaseId
INTO #Disease

FROM #BaseData B
INNER JOIN sExamination.tExaminDiseaseDetail EDD ON EDD.ExaminDiseaseId = B.ExaminationId AND EDD.IsObsolete = 0
INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = EDD.DiseaseId
INNER JOIN sExamination.tDiseaseSystemMaster DSM ON DSM.Id = DM.DiseaseSystemId;

SELECT 
	B.LocationId,
	DSI.Disease,
	DSI.DiseaseId
INTO #DiseaseUnique
FROM #BaseData B
INNER JOIN
(
	SELECT *
	FROM
	(
		SELECT 
			EDD.ExaminDiseaseId AS ExaminationId,
			DSM.Title AS Disease,
			DSM.Id AS DiseaseId,
			ROW_NUMBER() OVER (PARTITION BY EDD.ExaminDiseaseId ORDER BY EDD.Id DESC) rn
		FROM sExamination.tExaminDiseaseDetail EDD
		INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = EDD.DiseaseId
		INNER JOIN sExamination.tDiseaseSystemMaster DSM ON DSM.Id = DM.DiseaseSystemId
		WHERE EDD.IsObsolete = 0
	) X
	WHERE rn = 1
) DSI ON DSI.ExaminationId = B.ExaminationId;

-- Participant
SELECT ParticipantType, COUNT(*) Cnt, EMPType
FROM #BaseData
GROUP BY ParticipantType, EMPType;

-- Department
SELECT DepartmentName, COUNT(*) DepartmentCnt
FROM #BaseData
GROUP BY DepartmentName;

-- Cause
SELECT CauseName, COUNT(*) CauseCnt
FROM #BaseData
GROUP BY CauseName;

-- User
SELECT LoginTitle, COUNT(*) UserCnt
FROM #BaseData
GROUP BY LoginTitle;

-- Gender
SELECT Gender, COUNT(*) Gendercnt
FROM #BaseData
GROUP BY Gender;

-- Total
SELECT COUNT(*) TotalExaminationId FROM #BaseData;

-- Disease
SELECT Disease, COUNT(*) DiseaseId
FROM #Disease
GROUP BY Disease;

-- Nationality
SELECT Nationality, COUNT(*) Nationalitycnt
FROM #BaseData
GROUP BY Nationality;

SELECT 
	ISNULL(Disease,'N/A') AS Disease,
	COUNT(ISNULL(DiseaseId,0)) AS DiseaseId
FROM #DiseaseUnique TM
INNER JOIN sIp.tStoreLocationMaster L ON TM.LocationId = L.Id
WHERE L.IsActiveHealth = 1
GROUP BY Disease
ORDER BY DiseaseId DESC;

-- VisitType
SELECT VisitType, COUNT(*) VisitTypecnt
FROM #BaseData
GROUP BY VisitType;

-- Shifts
SELECT Shifts, COUNT(*) Shiftscnt
FROM #BaseData
GROUP BY Shifts;

DROP TABLE #BaseData;
DROP TABLE #Disease;
DROP TABLE #DiseaseUnique;

END

GO


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

--Select ''Builder1,
--		''Builder2,
--		''ReportId,
--		''DepartmentName,
--		''ExaminationDate,
--		''ParticipantCode,
--		''ParticipantName,
--		''ExaminationId,
--		''Medicines,
--		''Duration,
--		''PrescribedQuantity,
--		''UnitCost,
--		''Quantity,
--		''Amount,
--		''StockBatchId,
--		''StockId,
--		''Contractor,
--		''ContractorId,
--		''ParticipantSourceId,
--		''ParticipantType,
--		''LoginTitle,
--		''BatchNumber,
--		''RoundName
--		FROM sExamination.tSetupMaster

	SELECT EAED.Id
	INTO #Temp1
	FROM sExamination.tExamination EAED
	INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = EAED.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id
	WHERE
	STM.MainTypeId = 8 AND isnull(EAED.IsCancel,0) = 0
	AND (EAED.StoreLocationId = @rStoreLocationId)
	AND ((EAED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EAED.ExaminationDate < @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))	
	AND (EAED.OrgId =  @rOrgId)
	AND (EAED.CauseId=@rCaseCauseId or @rCaseCauseId=0)
	AND (EAED.ParticipantSourceTypeId=@rParticipantTypeId or @rParticipantTypeId=0)	
	AND (EAED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND (EAED.GradeId=@rGradeId OR @rGradeId=0)
	AND (EAED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (EAED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)
	AND (EAED.EmployeeStatusId=@rStatusId OR @rStatusId=0)
	OPTION(RECOMPILE)
	
	SELECT Distinct
	EAED.Id As ExaminationId,
	 @rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	@rReportId AS ReportId,
	 EAED.ExaminationDate,	
	--EAED.Id As ExaminationId,
	EAED.ParticipantSourceId,
	SIM.Title AS Medicines,
	PD.Duration,
	PD.PrescribedQuantity as PrescribedQuantityInOPD,
	(ISNULL(DB.Quantity,0) - ISNULL(DB.ReturnQuantity,0))as PrescribedQuantity,
	DB.UnitCost,
	(ISNULL(DB.Quantity,0) - ISNULL(DB.ReturnQuantity,0))as Quantity,
	((DB.Quantity - DB.ReturnQuantity) * DB.UnitCost) AS Amount,	
	case when Isnull(SIP.DispQtyAltLimit,0)>0 and (ISNULL(DB.Quantity,0) - ISNULL(DB.ReturnQuantity,0)) >= Isnull(SIP.DispQtyAltLimit,0) 
		 then ((ISNULL(DB.Quantity,0) - ISNULL(DB.ReturnQuantity,0))-Isnull(SIP.DispQtyAltLimit,0)) 
		 else 0 end as DispQtyAltLimitDiff,
	DB.Id AS StockBatchId,
	PD.StockItemId AS StockId,
	EAED.ParticipantSourceTypeId,
	--EM.Code,
	--EM2.Code,
	--O.OtherName,
	--EM.FirstName,
	--EM.LastName,
	 
	CASE EAED.ParticipantSourceTypeId 
	WHEN 95 THEN VM.Title 
	WHEN 1001 THEN VM2.Title 
	ELSE 'UNKNOWN' END AS Contractor,
	EJD.ContractorId As ContractorId,	
	CASE EAED.ParticipantSourceTypeId WHEN 95 THEN ETM.Title WHEN 1001 THEN 'Dep'	WHEN 1009 THEN BTM.Title END AS ParticipantType,
	ParticipantCode = CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
	CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.FirstName + ' ' + isnull(EM.LastName,'')
	WHEN 1001 THEN EFD.Name WHEN 1009 THEN CASE WHEN isnull(O.OtherName,'') <> '' THEN O.OtherName ELSE BM.FirstName + ' ' + isnull(BM.LastName,'') END END AS ParticipantName ,
	U.DisplayTitle as LoginTitle,
	ISNULL(SB.Number,'') as BatchNumber
	FROM 
	#Temp1 INNER JOIN 
	sExamination.tExamination EAED ON #Temp1.Id = EAED.Id
	INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = EAED.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id
	INNER JOIN sIp.tStoreLocationMaster SLM on EAED.StoreLocationId = SLM.Id
	INNER JOIN sExamination.tPrescription P ON P.SourceId= EAED.Id
	INNER JOIN sExamination.tPrescriptionDetail PD ON PD.PrescriptionId=P.Id AND PD.IsObsolete=0
	INNER JOIN sPharmacy.tDispense D ON D.PrescriptionDetailId=PD.Id
	INNER JOIN sPharmacy.tDispenseBatch DB ON DB.DispenseId = D.Id 
	inner join sProcurement.tStockBatch SB ON SB.Id=DB.StockBatchId
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=PD.StockItemId AND SIM.LocationId = SLM.LocationId
	INNER JOIN sSecurity.tUser U ON U.Id = EAED.CreatedUserID
	
	LEFT JOIN sHrm.tEmployeeMaster EM on EAED.ParticipantSourceId = EM.Id and EAED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EAED.ParticipantSourceId = EFD.Id and EAED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id	
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on EAED.ParticipantSourceId = BM.Id and EAED.ParticipantSourceTypeId = 1009	
	LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CsrBenefiterTypeId = BTM.Id
	LEFT JOIN sHrm.tEmployeeJobDetail EJD on EM.Id = EJD.EmployeeId 
	
	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD2 on EM2.Id = EJD2.EmployeeId
	LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM on EAED.OrganizationDepartmentId = ODM.Id
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON ODM.DepartmentGroupId = DGM.Id	
	LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id 
	LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId
	LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id=EJD.ContractorId
	LEFT JOIN sProcurement.tVendorMaster VM2 ON VM2.Id=EJD2.ContractorId
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM2 ON ETM2.Id = EJD2.EmployeeTypeId 
	LEFT JOIN sExamination.tOPD O ON O.ExaminationId = EAED.Id
	Left Join sIp.tstockItemTagDetail SITM On SITM.StockItemId=SIM.Id
	LEFT JOIN sIp.tStockItemPlanning SIP on SIP.StockItemId=SIM.Id and SIP.StorelocationID=@rStoreLocationId
	WHERE 
	
	(
		(EM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EM2.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(BM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1009)
		OR
		@rEmployeeCode = ''
	)
	 
	AND
	(
		(EJD.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rJobTitleId = 0
	)
	AND
	(
		(EJD.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeId = 0
	)	
	AND
	(			
		(EJD.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rContractorId=0
	)
	
	AND
	(
		(EPD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EFD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		((BM.GenderId = @rGenderId or O.GenderId = @rGenderId) AND EAED.ParticipantSourceTypeId = 1009)
		OR @rGenderId=0
	)
	
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1009)
		OR ISNULL(@rAgeTo,0)=0
	)
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1009)			
		OR ISNULL(@rAgeFrom,0)=0
	)

	AND	(SLM.LocationId = @rLocationId) 
	AND (SIM.IsNotInStore = 0)
	AND ((SIM.Code=@rItemCode) OR (ISNULL(@rItemCode,'')=''))
	AND ((SIM.Title=@rItemName) OR (ISNULL(@rItemName,'')=''))
	AND (isnull(BM.CSRBenefiterTypeId,0)=@rOtherTypeId or isnull(@rOtherTypeId,0)=0)
	--and ISNULL(convert(decimal(18,2),(DB.Quantity - DB.ReturnQuantity) * DB.UnitCost),0) > 0 
	and (SITM.StockItemTagId in (SELECT item FROM sCommon.fnsplit(@rTagIds,',')) or (@rTagIds=''))
	AND
	(
		(EJD.EmployeeSubTypeId = @rEmployeeSubTypeId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeSubTypeId = @rEmployeeSubTypeId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeSubTypeId = 0
	)
	AND
	(
		(EJD.EmployeeGroupId = @rEmployeeGroupId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeGroupId = @rEmployeeGroupId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeGroupId = 0
	)
	AND
	(
		(ETM.EmployeeTypeGroupId = @rEmployeeTypeGroupId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(ETM2.EmployeeTypeGroupId = @rEmployeeTypeGroupId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeGroupId = 0
	)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0) 
	AND ((FM.Id = @rFunctionId) OR (@rFunctionId = 0))

	OPTION(RECOMPILE)
	
	DROP TABLE #Temp1	
END


GO


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

--Select ''Builder1,
--		''Builder2,
--		''ReportId,
--		''DepartmentName,
--		''ExaminationDate,
--		''ParticipantCode,
--		''ParticipantName,
--		''ExaminationId,
--		''Medicines,
--		''Duration,
--		''PrescribedQuantity,
--		''UnitCost,
--		''Quantity,
--		''Amount,
--		''StockBatchId,
--		''StockId,
--		''Contractor,
--		''ContractorId,
--		''ParticipantSourceId,
--		''ParticipantType,
--		''LoginTitle,
--		''BatchNumber,
--		''RoundName
--		FROM sExamination.tSetupMaster

	SELECT EAED.Id
	INTO #Temp1
	FROM sExamination.tExamination EAED
	INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = EAED.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id
	WHERE
	STM.MainTypeId = 8 AND isnull(EAED.IsCancel,0) = 0
	AND (EAED.StoreLocationId = @rStoreLocationId)
	AND ((EAED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EAED.ExaminationDate < @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))	
	AND (EAED.OrgId =  @rOrgId)
	AND (EAED.CauseId=@rCaseCauseId or @rCaseCauseId=0)
	AND (EAED.ParticipantSourceTypeId=@rParticipantTypeId or @rParticipantTypeId=0)	
	AND (EAED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND (EAED.GradeId=@rGradeId OR @rGradeId=0)
	AND (EAED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (EAED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)
	AND (EAED.EmployeeStatusId=@rStatusId OR @rStatusId=0)
	OPTION(RECOMPILE)
	
	SELECT Distinct
	EAED.Id As ExaminationId,
	 @rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	@rReportId AS ReportId,
	 EAED.ExaminationDate,	
	--EAED.Id As ExaminationId,
	EAED.ParticipantSourceId,
	SIM.Title AS Medicines,
	PD.Duration,
	PD.PrescribedQuantity as PrescribedQuantityInOPD,
	(ISNULL(DB.Quantity,0) - ISNULL(DB.ReturnQuantity,0))as PrescribedQuantity,
	DB.UnitCost,
	(ISNULL(DB.Quantity,0) - ISNULL(DB.ReturnQuantity,0))as Quantity,
	((DB.Quantity - DB.ReturnQuantity) * DB.UnitCost) AS Amount,	
	case when Isnull(SIP.DispQtyAltLimit,0)>0 and (ISNULL(DB.Quantity,0) - ISNULL(DB.ReturnQuantity,0)) >= Isnull(SIP.DispQtyAltLimit,0) 
		 then ((ISNULL(DB.Quantity,0) - ISNULL(DB.ReturnQuantity,0))-Isnull(SIP.DispQtyAltLimit,0)) 
		 else 0 end as DispQtyAltLimitDiff,
	DB.Id AS StockBatchId,
	PD.StockItemId AS StockId,
	EAED.ParticipantSourceTypeId,
	--EM.Code,
	--EM2.Code,
	--O.OtherName,
	--EM.FirstName,
	--EM.LastName,
	 
	CASE EAED.ParticipantSourceTypeId 
	WHEN 95 THEN VM.Title 
	WHEN 1001 THEN VM2.Title 
	ELSE 'UNKNOWN' END AS Contractor,
	EJD.ContractorId As ContractorId,	
	CASE EAED.ParticipantSourceTypeId WHEN 95 THEN ETM.Title WHEN 1001 THEN 'Dep'	WHEN 1009 THEN BTM.Title END AS ParticipantType,
	ParticipantCode = CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
	CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.FirstName + ' ' + isnull(EM.LastName,'')
	WHEN 1001 THEN EFD.Name WHEN 1009 THEN CASE WHEN isnull(O.OtherName,'') <> '' THEN O.OtherName ELSE BM.FirstName + ' ' + isnull(BM.LastName,'') END END AS ParticipantName ,
	U.DisplayTitle as LoginTitle,
	ISNULL(SB.Number,'') as BatchNumber
	FROM 
	#Temp1 INNER JOIN 
	sExamination.tExamination EAED ON #Temp1.Id = EAED.Id
	INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = EAED.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id
	INNER JOIN sIp.tStoreLocationMaster SLM on EAED.StoreLocationId = SLM.Id
	INNER JOIN sExamination.tPrescription P ON P.SourceId= EAED.Id
	INNER JOIN sExamination.tPrescriptionDetail PD ON PD.PrescriptionId=P.Id AND PD.IsObsolete=0
	INNER JOIN sPharmacy.tDispense D ON D.PrescriptionDetailId=PD.Id
	INNER JOIN sPharmacy.tDispenseBatch DB ON DB.DispenseId = D.Id 
	inner join sProcurement.tStockBatch SB ON SB.Id=DB.StockBatchId
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=PD.StockItemId AND SIM.LocationId = SLM.LocationId
	INNER JOIN sSecurity.tUser U ON U.Id = EAED.CreatedUserID
	
	LEFT JOIN sHrm.tEmployeeMaster EM on EAED.ParticipantSourceId = EM.Id and EAED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EAED.ParticipantSourceId = EFD.Id and EAED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id	
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on EAED.ParticipantSourceId = BM.Id and EAED.ParticipantSourceTypeId = 1009	
	LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CsrBenefiterTypeId = BTM.Id
	LEFT JOIN sHrm.tEmployeeJobDetail EJD on EM.Id = EJD.EmployeeId 
	
	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD2 on EM2.Id = EJD2.EmployeeId
	LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM on EAED.OrganizationDepartmentId = ODM.Id
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON ODM.DepartmentGroupId = DGM.Id	
	LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id 
	LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId
	LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id=EJD.ContractorId
	LEFT JOIN sProcurement.tVendorMaster VM2 ON VM2.Id=EJD2.ContractorId
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM2 ON ETM2.Id = EJD2.EmployeeTypeId 
	LEFT JOIN sExamination.tOPD O ON O.ExaminationId = EAED.Id
	Left Join sIp.tstockItemTagDetail SITM On SITM.StockItemId=SIM.Id
	LEFT JOIN sIp.tStockItemPlanning SIP on SIP.StockItemId=SIM.Id and SIP.StorelocationID=@rStoreLocationId
	WHERE 
	
	(
		(EM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EM2.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(BM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1009)
		OR
		@rEmployeeCode = ''
	)
	 
	AND
	(
		(EJD.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rJobTitleId = 0
	)
	AND
	(
		(EJD.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeId = 0
	)	
	AND
	(			
		(EJD.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rContractorId=0
	)
	
	AND
	(
		(EPD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EFD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		((BM.GenderId = @rGenderId or O.GenderId = @rGenderId) AND EAED.ParticipantSourceTypeId = 1009)
		OR @rGenderId=0
	)
	
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1009)
		OR ISNULL(@rAgeTo,0)=0
	)
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1009)			
		OR ISNULL(@rAgeFrom,0)=0
	)

	AND	(SLM.LocationId = @rLocationId) 
	AND (SIM.IsNotInStore = 0)
	AND ((SIM.Code=@rItemCode) OR (ISNULL(@rItemCode,'')=''))
	AND ((SIM.Title=@rItemName) OR (ISNULL(@rItemName,'')=''))
	AND (isnull(BM.CSRBenefiterTypeId,0)=@rOtherTypeId or isnull(@rOtherTypeId,0)=0)
	and ISNULL(convert(decimal(18,2),(DB.Quantity - DB.ReturnQuantity) * DB.UnitCost),0) > 0 
	and (SITM.StockItemTagId in (SELECT item FROM sCommon.fnsplit(@rTagIds,',')) or (@rTagIds=''))
	AND
	(
		(EJD.EmployeeSubTypeId = @rEmployeeSubTypeId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeSubTypeId = @rEmployeeSubTypeId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeSubTypeId = 0
	)
	AND
	(
		(EJD.EmployeeGroupId = @rEmployeeGroupId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeGroupId = @rEmployeeGroupId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeGroupId = 0
	)
	AND
	(
		(ETM.EmployeeTypeGroupId = @rEmployeeTypeGroupId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(ETM2.EmployeeTypeGroupId = @rEmployeeTypeGroupId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeGroupId = 0
	)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0) 
	AND ((FM.Id = @rFunctionId) OR (@rFunctionId = 0))

	OPTION(RECOMPILE)
	
	DROP TABLE #Temp1	
END


GO


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

	 Insert INTO @Temp1 
	 SELECT *
	 From
	(
	SELECT EAED.Id
	FROM sExamination.tExamination EAED
	INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = EAED.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id
	WHERE
	STM.MainTypeId = 8 AND isnull(EAED.IsCancel,0) = 0
	AND (EAED.StoreLocationId = @rStoreLocationId)
	AND ((EAED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EAED.ExaminationDate < @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))	
	AND (EAED.OrgId =  @rOrgId)
	AND (EAED.CauseId=@rCaseCauseId or @rCaseCauseId=0)
	AND (EAED.ParticipantSourceTypeId=@rParticipantTypeId or @rParticipantTypeId=0)	
	AND (EAED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND (EAED.GradeId=@rGradeId OR @rGradeId=0)
	AND (EAED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (EAED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)
	AND (EAED.EmployeeStatusId=@rStatusId OR @rStatusId=0)
	Union
	SELECT EAED.Id	
	FROM sExamination.tArchieveExamination EAED
	INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = EAED.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id
	WHERE
	STM.MainTypeId = 8 AND isnull(EAED.IsCancel,0) = 0
	AND (EAED.StoreLocationId = @rStoreLocationId)
	AND ((EAED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EAED.ExaminationDate < @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))	
	AND (EAED.OrgId =  @rOrgId)
	AND (EAED.CauseId=@rCaseCauseId or @rCaseCauseId=0)
	AND (EAED.ParticipantSourceTypeId=@rParticipantTypeId or @rParticipantTypeId=0)	
	AND (EAED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND (EAED.GradeId=@rGradeId OR @rGradeId=0)
	AND (EAED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (EAED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)
	AND (EAED.EmployeeStatusId=@rStatusId OR @rStatusId=0)
	)as temp
	OPTION(RECOMPILE)

	SELECT
	EAED.Id As ExaminationId,
	 @rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	@rReportId AS ReportId,
	EAED.ExaminationDate,	
	EAED.Id As ExaminationId,
	EAED.ParticipantSourceId,
	SIM.Title AS Medicines,
	PD.Duration,
	PD.PrescribedQuantity,
	DB.UnitCost,
	DB.Quantity,
	((DB.Quantity - DB.ReturnQuantity) * DB.UnitCost) AS Amount,
	DB.Id AS StockBatchId,
	PD.StockItemId AS StockId,
	EAED.ParticipantSourceTypeId,
	--EM.Code,
	--EM2.Code,
	--O.OtherName,
	--EM.FirstName,
	--EM.LastName,
	 
	CASE EAED.ParticipantSourceTypeId 
	WHEN 95 THEN VM.Title 
	WHEN 1001 THEN VM2.Title 
	ELSE 'UNKNOWN' END AS Contractor,
	EJD.ContractorId As ContractorId,	
	CASE EAED.ParticipantSourceTypeId WHEN 95 THEN ETM.Title WHEN 1001 THEN 'Dep'	WHEN 1009 THEN BTM.Title END AS ParticipantType,
	ParticipantCode = CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
	CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.FirstName + ' ' + isnull(EM.LastName,'')
	WHEN 1001 THEN EFD.Name WHEN 1009 THEN CASE WHEN isnull(O.OtherName,'') <> '' THEN O.OtherName ELSE BM.FirstName + ' ' + isnull(BM.LastName,'') END END AS ParticipantName ,
	U.DisplayTitle as LoginTitle,
	ISNULL(SB.Number,'') as BatchNumber
	FROM
	@Temp1 as temp1 INNER JOIN 
	sExamination.tExamination EAED ON temp1.Id = EAED.Id
	INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = EAED.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id
	INNER JOIN sIp.tStoreLocationMaster SLM on EAED.StoreLocationId = SLM.Id
	INNER JOIN sExamination.tPrescription P ON P.SourceId= EAED.Id
	INNER JOIN sExamination.tPrescriptionDetail PD ON PD.PrescriptionId=P.Id AND PD.IsObsolete=0
	INNER JOIN sPharmacy.tDispense D ON D.PrescriptionDetailId=PD.Id
	INNER JOIN sPharmacy.tDispenseBatch DB ON DB.DispenseId = D.Id 
	inner join sProcurement.tStockBatch SB ON SB.Id=DB.StockBatchId
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=PD.StockItemId AND SIM.LocationId = SLM.LocationId
	INNER JOIN sSecurity.tUser U ON U.Id = EAED.CreatedUserID
	
	LEFT JOIN sHrm.tEmployeeMaster EM on EAED.ParticipantSourceId = EM.Id and EAED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EAED.ParticipantSourceId = EFD.Id and EAED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id	
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on EAED.ParticipantSourceId = BM.Id and EAED.ParticipantSourceTypeId = 1009	
	LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CsrBenefiterTypeId = BTM.Id
	LEFT JOIN sHrm.tEmployeeJobDetail EJD on EM.Id = EJD.EmployeeId 
	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD2 on EM2.Id = EJD2.EmployeeId
	LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM on EAED.OrganizationDepartmentId = ODM.Id
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON ODM.DepartmentGroupId = DGM.Id	 
	LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id 
	LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId
	LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id=EJD.ContractorId
	LEFT JOIN sProcurement.tVendorMaster VM2 ON VM2.Id=EJD2.ContractorId
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM2 ON ETM2.Id = EJD2.EmployeeTypeId 
	LEFT JOIN sExamination.tOPD O ON O.ExaminationId = EAED.Id
	Left Join sIp.tstockItemTagDetail SITM On SITM.StockItemId=SIM.Id
	WHERE 
	
	(
		(EM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EM2.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(BM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1009)
		OR
		@rEmployeeCode = ''
	)
	 
	AND
	(
		(EJD.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rJobTitleId = 0
	)
	AND
	(
		(EJD.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeId = 0
	)	
	AND
	(			
		(EJD.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rContractorId=0
	)
	
	AND
	(
		(EPD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EFD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		((BM.GenderId = @rGenderId or O.GenderId = @rGenderId) AND EAED.ParticipantSourceTypeId = 1009)
		OR @rGenderId=0
	)
	
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1009)
		OR ISNULL(@rAgeTo,0)=0
	)
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1009)			
		OR ISNULL(@rAgeFrom,0)=0
	)

	AND	(SLM.LocationId = @rLocationId) 
	AND (SIM.IsNotInStore = 0)
	AND ((SIM.Code=@rItemCode) OR (ISNULL(@rItemCode,'')=''))
	AND ((SIM.Title=@rItemName) OR (ISNULL(@rItemName,'')=''))
	AND (isnull(BM.CSRBenefiterTypeId,0)=@rOtherTypeId or isnull(@rOtherTypeId,0)=0)
	and ISNULL(convert(decimal(18,2),(DB.Quantity - DB.ReturnQuantity) * DB.UnitCost),0) > 0 
	and (SITM.StockItemTagId in (SELECT item FROM sCommon.fnsplit(@rTagIds,',')) or (@rTagIds=''))
	AND
	(
		(EJD.EmployeeSubTypeId = @rEmployeeSubTypeId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeSubTypeId = @rEmployeeSubTypeId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeSubTypeId = 0
	)
	AND
	(
		(EJD.EmployeeGroupId = @rEmployeeGroupId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeGroupId = @rEmployeeGroupId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeGroupId = 0
	)
	AND
	(
		(ETM.EmployeeTypeGroupId = @rEmployeeTypeGroupId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(ETM2.EmployeeTypeGroupId = @rEmployeeTypeGroupId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeGroupId = 0
	)	
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND ((FM.Id = @rFunctionId) OR (@rFunctionId = 0))

	union
	SELECT
	EAED.Id As ExaminationId,
	 @rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	@rReportId AS ReportId,
	EAED.ExaminationDate,	
	EAED.Id As ExaminationId,
	EAED.ParticipantSourceId,
	SIM.Title AS Medicines,
	PD.Duration,
	PD.PrescribedQuantity,
	DB.UnitCost,
	DB.Quantity,
	((DB.Quantity - DB.ReturnQuantity) * DB.UnitCost) AS Amount,
	DB.Id AS StockBatchId,
	PD.StockItemId AS StockId,
	EAED.ParticipantSourceTypeId,
	--EM.Code,
	--EM2.Code,
	--O.OtherName,
	--EM.FirstName,
	--EM.LastName,
	 
	CASE EAED.ParticipantSourceTypeId 
	WHEN 95 THEN VM.Title 
	WHEN 1001 THEN VM2.Title 
	ELSE 'UNKNOWN' END AS Contractor,
	EJD.ContractorId As ContractorId,	
	CASE EAED.ParticipantSourceTypeId WHEN 95 THEN ETM.Title WHEN 1001 THEN 'Dep'	WHEN 1009 THEN BTM.Title END AS ParticipantType,
	ParticipantCode = CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
	CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.FirstName + ' ' + isnull(EM.LastName,'')
	WHEN 1001 THEN EFD.Name WHEN 1009 THEN CASE WHEN isnull(O.OtherName,'') <> '' THEN O.OtherName ELSE BM.FirstName + ' ' + isnull(BM.LastName,'') END END AS ParticipantName ,
	U.DisplayTitle as LoginTitle,
	ISNULL(SB.Number,'') as BatchNumber
	FROM
	@Temp1 as temp INNER JOIN 
	sExamination.tArchieveExamination EAED ON temp.Id = EAED.Id
	INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = EAED.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id
	INNER JOIN sIp.tStoreLocationMaster SLM on EAED.StoreLocationId = SLM.Id
	INNER JOIN sExamination.tArchievePrescription P ON P.SourceId= EAED.Id
	INNER JOIN sExamination.tArchievePrescriptionDetail PD ON PD.PrescriptionId=P.Id AND PD.IsObsolete=0
	INNER JOIN sPharmacy.tArchieveDispense D ON D.PrescriptionDetailId=PD.Id
	INNER JOIN sPharmacy.tArchieveDispenseBatch DB ON DB.DispenseId = D.Id 
	inner join sProcurement.tStockBatch SB ON SB.Id=DB.StockBatchId
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=PD.StockItemId AND SIM.LocationId = SLM.LocationId
	INNER JOIN sSecurity.tUser U ON U.Id = EAED.CreatedUserID
	
	LEFT JOIN sHrm.tEmployeeMaster EM on EAED.ParticipantSourceId = EM.Id and EAED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EAED.ParticipantSourceId = EFD.Id and EAED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id	
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on EAED.ParticipantSourceId = BM.Id and EAED.ParticipantSourceTypeId = 1009	
	LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CsrBenefiterTypeId = BTM.Id
	LEFT JOIN sHrm.tEmployeeJobDetail EJD on EM.Id = EJD.EmployeeId 
	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD2 on EM2.Id = EJD2.EmployeeId
	LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM on EAED.OrganizationDepartmentId = ODM.Id
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON ODM.DepartmentGroupId = DGM.Id	 
	LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id 
	LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId
	LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id=EJD.ContractorId
	LEFT JOIN sProcurement.tVendorMaster VM2 ON VM2.Id=EJD2.ContractorId
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId 
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM2 ON ETM2.Id = EJD2.EmployeeTypeId
	LEFT JOIN sExamination.tArchieveOPD O ON O.ExaminationId = EAED.Id
	Left Join sIp.tstockItemTagDetail SITM On SITM.StockItemId=SIM.Id
	WHERE 
	
	(
		(EM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EM2.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(BM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1009)
		OR
		@rEmployeeCode = ''
	)
	 
	AND
	(
		(EJD.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rJobTitleId = 0
	)
	AND
	(
		(EJD.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeId = 0
	)	
	AND
	(			
		(EJD.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rContractorId=0
	)
	
	AND
	(
		(EPD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EFD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		((BM.GenderId = @rGenderId or O.GenderId = @rGenderId) AND EAED.ParticipantSourceTypeId = 1009)
		OR @rGenderId=0
	)
	
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1009)
		OR ISNULL(@rAgeTo,0)=0
	)
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1009)			
		OR ISNULL(@rAgeFrom,0)=0
	)

	AND	(SLM.LocationId = @rLocationId) 
	AND (SIM.IsNotInStore = 0)
	AND ((SIM.Code=@rItemCode) OR (ISNULL(@rItemCode,'')=''))
	AND ((SIM.Title=@rItemName) OR (ISNULL(@rItemName,'')=''))
	AND (isnull(BM.CSRBenefiterTypeId,0)=@rOtherTypeId or isnull(@rOtherTypeId,0)=0)
	and ISNULL(convert(decimal(18,2),(DB.Quantity - DB.ReturnQuantity) * DB.UnitCost),0) > 0 
	and (SITM.StockItemTagId in (SELECT item FROM sCommon.fnsplit(@rTagIds,',')) or (@rTagIds=''))
	AND
	(
		(EJD.EmployeeSubTypeId = @rEmployeeSubTypeId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeSubTypeId = @rEmployeeSubTypeId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeSubTypeId = 0
	)
	AND
	(
		(EJD.EmployeeGroupId = @rEmployeeGroupId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeGroupId = @rEmployeeGroupId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeGroupId = 0
	)
	AND
	(
		(ETM.EmployeeTypeGroupId = @rEmployeeTypeGroupId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(ETM2.EmployeeTypeGroupId = @rEmployeeTypeGroupId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeGroupId = 0
	)
	AND ((FM.Id = @rFunctionId) OR (@rFunctionId = 0))
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)

	OPTION(RECOMPILE)
	--DROP TABLE #Temp1	
END


GO


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

	 Insert INTO @Temp1 
	 SELECT *
	 From
	(
	SELECT EAED.Id
	FROM sExamination.tExamination EAED
	INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = EAED.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id
	WHERE
	STM.MainTypeId = 8 AND isnull(EAED.IsCancel,0) = 0
	AND (EAED.StoreLocationId = @rStoreLocationId)
	AND ((EAED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EAED.ExaminationDate < @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))	
	AND (EAED.OrgId =  @rOrgId)
	AND (EAED.CauseId=@rCaseCauseId or @rCaseCauseId=0)
	AND (EAED.ParticipantSourceTypeId=@rParticipantTypeId or @rParticipantTypeId=0)	
	AND (EAED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND (EAED.GradeId=@rGradeId OR @rGradeId=0)
	AND (EAED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (EAED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)
	AND (EAED.EmployeeStatusId=@rStatusId OR @rStatusId=0)
	Union
	SELECT EAED.Id	
	FROM sExamination.tArchieveExamination EAED
	INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = EAED.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id
	WHERE
	STM.MainTypeId = 8 AND isnull(EAED.IsCancel,0) = 0
	AND (EAED.StoreLocationId = @rStoreLocationId)
	AND ((EAED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EAED.ExaminationDate < @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))	
	AND (EAED.OrgId =  @rOrgId)
	AND (EAED.CauseId=@rCaseCauseId or @rCaseCauseId=0)
	AND (EAED.ParticipantSourceTypeId=@rParticipantTypeId or @rParticipantTypeId=0)	
	AND (EAED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND (EAED.GradeId=@rGradeId OR @rGradeId=0)
	AND (EAED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (EAED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)
	AND (EAED.EmployeeStatusId=@rStatusId OR @rStatusId=0)
	)as temp
	OPTION(RECOMPILE)

	SELECT
	EAED.Id As ExaminationId,
	 @rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	@rReportId AS ReportId,
	EAED.ExaminationDate,	
	EAED.Id As ExaminationId,
	EAED.ParticipantSourceId,
	SIM.Title AS Medicines,
	PD.Duration,
	PD.PrescribedQuantity,
	DB.UnitCost,
	DB.Quantity,
	((DB.Quantity - DB.ReturnQuantity) * DB.UnitCost) AS Amount,
	DB.Id AS StockBatchId,
	PD.StockItemId AS StockId,
	EAED.ParticipantSourceTypeId,
	--EM.Code,
	--EM2.Code,
	--O.OtherName,
	--EM.FirstName,
	--EM.LastName,
	 
	CASE EAED.ParticipantSourceTypeId 
	WHEN 95 THEN VM.Title 
	WHEN 1001 THEN VM2.Title 
	ELSE 'UNKNOWN' END AS Contractor,
	EJD.ContractorId As ContractorId,	
	CASE EAED.ParticipantSourceTypeId WHEN 95 THEN ETM.Title WHEN 1001 THEN 'Dep'	WHEN 1009 THEN BTM.Title END AS ParticipantType,
	ParticipantCode = CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
	CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.FirstName + ' ' + isnull(EM.LastName,'')
	WHEN 1001 THEN EFD.Name WHEN 1009 THEN CASE WHEN isnull(O.OtherName,'') <> '' THEN O.OtherName ELSE BM.FirstName + ' ' + isnull(BM.LastName,'') END END AS ParticipantName ,
	U.DisplayTitle as LoginTitle,
	ISNULL(SB.Number,'') as BatchNumber
	FROM
	@Temp1 as temp1 INNER JOIN 
	sExamination.tExamination EAED ON temp1.Id = EAED.Id
	INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = EAED.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id
	INNER JOIN sIp.tStoreLocationMaster SLM on EAED.StoreLocationId = SLM.Id
	INNER JOIN sExamination.tPrescription P ON P.SourceId= EAED.Id
	INNER JOIN sExamination.tPrescriptionDetail PD ON PD.PrescriptionId=P.Id AND PD.IsObsolete=0
	INNER JOIN sPharmacy.tDispense D ON D.PrescriptionDetailId=PD.Id
	INNER JOIN sPharmacy.tDispenseBatch DB ON DB.DispenseId = D.Id 
	inner join sProcurement.tStockBatch SB ON SB.Id=DB.StockBatchId
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=PD.StockItemId AND SIM.LocationId = SLM.LocationId
	INNER JOIN sSecurity.tUser U ON U.Id = EAED.CreatedUserID
	
	LEFT JOIN sHrm.tEmployeeMaster EM on EAED.ParticipantSourceId = EM.Id and EAED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EAED.ParticipantSourceId = EFD.Id and EAED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id	
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on EAED.ParticipantSourceId = BM.Id and EAED.ParticipantSourceTypeId = 1009	
	LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CsrBenefiterTypeId = BTM.Id
	LEFT JOIN sHrm.tEmployeeJobDetail EJD on EM.Id = EJD.EmployeeId 
	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD2 on EM2.Id = EJD2.EmployeeId
	LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM on EAED.OrganizationDepartmentId = ODM.Id
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON ODM.DepartmentGroupId = DGM.Id	 
	LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id 
	LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId
	LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id=EJD.ContractorId
	LEFT JOIN sProcurement.tVendorMaster VM2 ON VM2.Id=EJD2.ContractorId
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM2 ON ETM2.Id = EJD2.EmployeeTypeId 
	LEFT JOIN sExamination.tOPD O ON O.ExaminationId = EAED.Id
	Left Join sIp.tstockItemTagDetail SITM On SITM.StockItemId=SIM.Id
	WHERE 
	
	(
		(EM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EM2.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(BM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1009)
		OR
		@rEmployeeCode = ''
	)
	 
	AND
	(
		(EJD.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rJobTitleId = 0
	)
	AND
	(
		(EJD.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeId = 0
	)	
	AND
	(			
		(EJD.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rContractorId=0
	)
	
	AND
	(
		(EPD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EFD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		((BM.GenderId = @rGenderId or O.GenderId = @rGenderId) AND EAED.ParticipantSourceTypeId = 1009)
		OR @rGenderId=0
	)
	
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1009)
		OR ISNULL(@rAgeTo,0)=0
	)
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1009)			
		OR ISNULL(@rAgeFrom,0)=0
	)

	AND	(SLM.LocationId = @rLocationId) 
	AND (SIM.IsNotInStore = 0)
	AND ((SIM.Code=@rItemCode) OR (ISNULL(@rItemCode,'')=''))
	AND ((SIM.Title=@rItemName) OR (ISNULL(@rItemName,'')=''))
	AND (isnull(BM.CSRBenefiterTypeId,0)=@rOtherTypeId or isnull(@rOtherTypeId,0)=0)
	--and ISNULL(convert(decimal(18,2),(DB.Quantity - DB.ReturnQuantity) * DB.UnitCost),0) > 0 
	and (SITM.StockItemTagId in (SELECT item FROM sCommon.fnsplit(@rTagIds,',')) or (@rTagIds=''))
	AND
	(
		(EJD.EmployeeSubTypeId = @rEmployeeSubTypeId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeSubTypeId = @rEmployeeSubTypeId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeSubTypeId = 0
	)
	AND
	(
		(EJD.EmployeeGroupId = @rEmployeeGroupId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeGroupId = @rEmployeeGroupId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeGroupId = 0
	)
	AND
	(
		(ETM.EmployeeTypeGroupId = @rEmployeeTypeGroupId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(ETM2.EmployeeTypeGroupId = @rEmployeeTypeGroupId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeGroupId = 0
	)	
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND ((FM.Id = @rFunctionId) OR (@rFunctionId = 0))

	union
	SELECT
	EAED.Id As ExaminationId,
	 @rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	@rReportId AS ReportId,
	EAED.ExaminationDate,	
	EAED.Id As ExaminationId,
	EAED.ParticipantSourceId,
	SIM.Title AS Medicines,
	PD.Duration,
	PD.PrescribedQuantity,
	DB.UnitCost,
	DB.Quantity,
	((DB.Quantity - DB.ReturnQuantity) * DB.UnitCost) AS Amount,
	DB.Id AS StockBatchId,
	PD.StockItemId AS StockId,
	EAED.ParticipantSourceTypeId,
	--EM.Code,
	--EM2.Code,
	--O.OtherName,
	--EM.FirstName,
	--EM.LastName,
	 
	CASE EAED.ParticipantSourceTypeId 
	WHEN 95 THEN VM.Title 
	WHEN 1001 THEN VM2.Title 
	ELSE 'UNKNOWN' END AS Contractor,
	EJD.ContractorId As ContractorId,	
	CASE EAED.ParticipantSourceTypeId WHEN 95 THEN ETM.Title WHEN 1001 THEN 'Dep'	WHEN 1009 THEN BTM.Title END AS ParticipantType,
	ParticipantCode = CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
	CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.FirstName + ' ' + isnull(EM.LastName,'')
	WHEN 1001 THEN EFD.Name WHEN 1009 THEN CASE WHEN isnull(O.OtherName,'') <> '' THEN O.OtherName ELSE BM.FirstName + ' ' + isnull(BM.LastName,'') END END AS ParticipantName ,
	U.DisplayTitle as LoginTitle,
	ISNULL(SB.Number,'') as BatchNumber
	FROM
	@Temp1 as temp INNER JOIN 
	sExamination.tArchieveExamination EAED ON temp.Id = EAED.Id
	INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = EAED.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id
	INNER JOIN sIp.tStoreLocationMaster SLM on EAED.StoreLocationId = SLM.Id
	INNER JOIN sExamination.tArchievePrescription P ON P.SourceId= EAED.Id
	INNER JOIN sExamination.tArchievePrescriptionDetail PD ON PD.PrescriptionId=P.Id AND PD.IsObsolete=0
	INNER JOIN sPharmacy.tArchieveDispense D ON D.PrescriptionDetailId=PD.Id
	INNER JOIN sPharmacy.tArchieveDispenseBatch DB ON DB.DispenseId = D.Id 
	inner join sProcurement.tStockBatch SB ON SB.Id=DB.StockBatchId
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=PD.StockItemId AND SIM.LocationId = SLM.LocationId
	INNER JOIN sSecurity.tUser U ON U.Id = EAED.CreatedUserID
	
	LEFT JOIN sHrm.tEmployeeMaster EM on EAED.ParticipantSourceId = EM.Id and EAED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EAED.ParticipantSourceId = EFD.Id and EAED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id	
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on EAED.ParticipantSourceId = BM.Id and EAED.ParticipantSourceTypeId = 1009	
	LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CsrBenefiterTypeId = BTM.Id
	LEFT JOIN sHrm.tEmployeeJobDetail EJD on EM.Id = EJD.EmployeeId 
	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD2 on EM2.Id = EJD2.EmployeeId
	LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM on EAED.OrganizationDepartmentId = ODM.Id
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON ODM.DepartmentGroupId = DGM.Id	 
	LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id 
	LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId
	LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id=EJD.ContractorId
	LEFT JOIN sProcurement.tVendorMaster VM2 ON VM2.Id=EJD2.ContractorId
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId 
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM2 ON ETM2.Id = EJD2.EmployeeTypeId
	LEFT JOIN sExamination.tArchieveOPD O ON O.ExaminationId = EAED.Id
	Left Join sIp.tstockItemTagDetail SITM On SITM.StockItemId=SIM.Id
	WHERE 
	
	(
		(EM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EM2.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(BM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1009)
		OR
		@rEmployeeCode = ''
	)
	 
	AND
	(
		(EJD.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rJobTitleId = 0
	)
	AND
	(
		(EJD.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeId = 0
	)	
	AND
	(			
		(EJD.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rContractorId=0
	)
	
	AND
	(
		(EPD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EFD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		((BM.GenderId = @rGenderId or O.GenderId = @rGenderId) AND EAED.ParticipantSourceTypeId = 1009)
		OR @rGenderId=0
	)
	
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1009)
		OR ISNULL(@rAgeTo,0)=0
	)
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1009)			
		OR ISNULL(@rAgeFrom,0)=0
	)

	AND	(SLM.LocationId = @rLocationId) 
	AND (SIM.IsNotInStore = 0)
	AND ((SIM.Code=@rItemCode) OR (ISNULL(@rItemCode,'')=''))
	AND ((SIM.Title=@rItemName) OR (ISNULL(@rItemName,'')=''))
	AND (isnull(BM.CSRBenefiterTypeId,0)=@rOtherTypeId or isnull(@rOtherTypeId,0)=0)
	--and ISNULL(convert(decimal(18,2),(DB.Quantity - DB.ReturnQuantity) * DB.UnitCost),0) > 0 
	and (SITM.StockItemTagId in (SELECT item FROM sCommon.fnsplit(@rTagIds,',')) or (@rTagIds=''))
	AND
	(
		(EJD.EmployeeSubTypeId = @rEmployeeSubTypeId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeSubTypeId = @rEmployeeSubTypeId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeSubTypeId = 0
	)
	AND
	(
		(EJD.EmployeeGroupId = @rEmployeeGroupId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeGroupId = @rEmployeeGroupId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeGroupId = 0
	)
	AND
	(
		(ETM.EmployeeTypeGroupId = @rEmployeeTypeGroupId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(ETM2.EmployeeTypeGroupId = @rEmployeeTypeGroupId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeGroupId = 0
	)
	AND ((FM.Id = @rFunctionId) OR (@rFunctionId = 0))
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)

	OPTION(RECOMPILE)
	--DROP TABLE #Temp1	
END


GO


ALTER proc [sMro].[pExaminationCustomSearch]  
@rOrgId [int] = 0,  
@rUserId bigint = null,  
@rSetupId int=0,  
@rSetupGroupId int=0,  
@rEmployeeCompanyIds varchar(max)='',  
@rParticipantSourceId bigint = 0,  
--@rSourceTypeId int = 0,    
@rParticipantCode varchar(max)='',  
@rEmployeeName varchar(200)= '',  
@rFromDate date = '',  
@rToDate date = '',  
@rLocationId int,  
@rExaminationTypeId int = 0,  
@rStoreLocationId int = 0,  
@rExaminationStatusId int = 0,  
@rEmployeeTypeId int = 0,  
--@rParticipantSourceTypeId int = 0,  
@rTargetGroupIds varchar(max) ='',  
@rDepartmentGroupIds varchar(max) ='',  
@rDepartmentIds varchar(max) ='',  
@rDesignationIds varchar(max) ='',  
@rCompanyGroupIds varchar(max) ='',  
@rNationalId varchar(max) ='' ,
@rBusinessIds nvarchar(max) = '', -- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024
@rSubBusinessIds nvarchar(max) = '',-- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024
@rIsBusinessWise bit -- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024
as  
SET NOCOUNT ON  
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED  
BEGIN  
 IF(@rFromDate IS NULL)  
  SET @rFromDate='0001-01-01'  
   
 IF(@rToDate IS NULL)  
  SET @rToDate= convert(varchar, getdate(), 23)  
  
 Select distinct EED.ExaminationId,  
 EED.ParticipantCode as EmployeeCode,  
 EED.ParticipantName,  
 S.Title as StoreLocation,  
 SM.Title as Setup,  
 EED.ExaminationDate,  
 OD.Id as DepartmentId,  
 OD.Title as Department,  
 ECM.Title as CompanyName,  
 ESM.Title as Status
 --ISNULL(EPD.NationalityId,0) NationalityId
 --from sExamination.tExamination EED  
 from sExamination.vExtEmployeeExaminationDetail EED  
 LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EED.EmployeeId = EPD.EmployeeId  
 --inner join sHrm.tEmployeeMaster EM on EED.ParticipantSourceId = EM.Id  
 inner join sExamination.tSetupMaster SM on SM.Id =EED.SetupId  
 inner join sIp.tStoreLocationMaster S on EED.StoreLocationId = S.Id  
 left join sHrm.tEmployeeJobDetail EJD on EED.EmployeeId = EJD.EmployeeId  
 left join sCommon.tOrganizationDepartmentMaster OD on EED.OrganizationDepartmentId = OD.Id  
 left join sHrm.tEmployeeCompanyMaster ECM on ECM.Id=(case when @rIsBusinessWise=0 then EED.ExaminationCompanyId else EJD.EmployeeCompanyId end)   -- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024    
 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.tDepartmentGroupMaster DGM ON EED.DepartmentGroupId = DGM.Id AND DGM.IsObsolete=0   
 left join sExamination.tSetupGroupMaster SGM on SGM.Id=SM.SetupGroupId   
 --left join sSecurity.tUser Users on Users.Id = EED.CreatedUserId  
 left join sHrm.tEmployeeMaster EM1 on EM1.Id = EED.DoctorEmployeeId  
 LEFT JOIN sExamination.tStatusMaster ESM on ESM.Id = EED.StatusId   
 INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = EED.StoreLocationId  
 INNER JOIN sSecurity.tUserLocation UL on SLM.Id = UL.StoreLocationId  
 --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 = EED.EmployeeLocationId  
   
 where EED.OrgId = @rOrgId   
 and UL.UserId = @rUserId  
 AND ((EED.MainTypeId=@rExaminationTypeId) OR @rExaminationTypeId=0)  
 AND (EED.MainTypeId <> 8)  
 and (EED.ExaminationDate >= @rFromDate or isnull(@rFromDate,'') = '')  
 and (EED.ExaminationDate <= @rToDate or isnull(@rToDate,'') = '')   
 and ((EED.EmployeeId = @rParticipantSourceId) or (@rParticipantSourceId = 0))  
 --and (EED.ParticipantSourceTypeId = 95)  
 and ((EED.OrganizationDepartmentId IN (SELECT item FROM  sCommon.fnsplit(@rDepartmentIds,',')))  or @rDepartmentIds = '')  
 and (EED.SetupId = @rSetupId or isnull(@rSetupId,0) = 0)  
 and ((ISNULL(EED.ParticipantCode,'') IN (SELECT item FROM  sCommon.fnsplit(@rParticipantCode,','))) or (@rParticipantCode=''))  
 and ((EED.ParticipantName Like @rEmployeeName  + '%') or (@rEmployeeName = ''))  
 --and (EM.Code = @rParticipantCode or @rParticipantCode = '')  
 --and (EM.FirstName Like @rName  + '%' or @rName = '')  
 and ((EED.StoreLocationId = @rStoreLocationId) or @rStoreLocationId = 0)  
 --and (EED.StatusID = @rStatusId or  @rStatusId = 0)  
 and ((EED.EmployeecompanyId IN (SELECT item FROM  sCommon.fnsplit(@rEmployeeCompanyIds,','))) or  @rEmployeeCompanyIds = '')  
 and (SM.SetupGroupId = @rSetupGroupId or  @rSetupGroupId = 0)  
 and (ESM.Id = @rExaminationStatusId or  @rExaminationStatusId = 0)  
 and ((EED.ExaminationTargetGroupId IN (SELECT item FROM  sCommon.fnsplit(@rTargetGroupIds,',') )) or @rTargetGroupIds='')  
 AND ((EED.DepartmentGroupId IN (SELECT item FROM  sCommon.fnsplit(@rDepartmentGroupIds,',') ))  or (isnull(@rDepartmentGroupIds,'')=''))  
 AND ((EED.EmployeeDesignationId IN (SELECT item FROM  sCommon.fnsplit(@rDesignationIds,',') ))  or (isnull(@rDesignationIds,'')=''))  
 and (EED.EmployeeTypeId = @rEmployeeTypeId or  @rEmployeeTypeId = 0)  
 AND (ISNULL(@rCompanyGroupIds,'')='' OR ISNULL(ECM.CompanyGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCompanyGroupIds,',')))  
 AND ((EPD.NationalityId in (SELECT item FROM sCommon.fnsplit(@rNationalId,','))) OR (ISNULL(@rNationalId,'') = ''))  
 AND ((VTM.SectorId  IN(SELECT item FROM sCommon.fnsplit(@rBusinessIds,','))) OR (ISNULL(@rBusinessIds,'') = '')) -- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024
 AND ((CGM.VerticalId  IN(SELECT item FROM sCommon.fnsplit(@rSubBusinessIds,','))) OR (ISNULL(@rSubBusinessIds,'') = '')) -- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024
END  

GO


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

  GO

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

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

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

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

    -- Query 4: Referred to OHC Doctor
    SELECT EM.Id as Id,
	ISNULL(EM.EmployeePrefix + ' ','') + ISNULL(EM.FirstName + ' ','') + ISNULL(EM.LastName + ' ','') as Title
	from sCwb.tDoctorMaster DM
	INNER JOIN sCwb.tDoctorStoreLocation DSL ON DSL.EmployeeId = DM.EmployeeId
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.EmployeeId
	WHERE DSL.SubLocationId=@rStoreLocationId AND EM.StatusId = 7 AND DM.OrgId = @rOrgId 
    ORDER BY Id, Title DESC;

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

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

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

	-- Query 8: Wellness Activity Task
    SELECT Id,[Name] as Title,ActivityId, TargetValue, 
		   FrequencyTypeId, FrequencyCount, DurationDays
    FROM [sWellness].[tWellnessActivityTaskMaster]
END;

GO


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

        WHEN EE.ParticipantSourceTypeId = 1009
             THEN ISNULL(EE.Age,0)

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




GO


CREATE OR ALTER PROCEDURE[sAlert].[pAlertLogAdd]   
 @rXML nvarchar(max),  
 @rOrgId smallint  
   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
BEGIN TRY  
   
 BEGIN TRANSACTION  
 DECLARE @loXML XML;  
  
  SET @rXML=REPLACE(@rXML,'&','AND');  
 SET @loXML = CAST(@rXML AS XML);  
  
 DECLARE @lCount INT  
 DECLARE @lInterrorCode INT  
 --  @intDoc INT  
 --EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXML  
   
 DECLARE @lNextNumber BIGINT    
 DECLARE @lFromNextNumber BIGINT
 DECLARE @lMaxId BIGINT
 
 SELECT @lMaxId = ISNULL(MAX(Id),0) FROM sAlert.tAlertLog 
 WITH (UPDLOCK, HOLDLOCK) WHERE OrgId = @rOrgId

 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAlert.tAlertLog', 0, 1, 1,@outNextNumber = @lNextNumber output
 
 IF @lNextNumber <= @lMaxId
 BEGIN
     SET @lFromNextNumber = @lMaxId
 END
 ELSE
 BEGIN
     SET @lFromNextNumber = @lNextNumber - 1
 END
 
 INSERT INTO sAlert.tAlertLog  
  (  
   Id,  
   ContactId,  
   AlertMessage,  
   AlertSubject,  
   StatusId,  
   ResultMessage,  
   SMSType,  
   SourceEvent,  
   EventId,  
   EventName,  
   AlertModeId,  
   OrgId,  
   CreatedUserId,  
   CreatedDateTime,  
   UserId,  
   IsDaily,  
   IsWeekly,  
   IsMonthly,  
   ProviderAppointmentId , 
   ClaimIntimationDetailId
  )  
 SELECT  
   @lFromNextNumber + ROW_NUMBER() OVER(ORDER BY T.c.value('ContactId[1]','nvarchar(50)')),  
   T.c.value('ContactId[1]','nvarchar(500)') AS ContactId,  
   [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('AlertMessage[1]','nvarchar(max)')) AS AlertMessage,  
   [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('AlertSubject[1]','nvarchar(255)')) AS AlertSubject,  
   T.c.value('StatusId[1]','int') AS StatusId,  
   [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('ResultMessage[1]','nvarchar(255)')) AS ResultMessage,  
   T.c.value('SMSType[1]','nvarchar(50)') AS SMSType,  
   T.c.value('SourceEvent[1]','nvarchar(50)') AS SourceEvent,  
   T.c.value('EventId[1]','int') AS EventId,   
   [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('EventName[1]','nvarchar(100)')) AS EventName,  
   T.c.value('AlertModeId[1]','tinyint') AS AlertModeId,  
   @rOrgId,  
   CASE WHEN T.c.value('CreatedUserId[1]','bigint') = 1 THEN sCommon.fGetBigIntIdForOrg(T.c.value('CreatedUserId[1]','bigint'),@rOrgId) ELSE T.c.value('CreatedUserId[1]','bigint') END,  
     
   sCommon.fGetDate(),  
   T.c.value('UserId[1]','bigint') AS UserId,  
   case when T.c.value('Flag[1]','int') = 1 then 1 ENd,  
   case when T.c.value('Flag[1]','int') = 2 then 1 ENd,  
   case when T.c.value('Flag[1]','int') = 3 then 1 ENd,  
     T.c.value('ProviderAppointmentId[1]','bigint') AS ProviderAppointmentId  ,
	  T.c.value('ClaimIntimationDetailId[1]','bigint') AS ClaimIntimationDetailId  

    
 FROM  
  @loXML.nodes('/Table/AlertLog')T(c)  
 -- OPENXML (@intDoc, '/Table/AlertLog', 1)  
 --WITH  
 --(  
 -- ContactId nvarchar(50) 'ContactId',  
 -- AlertMessage nvarchar(255) 'AlertMessage',  
 -- AlertSubject nvarchar(255) 'AlertSubject',  
 -- StatusId int 'StatusId',  
 -- ResultMessage nvarchar(255) 'ResultMessage',  
 -- SMSType nvarchar(50) 'SMSType',  
 -- SourceEvent nvarchar(50) 'SourceEvent',  
 -- EventId int 'EventId',  
 -- AlertModeId tinyint 'AlertModeId',  
 -- CreatedUserId bigint 'CreatedUserId'  
 --)  
  
 SELECT @lCount = COUNT(1)  
  FROM   
  @loXML.nodes('/Table/AlertLog')T(c)  
  --OPENXML (@intDoc, '/Table/AlertLog', 1)  
  --   WITH ( ContactId nvarchar(50))  
  SET @lNextNumber  = @lCount + @lFromNextNumber   
    
  EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAlert.tAlertLog', @rCurrentNumber = @lNextNumber   
    
  --EXEC sp_xml_removedocument @intDoc  
    
  SELECT 1 AS Result,@lFromNextNumber+1 AS FromId,@lNextNumber AS ToId  
   
  COMMIT TRANSACTION  
    
 END TRY  
   
 BEGIN CATCH   
  ROLLBACK TRANSACTION
  
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)   
  select @rOrgId,'AlertLog_DBError',5000,ERROR_MESSAGE(),GETDATE()

  SELECT -1 AS Result
 END CATCH
END  

GO


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

BEGIN

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

IF(@rId = 0)
BEGIN

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


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

	SELECT @lMaxId = ISNULL(MAX(Id), 0) FROM sExamination.tHealthIndexParameterDetail 
	WITH (UPDLOCK, HOLDLOCK) WHERE OrgId = @rOrgId
	
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sExamination.tHealthIndexParameterDetail', 0, 1, 1,@outNextNumber = @lNextNumber output

	IF @lNextNumber <= @lMaxId
	BEGIN
		SET @lNextNumber = @lMaxId + 1
	END

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

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

	END
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	 IF(@rIsDelete = 1)
	BEGIN
		DELETE FROM sExamination.tHealthIndexParameterDetail  WHERE Id = @rId 	
	 END
	
  END
  SELECT @lNextNumber AS Result

  COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
  
insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)   
select @rOrgId,'HealthIndexParameterDetail_DBError',5000,ERROR_MESSAGE(),GETDATE()

SELECT -1 AS RESULT
END CATCH

END


GO


ALTER proc [sExamination].[pSaveHealthIndexParametersDetailN]
@rOrgId int,
@rUserId bigint,
@rIndexParameterId int,
@rIndexParaemters varchar(max)
as
begin

	DECLARE @LockedIds VARCHAR(MAX) = '';

	SELECT @LockedIds = STUFF((
		SELECT ',' + CAST(Id AS VARCHAR)
		FROM sExamination.tHealthIndexParameterMaster
		WHERE IsLock = 1
		FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
	, 1, 1, '');

	if not exists (select * from sExamination.tHealthIndexParameterMaster where StaticHealthIndexParameterId = @rIndexParameterId 
					and OrgId = @rOrgId and (Id in (SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@LockedIds,''),','))) or ISNULL(@LockedIds,'')='')
	begin
		insert into sExamination.tHealthIndexParameterMaster
		(
			Id,Code,Title,HealthIndexParameterTypeId,OrgId,IsObsolete,
			CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,
			StaticHealthIndexParameterId
		)
		select sCommon.fGetIntIdForOrg(Id,@rOrgId),Code,Title,HealthIndexParameterTypeId,
		@rOrgId,0,@rUserId,getdate(),@rUserId,getdate(),Id
		
		from sExamination.tStaticHealthIndexParameterMaster
		where Id = @rIndexParameterId
	end
	
	declare @tbltmpIndexParameterDetails table(tid int identity(1,1),pdid int)
	insert into @tbltmpIndexParameterDetails
	select Item from dbo.fSplitStr(@rIndexParaemters,',') where Item <> ''
	
	--delete from sExamination.tHealthIndexParameterDetail where OrgId = @rOrgId and StaticHealthParameterId = @rIndexParameterId
	delete from sExamination.tHealthIndexParameterDetail where OrgId = @rOrgId 
	            and HealthIndexParameterId = sCommon.fGetIntIdForOrg(@rIndexParameterId,@rOrgId) 
	            and HealthIndexParameterId not in (SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@LockedIds,''),','))
	
	insert into sExamination.tHealthIndexParameterDetail
	(
		Id,HealthIndexParameterId,FieldName,FromValue,ToValue,Points,
		DiagnosisRemark,GenderId,OrgId,StaticHealthParameterId
	)
	select sCommon.fGetIntIdForOrg(Id,@rOrgId),
	sCommon.fGetIntIdForOrg(StaticHealthIndexParameterId,@rOrgId),
	FieldName,FromValue,ToValue,Points,DiagnosisRemark,GenderId,@rOrgId,Id
	
	from sExamination.tStaticHealthIndexParameterDetail
	inner join @tbltmpIndexParameterDetails on pdid = Id
	where sCommon.fGetIntIdForOrg(StaticHealthIndexParameterId,@rOrgId) not in (SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@LockedIds,''),','))
end

GO


CREATE OR ALTER PROCEDURE[sExamination].[pValidateExaminationDataTable]
(
	@rExaminationDt [sExamination].[ExaminationAllParameterList] READONLY, -- Excel Data
	@examinationId int,
	@rOrgId int,
	@rType nvarchar(50) = '',
	@rSetupGroupId int = 0,
	@rIsMandatoryDoctor bit = false
)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
	DECLARE @lIsRestrictDataUploadToFreezeLocation varchar(5), @lIsRestrictDataUploadWithoutDocument varchar(5);
      
	select @lIsRestrictDataUploadToFreezeLocation = sConfig.fConfigurationValueGet('Provider.RestrictDataUploadToFreezeLocation',@rOrgId,0,0,0);
	select @lIsRestrictDataUploadWithoutDocument = sConfig.fConfigurationValueGet('Provider.RestrictDataUploadWithoutDocument',@rOrgId,0,0,0);

	DECLARE @tbltmp TABLE
	(
		tid INT IDENTITY(1,1),
		Id INT,
		Area INT,
		RequiredFlag INT,
		Flag INT,
		ParameterName VARCHAR(200),
		NRange VARCHAR(200),
		TestId INT,
		TestParameterId INT,
		TestDetailId INT,
		ListValueTypeId INT
	)

	-- START - Inserting all available parameter
	INSERT INTO @tbltmp

	SELECT 
		Id,ImportArea = CASE WHEN ImportArea = 'Required' THEN 1 WHEN ImportArea = 'Vital' THEN 2 
		WHEN ImportArea = 'Habit' THEN 3 WHEN ImportArea = 'Disease' THEN 4 WHEN ImportArea = 'History' THEN 5
		WHEN ImportArea = 'Diagnosis' THEN 6 WHEN ImportArea = 'Surgery' THEN 5 ELSE 0 END,
		RequiredFlag as ImportFlag,0 AS Flag,
		ImportParameter,isnull(ImportRange,'') AS ImportRange,0,0,0,0
	FROM 
		sConfig.tExaminationImportTemplate
	
	UNION ALL
			
	SELECT 
		   P.Id,9 as ImportArea,0 as ImportFlag,StaticParameterValueTypeId as Flag,
		   ImportCode as ImportParameter,isnull(NormalRange,'') as ImportRange,D.StaticTestId,
		   D.StaticTestParameterId,D.Id,P.StaticListValueTypeId
	FROM 
		sOrderEntry.tStaticTestParameterMaster P
	INNER JOIN 
		sOrderEntry.tStaticTestDetail D
	INNER JOIN 
		sOrderEntry.tStaticTestMaster T
	ON 
		T.Id = D.StaticTestId
	ON 
		P.Id = D.StaticTestParameterId
	WHERE 
		P.IsObsolete = 0 and T.IsObsolete = 0 and ImportCode <> ''
	
	UNION ALL
			
	SELECT 
		P.Id,9 AS ImportArea,0 AS ImportFlag,ParameterValueTypeId AS Flag,
		P.Code AS ImportParameter,isnull(NormalRange,'') AS ImportRange,D.TestId,
		D.TestParameterId,D.Id,P.ListValueTypeId
	FROM 
		sOrderEntry.tTestParameterMaster P
	INNER JOIN 
		sOrderEntry.tTestDetail D
	INNER JOIN 
		sOrderEntry.tTestMaster T
	ON 
		T.Id = D.TestId
	ON 
		P.Id = D.TestParameterId
	WHERE 
		P.IsObsolete = 0 and T.IsObsolete = 0 AND Isnull(P.StaticTestParameterId,0)=0

	UNION ALL
	
	SELECT Id,10,0,ParameterValueTypeId,ImportCode,isnull(NormalRange,''),StaticGeneralTemplateId,Id,0,0
	FROM sExamination.tStaticGeneralTemplateParameter WHERE IsObsolete = 0 and ImportCode <> ''
	-- END   - Inserting all available parameter

	--SELECT * FROM @tbltmp
	DECLARE @rTableDt [sExamination].[ExaminationImportTemplateList];
	DECLARE @LocationDSTable TABLE
	(
		Id INT, Title NVARCHAR(100), LocationId BIGINT
	)
	INSERT INTO @LocationDSTable select Id,Title,LocationId from sIp.tStoreLocationMaster Where OrgId = @rOrgId AND Title IN (select Distinct Item from dbo.fSplitStr([sSetup].[fPortalXMLTagsReplaceReverse](STUFF((SELECT ' ,' + SubLocation FROM @rExaminationDt FOR XML PATH('')),1, 2, '')),',') where Item <> '')

	DECLARE @CodeDSTable TABLE
	(
		Id BIGINT,CodeDS NVARCHAR(30), IsObsolete BIT 
	)
	INSERT INTO @CodeDSTable select Id,upper(Code)Code, IsObsolete from sHrm.tEmployeeMaster where OrgId = @rOrgId AND upper(Code) in (select Distinct Item from dbo.fSplitStr([sSetup].[fPortalXMLTagsReplaceReverse](STUFF((SELECT ' ,' + upper(Code) FROM @rExaminationDt FOR XML PATH('')),1, 2, '')),',') where Item <> '')

	DECLARE @SetupDSTable TABLE (Id BIGINT, Title NVARCHAR(100), SubLocationId BIGINT, SetupGroupId BIGINT)
	DECLARE @CombinedValue NVARCHAR(MAX);

	SELECT @CombinedValue = STUFF((SELECT ', ' + [sSetup].[fPortalXMLTagsReplaceReverse](LTRIM(RTRIM(Round))) + '&&' + [sSetup].[fPortalXMLTagsReplaceReverse](LTRIM(RTRIM(SubLocation))) FROM (SELECT DISTINCT Round, SubLocation FROM @rExaminationDt WHERE Round IS NOT NULL AND SubLocation IS NOT NULL) AS UniqueCombos FOR XML PATH('')), 1, 2, '');
	SET @CombinedValue = REPLACE(@CombinedValue, 'amp;', '&'); SET @CombinedValue = REPLACE(@CombinedValue, '&&&&', '&&');  SET @CombinedValue = REPLACE(@CombinedValue, ' ,', ','); SET @CombinedValue = REPLACE(@CombinedValue, ', ', ',');

	INSERT INTO @SetupDSTable (Id, Title, SubLocationId, SetupGroupId) EXEC [sExamination].[pGetExaminationEmployeeSetupList] @rOrgId,@CombinedValue,@examinationId;

	DECLARE @ListDSTable TABLE
	(
		ListId INT,	Title NVARCHAR(75), ParameterId INT, StaticListValueTypeId INT, flg INT
	)

	INSERT INTO @ListDSTable (ListId, Title, ParameterId, StaticListValueTypeId, flg) EXEC [sExamination].[pGetExaminationParameterListImport]

	DECLARE @DoctorDSTable TABLE
	(
		DoctorName NVARCHAR(50),
		EmployeeId BIGINT
	)

	DECLARE @cnt INT = 1;
	DECLARE @cntHeight INT = 1;
	DECLARE @excnt INT = 1;
	DECLARE @excnt2 INT = 1;
	DECLARE @tblcnt INT = 1;
	DECLARE @TemplateCount INT = 0;
	DECLARE @ExaminationCount INT = 0;

	INSERT INTO @rTableDt SELECT Id,Area,RequiredFlag,Flag,ParameterName,NRange,TestId,TestParameterId,TestDetailId,ListValueTypeId FROM @tbltmp;
	
	SET @TemplateCount = (SELECT Count(*) FROM @rTableDt);
	SET @ExaminationCount = (SELECT Count(*) FROM @rExaminationDt);


	DECLARE @rStrRes nvarchar(max) = '';
	DECLARE @rStrRestbl TABLE (Message NVARCHAR(MAX));
	DECLARE @rImportParameter nvarchar(50) = '';
	DECLARE @rRequiredFlag int = 0;
	DECLARE @rArea int = 0;
	DECLARE @rTestFlag int = 0;
	DECLARE @rFlag int = 0;
	DECLARE @rCode nvarchar(50) = '';
	DECLARE @rRound nvarchar(50) = '';

	WHILE @cnt < @TemplateCount + 1
	BEGIN
		WITH myTableWithRows AS (SELECT (ROW_NUMBER() OVER (ORDER BY(SELECT NULL))) AS ROW, * FROM @rTableDt)
		SELECT @rImportParameter = ParameterName, @rRequiredFlag = RequiredFlag, @rArea = Area FROM myTableWithRows WHERE ROW = @cnt;
		SET @cnt = @cnt + 1;
	END;	

	DECLARE @rFVC NVARCHAR(50) = '', @rFEV1 NVARCHAR(50) = '', @rPEFR NVARCHAR(50) = '', @rHeight NVARCHAR(50) = '';

	WITH CompletedExamination AS (
		SELECT 
			E.Id, 
			E.Code, 
			E.Round
		FROM sExamination.tExamination AS EXM
		INNER JOIN sHrm.tEmployeeMaster EM on EM.Id = EXM.ParticipantSourceId
		INNER JOIN sExamination.tSetupMaster SM on SM.Id = EXM.SetupId
		INNER JOIN sIp.tStoreLocationMaster SLM on SLM.Id = EXM.StoreLocationId
		INNER JOIN @rExaminationDt AS E
			ON E.Code = EM.Code AND E.Round = SM.Title AND E.SubLocation = SLM.Title
		Where EXM.StatusId = 4
	)

	INSERT INTO @rStrRestbl (Message)
	SELECT 'CompletedData - Code - ' + CAST(D.Id+1 AS NVARCHAR)
	FROM CompletedExamination AS D;

	WITH ProviderAppointmentWithoutDocument AS (
		SELECT E.Id, 
			E.Code, 
			E.Round
		FROM @rExaminationDt AS E
		INNER JOIN sHrm.tEmployeeMaster EM on EM.Code = E.Code
		WHERE EM.Id not in (SELECT EM.Id
							FROM @rExaminationDt AS E
							INNER JOIN sHrm.tEmployeeMaster EM on EM.Code = E.Code
							INNER JOIN sSupport.tProviderAppointment AS PA ON PA.PatientSourceId = EM.Id
							INNER JOIN sSupport.tProviderAppointmentDocument AS PAD ON PAD.ProviderAppointmentId = PA.Id
							INNER JOIN sExamination.tSetupMaster SM on SM.Id = PA.SetupId
							INNER JOIN sIp.tStoreLocationMaster SLM on SLM.Id = PA.StoreLocationId
							INNER JOIN sExamination.tSetupGroupMaster SGM on SGM.Id = SM.SetupGroupId 
							Where E.Round = SM.Title AND E.SubLocation = SLM.Title 
							AND SGM.Id = @rSetupGroupId  AND @rSetupGroupId <> 0)
		AND (@rType = 'Provider' OR @rType = 'Assign') AND @lIsRestrictDataUploadWithoutDocument = 'True' 
	)

	INSERT INTO @rStrRestbl (Message)
	SELECT 'ProviderAppointmentWithoutDocument - Code - ' + CAST(D.Id+1 AS NVARCHAR)
	FROM ProviderAppointmentWithoutDocument AS D;

	WITH NotAppointmentFreezeSublocation AS (
		SELECT E.Id, 
			E.Code, 
			E.Round
		FROM @rExaminationDt AS E
		INNER JOIN sHrm.tEmployeeMaster EM on EM.Code = E.Code
		WHERE EM.Id not in (SELECT EM.Id
							FROM @rExaminationDt AS E
							INNER JOIN sHrm.tEmployeeMaster EM on EM.Code = E.Code
							INNER JOIN sSupport.tProviderAppointment AS PA ON PA.PatientSourceId = EM.Id
							INNER JOIN sExamination.tSetupMaster SM on SM.Id = PA.SetupId
							INNER JOIN sIp.tStoreLocationMaster SLM on SLM.Id = PA.StoreLocationId
							INNER JOIN sExamination.tSetupGroupMaster SGM on SGM.Id = SM.SetupGroupId 
							Where E.Round = SM.Title AND E.SubLocation = SLM.Title 
							AND SGM.Id = @rSetupGroupId AND @rSetupGroupId <> 0)
		AND (@rType = 'Provider' OR @rType = 'Assign') AND @lIsRestrictDataUploadToFreezeLocation = 'True'
	)

	INSERT INTO @rStrRestbl (Message)
	SELECT 'NotAppointmentFreezeSublocation - Code - ' + CAST(D.Id+1 AS NVARCHAR)
	FROM NotAppointmentFreezeSublocation AS D;

	WITH ProviderAppointmentNotDone AS (
		SELECT E.Id, 
			E.Code, 
			E.Round
		FROM @rExaminationDt AS E
		INNER JOIN sHrm.tEmployeeMaster EM on EM.Code = E.Code
		WHERE EM.Id not in (SELECT EM.Id
							FROM @rExaminationDt AS E
							INNER JOIN sHrm.tEmployeeMaster EM on EM.Code = E.Code
							INNER JOIN sSupport.tProviderAppointment AS PA ON PA.PatientSourceId = EM.Id
							INNER JOIN sExamination.tSetupMaster SM on SM.Id = PA.SetupId
							INNER JOIN sExamination.tSetupGroupMaster SGM on SGM.Id = SM.SetupGroupId 
							Where SGM.Id = @rSetupGroupId AND @rSetupGroupId <> 0)
		AND (@rType = 'Provider' OR @rType = 'Assign')
	)

	INSERT INTO @rStrRestbl (Message)
	SELECT 'ProviderAppointmentNotDone - Code - ' + CAST(D.Id+1 AS NVARCHAR)
	FROM ProviderAppointmentNotDone AS D;

	WITH DuplicateEntries AS (
		SELECT 
			E.Code, 
			E.Round,
			COUNT(*) AS DuplicateCount
		FROM @rExaminationDt AS E
		GROUP BY E.Code, E.Round
		HAVING COUNT(*) > 1
	),

	DuplicateCodeValidation AS (
		SELECT 
			E.Id, 
			E.Code, 
			E.Round
		FROM @rExaminationDt AS E
		INNER JOIN DuplicateEntries AS DE
			ON E.Code = DE.Code AND E.Round = DE.Round
	)

	INSERT INTO @rStrRestbl (Message)
	SELECT 'DuplicateData - Code - ' + CAST(D.Id+1 AS NVARCHAR)
	FROM DuplicateCodeValidation AS D;

	-- START - Height Validation Start
	WHILE @cntHeight < @ExaminationCount + 1
	BEGIN
		DECLARE @FVCValue NVARCHAR(100), @FEV1Value NVARCHAR(100), @PEFRValue NVARCHAR(100), @HeightValue NVARCHAR(100);
 
        SELECT @FVCValue = FVC, @FEV1Value = FEV1, @PEFRValue = PEFR, @HeightValue = Height FROM @rExaminationDt WHERE Id = @cntHeight;
        IF((@FVCValue IS NOT NULL AND @FVCValue != '') OR (@FEV1Value IS NOT NULL AND @FEV1Value != '') OR (@PEFRValue IS NOT NULL AND @PEFRValue != ''))
        BEGIN
              IF((@FVCValue IS NOT NULL AND @FVCValue != '') AND (@FEV1Value IS NOT NULL AND @FEV1Value != '') AND (@PEFRValue IS NOT NULL AND @PEFRValue != ''))
			  BEGIN
					IF(@HeightValue IS NULL OR @HeightValue = '')
					BEGIN
						INSERT INTO @rStrRestbl (Message) VALUES ('EmptyData - Height - ' + CONVERT(NVARCHAR, (@cntHeight + 1)));
					END
			  END
			  ELSE
			  BEGIN
					IF(@FVCValue IS NULL OR @FVCValue = '')
					BEGIN
						INSERT INTO @rStrRestbl (Message) VALUES ('EmptyData - FVC - ' + CONVERT(NVARCHAR, (@cntHeight + 1)));
					END
					ELSE IF(@FEV1Value IS NULL OR @FEV1Value = '')
					BEGIN
						INSERT INTO @rStrRestbl (Message) VALUES ('EmptyData - FEV1 - ' + CONVERT(NVARCHAR, (@cntHeight + 1)));
					END
					ELSE IF(@PEFRValue IS NULL OR @PEFRValue = '')
					BEGIN
						INSERT INTO @rStrRestbl (Message) VALUES ('EmptyData - PEFR - ' + CONVERT(NVARCHAR, (@cntHeight + 1)));
					END
			  END
        END
		SET @cntHeight = @cntHeight + 1;
	END;
	-- END - Height Validation Start

	-- START - Declaration of other validations
	DECLARE @rExmParameterName NVARCHAR(50) = '';

	WITH Allvalidations AS (SELECT ROW_NUMBER() OVER (ORDER BY Id ASC) AS row,*, CASE
            WHEN ISDATE(
                RIGHT(LEFT(Examination_Date, 10), 4) + 
                SUBSTRING(LEFT(Examination_Date, 10), 4, 2) + 
                LEFT(LEFT(Examination_Date, 10), 2)
            ) = 1
            THEN 1
            ELSE 0
        END AS isValid,
        CASE
            WHEN ISDATE(
                RIGHT(LEFT(Examination_Date, 10), 4) + 
                SUBSTRING(LEFT(Examination_Date, 10), 4, 2) + 
                LEFT(LEFT(Examination_Date, 10), 2)
            ) = 1
            THEN CONVERT(
                DATE, 
                RIGHT(LEFT(Examination_Date, 10), 4) + 
                SUBSTRING(LEFT(Examination_Date, 10), 4, 2) + 
                LEFT(LEFT(Examination_Date, 10), 2), 
                112
            )
            ELSE NULL
        END AS convertedDate FROM @rExaminationDt)
	-- END - Assign value to other validations

	--select * from Allvalidations
	INSERT INTO @rStrRestbl (Message)

	-- START - Round, Sublocation, Code, Examination_Date, Nature_Of_Work, Doctor
	SELECT 'EmptyData - Round - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE ISNULL([Round], '') = ''

	UNION ALL
	SELECT 'InvalidData - Round - ' + CONVERT(NVARCHAR, (av.row + 1)) FROM 
	AllValidations av WHERE ISNULL([Round], '') != '' AND ISNULL(SubLocation, '') != '' AND NOT EXISTS 
	(
		SELECT 1 FROM @LocationDSTable WHERE UPPER(LTRIM(RTRIM(Title))) = [sSetup].[fPortalXMLTagsReplaceReverse](UPPER(LTRIM(RTRIM(SubLocation))))
	)

	UNION ALL
	SELECT 'InvalidData - Round - ' + CONVERT(NVARCHAR, (av.row + 1))
	FROM 
		AllValidations av
	WHERE 
		(ISNULL([Round], '') != '' AND ISNULL(SubLocation, '') != '' AND EXISTS (SELECT 1 FROM @LocationDSTable WHERE UPPER(LTRIM(RTRIM(Title))) = [sSetup].[fPortalXMLTagsReplaceReverse](UPPER(LTRIM(RTRIM(SubLocation)))))
	AND 
		((@examinationId IN (1, 6, 7) AND NOT EXISTS (SELECT 1 FROM @SetupDSTable WHERE UPPER(LTRIM(RTRIM(Title))) = UPPER(LTRIM(RTRIM([Round]))) AND SubLocationId IN (SELECT Id FROM @LocationDSTable WHERE Title = [sSetup].[fPortalXMLTagsReplaceReverse](SubLocation))))
	OR
		(@examinationId NOT IN (1, 6, 7) AND NOT EXISTS (SELECT 1 FROM @SetupDSTable WHERE Title = [sSetup].[fPortalXMLTagsReplaceReverse]([Round]) AND SubLocationId = 0)))) OR ISNULL(SubLocation, '') = ''

	UNION ALL
	SELECT 'InvalidData - SubLocation - ' + CONVERT(NVARCHAR, (row + 1))
	FROM AllValidations
	WHERE NOT EXISTS (SELECT 1 FROM @LocationDSTable WHERE Title = [sSetup].[fPortalXMLTagsReplaceReverse](SubLocation) AND ISNULL(SubLocation, '') != '') AND ISNULL(SubLocation, '') != ''
	
	UNION ALL
	SELECT 'EmptyData - SubLocation - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE ISNULL(SubLocation, '') = ''

	UNION ALL
	SELECT 'InvalidData - Code - ' +  + CONVERT(NVARCHAR, (row + 1))
	FROM AllValidations
	WHERE NOT EXISTS (SELECT 1 FROM @CodeDSTable WHERE CodeDS = Code AND ISNULL(Code, '') != '') AND ISNULL(Code, '') != ''

	UNION ALL
	SELECT 'EmptyData - Code - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE ISNULL(Code, '') = ''

	UNION ALL
	SELECT
		CASE 
			WHEN isValid = 1 AND convertedDate > GETDATE() THEN 'Future - Examination_Date - ' + CONVERT(NVARCHAR, (row + 1))
			ELSE 'InvalidData - Examination_Date - ' + CONVERT(NVARCHAR, (row + 1))
		END
	FROM AllValidations
	WHERE (ISNULL(Examination_Date, '') != '') AND ((isValid = 0) OR (isValid = 1 AND convertedDate > GETDATE()))

	UNION ALL
	SELECT 'EmptyData - Examination_Date - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE ISNULL(Examination_Date, '') = ''

	UNION ALL
	SELECT 'InvalidData - Nature_Of_Work - ' + CAST(row+1 AS NVARCHAR(10))
	FROM AllValidations
	WHERE ISNULL(Nature_Of_Work, '') != '' AND NOT EXISTS (SELECT Title from sExamination.tNatureOfWorkMaster where IsObsolete = 0 AND LTRIM(RTRIM(UPPER(Title))) = [sSetup].[fPortalXMLTagsReplaceReverse](LTRIM(RTRIM(UPPER(Nature_Of_Work)))))

	UNION ALL
	SELECT 'InvalidData - Doctor - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE ISNULL(Doctor, '') !='' AND NOT EXISTS (SELECT 1 FROM sCwb.tDoctorMaster DM INNER JOIN sHrm.tEmployeeMaster EM ON DM.EmployeeId = EM.Id WHERE DM.OrgId = @rOrgId AND EM.IsObsolete = 0 
					  AND (LTRIM(RTRIM(REPLACE(ISNULL(EM.FirstName,' ') + ' ' + ISNULL(EM.Lastname,' '),'  ',' '))) = ISNULL(Doctor,' ')) AND EM.Id > 0 )
	UNION ALL
SELECT 'EmptyData - Doctor - ' + CAST(row+1 AS NVARCHAR(10)) 
FROM Allvalidations
WHERE ISNULL(Doctor, '') = ''
  AND @rIsMandatoryDoctor = 1

	-- END - Round, Sublocation, Code, Examination_Date, Nature_Of_Work, Doctor

	UNION ALL
	-- START - By rule validation 
	SELECT 'InvalidData - By_Rule - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE By_Rule NOT IN ('YES', 'Y', '1', 'N', 'NO', '0', '', NULL)
	-- END   - By rule validation 

	-- START - Left & Right AC BC validation 
	UNION ALL
	SELECT 'InvalidData - Left_ac250 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_ac250 IS NOT NULL AND (Left_ac250 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_ac250 + '.0') = 0 OR Left_ac250 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_ac500 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_ac500 IS NOT NULL AND (Left_ac500 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_ac500 + '.0') = 0 OR Left_ac500 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_ac1000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_ac1000 IS NOT NULL AND (Left_ac1000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_ac1000 + '.0') = 0 OR Left_ac1000 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_ac2000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_ac2000 IS NOT NULL AND (Left_ac2000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_ac2000 + '.0') = 0 OR Left_ac2000 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_ac3000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_ac3000 IS NOT NULL AND (Left_ac3000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_ac3000 + '.0') = 0 OR Left_ac3000 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_ac4000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_ac4000 IS NOT NULL AND (Left_ac4000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_ac4000 + '.0') = 0 OR Left_ac4000 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_ac6000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_ac6000 IS NOT NULL AND (Left_ac6000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_ac6000 + '.0') = 0 OR Left_ac6000 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_ac8000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_ac8000 IS NOT NULL AND (Left_ac8000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_ac8000 + '.0') = 0 OR Left_ac8000 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_ac250 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_ac250 IS NOT NULL AND (Right_ac250 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_ac250 + '.0') = 0 OR Right_ac250 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_ac500 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_ac500 IS NOT NULL AND (Right_ac500 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_ac500 + '.0') = 0 OR Right_ac500 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_ac1000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_ac1000 IS NOT NULL AND (Right_ac1000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_ac1000 + '.0') = 0 OR Right_ac1000 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_ac2000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_ac2000 IS NOT NULL AND (Right_ac2000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_ac2000 + '.0') = 0 OR Right_ac2000 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_ac3000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_ac3000 IS NOT NULL AND (Right_ac3000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_ac3000 + '.0') = 0 OR Right_ac3000 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_ac4000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_ac4000 IS NOT NULL AND (Right_ac4000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_ac4000 + '.0') = 0 OR Right_ac4000 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_ac6000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_ac6000 IS NOT NULL AND (Right_ac6000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_ac6000 + '.0') = 0 OR Right_ac6000 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_ac8000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_ac8000 IS NOT NULL AND (Right_ac8000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_ac8000 + '.0') = 0 OR Right_ac8000 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_BC250 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_BC250 IS NOT NULL AND (Left_BC250 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_BC250 + '.0') = 0 OR Left_BC250 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_BC500 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_BC500 IS NOT NULL AND (Left_BC500 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_BC500 + '.0') = 0 OR Left_BC500 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_BC1000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_BC1000 IS NOT NULL AND (Left_BC1000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_BC1000 + '.0') = 0 OR Left_BC1000 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_BC2000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_BC2000 IS NOT NULL AND (Left_BC2000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_BC2000 + '.0') = 0 OR Left_BC2000 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_BC3000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_BC3000 IS NOT NULL AND (Left_BC3000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_BC3000 + '.0') = 0 OR Left_BC3000 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_BC4000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_BC4000 IS NOT NULL AND (Left_BC4000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_BC4000 + '.0') = 0 OR Left_BC4000 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_BC6000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_BC6000 IS NOT NULL AND (Left_BC6000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_BC6000 + '.0') = 0 OR Left_BC6000 > 256)

	UNION ALL
	SELECT 'InvalidData - Left_BC8000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Left_BC8000 IS NOT NULL AND (Left_BC8000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Left_BC8000 + '.0') = 0 OR Left_BC8000 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_BC250 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_BC250 IS NOT NULL AND (Right_BC250 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_BC250 + '.0') = 0 OR Right_BC250 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_BC500 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_BC500 IS NOT NULL AND (Right_BC500 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_BC500 + '.0') = 0 OR Right_BC500 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_BC1000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_BC1000 IS NOT NULL AND (Right_BC1000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_BC1000 + '.0') = 0 OR Right_BC1000 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_BC2000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_BC2000 IS NOT NULL AND (Right_BC2000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_BC2000 + '.0') = 0 OR Right_BC2000 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_BC3000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_BC3000 IS NOT NULL AND (Right_BC3000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_BC3000 + '.0') = 0 OR Right_BC3000 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_BC4000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_BC4000 IS NOT NULL AND (Right_BC4000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_BC4000 + '.0') = 0 OR Right_BC4000 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_BC6000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_BC6000 IS NOT NULL AND (Right_BC6000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_BC6000 + '.0') = 0 OR Right_BC6000 > 256)

	UNION ALL
	SELECT 'InvalidData - Right_BC8000 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE Right_BC8000 IS NOT NULL AND (Right_BC8000 LIKE '%[&><`,.!?; $]%' OR ISNUMERIC(Right_BC8000 + '.0') = 0 OR Right_BC8000 > 256)
	-- END - Left & Right AC BC validation 

	-- START - FVC & FEV1 & PEFR Validation
	UNION ALL
	SELECT 'InvalidData - FVC - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE FVC IS NOT NULL and FVC <> '' AND (FVC LIKE '%[&>\<`,!?;;$]%')

	UNION ALL
	SELECT 'InvalidData - FEV1 - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE FEV1 IS NOT NULL and FEV1 <> '' AND (FEV1 LIKE '%[&>\<`,!?;;$]%')

	UNION ALL
	SELECT 'InvalidData - PEFR - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE PEFR IS NOT NULL and PEFR <> ''AND (PEFR LIKE '%[&>\<`,!?;;$]%') 

	--UNION ALL
	--SELECT 'InvalidData - FVC - ' + CAST(row+1 AS NVARCHAR(10))
 --   FROM Allvalidations
 --   WHERE FVC IS NOT NULL and @rFVC <> '' AND ISNUMERIC(FVC) = 0

	--UNION ALL
	--SELECT 'InvalidData - FEV1 - ' + CAST(row+1 AS NVARCHAR(10))
 --   FROM Allvalidations
 --   WHERE FEV1 IS NOT NULL and @rFEV1 <> '' AND ISNUMERIC(FEV1) = 0

	--UNION ALL
 --   SELECT 'InvalidData - PEFR - ' + CAST(row+1 AS NVARCHAR(10))
 --   FROM Allvalidations
 --   WHERE PEFR IS NOT NULL and @rPEFR <> '' AND ISNUMERIC(PEFR) = 0

	UNION ALL
	SELECT 'InvalidData - FVC - ' + CAST(row+1 AS NVARCHAR(10))
    FROM Allvalidations
	WHERE FVC IS NOT NULL AND LTRIM(RTRIM(FVC)) <> ''
	AND (
		-- Invalid format conditions
		ISNUMERIC(FVC) = 0
		OR FVC LIKE '%[^0-9.\-]%'
		OR FVC LIKE '%[eEdD]%'
		OR (LEN(FVC) - LEN(REPLACE(FVC, '.', ''))) > 1
		OR (CHARINDEX('-', FVC) > 1)
		OR (FVC LIKE '-%' AND LEN(FVC) = 1)

		-- OR valid number but out of realistic range
		OR (
			ISNUMERIC(FVC) = 1 
			AND CAST(FVC AS FLOAT) NOT BETWEEN 0.5 AND 8
		)
	)

	UNION ALL
	SELECT 'InvalidData - FEV1 - ' + CAST(row+1 AS NVARCHAR(10))
    FROM Allvalidations
    WHERE FEV1 IS NOT NULL AND LTRIM(RTRIM(FEV1)) <> ''
	AND (
		ISNUMERIC(FEV1) = 0
		OR FEV1 LIKE '%[^0-9.\-]%'
		OR FEV1 LIKE '%[eEdD]%'
		OR (LEN(FEV1) - LEN(REPLACE(FEV1, '.', '')) > 1)
		OR (CHARINDEX('-', FEV1) > 1)
		OR (FEV1 LIKE '-%' AND LEN(FEV1) = 1)
		OR (ISNUMERIC(FEV1) = 1 AND CAST(FEV1 AS FLOAT) NOT BETWEEN 0.5 AND 7)
	)

	UNION ALL
    SELECT 'InvalidData - PEFR - ' + CAST(row+1 AS NVARCHAR(10))
    FROM Allvalidations
    WHERE PEFR IS NOT NULL AND LTRIM(RTRIM(PEFR)) <> ''
	AND (
		ISNUMERIC(PEFR) = 0
		OR PEFR LIKE '%[^0-9.\-]%'
		OR PEFR LIKE '%[eEdD]%'
		OR (LEN(PEFR) - LEN(REPLACE(PEFR, '.', '')) > 1)
		OR (CHARINDEX('-', PEFR) > 1)
		OR (PEFR LIKE '-%' AND LEN(PEFR) = 1)
		OR (ISNUMERIC(PEFR) = 1 AND CAST(PEFR AS FLOAT) NOT BETWEEN 1.3 AND 13.3)
	)

	-- END - FVC & FEV1 & PEFR Validation

	-- START - ProcessType & TargetGroup & AgencyName & ColorVision Validation
	UNION ALL
	SELECT 'InvalidData - ProcessType - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE ProcessType IS NOT NULL AND ProcessType <> '' AND NOT EXISTS (SELECT 1 FROM sCommon.tProcessTypeMaster WHERE  Title = ProcessType)

	UNION ALL
	SELECT 'InvalidData - TargetGroup - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE TargetGroup IS NOT NULL AND TargetGroup <> '' AND NOT EXISTS (SELECT 1 FROM sHrm.tTargetGroupMaster WHERE OrgId = @rOrgId AND LTRIM(RTRIM(UPPER(Title))) = [sSetup].[fPortalXMLTagsReplaceReverse](LTRIM(RTRIM(UPPER(TargetGroup)))))

	UNION ALL
	SELECT 'InvalidData - AgencyName - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE AgencyName IS NOT NULL AND AgencyName <> '' AND NOT EXISTS (SELECT 1 FROM sCommon.tMedicalAgencyMaster WHERE  IsObsolete = 0 and OrgId = @rOrgId and Title = [sSetup].[fPortalXMLTagsReplaceReverse](AgencyName))

	UNION ALL
	SELECT 'InvalidData - ColorVision - ' + CAST(row+1 AS NVARCHAR(10))
	FROM Allvalidations
	WHERE ColorVision IS NOT NULL and ColorVision <> '' AND NOT EXISTS (SELECT 1 FROM  sExamination.tColorVisionMaster WHERE  IsObsolete = 0 and Title = [sSetup].[fPortalXMLTagsReplaceReverse](ColorVision))
	-- END - ProcessType & TargetGroup & AgencyName & ColorVision Validation

	-- START - Validation for Left_acRemark and Right_acRemark
	INSERT INTO @rStrRestbl (Message)
	SELECT 'InvalidData - Left_acRemark - ' + CAST(RowNumber+1 AS NVARCHAR(10))
	FROM (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNumber, Left_acRemark FROM @rExaminationDt) AS ValidatedRecords
	WHERE Left_acRemark != '' AND ((UPPER(Left_acRemark) = UPPER('Normal hearing')) OR (UPPER(Left_acRemark) = UPPER('Conductive hearing loss')) OR
	NOT EXISTS (SELECT 1 FROM sExamination.tAudioMetryRemarkMaster WHERE IsObsolete = 0 AND Title = Left_acRemark));

	INSERT INTO @rStrRestbl (Message)
	SELECT 'InvalidData - Right_acRemark - ' + CAST(RowNumber+1 AS NVARCHAR(10))
	FROM (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNumber, Right_acRemark FROM @rExaminationDt) AS ValidatedRecords
	WHERE Right_acRemark != '' AND ((UPPER(Right_acRemark) = UPPER('Normal hearing')) OR (UPPER(Right_acRemark) = UPPER('Conductive hearing loss')) OR
		  NOT EXISTS (SELECT 1 FROM sExamination.tAudioMetryRemarkMaster WHERE IsObsolete = 0 AND Title = Right_acRemark));
	-- END - Validation for Left_acRemark and Right_acRemark
END
SELECT Message AS ValidationResults FROM @rStrRestbl WHERE Message IS NOT NULL and Message <> '';

GO

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

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

Go


IF NOT EXISTS (
    SELECT 1
    FROM sSecurity.tScreenValidationFieldMaster
    WHERE FieldId = 69
)
BEGIN
    INSERT INTO sSecurity.tScreenValidationFieldMaster
    (
        ScreenId,
        FieldId,
        FieldName
    )
    VALUES
    (20297, 69, 'Company');
END

IF NOT EXISTS (
    SELECT 1
    FROM sSecurity.tScreenValidationFieldMaster
    WHERE FieldId = 70
)
BEGIN
    INSERT INTO sSecurity.tScreenValidationFieldMaster
    (
        ScreenId,
        FieldId,
        FieldName
    )
    VALUES
    (20297, 70, 'Contractor');
END

Go


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


GO