GO 
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('21.01.15',210115,'BEGIN','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO 

 
GO
PRINT N'Altering [sCommunication].[tRegisteredUsers]...';


GO
ALTER TABLE [sCommunication].[tRegisteredUsers]
    ADD [AppVersion]      NVARCHAR (20)  NULL,
        [AppName]         NVARCHAR (100) NULL,
        [UpdatedDateTime] DATETIME       NULL;


GO
PRINT N'Altering [sErp].[tTripLog]...';


GO
ALTER TABLE [sErp].[tTripLog]
    ADD [IsManual] BIT NULL;


GO
PRINT N'Altering [sIp].[tStockItemMaster]...';


GO
ALTER TABLE [sIp].[tStockItemMaster] ALTER COLUMN [Code] NVARCHAR (50) NULL;


GO
PRINT N'Creating [sAdmission].[tAdmissionInquiryCriteria]...';


GO
CREATE TABLE [sAdmission].[tAdmissionInquiryCriteria] (
    [ClassId]   INT NOT NULL,
    [BatchId]   INT NOT NULL,
    [IsPublish] BIT NULL
);


GO
PRINT N'Creating [sCommon].[tSubmitDocumentScope]...';


GO
CREATE TABLE [sCommon].[tSubmitDocumentScope] (
    [SubmitDocumentId] INT      NOT NULL,
    [SourceTypeId]     SMALLINT NOT NULL,
    [SourceId]         BIGINT   NOT NULL
);


GO
PRINT N'Creating [sFee].[tEMandateDetail]...';


GO
CREATE TABLE [sFee].[tEMandateDetail] (
    [Id]                     SMALLINT       NOT NULL,
    [UtilCode]               NVARCHAR (50)  NOT NULL,
    [Short_Code]             NVARCHAR (50)  NOT NULL,
    [Merchant_Category_Code] NVARCHAR (50)  NOT NULL,
    [URL]                    NVARCHAR (500) NOT NULL
);


GO
PRINT N'Creating PK_tEMandateDetail...';


GO
ALTER TABLE [sFee].[tEMandateDetail]
    ADD CONSTRAINT [PK_tEMandateDetail] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);

 

GO


 
GO
PRINT N'Altering [sAlert].[fPeriodWiseAttendanceGet]...';


GO
ALTER FUNCTION [sAlert].[fPeriodWiseAttendanceGet](@rAcademicId bigint,@rSubjectId nvarchar(max), @rAttendanceDate date,@OrgId int)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @lSubjectName  VARCHAR(MAX)
Declare @v Table 
(
Id int IDENTITY,
SubjectId int
)
INSERT INTO @v
SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rSubjectId,',')

--Select * from #tmp

DECLARE @lCountSubjectId int,@lId int,@lSubjectId bigint

SELECT @lCountSubjectId=COUNT(Id) FROM @v
SELECT Top 1 @lId=Id FROM @v
DECLARE @lfinalResult  VARCHAR(MAX)=''
DECLARE @lResult  VARCHAR(MAX)=''
WHILE @lId <= @lCountSubjectId

			BEGIN
		
				SELECT @lSubjectId=SubjectId FROM @v WHERE Id=@lId
			
				SELECT @lSubjectName=Code from [sSetup].[tSubjectMaster] Where Id=@lSubjectId
				SET @lResult= @lSubjectName +':'
				(SELECT @lResult  = COALESCE(@lResult ,'') + ' P '
							+ CONVERT(VARCHAR(11),SR.PeriodNo,106) + ' - ' +
							(
							CASE  
							WHEN SR.IsPresent = 0 THEN 'Ab'
							WHEN  SR.IsPresent = 1 then 'Pr'
							END)
								+ ' , '
					from 
					sStudent.vStudentCommunication SC
					INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
					INNER JOIN [sSetup].[tSubjectMaster] SM ON SR.SubjectId=SM.Id 	
					WHERE (SC.OrgId=@OrgId) AND SR.AcademicId=@rAcademicId AND SubjectId=@lSubjectId AND AttendanceDate=@rAttendanceDate
						)
		
				  
				  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)

				  --Select @lResult
				  SET @lfinalResult=@lfinalResult + @lResult
				  --Set  @lResult1= '       '+ @lSubjectName +':' + @lResult
				  --Select @lResult1
				SET @lId=@lId+1
			END

--DROP TABLE #tmp

  RETURN  @lfinalResult

END
GO
PRINT N'Creating [sStudent].[fStudentDocumentClasswiseget]...';


GO
 
CREATE FUNCTION [sStudent].[fStudentDocumentClasswiseget] (@rDocumentId int,@rAcademicId bigint)
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS 
BEGIN

 DECLARE @lClassId int
 DECLARE @lStudentId bigint

 SELECT @lClassId = ClassId,@lStudentId = StudentId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
      DECLARE @rDocumentName Nvarchar(max)
      BEGIN
		SELECT @rDocumentName = ISNULL(STUFF(
			 (SELECT DISTINCT ',' + DocumentName FROM (SELECT DISTINCT SDM.DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @lClassId
			  where SD.StudentId=@lStudentId AND SDM.SubmitDocumentFunctionalityId = 1 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))

			  UNION ALL

			  SELECT DISTINCT SDM.DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			  LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id
			  where SD.StudentId=@lStudentId AND SDM.SubmitDocumentFunctionalityId = 1 AND DS.SubmitDocumentId is null  AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0)))
			  AS DocumentName
			  FOR XML PATH (''))
			  , 1, 1, ''),'')             
                                    
      END

     
      RETURN @rDocumentName
END
GO
PRINT N'Altering [sConfig].[fDisplayFieldGet]...';


GO


ALTER FUNCTION [sConfig].[fDisplayFieldGet](@rOrgId int)
RETURNS  @List TABLE (
		-- DisplayFieldId smallint,
		 IsDisplayFamilyDetail bit,
		 IsDisplaySiblingDetail bit,
		 IsDisplayPassportDetail bit,
		 IsDisplayBankDetail bit,
		 IsDisplayCBSEREGDetail bit,
		 IsDisplayCollegeDetail bit,
		 IsDisplayGOVREGNoDetail bit,
		 IsDisplayHealthDetail bit,
		 IsDisplayTransportDetail bit,
		 IsDisplayHostelDetail bit,
		 IsDisplayClubDetail bit,
		 IsDisplaySSCResultDDetail bit,
		 IsDisplayHSCResultDetail bit,
		 IsDisplayJeeDetail bit,
		 IsDisplayDiplomaDetail bit,
		 IsDisplayClassTeacherDetail bit,
		 OrgId smallint 
)  WITH EXECUTE AS CALLER
AS 
BEGIN

    declare @rDisplayFieldId smallint 
    declare @rIsDisplayFamilyDetail bit
    declare @rIsDisplaySiblingDetail bit 
    declare @rIsDisplayPassportDetail bit
    declare @rIsDisplayBankDetail bit 
    declare @rIsDisplayCBSEREGDetail bit 
    declare @rIsDisplayCollegeDetail bit 
    declare @rIsDisplayGOVREGNoDetail bit 
    declare @rIsDisplayHealthDetail bit 
    declare @rIsDisplayTransportDetail bit 
    declare @rIsDisplayHostelDetail bit 
    declare @rIsDisplayClubDetail bit 
    declare @rIsDisplaySSCResultDDetail bit 
    declare @rIsDisplayHSCResultDetail bit 
    declare @rIsDisplayJeeDetail bit 
    declare @rIsDisplayDiplomaDetail bit 
    declare @rIsDisplayClassTeacherDetail bit

	select @rIsDisplayFamilyDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 101
	select @rIsDisplaySiblingDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 102
	select @rIsDisplayPassportDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 103
	select @rIsDisplayBankDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 104
	select @rIsDisplayCBSEREGDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 105
	select @rIsDisplayCollegeDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 106
	select @rIsDisplayGOVREGNoDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 107
	select @rIsDisplayHealthDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 108
	select @rIsDisplayTransportDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 109
	select @rIsDisplayHostelDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 110
	select @rIsDisplayClubDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 111
	select @rIsDisplaySSCResultDDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 112
	select @rIsDisplayHSCResultDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 113
	select @rIsDisplayJeeDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 114
	select @rIsDisplayDiplomaDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 115
	select @rIsDisplayClassTeacherDetail=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 117

		 
	 	
	INSERT INTO @List 
	SELECT 
			
			
		   (CASE WHEN @rIsDisplayFamilyDetail Is Null THEN  0 ELSE 1 END) AS IsDisplayFamilyDetail,
		   (CASE WHEN @rIsDisplaySiblingDetail Is Null THEN 0 ELSE 1 END)AS IsDisplaySiblingDetail,
		   (CASE WHEN @rIsDisplayPassportDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayPassportDetail,
		   (CASE WHEN @rIsDisplayBankDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayBankDetail,
		   (CASE WHEN @rIsDisplayCBSEREGDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayCBSEREGDetail,
		   (CASE WHEN @rIsDisplayCollegeDetail Is Null THEN 0  ELSE 1 END)AS IsIsDisplayCollegeDetail,
		   (CASE WHEN @rIsDisplayGOVREGNoDetail Is Null THEN 0 ELSE  1 END)AS IsDisplayGOVREGNoDetail,
		   (CASE WHEN @rIsDisplayHealthDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayHealthDetail,
		   (CASE WHEN @rIsDisplayTransportDetail Is Null THEN 0 ELSE  1 END)AS IsDisplayTransportDetail,
		   (CASE WHEN @rIsDisplayHostelDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayHostelDetail,
		   (CASE WHEN @rIsDisplayClubDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayClubDetail,
		   (CASE WHEN @rIsDisplaySSCResultDDetail Is Null THEN 0  ELSE 1 END)AS IsDisplaySSCResultDDetail,
		   (CASE WHEN @rIsDisplayHSCResultDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayHSCResultDetail,
		   (CASE WHEN @rIsDisplayJeeDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayJeeDetail,
		   (CASE WHEN @rIsDisplayDiplomaDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayDiplomaDetail,
		   (CASE WHEN @rIsDisplayClassTeacherDetail Is Null THEN 0  ELSE 1 END)AS IsDisplayClassTeacherDetail,
		   @rOrgId AS OrgId
		  
	 
    RETURN  
    
END
GO

 
GO
PRINT N'Altering [sAlert].[pAppRegisteredUserGet]...';


GO
 
 
ALTER PROCEDURE [sAlert].[pAppRegisteredUserGet]
	@rOrgId int,
	@rOSTypeId tinyint=0,	
	@rFromDate date,
	@rToDate date,
	@rDepartmentId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rCode nvarchar(20)='',
	@rUserSourceTypeId smallint	,
	@rOrgGroupId int=0,
	@rStatusId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
if(@rUserSourceTypeId=2003)
BEGIN
SELECT 
	OM.Title AS OrganizationName,
	OM.Id AS OrgId,
	RU.UserId AS UserId,
	RU.UserSourceId AS UserSourceId,
	RU.UserSourceTypeId AS UserSourceTypeId,
	'Student' AS UserTypeName,
	SA.Code AS Code,
	SA.ClassName + ' - ' + SA.DivisionName AS Class,
	SA.Name AS Name,
	RU.CreatedDateTime AS Date,
	OT.Title AS OSType,
	RU.OSTypeId AS OSTypeId,
	SA.DepartmentName AS Department,
	CONVERT(bit,CASE WHEN ISNULL(RU.DeviceToken,'') = '' THEN 0 ELSE 1 END) AS IsDeviceToken,
	ISNULL(RU.DeviceToken,'') AS DeviceToken,
	ISNULL(RU.AppVersion,'') AS AppVersion
	FROM		
		sCommunication.tRegisteredUsers RU
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=RU.OrgId				
		INNER JOIN sAlert.tOSType OT ON OT.ID =RU.OSTypeId											
		INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId = RU.UserSourceId AND RU.UserSourceTypeId=2003	
	WHERE
	    ((RU.OrgId = @rOrgId) OR (@rOrgId=0))
		AND((RU.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))		
		AND((SA.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
	    AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CONVERT(date,RU.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,RU.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))	
		AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
		AND ((SA.StatusId = @rStatusId) OR (@rStatusId=0))
	ORDER BY RU.OrgId,RU.OSTypeId,RU.UserId ASC,RU.CreatedDateTime DESC	
END
ELSE
BEGIN
SELECT 
	OM.Title AS OrganizationName,
	OM.Id AS OrgId,
	RU.UserId AS UserId,
	RU.UserSourceId AS UserSourceId,
	RU.UserSourceTypeId AS UserSourceTypeId,
	'Employee' AS UserTypeName,
	Emp.Code  AS Code,
	Emp.DepartmentName As Department,	
	Emp.FirstName +  ' ' + Emp.LastName AS Name,
	RU.CreatedDateTime AS Date,
	OT.Title AS OSType,
	RU.OSTypeId AS OSTypeId,
	'' AS Class,
	CONVERT(bit,CASE WHEN ISNULL(RU.DeviceToken,'') = '' THEN 0 ELSE 1 END) AS IsDeviceToken,
	ISNULL(RU.DeviceToken,'') AS DeviceToken,
	ISNULL(RU.AppVersion,'') AS AppVersion
	FROM		
		sCommunication.tRegisteredUsers RU
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=RU.OrgId				
		INNER JOIN sAlert.tOSType OT ON OT.ID =RU.OSTypeId			
		
	    INNER JOIN sHrm.vExtEmployeeMaster Emp ON Emp.Id = RU.UserSourceId AND RU.UserSourceTypeId=95	    												
	WHERE
	((RU.OrgId = @rOrgId) OR (@rOrgId=0))
		AND((RU.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))	
	    AND((Emp.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND ((Emp.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CONVERT(date,RU.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,RU.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))	
		AND (OM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) 
		AND ((Emp.StatusId = @rStatusId) OR (@rStatusId=0))
		ORDER BY RU.OrgId,RU.OSTypeId,RU.UserId ASC,RU.CreatedDateTime DESC	
END
END
GO
PRINT N'Altering [sAlert].[pSubjectwiseStudentAttendanceStatusGet]...';


GO

ALTER PROCEDURE [sAlert].[pSubjectwiseStudentAttendanceStatusGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 --@rSubjectId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 --@rIsPresent bit,
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--SET @rToDate = dateadd(d,1,@rToDate)
	CREATE TABLE #TMP 
	(
	AcademicId bigint,
	Code nvarchar(20),
	Name nvarchar(300),
	MobileNo nvarchar(50),
	EmailId nvarchar(50),
	SubjectId bigint,
	AttendanceDate Date,
	DivisionName nvarchar(100)
	)
	INSERT INTO #TMP
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			SR.SubjectId,
			SR.AttendanceDate,
			DM.Code
					
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SR.SubjectId=SM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON SC.DivisionId=DM.Id
			
	WHERE
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		--AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--AND (SR.IsPresent = @rIsPresent)
		AND	SC.AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tStudentLeaveRequest WHERE LeaveFromDate = @rFromDate AND LeaveToDate=@rToDate)
		AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
		GROUP BY SC.AcademicId,SC.Code,SC.Name,SC.ParentContactNo,	SC.ParentEmail,SR.SubjectId,SR.AttendanceDate,DM.Code
   --ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.Rollno
   --Select * from #TMP
   Select 
   			AcademicId,
			Code,
			Name,
			MobileNo,	
			EmailId,
			AttendanceDate,
			replace (
			replace (
			replace(@rTemplate,'[Name]',tmp.Name),
			--'[Class]',ClassName),
			'[Division]',tmp.DivisionName),
			--'[AbsentDates]',SR.AttendanceDate),
			'[SubjectLectureStatusReason]', CHAR(13) +[sAlert].[fPeriodWiseAttendanceGet](tmp.AcademicId,STUFF(
                 (SELECT ',' + CONVERT(VARCHAR,tmp1.SubjectId) FROM #TMP tmp1
				  WHERE tmp1.AcademicId=tmp.AcademicId 
				  FOR XML PATH ('')), 1, 1, ''
               ),AttendanceDate,@rOrgId))
			AS MsgText,
			[sAlert].[fPeriodWiseAttendanceGet](tmp.AcademicId,STUFF(
                 (SELECT ',' + CONVERT(VARCHAR,tmp1.SubjectId) FROM #TMP tmp1
				  WHERE tmp1.AcademicId=tmp.AcademicId 
				  FOR XML PATH ('')), 1, 1, ''
               ),AttendanceDate,@rOrgId),
			   @rMailSubject AS Subject
		
    from #TMP tmp
	GROUP BY AcademicId,Code,Name,MobileNo,EmailId,AttendanceDate,DivisionName

	DROP TABLE #TMP
END
GO
PRINT N'Altering [sAttendance].[pStudentLeaveRequestAdd]...';


GO
 
ALTER PROCEDURE [sAttendance].[pStudentLeaveRequestAdd] 
	 
	 	@rAcademicId bigint,
        @rLeaveFromDate date,
        @rLeaveToDate date,
        @rLeaveReason nvarchar(200),
        @rCreatedUserId bigint 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	IF EXISTS(SELECT 1 FROM sAttendance.tStudentLeaveRequest WHERE AcademicId = @rAcademicId 
	   AND(( LeaveFromDate  BETWEEN @rLeaveFromDate AND @rLeaveToDate) OR (LeaveToDate BETWEEN @rLeaveFromDate AND @rLeaveToDate)
	   OR (@rLeaveFromDate  BETWEEN LeaveFromDate AND LeaveToDate) OR (@rLeaveToDate BETWEEN LeaveFromDate AND LeaveToDate)))
	BEGIN
		SELECT -11 AS RESULT
	END
	ELSE
	BEGIN
	 
	INSERT INTO sAttendance.tStudentLeaveRequest
		(
			AcademicId,
			LeaveFromDate,
			LeaveToDate,
			LeaveReason,
			CreatedUserId,
			CreatedDateTime 
		)
	VALUES
		(
			@rAcademicId,
			@rLeaveFromDate,
			@rLeaveToDate,
			@rLeaveReason, 
			@rCreatedUserId,
			sCommon.fGetDate()
		)
	Select 1 As Result	 
	END
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCertificate].[pRptLeavingCertificateGet]...';


GO

 
ALTER PROCEDURE [sCertificate].[pRptLeavingCertificateGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rLCNumber nvarchar(20)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromDate date='',
     @rToDate date='',
     @rCode nvarchar(20)='',
     @rName nvarchar(20)='',
	 @rUserName nvarchar(100)=''
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lIsOnPrePrinted bit = 0,@lIsDisplayReligion bit=0,@lConfigValue nvarchar(50),@lIsDisplayImageHeader bit = 0,@lOrgId smallint

DECLARE @lSchoolRemark1  nvarchar(500)
DECLARE @lSchoolRemark2  nvarchar(500)
DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0

Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId


SELECT @lOrgId=RG.OrgId,
@lSchoolRemark1 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark1,'')  ELSE RG.SchoolRemark1 END,
@lSchoolRemark2= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark2,'')  ELSE RG.SchoolRemark2 END,
@lSchoolRemark3 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark3,'')  ELSE RG.SchoolRemark3 END,
@lSchoolRequiredSignature= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRequiredSignature,'')  ELSE RG.SchoolRequiredSignature END 
 
FROM sCommon.tReportRemarkGroupMaster RGM LEFT JOIN sCommon.tReportRemarkGroupOrg RG ON RGM.Id = RG.ReportRemarkGroupId AND RG.OrgId = @rOrgId AND RG.ReportRemarkGroupId=3 WHERE RGM.Id=3
 
--WHERE  RG.OrgId=@rOrgId AND RG.ReportRemarkGroupId=3
 
--IF(@lOrgId IS NULL)
--BEGIN
--SELECT @lSchoolRemark1=DefaultRemark1,@lSchoolRemark2=DefaultRemark2,@lSchoolRemark3=DefaultRemark3,@lSchoolRequiredSignature=DefaultRequiredSignature FROM sCommon.tReportRemarkGroupMaster WHERE Id=3 
--END 


SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 178 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	
	
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--MR.PresentCount AS PresentDays ,
			--MR.TotalCount AS TotalDays ,
			L.Id,
			--(SELECT SUM(MR.PresentCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS PresentDaysSum ,
			--(SELECT SUM(MR.TotalCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS TotalDaysSum ,
			SM.Code,
			L.AcademicId,
			SM.FirstName,SM.MiddleName,SM.LastName,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			--0 As CastCategoryId,
			--ISNULL(SO.CastCategoryId,0) As CastCategoryId,
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			SA.PreviousSchool,
			SA.AdmissionDate,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			SO.GenderId,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(SC.PresentState,'') AS CityState,
			CM.DisplayTitle AS AdmissionStandard,
			CMS.DisplayTitle AS CurrentStandard,
			CMS.Title AS CurrentStandardTitle,
			--'' AS CurrentStandardInWords,
			SM.StatusId,
			L.LastExamName AS Result,
			L.LastExamResult AS FailOrPass,
			L.SubjectStudied AS SubjectNAme,
			L.RepeatDetail as PromotedorNot,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			--'' AS PromotedorNot,
			L.PromoteToClass  AS PromotedToClass,
			L.FeeDetail AS LastFeesPaid,
			L.FeeConcessionDetail AS AnyConcession,
			L.NCCScoutDetail  AS NCCScoutDetail,
			L.ExtraCurricularActivities AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			AD.PresentDaysAnnual AS PresentDaysSum,
			AD.TotalDaysAnnual AS TotalDaysSum,
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(L.ToCollege,'') AS ToCollege ,
			ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
			ISNULL(OM.University,'')AS University,
			@lSchoolRemark1 AS SchoolRemark1 ,
			@lSchoolRemark2 AS SchoolRemark2 ,
			@lSchoolRemark3 AS SchoolRemark3 ,
			@lSchoolRequiredSignature AS SchoolRequiredSignature,
			ISNULL(CSG.Inword,'')AS CurrentStandardInWords,
			SO.MotherTongue,
			SO.AdhaarNumber,
			vSA.SUId,
			CASE WHEN isnull(BM.FromDate,'')>Isnull(SA.AdmissionDate,'') THEN BM.FromDate ELSE SA.AdmissionDate END AS BatchDate,
			SO.BirthState,
			SO.BirthCountry,
			SD.BankAccountNumber,
			SO.UIDNumber,
			SD.BankName,
			SD.BankIFSCCode,
			SA.PreviousStandard 
			,L.TermsInInstitute,
			@lIDConfigValue AS ItemValue 
			,L.LCCopy
			,DM.InchargeEmployeeId AS ClassTeacher
			,vSA.BatchName AS BatchName,
			CSM.Title As CasteCategory,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SI.StudentPhoto,
			SA.AdmissionFormNumber,
			BM.FromDate as BatchStartDate,
			BM.ToDate as BatchEndDate,
			SO.UIDNumber,
			SC.PresentStreetOne AS Address1,
			SC.PresentStreetTwo AS Address2,
			SC.PresentStreetThree AS Address3,
			SC.PresentCity AS PresentCity,
			SC.PresentZipCode AS PresentZipCode,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			L.TotalDays,
			L.PresentDays,
			ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
		--sFinanceCommon.fNumberToWords(ISNULL(CM.ClassGroupId,0),'',OM.OrgGroupId) AS CurrentStandardInWords
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.PresentCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.PresentCount,0))
		--END AS Presentdays,
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.TotalCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.TotalCount,0))
		--END AS TotalCount
		@rUserName AS UserName,
		EI.EmployeeSign,
		EI1.EmployeeSign AS DivisionInchargeEmployeeSign,
		ISNULL(L.ProofOfDOB,'')AS ProofOfDOB
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			--INNER JOIN sStudent.tAcademic A ON L.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			--LEFT JOIN  sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id 
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			--AND BM.OrgGroupBatchId=vSA.OrgGroupBatchId
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sSetup.tDivisionInchargeEmployee DIE ON vSA.DivisionId = DIE.DivisionId AND DIE.BatchId = vSA.BatchId
			LEFT JOIN sHrm.tEmployeeImages EI1 ON EI1.EmployeeId = DIE.EmployeeId
	WHERE 
				L.OrgId=@rOrgId
				AND	vSA.BatchId = @rBatchId 
				AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
				AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				--AND ((L.LCDate=@rLCDate) OR (ISNULL(@rLCDate,'')=''))
				--AND ((L.LeftDate=@rLeftDate) OR (ISNULL(@rLeftDate,'')=''))
				--AND ((L.LCCopy=@rLCCopy) OR (@rLCCopy=0))
				--AND ((L.LCBookNumber=@rLCBookNumber) OR (@rLCBookNumber=''))
				AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
				AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
				AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
				AND ((DM.ClassId=@rClassId) OR(@rClassId=0))
				--group by MR.PresentCount,MR.TotalCount, SubM.Title, SM.Code,L.AcademicId,SM.FirstName,SM.LastName,SM.MiddleName,SF.FatherName,SF.MotherName,NM.Title,
				--SO.CastCategoryId,RM.Title,so.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,SO.DateOfBirth,SO.BirthDateInWord,SA.PreviousSchool,
				--	SA.AdmissionDate,L.LeftDate,L.LCReason,L.LCProgress,L.LCConduct,L.LCRemark,L.LCDate,SO.GenderId,
				--	OM.CityName,OM.StateName,CM.DisplayTitle,CMS.DisplayTitle,SM.StatusId,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
END
GO
PRINT N'Altering [sCommon].[pOrganizationSetupRemove]...';


GO
 
ALTER PROCEDURE [sCommon].[pOrganizationSetupRemove]
	 
	 @rOrgId bigint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
  --  BEGIN TRY
	
	 --BEGIN TRANSACTION
	 
	 --EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    
DELETE FROM sAccounting.tExpense WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tExpenseGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursementDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursementTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tActivity WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tActivityParticipant WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tAssignClub WHERE CAST(LEFT(ClubId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tEventAssign WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tEventEnrollment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tEventSchedule WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupAssign WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupDetail WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupParameter WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupStudent WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterList WHERE CAST(LEFT(HealthParameterId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthTrack WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tHouseMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tPlacement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tPlacementInvite WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tStudentImmunizationStatus WHERE CAST(LEFT(ImmunizationChartId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionForm WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormIssue WHERE OrgId = @rOrgId
DELETE FROM sAdmission.tAdmissionInquiry WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tAlertConfiguration WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tAlertLog WHERE OrgId = @rOrgId
DELETE FROM sAlert.tAlertQueue WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tAlertQueueDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tCustomTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tDepartmentRecipient WHERE CAST(LEFT(DepartmentId, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tEmailConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tEventTemplate WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tExternalRecipientMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tSMSConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSClass WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSIndicatorGrade WHERE CAST(LEFT(CCECSId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSScore WHERE CAST(LEFT(CCECSId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamMapping WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamSetting WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEFAGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAScore WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCEFASubject WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEResult WHERE AcademicId = @rOrgId
DELETE FROM sAssessment.tCCEResultDetail WHERE AcademicId = @rOrgId
DELETE FROM sAssessment.tExamCombine WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamStatus WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tExamsubgroupmaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tGeneralExamCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tGradeSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tGradeSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tLevelSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tLevelSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tOptionalSubject WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tRankSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tRankSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tResult WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAudit WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAuditDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tDepartmentLocation WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMaintenence WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMovement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMovementDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tRecordManualEvent WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tApplicableAttendanceType WHERE OrgId = @rOrgId
DELETE FROM sAttendance.tMonthlyRegister WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tMonthlySetup WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tStudentRegister WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tStudentSetup WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tSubjectBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tSubjectBatchStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAudit WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAuditLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAuditLogTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTable WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTableField WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAction WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tActionStatusMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tActionTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAudit WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tAuditLocation WHERE CAST(LEFT(AuditId, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tAuditReasonMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAuditStatusMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAuditTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tDocument WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tDocumentTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tFinding WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tFindingTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tInspection WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tQuestionAnswerMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionAnswerTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionMainGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionnairesMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionResponse WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tQuestionSubGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tSeverityMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBiometric.tPunchMaster WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sCertificate.tBonafide WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCertificate.tCharacter WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tFirstTrial WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCertificate.tLeaving WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tAgeGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tClinicMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId


DELETE FROM sCommon.tDurationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tExceptions WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sCommon.tFileUpload WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tFirstAidMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tFunctionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tLocationMaster WHERE OrgId = @rOrgId
DELETE FROM sCommon.tOrganizationDepartmentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPrefixSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPublicHolidayMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPublicHolidayTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tReasonMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tReportFormatGroupOrg WHERE OrgId = @rOrgId
 
DELETE FROM sCommunication.tAssignment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignmentScope WHERE CAST(LEFT(AssignmentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignmentView WHERE CAST(LEFT(AssignmentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignTask WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tBehaviour WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussion WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionComment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionGroup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionGroupMember WHERE CAST(LEFT(DiscussionGroupId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tPhotoCategoryOrg WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tQueryCategoryOrg WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tUploadBookLog WHERE CAST(LEFT(BookLogId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tUploadResult WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tColorLegendDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tConfigurationSetup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId AND SourceTypeId <> 2010
DELETE FROM sConfig.tCultureConfiguration WHERE OrgId = @rOrgId
DELETE FROM sConfig.tImport WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sConfig.tLocalDeviceSetting WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tMachineMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tMachinePrinterMapping WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tPrinterMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sEExam.tTestAssign WHERE CAST(LEFT(TestId, 4) AS int) = @rOrgId
DELETE FROM sEExam.tTestMaster WHERE OrgId = @rOrgId
DELETE FROM sEExam.tTestParticipant WHERE CAST(LEFT(TestId, 4) AS BIGINT) = @rOrgId
DELETE FROM sEExam.tTestParticipantAnswer WHERE CAST(LEFT(TestId, 4) AS INT) = @rOrgId
DELETE FROM sEExam.tTestQuestion WHERE CAST(LEFT(TestId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tChargeReceipt WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tChargeReceiptDetail WHERE CAST(LEFT(ChargeReceiptId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeAllocation WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeOptional WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tReceipt WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tReceiptDetail WHERE CAST(LEFT(ReceiptId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFixedAsset.tCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFixedAsset.tLocationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFrontOffice.tVisitorLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tActivityIndicatorScore WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tAnusuchiB WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tClassActivity WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tExamSetting WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tGSEBExamMapping WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tHetuMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tAnusuchiB WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResult WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResultDetail WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResultDetailOptional WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tSubjectIndicatorMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tAssignRoom WHERE CAST(LEFT(RoomId, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tHostelWarden WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeAttendance WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeCommunications WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeDesignationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeFamilyDetails WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeGradeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeImages WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeJobDetail WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeePersonalDetail WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeePreviousEmployment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeStatutoryAndOther WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tGuestMaster WHERE OrgId = @rOrgId
DELETE FROM sHrm.tLeave WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tLeaveTypeGradeSettings WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sHrm.tLeaveTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tWorkingDays WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sIp.tBinMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tItemStandardPriceLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tStockItemBin WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tStockItemPlanning WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tStockItemPurchaseUom WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tWeightedAverageCostLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tAssignOrganization WHERE OrgId = @rOrgId
DELETE FROM sLibrary.tBookLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tBookLogPenalty WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tBooksForClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sLibrary.tIssueSetting WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sOmr.tAnswerKeySetup WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tExamSetup WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tScanHistory WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sOmr.tSetting WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sOmr.tSheetCallibration WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tTempAnsKeyAnalysis WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tIssueReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tIssueReturnDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tOrderEntry WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sOrderEntry.tOrderEntryBatch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sOrderEntry.tServiceItemTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tFirstAidEmoloyee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidEmployeeDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidInspection WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidInspectionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNote WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturnBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturnDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tPurchaseOrder WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tPurchaseOrderDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustmentBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAudit WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAuditDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockFreezeAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockFreezeAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInward WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardReturnBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssue WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockItemFreeze WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockTransfer WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockVerification WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockVerificationApproval WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSecurity.tDivisionPermission WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tLdapUser WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUser WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserAccess  WHERE CAST(LEFT(UserId, 4) AS int) = @rOrgId
DELETE FROM sSecurity.tUserFavoriteScreen WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserLocation WHERE CAST(LEFT(StoreLocationId, 4) AS INT) = @rOrgId
DELETE FROM sSecurity.tUserLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserOrganization WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSecurity.tUserPreference WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserProfile WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserRole WHERE CAST(LEFT(UserId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId
DELETE FROM sSetup.tClassMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tClassSubject WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDepartmentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDivisionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
 
DELETE FROM sSetup.tReportConfiguration WHERE OrgId = @rOrgId
DELETE FROM sSetup.tReportSetting WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSetup.tSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tTermMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tAcademic WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tAcademicDetail WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentAdmission WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentCommunication WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentFamily WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentHealth WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentImages WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentOther WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tContactMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tContactTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tImageMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tImageTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tLinkMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tVideoMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tVideoTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTax.tTaxRateSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tDivisionWorkLoad WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tProxySetting WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTeacherWorkLoad WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeSetup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeTable WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeTableSchema WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTransport.tAssignRoute WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCECSExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEFAExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamCombineTerm WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tGradeSujbectExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tStudentRemark WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tSubjectIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tTempAllExam
DELETE FROM sAssessment.tTempCoScholasticExam

DELETE FROM sFee.tAccountMapping WHERE CAST(LEFT(FeeSetupId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tDepositAdd WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tDepositAdjustment WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tDepositBalance WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tDepositRefund WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipEligibleStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipMaster WHERE CAST(LEFT(BatchId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipReceive WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipStudentPaid WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSetup.tYearChangeDivisionMapping WHERE CAST(LEFT(OldDivisionId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tClasswork WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tLessonPlan WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tLessonPlanResource WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tTopicMaster WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tPrintTemplate WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tPrintTemplateStudent WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tStudentGatePass WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tFeeHeadOrgwise WHERE OrgId = @rOrgId
DELETE FROM sFee.tReceiptBookOrgwise WHERE OrgId = @rOrgId

DELETE FROM sAcademic.tTeacherSubject WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tTeacherSubjectDivision WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionCriteriaMaster WHERE OrgId = @rOrgId
--DELETE FROM sAdmission.tAdmissionCriteriaStudent WHERE CAST(LEFT(AdmissionSetupId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormSelected WHERE CAST(LEFT(AdmissionFormId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionSetup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tFilterCriteria WHERE OrgId = @rOrgId
DELETE FROM sAttendance.tFilterCriteriaDetail WHERE CAST(LEFT(FilterCriteriaId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tYearlyRegister WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tWinfeeDetail WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeAttendanceRegister WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeICardOrg WHERE OrgId = @rOrgId
DELETE FROM sSecurity.tUserDashlet WHERE CAST(LEFT(UserId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tICardOrg WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionSetupStudent WHERE CAST(LEFT(AdmissionSetupId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSForClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tActivityLog WHERE CAST(LEFT(OrgId, 4) AS INT)  = @rOrgId
DELETE FROM sAudit.tReceiptDelete WHERE BatchId = @rOrgId
DELETE FROM sAudit.tReceiptDetailDelete WHERE CAST(LEFT(ReceiptId, 4) AS INT) = @rOrgId

DELETE FROM sCommunication.tViewResult WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tViewResultDetail WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrgInfo WHERE OrgId = @rOrgId

DELETE FROM sStudent.tStudentCustomTag WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionCriteria WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormFamilyDetail WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormParentAcademic WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormReference WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormSibling WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormStudentAcademic WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCESubjectActivityMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCESubjectSubActivityExamScore WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCESubjectSubActivityMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tResultAnalysis WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDetail WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tReportOrg WHERE ScopeSourceId = @rOrgId AND ScopeSourceTypeId = 2021
DELETE FROM sAssessment.tCCESubjectSubActivityIndicatorMaster WHERE  OrgId = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDivision WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDivisionDetail WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFrontOffice.tStudentGatePass WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgCalander WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgDrive WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgYouTube WHERE OrgId = @rOrgId
DELETE FROM sHrm.tLeaveBalance WHERE CAST(LEFT(BatchId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceAdd WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sTimetable.tAssignTeacher WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sTimetable.tDivision WHERE CAST(LEFT(OrgId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tSubject WHERE CAST(LEFT(OrgId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tSubjectTimeOff WHERE CAST(LEFT(SubjectId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTeacher WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeQualification WHERE OrgId = @rOrgId
DELETE FROM sSecurity.tUserDashboardNotification WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sTransport.tAssignTransportOrg WHERE OrgId = @rOrgId

--DELETE FROM sFee.tOnlinePayment WHERE  CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
--DELETE FROM sFee.tOnlinePaymentDetail WHERE  CAST(LEFT(OnlinePaymentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tReceiptRefund WHERE  CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tReceiptRefundDetail WHERE  CAST(LEFT(ReceiptRefundId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformIssue WHERE  CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformIssue WHERE  CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformItemForClass WHERE  CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sIp.tUniformOrder WHERE  CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformOrderDetail WHERE  CAST(LEFT(UniformOrderId, 4) AS BIGINT) = @rOrgId
 
DELETE FROM sFee.tFeeInvoice WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tFeeInvoiceDetail WHERE CAST(LEFT(FeeInvoiceId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFee WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeDetail WHERE CAST(LEFT(OnlineFeeId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tCertificateEmployment WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sOp.tPaymentTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrgImages WHERE OrgId = @rOrgId
DELETE FROM sStudent.tStudentadditional WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tStudentBatchStatus WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId

DELETE FROM sCommon.tPrefixConfig WHERE OrgId = @rOrgId
DELETE FROM sConfig.tDisplayFieldOrg WHERE OrgId = @rOrgId
DELETE FROM sHrm.tCertificateExperience WHERE OrgId = @rOrgId
DELETE FROM sHrm.tCertificateRelieving WHERE OrgId = @rOrgId
DELETE FROM sRFID.tAttendance WHERE OrgId = @rOrgId
DELETE FROM sRFID.tRegistration WHERE CAST(LEFT(RegistrtionId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchClassLecture WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tStudentSibling WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tTranscriptAssessment WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sTally.tStudentLedgerMapping WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

/* -- Date : 13/06/2016 -- */
DELETE FROM sActivity.tEventAttendance WHERE CAST(LEFT(SourceId, 4) AS INT) = @rOrgId
DELETE FROM sCanteen.tAssignOrganization WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tRegisteredUsers WHERE OrgId = @rOrgId
DELETE FROM sStudent.tCollegeDetail WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

-- 15.7.2016
DELETE FROM sFrontOffice.tInwardRegister WHERE OrgId = @rOrgId
DELETE FROM sFrontOffice.tOutwardRegister WHERE OrgId = @rOrgId
DELETE FROM sSetup.tSubjectGroupMaster WHERE OrgId = @rOrgId

/* -- Date : 12/08/2016 -- */
DELETE FROM sAssessment.tExamCombineSubject WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tResultDetailOther WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDivisionInchargeEmployee WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tEnrollmentStatusOrg WHERE OrgId = @rOrgId
DELETE FROM sStudent.tEnrollmentStatusStudent WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tLinkSibling WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

/* -- Date : 17/09/2016 -- */

DELETE FROM sAssessment.tTempAllExamSubjectActivity WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tTempAttendance WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId

/* -- Date : 05/10/2016 -- */

DELETE FROM sAdmission.tAdmissionInquiryFollowup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
--DELETE FROM sAssessment.tStaticCCECSGroupMaster WHERE OrgId = @rOrgId
--DELETE FROM sAssessment.tStaticCCECSMaster WHERE OrgId = @rOrgId

/* -- Date : 20/10/2016 -- */

DELETE FROM sAssessment.tOptionalCCECS WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId

/* -- Date : 24/11/2016 -- */
DELETE FROM sBiometric.tMonthTrans WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId

/* -- Date : 23/12/2016 -- */
DELETE FROM sAdmission.tAdmissionFormReceipt WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamStatus WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tAttendanceGroup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tAttendanceGroupStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tAccountPosting WHERE CAST(LEFT(AccountId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceAddRequest WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId

/* -- Date : 14/02/2017 -- */

DELETE FROM sCRM.tChannelPartnerMaster WHERE OrgId = @rOrgId
DELETE FROM sCRM.tInstituteGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sCRM.tInstituteMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrganizationOtherDetail WHERE OrgId = @rOrgId

DELETE FROM sAppraisal.tConduct WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tAllBatchClassGroup WHERE OrgId= @rOrgId
DELETE FROM sAssessment.tAllBatchResult WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tAllBatchSubject WHERE OrgId= @rOrgId
DELETE FROM sHrm.tEmployeeTravel WHERE OrgId= @rOrgId


DELETE FROM sLoan.tLoanDetail WHERE OrgId= @rOrgId
DELETE FROM sLoan.tLoanEMI WHERE CAST(LEFT(LoanDetailId, 4) AS BIGINT) = @rOrgId
DELETE FROM sLoan.tLoanPayrollMapping WHERE OrgId= @rOrgId
DELETE FROM sLoan.tLoanTypeMaster WHERE OrgId= @rOrgId
DELETE FROM sPayroll.tPayrollCustomSearch WHERE OrgId= @rOrgId
DELETE FROM sErp.tChannelMaster WHERE OrgId = @rOrgId

DELETE FROM sAccounting.tExpenseDetail WHERE CAST(LEFT(ExpenseId, 4) AS int) = @rOrgId
DELETE FROM sAccounting.tExpenseSubGroupMaster WHERE OrgId= @rOrgId
DELETE FROM sAppraisal.tAppraisalTypeMaster WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tBusinessHeadsRatingStatus WHERE CAST(LEFT(AppraisalTypeId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployee WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeDetail WHERE CAST(LEFT(KPAEmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeRating WHERE CAST(LEFT(KPAEmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeRatingDetail WHERE CAST(LEFT(KPAEmployeeRatingId, 4) AS bigint) = @rOrgId
DELETE FROM sPoliciesForms.tFolderFile WHERE OrgId = @rOrgId
DELETE FROM sPoliciesForms.tFolderFilePermission WHERE CAST(LEFT(FolderFileId, 4) AS int) = @rOrgId


DELETE FROM sFee.tFeeMainGroupOptionalFee WHERE OrgId = @rOrgId
DELETE FROM sFee.tFeeStructureDetail WHERE CAST(LEFT(FeeStructureId, 4) AS int) = @rOrgId
DELETE FROM sFee.tFeeStructureMaster WHERE OrgId = @rOrgId
DELETE FROM sFrontOffice.tEmployeeGatePass WHERE OrgId = @rOrgId
DELETE FROM sHostel.tHostelStudentGatePass WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sTransport.tAttendanceRegister WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAssessment.tCCESubjectActivityExamScore WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tTempAll_Exam WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sCanteen.tAttendanceForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCanteen.tRegisterForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCertificate.tTransfer WHERE OrgId = @rOrgId
DELETE FROM sCanteen.tRegisterForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sErp.tLeadFollowup WHERE CAST(LEFT(LeadId, 4) AS int) = @rOrgId
DELETE FROM sErp.tLeadMaster WHERE OrgId = @rOrgId


DELETE FROM sAdmission.tAdmissionHSCDetail WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sBiometric.tEmployeeCheckIn WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId

DELETE FROM sBiometric.tEmployeeLateStatus WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId

DELETE FROM sCommon.tSubmitDocumentMaster WHERE OrgId = @rOrgId
DELETE FROM sStudent.tStudentDocument WHERE CAST(LEFT(SubmitDocumentMasterId, 4) AS int) = @rOrgId
DELETE FROM sTimetable.tAnnualSubjectWorkLoad WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId

DELETE FROM sFee.tReceiptDeleted WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sFee.tReceiptDetailDeleted WHERE CAST(LEFT(ReceiptId, 4) AS bigint) = @rOrgId

DELETE FROM sAttendance.tStudentLeaveRequest WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sInfrastructure.tResourceMaster WHERE CAST(LEFT(Id, 4) AS int) = @rOrgId
DELETE FROM sInfrastructure.tResourceRequest WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgId

DELETE FROM sAlumni.tRegistration WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tMonthlyStatusUpdate WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tDSR WHERE OrgId = @rOrgId
DELETE FROM sErp.tDSRWorkTypeMaster WHERE OrgId = @rOrgId
DELETE FROM sErp.tProjectMaster WHERE OrgId = @rOrgId
DELETE FROM sFee.tFeeFollowup WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
 
DELETE FROM sActivity.tWeekOffSetting WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tAllBatchResultCoScholestic WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tEmployeeDocument WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tChangeIdLog WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sAlert.tAssociateRecipient WHERE CAST(LEFT(ForUserId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tPreLessonPlan WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAssessment.tAllBatchResultGrade WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId

DELETE FROM sVts.tvtsClassMaster WHERE CAST(LEFT(ClassId, 4) AS int) = @rOrgId
DELETE FROM sVts.tvtsOrganizationMaster WHERE OrgId = @rOrgId
DELETE FROM sVts.tvtsStudent WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tLeadChannelPartnerMaster WHERE  OrgId = @rOrgId


DELETE FROM sAlumni.tStudentMapping WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tUserFeedback WHERE CAST(LEFT(UserId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeExpense WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId


DELETE FROM sAdmission.tAdmissionCriteriaForm WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormField WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tGradeSetClassSubjectDetail WHERE CAST(LEFT(Id, 4) AS int) = @rOrgId
DELETE FROM sAssessment.tGradeSetClassSubjectMaster WHERE OrgId = @rOrgId
DELETE FROM sBiometric.BioDetailMapping WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tLog WHERE OrgId = @rOrgId

DELETE FROM sCertificate.tOtherCertificate WHERE OrgId = @rOrgId
DELETE FROM sWorkflow.tApprovalAction WHERE CAST(LEFT(ActionUserId, 4) AS bigint) = @rOrgId
DELETE FROM sWorkflow.tApprovalRequest WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sWorkflow.tFunctionalityApprovingAuthority WHERE OrgId = @rOrgId
DELETE FROM sWorkflow.tFunctionalityApprovingDepartment WHERE OrgId = @rOrgId

DELETE FROM sBiometric.tProcess WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tConfiguration WHERE OrgId = @rOrgId

DELETE FROM sAcademic.tHomeworkCheck WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId

DELETE FROM sAdmission.tAdmissionCriteriaFee WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormFee WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId


DELETE FROM sFee.tFeeOpening WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sTransport.tChangeRouteLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tClassworkConfig WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tPunchData WHERE CAST(LEFT(StudentID, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tCallLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tMarketingActivityPlan WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
--DELETE FROM tMarketingActivityStatus WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tTripLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId


DELETE FROM sAudit.HistoryLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAudit.tOperationLog WHERE CAST(LEFT(SourceId, 4) AS int) = @rOrgId

--DELETE FROM sErp.tCustomerTicket WHERE OrgId= @rOrgId
DELETE FROM sPayroll.tPayProcessEmployeeRemark WHERE CAST(LEFT(EmployeeId, 4) AS int) = @rOrgId


/*==============================*/

DELETE FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgId


DELETE FROM sAlert.tAlertLogHistory WHERE OrgId= @rOrgId
DELETE FROM sAlert.tNotificationLogHistory WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeCommunications WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeFamilyDetails WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeJobDetail WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeeMaster WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeePersonalDetail WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeeStatutoryAndOther WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sSecurity.tUserLogHistory WHERE OrgId= @rOrgId
DELETE FROM sStudent.tAcademicStudent WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentAdditional WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentCommunication WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentFamily WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentHealth WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentOther WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tStudentCustomFieldData WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tStudentMasterDelete WHERE OrgId= @rOrgId

DELETE FROM sAudit.ChangeLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tCertificateIncrement WHERE OrgId= @rOrgId
DELETE FROM sAudit.ChangeLog WHERE CAST(LEFT(ScreenId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tClassworkView WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sBiometric.tPunchCount WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sFrontOffice.tOTPLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tLeaveDeduction WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId


DELETE FROM sAdmission.tAdmissionCriteriaDocument WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionStudentDocument WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sTimetable.tTimeTableTime WHERE CAST(LEFT(DivisionId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeWorkingDays WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId

DELETE FROM sErp.tContactBookMaster WHERE OrgId= @rOrgId
DELETE FROM sErp.tEmployeeERPDetail WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sFrontOffice.tLostFoundRegisterScope WHERE CAST(LEFT(SourceId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeChangeHistory WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sCommon.tReportTemplate WHERE OrgId= @rOrgId
DELETE FROM sTransport.tBusRouteAssignedTo WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sWorkflow.tStudentDataChange WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tOnlineLearning WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAssignment WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAssignmentSubmit WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAttendance WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAttendanceLog WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningReference WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningResource WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningScope WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tTempOnlineLearningScope WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tChat WHERE CAST(LEFT(FromSourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tTempChatGroupScope WHERE CAST(LEFT(MemberSourceId, 4) AS bigint) = @rOrgId


DELETE FROM sAcademic.tOnlineMeetingSettings WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tDigitalForm WHERE OrgId= @rOrgId
DELETE FROM sStudent.tDigitalFormScope WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId
DELETE FROM sStudent.tDigitalFormField WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId
DELETE FROM sStudent.tDigitalFormStudent WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningView WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId

DELETE FROM sOp.tPaymentTransactionHistory WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROMsFee.tOnlineFeeHistory WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeDetailHistory WHERE CAST(LEFT(OnlineFeeId, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tStudentDocumentUpload WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId

DELETE FROM sFee.tFeeAllocationHistory WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sCommon.tUploadDocument WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId

DELETE FROM sFee.tFeeAllocationStudent WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeClassBatchStatus WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeBatch WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tEmployeeDocumentUpload WHERE OrgId = @rOrgId

DELETE FROM [sHrm].[tEmployeeCustomFieldData] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId

DELETE FROM [sCommunication].[tDailyThoughtAssign] WHERE OrgId= @rOrgId
DELETE FROM [sFee].[tEMandate] WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgId

DELETE FROM [sAdmission].[tAdmissionInquiryCriteria] WHERE CAST(LEFT([ClassId], 4) AS int) = @rOrgId
DELETE FROM [sCommon].[tSubmitDocumentScope] WHERE CAST(LEFT([SubmitDocumentId], 4) AS int) = @rOrgId

--EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

	SELECT 1 AS Result
 
-- COMMIT TRANSACTION
		
--	END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
		
--	END CATCH
END
GO
PRINT N'Altering [sCommunication].[peContentAdd]...';


GO
 
ALTER PROCEDURE [sCommunication].[peContentAdd] 
			
           @rSourceTypeId smallint
           ,@rSourceId bigint           
           ,@rAssignId int,
		   @rPathName nvarchar(500),
		   @reContentTypeId int,
		   @rTitle nvarchar(200) = '',
		   @rRemark nvarchar(500) = '',
		   @rOrgGroupBatchId int = 0,
		   @rIsBatchIndependent bit = 0,
		   @rContentSourceId int = 0,
		   @rCreatedUserId bigint = 0
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount int
BEGIN 

set @lCount =  ( select ISNULL(COUNT(1),0) from sCommunication.teContent where  SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND AssignedToId=@rAssignId AND  [PathName]= @rPathName)
   
	If (@lCount <> 0)
		BEGIN
			SELECT -11 AS RESULT
			--UPDATE sCommunication.teContent SET SourceTypeId=@rSourceTypeId , SourceId=@rSourceId , [PathName]=@rPathName,AssignedToId=@rAssignId,eContentTypeId = @reContentTypeId			   
			--,ContentTypeSourcetId=  @rContentSourceId,Title=@rTitle,Remark=@rRemark,IsBatchIndependent=@rIsBatchIndependent
			--where  SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId AND AssignedToId=@rAssignId AND  [PathName]= @rPathName
			--SELECT 1 AS Result
	  END 
	ELSE
			
			INSERT INTO sCommunication.teContent
			(
				SourceTypeId
			   ,SourceId
			   ,AssignedToId
			   ,eContentTypeId
			   ,ContentTypeSourcetId
			   ,PathName
			   ,Title
			   ,Remark
			   ,IsBatchIndependent
			   ,OrgGroupBatchId
			   ,CreatedUserId
			   ,CreatedDateTime
			)
			VALUES
			(	@rSourceTypeId
			   ,@rSourceId
			   ,@rAssignId
			   ,@reContentTypeId
			   ,@rContentSourceId
			   ,@rPathName
			   ,@rTitle
			   ,@rRemark
			   ,@rIsBatchIndependent
			   ,@rOrgGroupBatchId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			)		
			SELECT 1 AS Result
	END
	
	 
END
GO
PRINT N'Altering [sCommunication].[pMyBookGet]...';


GO
ALTER PROCEDURE [sCommunication].[pMyBookGet]
	 
	 @rReaderSourceTypeId smallint,
	 @rReaderSourceId bigint,
	 @rBatchId int,
	 @rStatusId int=0,
	 @rLibraryId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 



	select 
		BL.Id AS BookLogId,
		BM.Title AS BookTitle,
		BL.LogDate AS IssueDate,
		--BL.IsCurrentStatus AS IsReturnPending,
		BL.StatusId AS StatusId,
		--SM.Title As StatusName,
		(CASE WHEN (ISNULL(BL.ReturnDate,'')!='' OR BL.BookActionStatusId=1) THEN 'Return'
			 WHEN BL.BookActionStatusId=2 THEN 'Release'
			 ELSE SM.Title END) AS StatusName,
		CASE WHEN BL.IsCurrentStatus = 1 THEN 'Pending' ELSE 'Return' END AS IsReturnPending,
		BL.DueDate,
		BL.LibraryId ,
		ISNULL(BM.Author,'')AS Author
	--CASE WHEN BL.IsCurrentStatus = 0 THEN BL.DueDate ELSE '' END AS DueDate

	  from 
		  sLibrary.tBookLog BL 
		  INNER JOIN sLibrary.tBookMaster BM
		  ON BL.ResourceSourceId = BM.Id AND BL.ResourceSourceTypeId = 2009  
		  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = BL.StatusId AND SM.statusTypeId = 106
	  WHERE 
		  --BL.statusId = 523
		  BL.ReaderSourceId = @rReaderSourceId
		  AND BL.ReaderSourceTypeId = @rReaderSourceTypeId
		  AND (BL.StatusId = @rStatusId OR @rStatusId=0)
		  AND (BL.LibraryId= @rLibraryId OR @rLibraryId=0)
		  AND (SM.Id!=521 OR ISNULL(BL.BookActionStatusId,0)!=0)
	  
	  ORDER BY BL.LogDate DESC,BL.CreatedDateTime DESC

END
GO
PRINT N'Altering [sCommunication].[pMyUpdateGet]...';


GO
 
ALTER PROCEDURE [sCommunication].[pMyUpdateGet]  
@rOrgId int,    
@rBatchId int,  
@rOrgGroupBatchId int,  
@rUserId bigint,  
@rUserSourceId bigint,  
@rUserSourceTypeId int,  
@rSyncedAssignmentId bigint,  
@rSyncedCircularId bigint,  
@rSyncedPollId bigint,  
@rSyncedQueryCommentId bigint,  
@rSyncedNewsId bigint,  
@rSyncedBlogId bigint,  
@rSyncedBehaviourId bigint,  
@rSyncedActivityId bigint,  
@rSyncedResultId bigint,  
@rSyncedAssignTaskId bigint,  
@rSyncedPhotoCategoryId int,  
@rVersionNumber nvarchar(30)='',  
@rDeviceToken nvarchar(200)='',  
@rOSTypeId smallint = 0,
@rAppVersion nvarchar(20)='',
@rAppName nvarchar(100)=''

 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
 DECLARE @lAcademicId bigint,  
  @lScopeSourceId int,  
  @lScopeSourceTypeId int,  
  @lStudentId bigint,  
  @lClassId int,  
  @lDivisionId int,  
  @lOrgId int,  
  @lDepartmentId int,  
  @lAssignmentStatus bit=0,  
  @lCircularStatus bit=0,  
  @lPollStatus bit=0,  
  @lQueryStatus bit=0,  
  @lBlogStatus bit=0,  
  @lNewsStatus bit=0,  
  @lBehaviourStatus bit=0,  
  @lActivityStatus bit=0,  
  @lResultStatus bit=0,  
  @lAssignTaskStatus bit=0,  
  @lPhotoCategoryStatus bit=0,  
  @lIsActive bit=0,  
  @lIsOptimizeAppImageUpload bit=0  
  
IF( @rUserSourceTypeId = 2003)   
BEGIN  
  SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId  
  FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM  
 ON A.BatchId = BM.Id AND BM.IsActive = 1   
 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId  
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
--SELECT @lAcademicId = Id, @lScopeSourceId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rUserSourceId AND BatchId = @rBatchId  
SET @lScopeSourceId = @lDivisionId  
SET @lScopeSourceTypeId = 2005  
END  
ELSE  
BEGIN  
 SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId  FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD  
    ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId AND ISNULL(EM.IsOtherUser,0) = 0  
--SELECT @lScopeSourceId = OrganizationDepartmentId FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId  
SET @lScopeSourceId = @lDepartmentId  
SET @lScopeSourceTypeId = 2004  
END  
--IF EXISTS(SELECT 1 FROM sCommunication.tAssignmentScope ASO INNER JOIN  sCommunication.tAssignment A  
-- ON A.Id = ASO.AssignmentId  
--WHERE ASO.AssignmentId > @rSyncedAssignmentId AND ASO.SourceTypeId = @lScopeSourceTypeId AND ASO.SourceId = @lScopeSourceId AND A.BatchId=@rBatchId)  
--SET @lAssignmentStatus = 1  
  
  
--IF( @rUserSourceTypeId = 2003)   
--BEGIN  
  
--    IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS WHERE  
--      ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId)   
--      OR (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId)  
--      OR (CS.SourceTypeId = 2016 AND CS.SourceId =@lClassId)  
--      OR (CS.SourceTypeId = 2005 AND CS.SourceId =@lDivisionId)  
--      OR (CS.SourceTypeId = 2003 AND CS.SourceId =@lStudentId)  
--      OR (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId)  
--      )  
--       AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D ON D.CircularId= C.Id  
--      --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId  
--        WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)  
--        AND C.AssigneeId IN (1,2) AND C.OrgGroupBatchId=@rOrgGroupBatchId)   
--      SET @lCircularStatus = 1  
  
--END   
--ELSE  
--BEGIN  
-- IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS  
--       WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId))  
--       AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D ON D.CircularId= C.Id  
--       --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId  
--       WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)  
--       AND C.AssigneeId IN (1,3) AND C.OrgGroupBatchId=@rOrgGroupBatchId)   
--     SET @lCircularStatus = 1         
  
--END  
--IF EXISTS(SELECT 1 FROM sCommunication.tCircularScope WHERE  CircularId > @rSyncedCircularId AND SourceTypeId = @lScopeSourceTypeId AND SourceId = @lScopeSourceId)  
--SET @lCircularStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tPoll P INNER JOIN sCommunication.tPollMember PM ON P.Id=PM.PollId  
-- WHERE PM.PollId > @rSyncedPollId AND PM.SourceTypeId = @lScopeSourceTypeId AND PM.SourceId = @lScopeSourceId AND P.OrgGroupBatchId=@rOrgGroupBatchId)  
--SET @lPollStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tBlogScope BS INNER JOIN sCommunication.tBlog B  
--ON B.Id = BS.BlogId  
--WHERE B.IsPublish = 1 AND BS.BlogId > @rSyncedBlogId AND BS.SourceTypeId = 2021 AND BS.SourceId = @rOrgId AND B.OrgGroupBatchId = @rOrgGroupBatchId)  
--SET @lBlogStatus = 1  
  
--IF EXISTS(SELECT 1 FROM  sCommunication.tNews N INNER JOIN sCommunication.tNewsScope NS ON N.Id=NS.NewsId   
--   WHERE NS.NewsId > @rSyncedNewsId AND NS.SourceTypeId = 2021 AND NS.SourceId = @rOrgId AND N.OrgGroupBatchId = @rOrgGroupBatchId)  
--SET @lNewsStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tNewsScope WHERE NewsId > @rSyncedNewsId AND SourceTypeId = @rOrgId AND SourceId = 1016)  
--SET @lNewsStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tUploadResult WHERE Id > @rSyncedResultId AND DivisionId = @lScopeSourceId AND BatchId=@rBatchId AND IsObsolete=0 )  
--SET @lResultStatus = 1  
  
--IF EXISTS(SELECT 1 FROM    
--sCommunication.tPhotoCategoryMaster PCM  
--INNER JOIN sCommunication.tPhotoCategoryScope PCO   
--ON PCM.Id=PCO.PhotoCategoryId WHERE PCM.Id > @rSyncedPhotoCategoryId AND LEFT(PCO.ScopeSourceId,4) = @rOrgId  AND PCM.IsObsolete=0 )  
--SET @lPhotoCategoryStatus = 1  
  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tAssignTask WHERE  Id > @rSyncedAssignTaskId AND AssignedToSourceTypeId = @rUserSourceTypeId   
--AND AssignedToSourceId = @rUserSourceId AND IsCompleted=0 AND IsClosed=0 AND OrgId=@rOrgId)  
--SET @lAssignTaskStatus = 1  
  
  
--IF EXISTS(SELECT 1 FROM  sActivity.tActivity A INNER JOIN sActivity.tActivityParticipant AP ON A.Id=AP.ActivityId  
-- WHERE AP.ActivityId > @rSyncedActivityId AND AP.SourceTypeId = @rUserSourceTypeId AND AP.SourceId = @rUserSourceId AND A.BatchId=@rBatchId)  
--SET @lActivityStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tBehaviour WHERE Id > @rSyncedBehaviourId AND AcademicId = @lAcademicId )  
--SET @lBehaviourStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tQuery Q INNER JOIN sCommunication.tQueryComment QC ON Q.Id=QC.QueryId  
--WHERE Q.CreatedUserId=@rUserId AND Q.IsUserView=0 AND QC.Id>@rSyncedQueryCommentId AND QC.CreatedUserId <> @rUserSourceId AND Q.OrgGroupBatchId=@rOrgGroupBatchId)  
--SET @lQueryStatus = 1  
   
IF(@rUserSourceTypeId = 2003)  
BEGIN   
 DECLARE @lStatusId1 smallint=0  
  SELECT @lStatusId1 = StatusId FROM sStudent.tStudentMaster SM WHERE Id = @rUserSourceId  
 IF(@lStatusId1=1)  
 BEGIN   
  SET @lIsActive = 1  
 END ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
ELSE IF(@rUserSourceTypeId = 95)  
BEGIN   
 DECLARE @lStatusId2 smallint=0  
 SELECT @lStatusId2 = StatusId FROM sHrm.tEmployeeMaster EM WHERE Id = @rUserSourceId --AND ISNULL(EM.IsOtherUser,0) = 0  
 IF(@lStatusId2=7)  
 BEGIN   
  SET @lIsActive = 1  
 END ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
ELSE IF(@rUserSourceTypeId = 1)  
BEGIN   
 DECLARE @IsObsolete smallint=0  
 SELECT @IsObsolete=ISNULL(IsObsolete,0) FROM sSecurity.tUser WHERE Id = @rUserId  
 IF(@IsObsolete=0)  
 BEGIN   
  SET @lIsActive = 1  
 END   
 ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
  
IF(@lIsActive=1)  
BEGIN  
 DECLARE @lIsObsolete bit=0  
 SELECT @lIsObsolete=ISNULL(IsObsolete,0) FROM sSecurity.tUser WHERE Id = @rUserId  
  
 IF(@lIsObsolete=0)  
  SET @lIsActive = 1  
 ELSE  
  SET @lIsActive = 0  
END  
  
  
DECLARE @lOrgGroupId int=0  
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id =@rOrgId  
DECLARE @lOptimizeAppImageUpload nvarchar(50)  
SELECT @lOptimizeAppImageUpload = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 247 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
IF (@lOptimizeAppImageUpload IS NULL) OR (@lOptimizeAppImageUpload = 'False')  
 SET @lIsOptimizeAppImageUpload = 0  
ELSE  
 SET @lIsOptimizeAppImageUpload = 1   
   
DECLARE @lAlertRemark nvarchar(2000) = ''  
   
--IF(@rVersionNumber IS NULl OR @rVersionNumber='')  
--BEGIN  
-- DECLARE @lUserName nvarchar(100)=''  
-- DECLARE @lUserPassword nvarchar(100)=''  
-- DECLARE @lBatch nvarchar(100)=''  
-- SELECT @lBatch = Title  FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
   
-- SELECT @lUserName=UserName,@lUserPassword=UserPassword FROM sSecurity.tTempUser WHERE UserId = @rUserId  
-- SET @lAlertRemark = 'Plese install the new app from this location (https://play.google.com/store/apps/details?id=com.vidyalaya.pinnacleschoolgandhinagarnew) Uninstall the old app. Login in new app with  
--       Registration Number : '+LEFT(@rOrgGroupBatchId,4) +'  
--       User Name : '+@lUserName+'  
--       Password : '+@lUserPassword+'  
--       Batch :' + @lBatch  
--END  
--ELSE   
BEGIN  
 SELECT @lAlertRemark=AlertRemark FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @lOrgGroupId  
END  
  
DECLARE @lMobileAppModuleAutoSyncToken nvarchar(50)  
SELECT @lMobileAppModuleAutoSyncToken = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 317 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
  
  
DECLARE @lIsStopApplicationAccess bit=0  
DECLARE @lStudentCustomAlert nvarchar(1000)=''  
IF(@rUserSourceTypeId=2003)  
SELECT @lIsStopApplicationAccess = ISNULL(IsStopApplicationAccess,0) ,@lStudentCustomAlert= ISNULL(StudentCustomAlert,'') FROM sStudent.tStudentCommunication WHERE StudentId = @rUserSourceId  
  
  
IF(LEN(@rDeviceToken) > 0)  
BEGIN   
 DECLARE @lDeviceToken nvarchar(200)=''  
 SELECT @lDeviceToken = DeviceToken FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId  
  
 DECLARE @lConfigValue nvarchar(50)=''  
 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 374 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
  
 IF @lConfigValue IS NULL   
 SET @lConfigValue = 'False'  
  
 IF @lConfigValue = 'True'  
 BEGIN  
 IF(@lDeviceToken!=@rDeviceToken)  
  SET @lIsActive=0  
 END  
  
 SELECT @lDeviceToken = DeviceToken FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND DeviceToken=@rDeviceToken  
  
 IF(@lDeviceToken IS NULL OR @lDeviceToken='' OR ISNULL(@lDeviceToken,'') = '')  
  SET @lIsActive=0  
END  
  
DECLARE @lActiceClassBatchId NVARCHAR(MAX) = '',@lBatchClassId int  
   
IF(@rUserSourceTypeId = 2003)  
BEGIN   
 SELECT @lBatchClassId = A.ClassId  
 FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id  
 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId  
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
  
 IF EXISTS(SELECT BatchId FROM [sSetup].[tBatchClass] BC INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BC.BatchId WHERE ClassId = @lBatchClassId AND IsBatchClassActive = 1 AND BM.IsActive = 1)  
 BEGIN  
  SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,BC.BatchId)+','+ BM.Title FROM [sSetup].[tBatchClass] BC INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BC.BatchId WHERE BC.ClassId = @lBatchClassId AND BC.IsBatchClassActive = 1 AND BM.IsActive = 1  
 END  
 ELSE  
 BEGIN  
  SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,Id) +','+ Title FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
 END  
END  
ELSE IF(@rUserSourceTypeId = 95)  
BEGIN  
 SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,Id) +','+ Title FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
END  


IF(LEN(ISNULL(@rAppVersion,'')) > 0 AND LEN(ISNULL(@rAppVersion,'')) > 0)
BEGIN
	UPDATE sCommunication.tRegisteredUsers
	SET
		AppVersion = @rAppVersion,
		AppName = @rAppName,
		UpdatedDateTime = sCommon.fGetDate()
	WHERE 
		DeviceToken = @rDeviceToken 
		AND OsTypeId = @rOSTypeId
		AND OrgId=@rOrgId AND UserId=@rUserId 
		AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId
END
CREATE TABLE #Module (  
Id int,  
Title nvarchar(2000),  
IsNew bit )  
INSERT INTO #Module VALUES (1,'IsActiveCheck',CONVERT(bit,@lIsActive))  
INSERT INTO #Module VALUES (2,'IsOptimizeAppImageUpload',@lIsOptimizeAppImageUpload)  
INSERT INTO #Module VALUES (3,ISNULL(@lAlertRemark,''),1)  
INSERT INTO #Module VALUES (4,ISNULL(@lMobileAppModuleAutoSyncToken,0),1)  
INSERT INTO #Module VALUES (5,'Is Stop Application Access',@lIsStopApplicationAccess)  
INSERT INTO #Module VALUES (6,@lStudentCustomAlert,1)  
INSERT INTO #Module VALUES (20085,'Circular',0)  
INSERT INTO #Module VALUES (20088,'Query',0)  
INSERT INTO #Module VALUES (20099,'Blog',0)  
INSERT INTO #Module VALUES (20104,'News',0)  
INSERT INTO #Module VALUES (20172,'AssignTask',0)  
INSERT INTO #Module VALUES (20183,'Gallery',0)  
INSERT INTO #Module VALUES (20204,'Poll',0)  
INSERT INTO #Module VALUES (20093,'Assignment',0)  
INSERT INTO #Module VALUES (20209,'Activity',0)  
INSERT INTO #Module VALUES (20130,'Behaviour',0)  
INSERT INTO #Module VALUES (20180,'Result',0)  
INSERT INTO #Module VALUES (7,@lActiceClassBatchId,1)  
   
SELECT * FROM #Module  
   
--SELECT @lAssignmentStatus AS Assignment,@lCircularStatus AS Circular,@lPollStatus AS Poll,@lQueryStatus AS Query,  
--@lBlogStatus AS Blog,@lNewsStatus AS News,@lBehaviourStatus AS Behaviour,  
--@lActivityStatus AS Activity,@lResultStatus AS Result,@lAssignTaskStatus AS AssignTask,@lPhotoCategoryStatus AS Gallery  
  
END
GO
PRINT N'Altering [sCommunication].[pOnlineLearningLectureListDetailsGet]...';


GO
 
 
ALTER PROCEDURE [sCommunication].[pOnlineLearningLectureListDetailsGet]
	 @rOnlineLearningId bigint ,
	 @rSourceId bigint,
	 @rOrgId int,
	 @rSourceTypeId int,
	 @rIsAdmin bit 
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
		
	IF (@rSourceTypeId = 2001)
	BEGIN 
	DECLARE @lStudentName nvarchar(100), @lClassDivisionName nvarchar(50),@lStudentId bigint
	SELECT @lStudentId= A.StudentId, @lStudentName = ISNULL(SM.FirstName,'')+' '+ISNULL(SM.MiddleName,'') +' '+ISNULL(SM.LastName,''), @lClassDivisionName = CM.Title +' ' +DM.Title
				FROM sStudent.tAcademic A 
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
				WHERE A.Id = @rSourceId 
		SELECT 
			OL.Id As OnlineLearningId,
			ISNULL(OL.Title,'') As Title,
			CONVERT(NVARCHAR,OL.StartTime,108) as FromTime,
			CONVERT(NVARCHAR,OL.EndTime,108) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			@lClassDivisionName AS ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.IsTrackAttendance AS IsTrackAttendance,
			ISNULL(OL.MeetingId ,'') As MeetingId,
			ISNULL(OL.MeetingPassword,'') As MeetingPassword,
			ISNULL(OL.IsAssignment,0) As IsAssignment,
			ISNULL(OL.IsReference,0)AS IsReference,
			ISNULL(OL.IsResource,0) As IsResource,
			ISNULL(OL.IsMeetingStarted,0) AS IsMeetingStarted,
			ISNULL(OL.LecturePath,'')AS LecturePath,
			ISNULL(OL.IsDisplayMeetingId,'') AS IsDisplayMeetingId,
			ISNULL(DM.Title,'') As LearningType,
			@lStudentName As StudentName,
			ISNULL(OL.IsSubmitAssignment,0) As IsSubmitAssignment,
			ISNULL(OL.IsTakeTest ,0) As IsTakeTest,
			ISNULL(OL.TestId ,0) As TestId,
			ISNULL((SELECT sTP.Id FROM sEExam.tTestParticipant sTP Where sTP.SourceId = @lStudentId and sTP.TestId = OL.TestId 
			),0) AS TestParticipantId,
			ISNULL((SELECT CASE WHEN sTp.TestStatusId=545 THEN 'True' ELSE 'False' END FROM sEExam.tTestParticipant sTP Where sTP.SourceId = @lStudentId and sTP.TestId = OL.TestId),'false') As IsTestCompleted,
			--'false' As IsTestCompleted,
			ISNULL(sTM.Title,'') AS TestName,
			[sEExam].[fCheckIsHTMLGet] (sTM.Id) AS IsHtml,
			ISNULL(OMS.IsOnParticipantVideo ,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) As IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) As IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) As IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) As IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) As IsOnHostscreenShare,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			ISNULL(OL.IsMeetingCreated,0) As IsMeetingCreated,
			ISNULL(OMS.APIKey ,'') As APIKey,
			ISNULL(OMS.APISecret ,'') As APISecret,
			'' As AccountEmailId,
			'' As AccountPassword,
			ISNULL(OL.AssignmentRemark,'') As AssignmentRemark,
			ISNULL(OL.IsTrackAssignmentView,0) As IsTrackAssignmentView,
			ISNULL((SELECT ISNULL(EM1.FirstName,'') +' ' + ISNULL(EM1.MiddleName,'') +' ' + ISNULL(EM1.LastName ,'') FROM sHrm.tEmployeeMaster EM1 WHERE EM1.Id = OL.CoTeacherEmployeeId1),'') as CoTeacher1Name,
			ISNULL((SELECT ISNULL(EM1.FirstName,'') +' ' + ISNULL(EM1.MiddleName,'') +' ' + ISNULL(EM1.LastName ,'') FROM sHrm.tEmployeeMaster EM1 WHERE EM1.Id = OL.CoTeacherEmployeeId2),'') as CoTeacher2Name,
			ISNULL(sTM.IsAllowReview,0) As IsAllowReview,
			ISNULL(OLV.AssignmentTeacherRemark,'') AS TeacherAssignmentRemark,
			OL.BatchId,
			ISNULL(CONVERT(NVARCHAR,OL.AssignmentSubmissionEndDate),'') As SubmissionEndDate,
			OL.ClassId,
			OL.SubjectId
	 FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId			 			
            INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			LEFT JOIN sEExam.tTestMaster sTM ON sTM.Id = OL.TestId
			LEFT JOIN sAcademic.tOnlineMeetingSettings OMS ON OMS.OnlineLearningId = OL.Id
			LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = @rSourceId
            
	 WHERE
			 OL.Id = @rOnlineLearningId
			AND OL.IsCompleted <> 721
			 
			 
			
			ORDER BY OL.CreatedDateTime
	
		END
		
		IF(@rSourceTypeId = 95)
		BEGIN
		DECLARE @lAdminName nvarchar(200)
			IF (@rIsAdmin = 1)
			SELECT @lAdminName = ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') 
			FROM sHrm.tEmployeeMaster EM WHERE EM.Id = @rSourceId
			
		SELECT 
			OL.Id As OnlineLearningId,
			ISNULL(OL.Title,'') As Title,
			CONVERT(NVARCHAR,OL.StartTime,108) as FromTime,
			CONVERT(NVARCHAR,OL.EndTime,108) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			CASE WHEN @rIsAdmin = 0 THEN ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') 
			WHEN @rIsAdmin = 1 THEN @lAdminName END As TeacherName,
			--SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CM.Title As ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.IsTrackAttendance AS IsTrackAttendance,
			ISNULL(OL.MeetingId ,'') As MeetingId,
			ISNULL(OL.MeetingPassword,'') As MeetingPassword,
			ISNULL(OL.IsAssignment,0) As IsAssignment,
			ISNULL(OL.IsReference,0)AS IsReference,
			ISNULL(OL.IsResource,0) As IsResource,
			ISNULL(OL.IsMeetingStarted,0) AS IsMeetingStarted,
			ISNULL(OL.LecturePath,'')AS LecturePath,
			ISNULL(OL.IsDisplayMeetingId,'') AS IsDisplayMeetingId,
			ISNULL(DM.Title,'') As LearningType,
			'' As StudentName,
			ISNULL(OL.IsSubmitAssignment,0) As IsSubmitAssignment,
			ISNULL(OL.IsTakeTest ,0) As IsTakeTest,
			ISNULL(OL.TestId ,0) As TestId,
			0 As TestParticipantId,
			'' As IsHtml,
			ISNULL(OMS.IsOnParticipantVideo ,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) As IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) As IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) As IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) As IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) As IsOnHostscreenShare,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			ISNULL(OL.IsMeetingCreated,0) As IsMeetingCreated,
			ISNULL(OMS.APIKey ,'') As APIKey,
			ISNULL(OMS.APISecret ,'') As APISecret,
			ISNULL(OMS.APIKey ,'') As APIKey,
			ISNULL(OMS.APISecret ,'') As APISecret,
			CASE WHEN @rIsAdmin = 0 THEN ISNULL(OMS.AccountEmailId ,'') 
			WHEN @rIsAdmin = 1 THEN '' END As AccountEmailId,
			CASE WHEN @rIsAdmin = 0 THEN ISNULL(OMS.AccountPassword,'') 
			WHEN @rIsAdmin = 1 THEN '' END As AccountPassword,
			'' as AssignmentRemark,
			--,
			--ISNULL(TP.Id, 0) AS TestParticipantId,
			--ISNULL(sTM.Title,'') AS TestName,
			--[sEExam].[fCheckIsHTMLGet] (sTM.Id) AS IsHtml
			ISNULL(OL.IsTrackAssignmentView,0) As IsTrackAssignmentView,
			ISNULL((SELECT ISNULL(EM1.FirstName,'') +' ' + ISNULL(EM1.MiddleName,'') +' ' + ISNULL(EM1.LastName ,'') FROM sHrm.tEmployeeMaster EM1 WHERE EM1.Id = OL.CoTeacherEmployeeId1),'') as CoTeacher1Name,
			ISNULL((SELECT ISNULL(EM1.FirstName,'') +' ' + ISNULL(EM1.MiddleName,'') +' ' + ISNULL(EM1.LastName ,'') FROM sHrm.tEmployeeMaster EM1 WHERE EM1.Id = OL.CoTeacherEmployeeId2),'') as CoTeacher2Name,
			ISNULL(sTM.IsAllowReview,0) As IsAllowReview,
			OL.BatchId,
			ISNULL(CONVERT(NVARCHAR,OL.AssignmentSubmissionEndDate),'') As SubmissionEndDate,
			OL.ClassId,
			OL.SubjectId
		FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId 
            --INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = OL.ClassId AND SA.OrgId = @rOrgId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            LEFT JOIN sEExam.tTestMaster sTM ON sTM.Id = OL.TestId
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			--LEFT JOIN sE sEExam.tTestParticipant TP ON sTM.Id=TP.TestId
			LEFT JOIN sAcademic.tOnlineMeetingSettings OMS ON OMS.OnlineLearningId = OL.Id
            
		WHERE
			 OL.Id = @rOnlineLearningId
			-- AND OL.TeacherEmployeeId = @rSourceId
			 AND OL.IsCompleted <> 721
			
			ORDER BY OL.CreatedDateTime
			
			END
		
END
GO
PRINT N'Altering [sEExam].[pTestParticipantAdd]...';


GO
ALTER PROCEDURE [sEExam].[pTestParticipantAdd]
	  
	@rId bigint,
	@rTestId int,
	@rSourceId bigint,
	@rSourceTypeId int, 
	@rTestDate date=NULL,
	@rStartTime time(7)=NULL,
	@rEndTime time(7)=NULL,
	@rTestStatusId smallint=NULL,
	@rTotalMarks decimal(6,2)=NULL,
	@rScoredMarks decimal(6,2)=NULL,
	@rTotalQuestions int=NULL,
	@rRightQuestions int=NULL,
	@rWrongQuestions int=NULL,
	@rNotAttemptedQuestions int=NULL,
	@rSkippQuestion int=NULL,
	@rOrgId int,
	@rMode smallint,
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF(@rId = 0)
	BEGIN 
	DECLARE @lNextNumber bigint     
	EXECUTE sCommon.pTableRowIdGet  @rOrgId, 'sEExam.tTestParticipant', 0, 1, 1,@outNextNumber = @lNextNumber output
	END 

	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	
 IF(@rSourceTypeId = 2005)
   BEGIN   
		 DELETE TP FROM sEExam.tTestParticipant TP INNER JOIN sStudent.vStudentAcademic VSA 
		 ON TP.SourceId = VSA.StudentId 
		 Where DivisionId = @rSourceId  AND TestId = @rTestId AND VSA.BatchId=@rBatchId
		 

		  --Delete Participant Answer
			DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
			INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
			INNER JOIN sStudent.vStudentAcademic VSA ON TP.SourceId = VSA.StudentId 
			WHERE TPA.TestId= @rTestId  
			AND VSA.DivisionId = @rSourceId  AND VSA.BatchId = @rBatchId

		    --IF(@rId = 0)
		     BEGIN
			 INSERT INTO sEExam.tTestParticipant
			 SELECT @rTestId,2003,StudentId,@rTestDate,@rStartTime,@rEndTime,543,
			 @rTotalMarks,@rScoredMarks,@rTotalQuestions,@rRightQuestions,@rWrongQuestions,@rNotAttemptedQuestions,@rSkippQuestion,@lNextNumber + ROW_NUMBER() over(order by StudentId desc),''
			 FROM sStudent.vStudentAcademic VSA Where DivisionId = @rSourceId AND VSA.BatchId=@rBatchId
			  
			 SELECT @lNextNumber = MAX(Id) from sEExam.tTestParticipant where Id like  CONVERT(nvarchar(50),@rOrgId) + '%'
             EXECUTE sCommon.pTableRowIdModify  @rOrgId,'sEExam.tTestParticipant',@lNextNumber,0,0,0,@lNextNumber output 
			  
			 UPDATE  TA 
			 SET TA.TestStatusId = 543
			 FROM sEExam.tTestAssign TA INNER JOIN sStudent.vStudentAcademic VSA 
			 ON TA.SourceId = VSA.StudentId 
			 Where DivisionId = @rSourceId AND TA.TestId = @rTestId  AND VSA.BatchId=@rBatchId
			 END
           
         SELECT 1 AS Result 
   END 
    --EXECUTE sCommon.pTableRowIdModify   @rOrgId,'sEExam.tTestParticipant',@lNextNumber,0,0,0,@lNextNumber output 
   
ELSE
	 
   IF NOT EXISTS(SELECT 1 FROM sEExam.tTestParticipant Where  TestId = @rTestId 
   AND SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId)	
   BEGIN
  
	INSERT INTO sEExam.tTestParticipant
		(
			Id,
			TestId,
			SourceId,
			SourceTypeId,
			TestDate,
			StartTime,
			EndTime,
			TestStatusId,
			TotalMarks,
			ScoredMarks,
			TotalQuestions,
			RightQuestions,
			WrongQuestions,
			NotAttemptedQuestions,
			SkippQuestions			
		)
	VALUES
		(
			@lNextNumber,
			@rTestId,
			@rSourceId,
			@rSourceTypeId,
			@rTestDate,
			CONVERT(CHAR(7),@rStartTime,108),
			--@rStartTime,
			@rEndTime,
			@rTestStatusId,
			@rTotalMarks,
			@rScoredMarks,
			@rTotalQuestions,
			@rRightQuestions,
			@rWrongQuestions,
			@rNotAttemptedQuestions,
			@rSkippQuestion
			
		)    
	--UPDATE sEExam.tTestParticipant SET TestStatusId = 1 WHERE SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
	 --1 For Activated ,0 For Deactivated
	--SELECT 1 AS Result  
	END
	 ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	 IF(@rMode=1)
	 BEGIN
	  
	    UPDATE sEExam.tTestParticipant
	    SET
	     TestDate=@rTestDate,
	     StartTime=@rStartTime,
	     TestStatusId=@rTestStatusId,
	     TotalMarks=@rTotalMarks
	     WHERE Id = @rId
 	     --TestId = @rTestId AND SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId
	     --SELECT 11 AS Result 	
	 END
	 ELSE IF(@rMode=2)
	 BEGIN
	 
	 UPDATE sEExam.tTestParticipant
	    SET
	     
	     --EndTime=@rEndTime,
	     TestStatusId=@rTestStatusId,
	     ScoredMarks=@rScoredMarks,
	     TotalQuestions=@rTotalQuestions,
	     RightQuestions=@rRightQuestions,
	     WrongQuestions=@rWrongQuestions,
	     NotAttemptedQuestions=@rNotAttemptedQuestions,
	     SkippQuestions = @rSkippQuestion
	      
	     WHERE Id = @rId 
	     --TestId = @rTestId AND SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId
	     --SELECT 11 AS Result 
	  END    
	 END
	 
	 --UPDATE sEExam.tTestParticipant SET TestStatusId = @rTestStatusId WHERE SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
	 UPDATE sEExam.tTestParticipant SET TestStatusId = @rTestStatusId , ScoredMarks = 0 ,RightQuestions =0 , WrongQuestions =0 ,SkippQuestions =0 ,NotAttemptedQuestions =0 WHERE SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId
	 UPDATE sEExam.tTestAssign SET TestStatusId = @rTestStatusId Where SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND TestId = @rTestId

	 
    --Delete Participant Answer
		DELETE TPA FROM sEExam.tTestParticipantAnswer TPA 
		INNER JOIN sEExam.tTestParticipant TP ON TPA.TestParticipantId=TP.Id
		INNER JOIN sStudent.vStudentAcademic VSA ON TP.SourceId = VSA.StudentId 
		WHERE TPA.TestId= @rTestId  
		AND TP.SourceId = @rSourceId  AND TP.SourceTypeId = @rSourceTypeId

	 SELECT 1 AS Result
	 	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sErp].[ptTripLogAdd]...';


GO


ALTER PROCEDURE [sErp].[ptTripLogAdd]    
	
	@rEmployeeId bigint,
	@rLatitudeAxis nvarchar(20)='',
	@rLongitudeAxis nvarchar(20)='',
	@rUpdatedDateTime DATETIME='',
	@rUpdatedUserId bigint=0,
	@rFollowupId bigint = 0,
	@rTripLogStatusId tinyint = 0,
	@rTripDistance decimal(10,2)= 0.00,
	@rFollowupLocation nvarchar(200)='',
	@rBaseDisplacement decimal(10,2) =0.00,
	@rIsManual bit =0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		INSERT INTO [sErp].[tTripLog]
           ([EmployeeId],[LatitudeAxis],[LongitudeAxis],[UpdatedDateTime],[UpdatedUserId],[FollowupId],[TripLogStatusId],[TripDistance],[FollowupLocation],[BaseDisplacement] ,[IsManual])
     VALUES
           (@rEmployeeId,
           @rLatitudeAxis,
           @rLongitudeAxis,
           CASE WHEN @rIsManual = 1 THEN @rUpdatedDateTime ELSE sCommon.fGetDate()END,
           @rUpdatedUserId,
           @rFollowupId,
           @rTripLogStatusId,
           @rTripDistance,
           @rFollowupLocation,
           @rBaseDisplacement,
           @rIsManual)
		SELECT 1 AS Result 
		SELECT EM.FirstName +' '+ EM.LastName AS EmployeeName,CASE WHEN @rIsManual = 1 THEN @rUpdatedDateTime ELSE sCommon.fGetDate()END As CheckInTime FROM sHrm.tEmployeeMaster EM WHERE Id = @rEmployeeId
		SELECT Id As UserId FROM [sSecurity].[tUser] WHERE SourceId = @rEmployeeId AND SourceTypeId = 95
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptDetailsGet]...';


GO
 

ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
			
			
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date='',
			@rClassId int = 0,
			@rOrgIds nvarchar(max) = '',
			@rReceiptPrintGroupId nvarchar(100)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	Declare @lIDConfigValue nvarchar(50)='',@lOrgGroup_Id int=0
	Select @lOrgGroup_Id = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	 
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @rReceiptId

		SELECT  @lAmountInWord = sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(@lReceiptAmount,0.00),1,2,@lOrgGroupId)
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
		SELECT  @lCurrencyTitle = [sFinanceCommon].[fDefaultCurrencyTitleGet](@lOrgGroupId) 
	END
	ELSE
	BEGIN
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	END

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,
			--SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,
			
			--changes by Jash on 06/11/2020--%
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),ISNULL(FR.PaymentTransactionId,''))  END AS ChequeNo,
			--CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo
			--	WHEN ISNULL(PT.BankTransactionId,'') = '' THEN  CONVERT(nvarchar(20),FR.PaymentTransactionId)
			--	ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) +' - '+ CONVERT(nvarchar(20),PT.BankTransactionId) END AS ChequeNo,
			--%


			--ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,			
			
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN @lAmountInWord 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,
			
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			(CASE WHEN  U.SourceTypeId = 2003 
			  THEN -- Navrachana
				'Online Generated'
				ELSE ISNULL(U.DisplayTitle,'') END) AS UserName,
			--ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0  THEN 
			--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	
				  
			  
			(CASE WHEN  RBM.ReportId = 20576
			      THEN -- HM patel report
				  [sFee].[fReceiptMonthDetailGet](FR.ID,0)
			      WHEN RBM.ReportId = 30457 
			      THEN
				  [sFee].[fReceiptMonthDetailGet](FR.ID,1)		
			      WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
				  [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Head wise Month name in detail
				  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN				
				  [sFee].[fFeeMonthNameGet](FR.ID,FM.Id) -- Fee wise Month name in detail
			ELSE '' END) 
			AS MonthDetail,    

			
			(CASE WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
					 Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
					sFee.tReceipt FR1				
					INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
					INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
					INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
					INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
					Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					Order By FS.StartDate
					FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' )    -- Fee Head wise Fee Duration
				  WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN
					FS.FeeDuration -- Fee wise Fee Duration
				 ELSE '' END) AS FeeDuration,
			
			--Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
			--sFee.tReceipt FR1				
			--INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
			--INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
			--INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
			--INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
			--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
			----Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			-- Order By FS.StartDate
			--FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' ) AS FeeDuration,
			
			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN  FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN  FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
	        ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue ,
	        SF.FatherName,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,

			(ISNULL((CASE WHEN SC.PresentStreetOne IS NOT NULL AND SC.PresentStreetOne!='' THEN ''+ SC.PresentStreetOne END),'')+
			ISNULL((CASE WHEN SC.PresentStreetTwo IS NOT NULL AND SC.PresentStreetTwo!=''  THEN ', '+ SC.PresentStreetTwo END),'')+
			ISNULL((CASE WHEN SC.PresentStreetThree IS NOT NULL AND SC.PresentStreetThree!=''  THEN ', '+ SC.PresentStreetThree END),'')+
			ISNULL((CASE WHEN SC.PresentCity IS NOT NULL AND SC.PresentCity!=''  THEN ', ' + SC.PresentCity  END),'')+
			ISNULL((CASE WHEN SC.PresentState IS NOT NULL AND SC.PresentState!=''  THEN  ', '+ SC.PresentState END),'')+
			ISNULL((CASE WHEN SC.PresentZipCode IS NOT NULL AND SC.PresentZipCode!=''  THEN  ', '+ SC.PresentZipCode  END),''))
			 AS PresentAdress,
			--ISNULL(SC.PresentStreetOne +','+ SC.PresentStreetTwo +','+ SC.PresentStreetThree +','+ SC.PresentCity +','+ SC.PresentState +'-'+ SC.PresentZipCode ,'') AS PresentAdress,
			SC.ParentContactNo,
			ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount,
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,0),0) END) AS PendingFeeAmount,
			SA.FirstName,
			SA.LastName,
			ISNULL([sFee].[fFeeAmountSumGet](FR.SourceId),0) AS FeeAmount
	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
END
GO
PRINT N'Altering [sHrm].[pEmployeeProfileFullGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeProfileFullGet]  
 @rEmployeeId bigint,  
 --newly added parameter for report   
 @rBuilder1 nvarchar(max)='',  
 @rBuilder2 nvarchar(max)='',  
 @rReportId smallint = 0,  
 @rOrgId smallint = 0,  
 @rStrEmployeeId nvarchar(max)='',  
 @rEmployeeTypeId [int] =0,  
 @rDepartmentId [int]= 0,  
 @rGradeId [int]= 0,  
 @rGenderId [int]= 0,   
 @rDesignationId [int]= 0,   
 @rAgeFrom nvarchar(10)='',  
 @rAgeTo nvarchar(10)='',  
 @rEmployeeCode nvarchar(50)='',  
 @rEmployeeGroupId smallint= 0,  
 @rEmployeeStatusId smallint=0  
   
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
   
BEGIN   
  
SELECT   
   --Personal Details  
   EM.Id,  
   EM.Code,  
   ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName,  
   ISNULL(EP.UIDNumber,'') AS UIDNumber,  
   ISNULL(EP.DateOfBirth,'') AS DateOfBirth,  
   ISNULL(GM.Title,'') AS Gender,  
   ISNULL(MM.Title,'') AS MeritalStatus,  
   ISNULL(BGM.Title,'') AS BloodGroup,  
   ISNULL(EP.Qualification,'') AS Qualification,  
   ISNULL(EP.FamilyCast,'') AS FamilyCast,  
   --Communication  
   ISNULL(EC.PresentStreetOne,'')+' '+ISNULL(EC.PresentStreetTwo,'')+' '+ISNULL(EC.PresentStreetThree,'') AS PresentAddress,  
   ISNULL(EC.PresentCity,'') AS PresentCity,  
  ISNULL(EC.PresentState,'') AS PresentState,  
  ISNULL(EC.PresentCountry,'') AS PresentCountry,  
  ISNULL(EC.PresentZipCode,'') AS PresentZipCode,  
  ISNULL(EC.PresentContactNo,'') AS PresentContactNo,  
  ISNULL(EC.PermanentStreetOne,'')+' '+ISNULL(EC.PermanentStreetTwo,'')+' '+ISNULL(EC.PermanentStreetThree,'') AS PermanentAddress,  
  ISNULL(EC.PermanentCity,'') AS PermanentCity,  
  ISNULL(EC.PermanentState,'') AS PermanentState,  
  ISNULL(EC.PermanentCountry,'') AS PermanentCountry,  
  ISNULL(EC.PermanentZipCode,'') AS PermanentZipCode,  
  ISNULL(EC.PermanentContactNo,'') AS PermanentContactNo,  
   ISNULL(EC.EmergencyStreetOne,'')+' '+ISNULL(EC.EmergencyStreetTwo,'')+' '+ISNULL(EC.EmergencyStreetThree,'') AS EmergencyAddress,  
  ISNULL(EC.EmergencyCity,'') AS EmergencyCity,  
  ISNULL(EC.EmergencyState,'') AS EmergencyState,  
  ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,  
  ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,  
  ISNULL(EC.EmergencyContactNo,'') AS EmergencyContactNo,  
  --Job Details  
  ISNULL(EJ.DateOfJoining,'') AS DateOfJoining,    
  (COALESCE(CAST(EJ.DateOfleaving AS NVARCHAR(23)),'')) AS DateOfleaving,  
  ISNULL(EJ.JobRemark,'') AS JobRemark,  
  ISNULL(EJ.ReferenceRemark,'') AS ReferenceRemark,  
  ISNULL(EDM.Title,'') AS EmployeeDesignation,  
  ISNULL(DM.Title,'') AS OrganizationDepartment,  
  ISNULL(EGM.Title,'') AS EmployeeGrade,  
  ISNULL(GrpM.Title,'') AS EmployeeGroup,  
  ISNULL(ETM.Title,'') AS EmployeeType,  
  ISNULL(EJ.ProbationUptoDate,'') AS ProbationUptoDate,  
  ISNULL(EJ.AhdocUptoDate,'') AS AhdocUptoDate,  
  ISNULL(EJ.PermanentDate,'') AS PermanentDate,  
  ISNULL(EJ.DateOfResignation,'') AS DateOfResignation,  
  ----Previous Employment  
  --ISNULL(EPE.CompanyName,'') AS PrevCompanyName,  
  --ISNULL(EPE.Designation,'') AS PrevDesignation,  
  --ISNULL(EPE.Duration,'') AS Duration,  
  --ISNULL(EPE.LastSalary,0) AS LastSalary,  
  --ISNULL(EPE.ReasonForLeaving,'') AS ReasonForLeaving,  
  --ISNULL(EPE.JobDescription,'') AS JobDescription,  
  --Notification Details  
  ISNULL(EC.PersonalEmail,'') As PersonalEmail,  
  ISNULL(EC.MobileNumber,'') AS MobileNumber,  
  ISNULL(EC.PhoneNoCompany,'') AS PhoneNoCompany,  
  ISNULL(EC.ExtensionNo,'') AS ExtensionNo,  
  ISNULL(EC.CompanyEmail,'') AS CompanyEmail,  
  --EI.EmployeePhoto,  
  CASE @rReportId WHEN 0 THEN ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) ELSE EI.EmployeePhoto END AS EmployeePhoto ,  
  ISNULL(ESO.AccountNumber,'') AS AccountNumber,  
  ISNULL(ESO.BankName,'') AS BankName,  
  ISNULL(ESO.Branch,'') AS BankBranch,  
  ISNULL(ESO.PanNumber,'') AS PanNumber,  
  ISNULL(ESO.UAN,'') AS UANNumber,  
  ISNULL(ESO.EPFNumber,'') AS EPFNumber,  
  ISNULL(ESO.IncrementDate,'') AS IncrementDate,  
  ISNULL(ESO.BasicPay,0) AS BasicPay,  
     --ISNULL(EFD.Occupation,'') AS Occupation,  
  convert(nvarchar(20),EM.Id) AS EmployeeIdText,  
  convert(nvarchar(20),@rOrgId) AS OrgIdText,  
  ISNULL(EJ.OrganizationDepartmentId,0) AS DepartmentId,  
  OM.DisplayTitle AS OrgTitle,  
  ISNULL(EP.AdhaarNumber,'') AS AdhaarNumber,  
  ISNULL(ESO.Payscale,'') AS Payscale,  
  --[sHrm].[fTeachingSubjectGet] (EM.Id) AS TeachingSubject  
  EJ.Subjects AS TeachingSubject  
  FROM   
  sHrm.tEmployeeMaster EM   
  LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.ID = EC.EmployeeId  
  INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId = EM.Id  
  INNER JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.ID    
  --INNER JOIN sHrm.tEmployeePreviousEmployment EPE ON EPE.EmployeeId=EM.ID  
  LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = EP.BloodGroupId      
  LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EP.GenderId  
  LEFT JOIN sCommon.tMaritalStatusMaster MM ON MM.Id =  EP.MaritalstatusId  
  --LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EJ.ReligionId  
  LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id  
  LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.ID = EJ.EmployeeDesignationId  
  LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJ.OrganizationDepartmentId  
  LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id=EJ.EmployeeTypeId  
  LEFT JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id=EJ.EmployeeGradeId  
  LEFT JOIN sHrm.tEmployeeGroupMaster GrpM ON GrpM.Id=EJ.EmployeeGroupId  
  LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id  
  --LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON EFD.EmployeeId = EM.Id  
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId    
  WHERE   
  (EM.Id=@rEmployeeId OR @rEmployeeId = 0)  
  AND (ISNULL(EM.Id,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='')   
  AND ((EM.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )  
  AND (ETM.Id = @rEmployeeTypeId OR @rEmployeeTypeId = 0)  
  AND (DM.Id = @rDepartmentId OR @rDepartmentId = 0)  
  AND (EM.StatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)  
  AND (GrpM.Id=@rEmployeeGroupId OR @rEmployeeGroupId=0)   
  AND (EGM.Id = @rGradeId OR @rGradeId = 0)  
  AND (EDM.Id = @rDesignationId OR @rDesignationId = 0)  
  AND (GM.Id = @rGenderId OR @rGenderId = 0)  
  AND ((DATEDIFF(yy,EP.DateOfBirth,sCommon.fGetDate()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))  
  AND ((DATEDIFF(yy,EP.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))  
  AND  ( EM.OrgId = @rOrgId OR @rOrgId = 0)  
  --AND ISNULL(EM.IsOtherUser,0) = 0     
END
GO
PRINT N'Altering [sHrm].[pStaffAttendaceDashboardGet]...';


GO
 
 
ALTER PROCEDURE [sHrm].[pStaffAttendaceDashboardGet]
	 
	 @rTypeId smallint,
	 @rUptoDate date='',
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDepartmentId int=0,
	 @rCommonOrgGroupBatchId int=0,
	 @rSyncDate int =0,
	 @rUserId bigint =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

if @rTypeId=1
BEGIN
	IF(@rSyncDate=1)
		BEGIN
			DELETE  sHrm.tTempStaffAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			INSERT INTO sHrm.tTempStaffAttendance
	SELECT     
    OGM.Id AS OrgGroupId,
    OGM.Title As OrgGroupTitle,
    0 As OrgId,
	'' As OrgTitle,
 --TotalCount
			ISNULL((SELECT COUNT(EM.Id) FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
			INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
			WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 AND  ISNULL(EM.IsOtherUser,0) = 0),0) 
			AS TotalCount,

 --PresentCount
    ISNULL((SELECT 
        COUNT(ETRP.EmployeeId) 
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DME.OrgGroupId=OGM.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
      ),0) AS PresentCount,
--AbsentCount
      ISNULL((SELECT 
         COUNT(ETRP.EmployeeId) 
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
      WHERE DME.OrgGroupId=OGM.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
            AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
      ),0) As AbsentCount,
--LeaveCount
    ISNULL( (SELECT 
        COUNT(EM.Id)
     FROM sHrm.tLeave SHT
          INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId				
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		  INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				
	 WHERE DME.OrgGroupId=OGM.Id  AND COGBM.Id=@rCommonOrgGroupBatchId   and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  AND((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	),0) As LeaveCount,
--AB10Count
	 ISNULL((SELECT 
	    COUNT(EmployeeId) 
	FROM(
         SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,
             (OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR						
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
		WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
		
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	 ) AS Tmp),0) As 'AB10Count',
--AB3DaysCount
    ISNULL((SELECT 
	   COUNT(EmployeeId) FROM(
	      SELECT 
	          ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		      d.EmployeeId,
		      AttendanceDate,
		      d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
              INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			  INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
         WHERE
              DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
              IsPresent IN(0) 
              AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
         GROUP BY d.EmployeeId,AttendanceDate,IsPresent
         ) as sfsf
     WHERE rowno=3),0) as AB3DaysCount,
--Leave3DayCount    
  ISNULL((SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d
		 	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
             INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
             LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
           DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
          d.ToDate=CONVERT(char(10), @rUptoDate,126)
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
    ),0)  As Leave3DayCount,
   
--HundredPerAttnCount		
    ISNULL((SELECT 
      COUNT(EmployeeId) FROM (
          SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,(OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) as PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(numeric(10,2),((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage												
		  FROM sHrm.tEmployeeAttendanceRegister EAR						
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID						
						INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID						
		  WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)		
		  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	   ) AS Tmp),0) As 'HundredPerAttnCount',
--PendingCount	  
	    ISNULL((SELECT 
        COUNT(EM.Id) 
		 FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	 WHERE OGM.Id=OGMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 AND  ISNULL(EM.IsOtherUser,0) = 0
	 
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ),0) AS PendingCount,
	   
	   @rUptoDate,
		  @rCommonOrgGroupBatchId,GetDate()	
	   
    FROM sSetup.tOrgGroupMaster OGM
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    WHERE OGM.Id<>1 AND COGBM.Id=@rCommonOrgGroupBatchId   AND ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
	And ISNULL(OGM.IsObsolete,0) = 0
	SELECT * FROM sHrm.tTempStaffAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		END
	ELSE
		Print 1
		BEGIN
			  IF  Exists(select 1 from sHrm.tTempStaffAttendance    where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND EmployeeAttendanceDate=  CONVERT(date,@rUptoDate,102)AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
			BEGIN
	
				SELECT * FROM sHrm.tTempStaffAttendance   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN
			DELETE  sHrm.tTempStaffAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			INSERT INTO sHrm.tTempStaffAttendance
--TotalCount	
				SELECT     
    OGM.Id AS OrgGroupId,
    OGM.Title As OrgGroupTitle,
    0 As OrgId,'' As OrgTitle,
	    ISNULL((SELECT 
        COUNT(EM.Id) 
     FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
          --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				    
		  --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		  --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID          
	 WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0),0) AS TotalCount,
  --  (SELECT 
  --      COUNT(EM.Id) 
  --   FROM sHrm.tEmployeeMaster EM
		--  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		--  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--  --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --        --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
  --        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				    
		--  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		--  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID          
	 --WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
	 --and EM.statusid=7) AS Total,

    ISNULL((SELECT 
        COUNT(ETRP.EmployeeId) 
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DME.OrgGroupId=OGM.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
		   and EM.statusid=7
      ),0) AS PresentCount,

     ISNULL((SELECT 
         COUNT(ETRP.EmployeeId) 
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
      WHERE DME.OrgGroupId=OGM.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
            AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			 and EM.statusid=7
      ),0) As AbsentCount,
      
    ISNULL((SELECT 
        COUNT(EM.Id)
     FROM sHrm.tLeave SHT
          INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId				
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		  INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				
	 WHERE DME.OrgGroupId=OGM.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
		  AND((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  and EM.statusid=7
	),0) As LeaveCount,

	ISNULL((SELECT 
	    COUNT(EmployeeId) 
	FROM(
         SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,
             (OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR						
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
		WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
		
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	 ) AS Tmp),0) As 'AB10Count',

   ISNULL((SELECT 
	   COUNT(EmployeeId) FROM(
	      SELECT 
	          ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		      d.EmployeeId,
		      AttendanceDate,
		      d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
              INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			  INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
         WHERE
              DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
              IsPresent IN(0) 
              AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			  and EM.statusid=7
         GROUP BY d.EmployeeId,AttendanceDate,IsPresent
         ) as sfsf
     WHERE rowno=3),0) as AB3DaysCount,
    
 ISNULL((SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d
		 	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
             INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
             LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
           DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
          d.ToDate=CONVERT(char(10), @rUptoDate,126) 
		  and EM.statusid=7
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
    ),0)  As Leave3DayCount,
   
		
   ISNULL((SELECT 
      COUNT(EmployeeId) FROM (
          SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,(OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) as PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(numeric(10,2),((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage												
		  FROM sHrm.tEmployeeAttendanceRegister EAR						
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID						
						INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID						
		  WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)		
		  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	   ) AS Tmp),0) As 'HundredPerAttnCount',

	   ISNULL((SELECT COUNT(EM.Id) 
		 FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		 WHERE OGM.Id=OGMM.Id 
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
							WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ),0) AS PendingCount,
	   @rUptoDate,
		  @rCommonOrgGroupBatchId,GetDate()	
	   
    FROM sSetup.tOrgGroupMaster OGM
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    WHERE OGM.Id<>1 AND COGBM.Id=@rCommonOrgGroupBatchId  AND ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
	And ISNULL(ISNULL(OGM.IsObsolete,0),0) = 0
	SELECT * FROM sHrm.tTempStaffAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			END
		END
  END
  
ELSE IF @rTypeId=2  

BEGIN
IF(@rUserId = 0)
  BEGIN
  SELECT 
     OGMT.Id As OrgGroupId,
     OM.Id AS OrgId, 
     OM.DisplayTitle AS OrgTitle,
     OGMT.Title As OrgGroupTitle,
	 (SELECT 
         COUNT(EM.Id) 
      FROM sHrm.tEmployeeMaster EM
		 INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
         --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
         INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
       WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
       AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) As TotalCount,
   --  (SELECT 
   --      COUNT(EM.Id) 
   --   FROM sHrm.tEmployeeMaster EM
		 --INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 --INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 ----INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --      --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
   --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
   --    WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
   --    AND EM.statusid=7) As Total,
        
      (SELECT 
          COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
       WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=1  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS PresentCount,
        
      (SELECT 
           COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEM ON OMEM.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OMEM.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=0  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS AbsentCount, 	

	   (SELECT 
	         COUNT(EM.Id)
        FROM sHrm.tLeave SHT
           INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
           INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
		   INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		      
		   INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	       LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID				
		 WHERE EJD.OrgId=OM.Id AND				
			  ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			   AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  AND COGBM.Id=@rCommonOrgGroupBatchId		
			   and EM.statusid=7		
		) As LeaveCount,
		
   (SELECT 
	   COUNT(EmployeeId) FROM(
           SELECT    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DME.Id,DME.Code As DeptCode,
              (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  (EC.MobileNumber) AS ContactNo,
			   COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
               CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
			FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID												
			WHERE EJD.OrgId=OM.Id AND 
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
				and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	      ) AS Tmp) As 'AB10Count',
	
	(SELECT COUNT(EmployeeId) from(
	    SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
		FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
              AND COGBM.Id=@rCommonOrgGroupBatchId
			  and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) as T
        WHERE rowno=3) AS AB3DaysCount,
        
     (SELECT 
        COUNT(EmployeeId) FROM(
	       SELECT 
			d.EmployeeId,
			d.FromDate,
			d.ToDate
		  FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
		and EM.statusid=7
        ) AS Temp 
        WHERE (DATEDIFF(d, FromDate, ToDate)=2)
        )  AS Leave3DayCount,
      
    (SELECT 
        COUNT(EmployeeId) FROM  (
           SELECT    
             OGMEL.Id as OrgGroupId,
             OGMEL.Title As OrgGroupTitle,
             OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
             DME.Id,DME.Code As DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 (EC.MobileNumber) AS ContactNo,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
              convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage

            FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		    WHERE EJD.OrgId=OM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                 EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				 and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	     ) AS Tmp) As 'HundredPerAttnCount'
		 ,
	(SELECT  COUNT(EM.Id) 
		FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	 WHERE OM.Id=OMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ) AS PendingCount,
	   getdate()AS UpdateDate
			
    FROM 
       sSetup.tOrgGroupMaster OGMT 
    INNER JOIN sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId    
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
    WHERE OGMT.Id=@rOrgGroupId AND COGBML.Id=@rCommonOrgGroupBatchId 
	And ISNULL(OGMT.IsObsolete,0) = 0
  END   
ELSE IF(@rUserId <> 0)
  BEGIN
  SELECT 
     OGMT.Id As OrgGroupId,
     OM.Id AS OrgId, 
     OM.DisplayTitle AS OrgTitle,
     OGMT.Title As OrgGroupTitle,
	 (SELECT 
         COUNT(EM.Id) 
      FROM sHrm.tEmployeeMaster EM
		 INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
         --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
         INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
       WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
       AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) As TotalCount,
   --  (SELECT 
   --      COUNT(EM.Id) 
   --   FROM sHrm.tEmployeeMaster EM
		 --INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 --INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 ----INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --      --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
   --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
   --    WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
   --    AND EM.statusid=7) As Total,
        
      (SELECT 
          COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
       WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=1  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS PresentCount,
        
      (SELECT 
           COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEM ON OMEM.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OMEM.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=0  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS AbsentCount, 	

	   (SELECT 
	         COUNT(EM.Id)
        FROM sHrm.tLeave SHT
           INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
           INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
		   INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		      
		   INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	       LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID				
		 WHERE EJD.OrgId=OM.Id AND				
			  ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			   AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  AND COGBM.Id=@rCommonOrgGroupBatchId		
			   and EM.statusid=7		
		) As LeaveCount,
		
   (SELECT 
	   COUNT(EmployeeId) FROM(
           SELECT    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DME.Id,DME.Code As DeptCode,
              (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  (EC.MobileNumber) AS ContactNo,
			   COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
               CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
			FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID												
			WHERE EJD.OrgId=OM.Id AND 
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
				and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	      ) AS Tmp) As 'AB10Count',
	
	(SELECT COUNT(EmployeeId) from(
	    SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
		FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
              AND COGBM.Id=@rCommonOrgGroupBatchId
			  and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) as T
        WHERE rowno=3) AS AB3DaysCount,
        
     (SELECT 
        COUNT(EmployeeId) FROM(
	       SELECT 
			d.EmployeeId,
			d.FromDate,
			d.ToDate
		  FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
		and EM.statusid=7
        ) AS Temp 
        WHERE (DATEDIFF(d, FromDate, ToDate)=2)
        )  AS Leave3DayCount,
      
    (SELECT 
        COUNT(EmployeeId) FROM  (
           SELECT    
             OGMEL.Id as OrgGroupId,
             OGMEL.Title As OrgGroupTitle,
             OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
             DME.Id,DME.Code As DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 (EC.MobileNumber) AS ContactNo,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
              convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage

            FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		    WHERE EJD.OrgId=OM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                 EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				 and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	     ) AS Tmp) As 'HundredPerAttnCount'
		 ,
	(SELECT  COUNT(EM.Id) 
		FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	 WHERE OM.Id=OMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ) AS PendingCount,
	   getdate()AS UpdateDate
			
    FROM 
       sSetup.tOrgGroupMaster OGMT 
    INNER JOIN sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId    
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
	INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id
    WHERE OGMT.Id=@rOrgGroupId AND COGBML.Id=@rCommonOrgGroupBatchId 
	And OGMT.IsObsolete = 0 AND U.UserId = @rUserId
  END 
  END
  
  
else if @rTypeId=3   
  BEGIN
--TotalCount
    (SELECT 
      (DME.Id) As DepartmentId,
        DME.Code As DepartmentCode,OGMM.Id AS OrgGroupId,
        OGMM.Title As OrgGroupTitle,0 As OrgId,'' As OrgTitle,
        COUNT(DME.Id) As TotalCount,
--PresentCount
	(SELECT 
            COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	   WHERE DME.Id=DMER.Id 
			and ETRP.IsPresent=1 
			AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
	   ) AS PresentCount,
--AbsentCount			
	  (SELECT COUNT(ETRP.EmployeeId) 
            FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
	   WHERE DME.Id=DMER.Id and ETRP.IsPresent=0 
			AND ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
			and EM.statusid=7
		) AS AbsentCount,
--LeaveCount			
   (SELECT    
        COUNT(EM.Id)
    FROM sHrm.tLeave SHT
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
	WHERE DME.Id=DMER.Id AND				
			((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		     AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))		
			 and EM.statusid=7		
	) AS LeaveCount,
				
--AB10%Count				
     (SELECT 
         COUNT(EmployeeId) 
      FROM (
         SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id) AS FLOAT))*100)) as Percentage		
		FROM sHrm.tEmployeeAttendanceRegister EAR
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
		WHERE DME.Id=DMER.Id AND 
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
	    GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	    HAVING CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id) AS FLOAT))*100))<=90
	     ) AS Tmp) AS 'AB10Count',
	           
--AB3DaysCount	           
      (SELECT 
          COUNT(EmployeeId) FROM(
	         SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
	   FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	    WHERE
            DME.Id=DMER.Id  AND IsPresent IN(0) 
            AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) AS T
        WHERE rowno=3) as AB3DaysCount,
  --Leave3DayCount
   (SELECT COUNT(EmployeeId) FROM(
	   SELECT
			d.EmployeeId,d.FromDate,d.ToDate
	   FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE
			 DME.Id=DMER.Id AND 
			 d.ToDate=CONVERT(char(10), @rUptoDate,126)   
			 and EM.statusid=7     
        ) AS Temp WHERE (DATEDIFF(d, FromDate, ToDate)=2)        
      )  AS Leave3DayCount,
        
--HundredPerAttnCount     
        
  (SELECT 
      COUNT(EmployeeId) FROM(
         SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,
            (OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) as Percentage		
	      FROM sHrm.tEmployeeAttendanceRegister EAR			
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE DME.Id=DMER.Id AND 		
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	  ) AS Tmp) As 'HundredPerAttnCount',

--PendingCount


	  (	select COUNT(*) from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
	where    EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126)) AND DMER.Id = DME.Id AND DMER.OrgGroupId = OGMM.Id and EM.statusid=7) 
	AS PendingCount

	FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
        --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	WHERE OGMM.ID=@rOrgGroupId AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 --AND COGBML.Id=@rCommonOrgGroupBatchId AND 
	And ISNULL(OGMM.IsObsolete,0) = 0
	GROUP BY DME.Id,DME.Code,OGMM.Id,OGMM.Title
	) 
					
  END
  
  
else if @rTypeId=4 
  BEGIN     
     SELECT (DME.Id) As DepartmentId,
         DME.Code As DepartmentCode,
         OGMM.Id AS OrgGroupId,OGMM.Title As OrgGroupTitle,
         OM.Id As OrgId,OM.DisplayTitle As OrgTitle,
         COUNT(DME.Id) As TotalCount, 
         (SELECT 
            COUNT(ETRP.EmployeeId) 
          FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE DME.Id=DMER.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId  
			AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7
           ) As PresentCount,
			
	  (SELECT 
	      COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
       WHERE DME.Id=DMER.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId  
	   and EM.statusid=7
	   AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId  
			AND ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
	  ) AS AbsentCount,
			
			
      (SELECT 
       COUNT(EM.Id)
      FROM sHrm.tLeave SHT
            INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
	        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	       
	        INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
            LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
	  WHERE DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  				
			((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			 AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			 and EM.statusid=7
	  ) As LeaveCount,
				
				
     (SELECT 
         COUNT(EmployeeId) FROM  (
            SELECT    
                OGMEL.Id as OrgGroupId,
                OGMEL.Title AS OrgGroupTitle,
                OMEL.Id AS OrgId,(OMEL.Title) As OrgTitle,
                DMER.Id,DMER.Code AS DepartmentCode,
                (EM.Id)EmployeeID,
                (EM.FirstName+' '+EM.LastName) AS EmployeeName,
				(EC.MobileNumber) AS ContactNo,
				COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
                CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) as Percentage

			 FROM sHrm.tEmployeeAttendanceRegister EAR				
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
			 WHERE DME.Id=DMER.Id AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
				and EM.statusid=7
			 GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	         HAVING CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100))<=90
	       ) AS Tmp) As 'AB10Count',
	           
	           
   (SELECT 
       COUNT(EmployeeId) FROM(
	      SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
			    d.EmployeeId,
			    AttendanceDate,
			    d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId  AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  
			IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, CONVERT(DATE, @rUptoDate, 126)) AND @rUptoDate    
			and EM.statusid=7           
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) AS T
        WHERE rowno=3) AS AB3DaysCount,
        
  (SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT 
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d		
 			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId	
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		  
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE
			 DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND 
			 d.ToDate=CONVERT(CHAR(10), @rUptoDate,126)     
			 and EM.statusid=7   
        ) AS Temp WHERE (DATEDIFF(d, FromDate, ToDate)=2)       
    )  AS Leave3DayCount,
        
        
    (SELECT 
       COUNT(EmployeeId) FROM  (
          SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(Count(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE DME.Id=DMER.Id AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
			and EM.statusid=7
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	) AS Tmp) As 'HundredPerAttnCount',
	 (	select COUNT(*) from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
	where  OM.Id=OMM.Id and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126)) AND DMER.Id = DME.Id AND DMER.OrgGroupId=OGMM.Id and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) 
	AS PendingCount
  
   FROM sHrm.tEmployeeMaster EM
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
     --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
    INNER JOIN sHrm.tEmployeeJobDetail EJD1 ON EJD1.EmployeeId=EM.ID
    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD1.OrgGroupDepartmentId
	LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID              
  WHERE DME.OrgGroupId=@rOrgGroupId And EJD1.OrgId=@rOrgId and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 --AND COGBML.Id=@rCommonOrgGroupBatchId 
  And ISNULL(OGMM.IsObsolete,0) = 0
  GROUP BY DME.Id,DME.Code,OGMM.Id,OGMM.Title,OM.Id,OM.DisplayTitle
	 
END  
   
   
else if @rTypeId=5   

BEGIN
   (SELECT(DM.code) As Dept,
          (EM.Id) As EmployeeId,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
          (EC.MobileNumber) AS ContactNo
    FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
			INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DM.Id=@rDepartmentId --AND COGBM.Id=@rCommonOrgGroupBatchId 
	  And ISNULL(OGMM.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
     )
END
   
ELSE IF @rTypeId=31
 BEGIN
     SELECT 
        (OGMM.id) AS OrgGroupId,(OGMM.Title) As OrgGroupTitle,
        (OM.id) OrgId,(OM.Title) OrgTitle,
        (DME.Code) As DepartmentCode,
		(EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
     FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --      INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	    
        LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID                    
	 WHERE DME.OrgGroupId=@rOrgGroupId --AND COGBM.Id=@rCommonOrgGroupBatchId 
	  And ISNULL(OGMM.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	 AND DME.Id=@rDepartmentId--) As Total
       
 END   
 
ELSE IF @rTypeId=41 
 BEGIN
	SELECT 
	   (OGMM.id) As OrgGroupId,
	   (OGMM.Title) As OrgGroupTitle,
	   (OM.id) OrgId,(OM.Title) OrgTitle,
	   DME.Code As DepartmentCode,(EM.Id)EmployeeID,
	   (EM.Code)EmployeeCode,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
	   ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
	   (EC.MobileNumber) AS ContactNo
     FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --      INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	   
        LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	WHERE 
		EJD.OrgId=@rOrgId --AND COGBM.Id=@rCommonOrgGroupBatchId 
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0	
		 And ISNULL(OGMM.IsObsolete,0) = 0
		AND ((@rDepartmentId <>1 AND DME.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))   
 END   
 
ELSE IF @rTypeId=32   

BEGIN
    SELECT 
        (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
        ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
    FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	 WHERE DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId and  ETRP.IsPresent=1
	  And ISNULL(OGME.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
		
END

else if @rTypeId=42  

BEGIN
    SELECT 
        (OGME.id) As OrgGroupId,
        (OGME.Title) As OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code As DepartmentCode,
        (EM.Id)EmployeeID,
		(EM.Code)EmployeeCode,
        (EM.FirstName+' '+EM.LastName) AS EmployeeName,
        ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE EJD.OrgId=@rOrgId
		and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		and  ETRP.IsPresent=1
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		And ISNULL(OGME.IsObsolete,0) = 0
		and ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
	
END


else if @rTypeId=33  
  BEGIN
     SELECT 
        (OGME.id) As OrgGroupId,
        (OGME.Title) As OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code As DepartmentCode,
		(EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			
	where DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId and  ETRP.IsPresent=0  AND COGBM.Id=@rCommonOrgGroupBatchId 
	And ISNULL(OGME.IsObsolete,0) = 0
	and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	    AND ETRP.AttendanceDate = CONVERT(CHAR(10),  @rUptoDate,126)
	
  END   
  
  ELSE IF @rTypeId=43   
  BEGIN
     SELECT 
       (OGME.id) As OrgGroupId,
       (OGME.Title) As OrgGroupTitle,
 (OME.id) OrgId,(OME.Title) OrgTitle,
       DMER.Code As DepartmentCode,
       (EM.Id)EmployeeID,
	   (EM.Code)EmployeeCode,
       (EM.FirstName+' '+EM.LastName) AS EmployeeName,
       ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
       (EC.MobileNumber) AS ContactNo
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	  WHERE EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId 
		and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		and  ETRP.IsPresent=0 
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		And ISNULL(OGME.IsObsolete,0) = 0
		and ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
	
  END 
   
 ELSE IF @rTypeId=34 
   
   BEGIN
      
       select (OGMEL.id) As OrgGroupId,
              (OGMEL.Title) As OrgGroupTitle,
              (OMEL.id) OrgId,(OMEL.Title) OrgTitle,
              DMER.Code As DepartmentCode,
              (EM.Id)EmployeeID,
			  (EM.Code)EmployeeCode,
              (EM.FirstName+' '+EM.LastName) AS EmployeeName,
              ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
              (EC.MobileNumber) AS ContactNo
       FROM sHrm.tLeave SHT
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	   WHERE DMER.OrgGroupId=@rOrgGroupId AND DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId 
	   And OGMEL.IsObsolete = 0
	   and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   AND			
				((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
   
   END
   
   
 ELSE IF @rTypeId=44    
   BEGIN
       SELECT (OGMEL.id) As OrgGroupId,
              (OGMEL.Title) As OrgGroupTitle,
              (OMEL.id) OrgId,(OMEL.Title) OrgTitle,
              DMER.Code As DepartmentCode,
			  (EM.Id)EmployeeID,
              (EM.Code)EmployeeCode,
			  (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
              (EC.MobileNumber) AS ContactNo
       FROM sHrm.tLeave SHT
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	   WHERE EJD.OrgId=@rOrgId	AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And OGMEL.IsObsolete = 0
	   and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
				AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And				
				 ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			     AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		
   END
   
 ELSE IF @rTypeId=35 
   
   BEGIN

    select * from (
          select    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,--DMER.Id,DMER.Code As DeptCode,
              (EM.Id)EmployeeID,
			  (EM.Code)EmployeeCode,
			  (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			  (EC.MobileNumber) AS ContactNo,DMER.Code As DepartmentCode,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
			  convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		  FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			
		  WHERE DMER.OrgGroupId=@rOrgGroupId  AND DMER.Id=@rDepartmentId 
		  And OGMEL.IsObsolete = 0
		  
		  AND COGBM.Id=@rCommonOrgGroupBatchId AND
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,EJD.DateOfJoining,EDM.title,
				EM.Id,(EM.Code),(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),DMER.Code
	       HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	   ) AS Tmp
      
   END
   
   
   else if @rTypeId=45 
   
   BEGIN
   
    SELECT * FROM (
          SELECT    
               OGMEL.Id as OrgGroupId,
               OGMEL.Title As OrgGroupTitle,
               OMEL.Id As OrgId,
               (OMEL.Title) As OrgTitle,
               (EM.Id)EmployeeID,
			   (EM.Code)EmployeeCode,
               (EM.FirstName+' '+EM.LastName) AS EmployeeName,
               ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
				(EC.MobileNumber) AS ContactNo,DMER.Code As DepartmentCode,
				count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
                convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		  FROM sHrm.tEmployeeAttendanceRegister EAR				
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId			
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE EJD.OrgId=@rOrgId  AND COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
			    and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) AND
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
				GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,EJD.DateOfJoining,EDM.title
				,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),DMER.Code 
	       HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	    ) AS Tmp
      
   END
   
   
 ELSE IF @rTypeId=36
  
  BEGIN
    (SELECT Temp.OrgGroupId,
            Temp.OrgGroupTitle,
            Temp.OrgId,Temp.OrgTitle,
            (EMR.Id) As EmployeeId,
			EMR.Code As EmployeeCode,
            (EMR.FirstName+' '+EMR.LastName) AS EmployeeName,
            ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
            (ECR.PresentContactNo) AS ContactNo,
			DepartmentCode
     FROM(select ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		    d.EmployeeId,(EM.Code)EmployeeCode,
		    AttendanceDate,d.IsPresent,
		    OGMEL.Id As OrgGroupId,
		    OGMEL.Title As OrgGroupTitle,
		    OMEL.Id As OrgId,OMEL.Title As OrgTitle,
		    DMER.Code As DepartmentCode
          FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
        WHERE
            DMER.OrgGroupId=@rOrgGroupId And DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
			AND 
            IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate       
        Group By d.EmployeeId,EM.Code,AttendanceDate,IsPresent,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Code 
        ) As Temp
            INNER JOIN sHrm.tEmployeeMaster EMR ON EMR.ID=Temp.EmployeeId AND  ISNULL(EMR.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMR.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications ECR on EMR.ID=ECR.EmployeeID        
        where rowno=3
      ) 
       
  END
  
  
  
 ELSE IF @rTypeId=46 
 
  BEGIN
  (SELECT Temp.OrgGroupId,
          Temp.OrgGroupTitle,
          Temp.OrgId,Temp.OrgTitle,
          (EMR.Id) As EmployeeId,
		  EMR.Code As EmployeeCode,
          (EMR.FirstName+' '+EMR.LastName) AS EmployeeName,	
          ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,	
          (ECR.PresentContactNo) AS ContactNo,DepartmentCode
      FROM(
	      select 
	         ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
			 d.EmployeeId,
			 EM.Code As EmployeeCode,
			 AttendanceDate,d.IsPresent,
			 OGMEL.Id As OrgGroupId,
			 OGMEL.Title As OrgGroupTitle,
			 OMEL.Id As OrgId,
			 OMEL.Title As OrgTitle,
			 DMER.Code As DepartmentCode
		   FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
        EJD.OrgId=@rOrgId 
        AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And OGMEL.IsObsolete = 0
		and EM.statusid=7
		AND
        IsPresent IN(0) AND COGBM.Id=@rCommonOrgGroupBatchId 
        AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
        Group By d.EmployeeId,EM.Code,AttendanceDate,IsPresent,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Code 
        ) As Temp
		INNER JOIN sHrm.tEmployeeMaster EMR ON EMR.ID=Temp.EmployeeId AND  ISNULL(EMR.IsOtherUser,0) = 0
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMR.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications ECR on EMR.ID=ECR.EmployeeID
      WHERE rowno=3
    ) 
    
  END

  ELSE IF @rTypeId=37
  
  BEGIN
     (SELECT * FROM(
	     SELECT
			d.FromDate,
			d.ToDate,
			OGMEL.Id As OrgGroupId,
			OGMEL.Title As OrgGroupTitle,
			OMEL.Id As OrgId,
			OMEL.Title As OrgTitle,
			EM.Code As EmployeeId,
			EM.ID As EmployeeCode,
			(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
            (EC.MobileNumber) AS ContactNo,
            DME.Code As DepartmentCode
		FROM sHrm.tLeave d
	 	    INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
		    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		    LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		    LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE
			d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
			and DME.OrgGroupId=@rOrgGroupId AND DME.Id=@rDepartmentId And OGMEL.IsObsolete = 0
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
      ) 
  END

  ELSE IF @rTypeId=47   
  
  BEGIN
  
     (SELECT * from(
	     SELECT
			d.FromDate,
			d.ToDate,
			OGMEL.Id As OrgGroupId,
			OGMEL.Title As OrgGroupTitle,
			OMEL.Id As OrgId,OMEL.Title As OrgTitle,
			EM.Code As EmployeeId,
			EM.Id As EmployeeCode,
			(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			(EC.MobileNumber) AS ContactNo,DME.Code As DepartmentCode
		  FROM sHrm.tLeave d
		 	    INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			    LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			    LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE
          d.ToDate=CONVERT(char(10), @rUptoDate,126)
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
          AND EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
          AND ((@rDepartmentId <>1 AND DME.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) 
        ) AS Temp where (DATEDIFF(d, FromDate, ToDate)=2)        
      ) 
  
  
  END 
  
  
  else if @rTypeId=38
  
  BEGIN
      SELECT    
          OGMEL.Id as OrgGroupId,
          OGMEL.Title As OrgGroupTitle,
          OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
          DMER.Id,DMER.Code As DepartmentCode,
          (EM.Id)EmployeeID,
		  (EM.Code)EmployeeCode,
          (EM.FirstName+' '+EM.LastName) AS EmployeeName,
           ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
		  (EC.MobileNumber) AS ContactNo,
		   count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
		   convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
	  FROM sHrm.tEmployeeAttendanceRegister EAR		
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	  WHERE DMER.OrgGroupId=@rOrgGroupId AND DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0 
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	  AND		
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
	  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),EJD.DateOfJoining,EDM.title
	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
  
  END
  
  
  ELSE IF @rTypeId=48 
  
  BEGIN
      
      SELECT    
           OGMEL.Id as OrgGroupId,
           OGMEL.Title As OrgGroupTitle,
           OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
           DMER.Id,DMER.Code As DepartmentCode,
           (EM.Id)EmployeeID,
		   (EM.Code)EmployeeCode,
           (EM.FirstName+' '+EM.LastName) AS EmployeeName,
            ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage						
		FROM sHrm.tEmployeeAttendanceRegister EAR			
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId  And OGMEL.IsObsolete = 0
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
			and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),EJD.DateOfJoining,EDM.title
		HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
  END

  ELSE IF @rTypeId=39   

BEGIN
    SELECT 
       (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
	 from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	where DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId And ISNULL(OGME.IsObsolete,0) = 0
	and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	AND EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))		
END

  ELSE IF @rTypeId=49   

BEGIN
    SELECT 
        (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,
		(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
	 from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		

		WHERE EJD.OrgId=@rOrgId
		AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		And ISNULL(OGME.IsObsolete,0) = 0
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		AND   EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10),@rUptoDate,126))		
		
END


END
GO
PRINT N'Altering [sIp].[pStockItemMasterAdd]...';


GO
 
ALTER PROCEDURE [sIp].[pStockItemMasterAdd]
    @rOrgGroupId int,
	@rCode [nvarchar](100),
	@rTitle [nvarchar](100),
	@rCreatedUserId [bigint],
	@rStockItemCategoryId int,	 
	@rIsBatchWiseTracking [bit],
	@rIssueStockUomId [int],
	@rItemSubGroupId [int],
	@rMaximumInventory [decimal](12, 2),	
	@rReOrderPoint [decimal](12, 2),
	@rSafetyStock [decimal](12, 2),	 
	@rStandardPrice [decimal](22, 6), 
	@rTaxGroupId Int,	 
	@rVendorId [int],	 
	@rIsObsolete [bit],
	@rStoreLocationId int,
	@rIsBlockedForIssue bit,	
	@rDrugRemark nvarchar(500),
	@rOrgId int=0,
	@rBinId int=0,
	@rReorderQuantity decimal(12,2)=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

--IF NOT EXISTS (SELECT 1 FROM sIp.tStockItemMaster WHERE UPPER(UniversalProductCode) = UPPER(@rUniversalProductCode) AND UPPER(UniversalProductCode) <> NULL  )
 
BEGIN

DECLARE @lCount INT 
DECLARE @StoreLocationId INT 
DECLARE @rStockBatchId INT

 --IF NOT EXISTS (SELECT 1 FROM sIp.tStockItemMaster WHERE UPPER(Code) = UPPER(@rCode) AND OrgGroupId = @rOrgGroupId AND LocationId=@rLocationId)
 --BEGIN	

	DECLARE @lNextNumber INT
	 
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sIp.tStockItemMaster',@lNextNumber = @lNextNumber output
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sIp.tStockItemMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sIp.tStockItemMaster
		(
			Id,
			Code,
			Title,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,		
			StockItemCategoryId,			 
			IsBatchWiseTracking,
			IssueStockUomId,
			ItemSubGroupId, 
			TaxGroupId,		 
			VendorId, 			 
			IsObsolete,
			OrgGroupId,
			IsBlockedForIssue,
			StoreLocationId,		
			Remark,
			LocationId,
			BinId
			
	
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCreatedUserId,
			sCommon.fGetDate(),			
			@rStockItemCategoryId, 			 
			@rIsBatchWiseTracking,			 
			@rIssueStockUomId,
			@rItemSubGroupId,			
			(CASE WHEN @rTaxGroupId <= 0 THEN NULL ELSE @rTaxGroupId END),	 
		     @rVendorId  ,			 
			@rIsObsolete,
			@rOrgGroupId,
			@rIsBlockedForIssue,
			@rStoreLocationId,			
			@rDrugRemark,
			@rStoreLocationId,
			@rBinId	
		)
 
 
CREATE TABLE #tmpStoreLocation
(
	Id int identity,
	StoreLocationId int
)	 
		 
INSERT INTO #tmpStoreLocation
SELECT Id FROM sIP.tStoreLocationMaster WHERE Id = @rStoreLocationId

SELECT @lCount =  COUNT(Id) FROM #tmpStoreLocation

WHILE @lCount > 0 
 	BEGIN

 		SELECT  @StoreLocationId = StoreLocationId 
 	   FROM #tmpStoreLocation WHERE Id = @lCount	
 
	EXECUTE [sIp].[pStockItemPlanningAdd] 0,@lNextNumber,@rMaximumInventory,@rReorderPoint,@rSafetyStock,@rStandardPrice,null,null,@StoreLocationId,@rOrgGroupId,@rReorderQuantity
 	EXECUTE sProcurement.pStockBatchAdd  @rOrgGroupId,@StoreLocationId,@lNextNumber,null,null,0,@rCreatedUserId ,@rStandardPrice,  @rStockBatchId
 
		SET @lCount = @lCount - 1
	END	
 	
	EXECUTE	sIp.pStockItemPurchaseUomAdd @rOrgGroupId,@lNextNumber,@rIssueStockUomId,1,0,@rCreatedUserId	
 
	
	EXEC [sIp].[pItemStandardPriceLogAdd] @lNextNumber, @rStandardPrice, @rCreatedUserId,@rOrgGroupId

SELECT @lNextNumber AS RESULT 
    
 END
 
-- ELSE
--	BEGIN
--		SELECT -100 AS RESULT 
--	END
--END
   
 
--ELSE
--	BEGIN
--		SELECT -300 AS RESULT
--	END
--END




/****** Object:  StoredProcedure [sIp].[pStockItemMasterModify]    Script Date: 07/09/2013 16:20:05 ******/
SET ANSI_NULLS ON
GO
PRINT N'Altering [sIp].[pStockItemMasterModify]...';


GO
 
ALTER PROCEDURE [sIp].[pStockItemMasterModify]
	 
	@rId [int],
	@rCode [nvarchar](100),
	@rTitle [nvarchar](100),
	@rUpdatedUserId [bigint],	 
	@rStockItemCategoryId [int],	 
	@rIsBatchWiseTracking [bit], 
	@rIssueStockUomId [int],
	@rItemSubGroupId [int],
	@rMaximumInventory [decimal](12, 2),	 
	@rReOrderPoint [decimal](12, 2),
	@rSafetyStock [decimal](12, 2),
	@rStandardPrice [decimal](22, 6), 
 	@rTaxGroupId [int],  
	@rVendorId [int],	
	@rIsObsolete [bit], 
	@rIsBlockedForIssue bit, 
	@rDrugRemark nvarchar(500),
	@rStoreLocationId int,	
	@rOrgGroupId int,
	@rOrgId INT,
	@rBinId int=0,
	@rReorderQuantity decimal(12,2)=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 DECLARE @lCount INT 
DECLARE @StoreLocationId INT 
	--SELECT @rId
	 UPDATE sIp.tStockItemMaster
		SET 
			Code = @rCode,
			Title = @rTitle,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),			 
			StockItemCategoryId = @rStockItemCategoryId,		 
			IsBatchWiseTracking = @rIsBatchWiseTracking,			 
			IssueStockUomId = @rIssueStockUomId,
			ItemSubGroupId = @rItemSubGroupId,
			TaxGroupId = (CASE WHEN @rTaxGroupId <= 0 THEN NULL ELSE @rTaxGroupId END),			 
			VendorId = (CASE WHEN @rVendorId <= 0 THEN NULL ELSE @rVendorId END),
			IsObsolete = @rIsObsolete,
			IsBlockedForIssue = @rIsBlockedForIssue,
			StoreLocationId = @rStoreLocationId,			 
			Remark = @rDrugRemark,
			BinId=@rBinId 
			 
		 
			
	  WHERE Id = @rId
	  
	EXEC [sIp].[pItemStandardPriceLogAdd] @rId, @rStandardPrice, @rUpdatedUserId,@rOrgGroupId
	
 	EXECUTE [sIp].[pStockItemPlanningModify]  @rId,@rMaximumInventory,@rReorderPoint,@rSafetyStock,@rStandardPrice,null,null,@rStoreLocationId,@rReorderQuantity
		
	--EXECUTE sProcurement.pStockBatchAdd  @rOrgId,@rStoreLocationId,@rId,null,null,0,@rUpdatedUserId 
		
SELECT @rId AS RESULT
END

/****** Object:  StoredProcedure [sCwb].[pDoctorActivityTypeMasterGet]    Script Date: 07/09/2013 16:20:51 ******/
SET ANSI_NULLS ON
GO
PRINT N'Altering [sLibrary].[pRptBookListGet]...';


GO


 
ALTER PROCEDURE [sLibrary].[pRptBookListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookSubjectText nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150)='',
	 @rIsDetail bit=0,
	 @rFromPurchaseDate date='',
	 @rToPurchaseDate date='',
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 --@rOrgGroupId int,
	 @rFromCode nvarchar(25) ='',
	 @rToCode nvarchar(25) ='',
	 @rSpecificCode nvarchar(max) ='',
	 @rBookSubjectDrop nvarchar(500)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	--DECLARE @rFromCodeInt INT, @rToCodeInt INT
	--DECLARE @BookConfig NVARCHAR, @rFromCodeString NVARCHAR, @rToCodeString NVARCHAR
	--SELECT @BookConfig = ItemValue From sConfig.tConfigurationSetup	WHERE ConfigurationId = 260 AND SourceId = @rOrgGroupId
	
	--SET @rFromCodeInt = Convert(Int,ISNULL(@rFromCode,0))
	--SET @rToCodeInt = Convert(Int,ISNULL(@rToCode,0))
	--SET @rFromCodeString = Convert(nvarchar,ISNULL(@rFromCode,''))
	--SET @rToCodeString = Convert(nvarchar,ISNULL(@rToCode,''))
	
	DECLARE @ListofBookCodes TABLE(Code nvarchar(25), ID INT IDENTITY(1,1));
		INSERT INTO @ListofBookCodes
	
	select q2.value from
		(SELECT cast('<x>'+replace(@rSpecificCode,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
		(SELECT x.value('.','nvarchar(max)') as value FROM thexml.nodes('x') as f(x))q2
		

	BEGIN	  
		SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rBookSubjectText = sCommon.fSearchStringGet(@rBookSubjectText)
		SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
		SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
		SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
		SET @rBookDepartment = sCommon.fSearchStringGet(@rBookDepartment)
    END

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Code,
		BM.Title As BookTitle,
		BM.Publisher,BM.Supplier,
		BM.BookSubject,
		BM.Code AS BookCode,
		BM.BookLanguage,
		BM.BookCustomTag,
		BM.BookCustomTag,
		BM.Location,
		BM.ISBNNumber,
		LM.ReportOrgTitle,
        LM.SmallAddress1,
        LM.SmallAddress2,
        CASE WHEN BM.BookDepartment is null THEN 'Blank'
            WHEN BM.BookDepartment='' THEN 'Blank'  ELSE BM.BookDepartment END AS  BookDepartment,
        BM.NoOfCopies,
        @rIsDetail AS IsDetail,
        LM.Code AS LibraryCode,	       
         LM.Title AS LibraryTitle,
        BM.AccessionNo AS AccessionNo
	FROM 
		sLibrary.tBookMaster BM
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.BookDepartment like @rBookDepartment) OR (@rBookDepartment=''))
		AND ((BM.PurchaseDate >= @rFromPurchaseDate) OR (ISNULL(@rFromPurchaseDate,'') = ''))
		AND ((BM.PurchaseDate <= @rToPurchaseDate) OR (ISNULL(@rToPurchaseDate,'') ='') OR (BM.PurchaseDate is null))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((Convert(nvarchar(25),ISNULL(BM.Code,'')) >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
		AND ((Convert(nvarchar(25),ISNULL(BM.Code,'')) <= @rToCode) OR (ISNULL(@rToCode,'') = ''))
		AND ((BM.Code IN(SELECT Code FROM @ListofBookCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		--AND CASE WHEN @BookConfig = 'True' THEN BM.Code >= @rFromCodeString ELSE BM.Code > @rFromCodeInt END AS BM.Code
		--AND CASE WHEN @BookConfig = 'True' THEN BM.Code <= @rToCodeString ELSE BM.Code > @rToCodeInt END AS BM.Code	
	END
GO
PRINT N'Altering [sPayroll].[pEmployeePayrollListGet]...';


GO
 
ALTER PROCEDURE [sPayroll].[pEmployeePayrollListGet]

	@rPayrollId int,
	@rPayrollGroupId int,
	@rForYear int,
	@rForMonth int
 
AS
SET NOCOUNT ON

BEGIN
		SELECT 
			EM.Code AS Code,
			ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
			ISNULL(ETM.Title,'') As EmployeeType,
			OM.DisplayTitle AS OrganizationName,
			ODM.Title AS OrganizationDepartmentName,
			PGM.Title AS PayrollGroupName,
			ISNULL(AT.TotalWorkingDays,0) AS WorkingDays, 
			ISNULL(AT.LWP,0) AS LWP,
			(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0) ) AS PresentDays
		FROM 
			sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id  
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON ESO.PayrollGroupId = PGM.ID
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId			
			INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.Id
			INNER JOIN sSetup.tBatchMaster BM ON AT.BatchId = BM.Id	AND BM.IsActive = 1
		WHERE 
			ESO.PayrollId = @rPayrollId 
			AND ((ESO.PayrollGroupId=@rPayrollGroupId) OR (@rPayrollGroupId=0))
			AND AT.ForYear = @rForYear AND AT.ForMonth = @rForMonth
			AND ISNULL(EM.IsOtherUser,0) = 0 
		ORDER BY EM.OrgId,EM.Number
		--,EM.Code
END
GO
PRINT N'Altering [sPayroll].[pPaySetupElementWiseEmployeeGet]...';


GO
 

ALTER PROCEDURE [sPayroll].[pPaySetupElementWiseEmployeeGet]
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rPayrollId int,
	 @rPayElementId int,
	 @rPayrollYearId int=0,
	 @rPayrollGroupId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    SELECT  
		ISNULL(PS.Id,0) AS PaySetupId,
		EM.EmployeeId,
		EM.EmployeeName,
		EM.Code,
		EM.DepartmentName,
		PS.Amount,
		ISNULL(PE.SortOrder,0) AS ProcessOrder,
		ISNULL(PS.PayElementId,0) AS PayElementId,
		ISNULL(PS.DefaultAmount,0) AS DefaultAmount,
		PS.PayrollYearId
	FROM sHrm.vEmployeeCommonDetail EM
		INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON EM.EmployeeId = ESO.EmployeeId	 
		LEFT JOIN sPayroll.tPaySetup PS ON PS.SourceId = EM.EmployeeId  
		AND SourceTypeId = @rSourceTypeId 
		AND PS.PayElementId = @rPayElementId
		AND PS.PayRollId = ESO.PayrollId
		AND PS.PayRollYearId = @rPayrollYearId
		INNER JOIN sPayroll.tPaySetup PS1 ON PS1.SourceId = ESO.PayrollGroupId AND PS1.SourceTypeId = 2020
		LEFT JOIN sPayroll.tPayElement PE ON PS1.PayElementId = PE.ID 
	WHERE  ESO.PayrollId = @rPayrollId 
		AND (ESO.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId=0)
		AND EM.EmployeeStatusId=7
		AND ISNULL(EM.IsOtherUser,0)=0 
		AND PE.ID=@rPayElementId
		AND PS1.PayrollYearId = @rPayrollYearId
	ORDER BY EM.OrgId,EM.Number
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeeSalaryDetail]...';


GO


ALTER PROCEDURE [sPayroll].[pRptEmployeeSalaryDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rReportId smallint=0,
	 @rOrderByField nvarchar(20)='',
	 @rMonths nvarchar(50)='',
	 @rOrgId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)

	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	SELECT
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		EM.EmployeeDesignation,
		EM.EmployeeGrade,
		ESO.EPFNumber,
		ESO.PanNumber,
		PPE.TotalEarning,		
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		PE.Amount As PPEAmount,
		P.Title AS PayElementTitle,
		P.ID AS PayElementId,
		P.PayElementTypeId,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber, 
		MM.Title AS MonthName,
		P.Title AS PayElementName,
		P.Code AS PayElementCode,
		(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.WorkingDays,@lMonthDay) else 0 END) AS WorkingDays,
		--ISNULL(EWD.WorkingDays,@lMonthDay) AS WorkingDays,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.Lwp else 0 END) AS Lwp,
		(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.PaidLeave,0) else 0 END) AS PaidLeave,
		P.SortOrder,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		PPE.GrossBasic,
		P.PayElementDefaultId,
		ISNULL(EPD.Qualification,'') AS Qualification,
		EJD.DateOfJoining AS DateOfAppointment,
		ISNULL(ESO.PayScale,'') AS PayScale,
		EPD.DateOfBirth,
		ISNULL(ROG.SelectableField,'') AS SelectableField,
		RGO.SchoolRequiredSignature ,
		RGO.SchoolRemark1,
		ISNULL(ESO.BasicPay,0) AS BasicPay,
		DAY(DATEADD(DD,-1,DATEADD(mm, DATEDIFF(mm, 0, CONVERT(DATE,CONVERT(nvarchar,PP.SalaryMonth) +'/01/'+CONVERT(nvarchar,PP.SalaryYear)) ) + 1, 0))) AS MonthDay,
		ESO.UAN,
		EPD.GenderId,
		ISNULL(PPR.Remark,'') AS PayProcessEmployeeRemark,
		tEM.FirstName,
		tEm.LastName,
		EM.DateOfJoining,
		OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
		ISNULL(REPLACE(REPLACE(
		(SELECT STUFF(
		(
		  SELECT  ' ' + Leave FROM -- create comma separated values
			(
					Select '<br>'+('<b>'+ LTM.Code +'</b>' +' - '+ CAST(SUM(CAST(L.NoOfLeave AS FLOAT)) AS varchar(50)) ) + '</br>'AS Leave 
					from 
					sHrm.tLeaveTypeMaster LTM  
					INNER JOIN sHrm.tLeave L ON  EM.EmployeeId = L.EmployeeId 
					INNER JOIN sCommon.tStatusMaster SM ON SM.Id=L.StatusId
					Where EM.EmployeeId=EM.EmployeeId AND LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0 
					AND LTM.Id = L.LeaveTypeId AND SM.Id=550
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					GROUP BY LTM.Code
					)AS T FOR XML PATH('')
		)
		,1,1,'')),'&lt;','<'),'&gt;','>')
		,'') AS LeaveCount,
		tEM.Number
		
	FROM 
	sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	LEFT JOIN sCommon.tReportOrgGroup ROG ON ROG.OrgGroupId=PY.OrgGroupId AND (ROG.ReportId = @rReportId OR @rReportId = 0) 
	LEFT JOIN sCommon.tReportRemarkGroupOrg RGO ON RGO.OrgId = tEM.OrgID AND RGO.ReportRemarkGroupId =  4
	LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
	AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
	left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	
	--LEFT JOIN sHrm.tEmployeeWorkingDays EWD ON tEM.Id = EWD.EmployeeId AND PP.SalaryMonth=EWD.ForMonth AND PP.SalaryYear=EWD.ForYear
where 
      (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND (P.IsObsolete=0)
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
END
GO
PRINT N'Altering [sStudent].[pStudentDocumentClassWiseGet]...';


GO

 

ALTER PROCEDURE [sStudent].[pStudentDocumentClassWiseGet]
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int,
    @rSUId nvarchar(20)='',
    @rUserId bigint=0,
    @rMultiCode nvarchar(max)='',
	@rDocumentId int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			--SD.DocumentName
			--ISNULL(STUFF(
			-- (SELECT DISTINCT ',' + SDM.DocumentName
			--  FROM sCommon.tSubmitDocumentMaster SDM
			--  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			--  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @rClassId
			--  where SD.StudentId=SA.StudentId AND SDM.SubmitDocumentFunctionalityId = 1 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))
			--  FOR XML PATH (''))
			--  , 1, 1, ''),'')  AS DocumentName,
			  ISNULL(sStudent.fStudentDocumentClasswiseget(@rDocumentId,SA.AcademicId),'') AS DocumentName
			
  FROM 
          sStudent.vStudentAcademic SA
		  --LEFT JOIN sStudent.tStudentDocument SD ON SD.StudentId=SA.StudentId
		  INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			--SD.DocumentName
			ISNULL(STUFF(
			 (SELECT DISTINCT ',' + SDM.DocumentName
			  FROM sCommon.tSubmitDocumentMaster SDM
			  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @rClassId
			  where SD.StudentId=SA.StudentId AND SDM.SubmitDocumentFunctionalityId = 1 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))
			  FOR XML PATH (''))
			  , 1, 1, ''),'')  AS DocumentName
			
			
  FROM 
          sStudent.vStudentAcademic SA
		  --LEFT JOIN sStudent.tStudentDocument SD ON SD.StudentId=SA.StudentId
          INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)	
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
  
	
END
GO
PRINT N'Altering [sStudent].[pStudentDocumentget]...';


GO

 
ALTER PROCEDURE [sStudent].[pStudentDocumentget]
	 
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int=0,
	 @rCode nvarchar(20),
	 @rStatusId smallint,
	 @rBatchId int,
	 @rDepartmentId int,
	 @rSUId nvarchar(20)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		SET @rCode= sCommon.fSearchStringGet(@rCode)
		SET @rSUId= sCommon.fSearchStringGet(@rSUId)
    DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
	IF (@rClassId = 0)
	BEGIN
    select @cols = STUFF((SELECT ',' + QUOTENAME(DocumentName) 
                    from  sCommon.tSubmitDocumentMaster WHERE  OrgId=@rOrgId  AND SubmitDocumentFunctionalityId=1
                    Order by Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
      If(ISNULL(@Cols,'')='')
		 BEGIN
		    SELECT -101 AS Result
		 RETURN
		 END
	END
	ELSE
	BEGIN
	select @cols = ISNULL(STUFF(
	(SELECT DISTINCT ',' + DocumentName FROM (
	SELECT QUOTENAME(DM.DocumentName)  AS DocumentName
                    from  sCommon.tSubmitDocumentMaster DM 
					INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=DM.Id AND DS.SourceId = @rClassId
					WHERE  OrgId=@rOrgId  AND SubmitDocumentFunctionalityId=1

	UNION ALL

	SELECT QUOTENAME(D.DocumentName) AS DocumentName FROM sCommon.tSubmitDocumentMaster D
			LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id
			WHERE DS.SubmitDocumentId is null AND D.SubmitDocumentFunctionalityId = 1) AS DocumentName
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,''),'-101')
	END
  set @query = 'SELECT Name,Code,SUID,Class,RollNo,' + @cols + ' from 
             (
               SELECT
               SA.Name,SA.Code,SA.SUID,SA.RollNo,(SA.ClassName+''-''+SA.DivisionName) AS Class,S.DocumentName,CASE WHEN D.SubmitDocumentMasterId IS NULL  THEN ''No'' ELSE ''Yes'' END AS DocumentId
               FROM  sStudent.vStudentAcademic SA 
               LEFT JOIN sStudent.tStudentDocument D ON SA.StudentId=D.StudentId 
               LEFT JOIN sCommon.tSubmitDocumentMaster  S ON S.Id=D.SubmitDocumentMasterId AND SubmitDocumentFunctionalityId=1
		        WHERE 
	          ((SA.OrgId=' + CAST(@rOrgId AS NVARCHAR(50))+'))
	          AND ((SA.BatchId=' + CAST(@rBatchId AS NVARCHAR(50))+'))
	          AND ((SA.DivisionId=' + CAST(@rDivisionId AS NVARCHAR(30))+') OR ('+CAST(@rDivisionId AS NVARCHAR(50))+'= 0))
	          AND ((SA.BatchId=' + CAST(@rBatchId AS NVARCHAR(30))+') OR ('+CAST(@rBatchId AS NVARCHAR(50))+'= 0))
	          AND ((SA.ClassId=' + CAST(@rClassId AS NVARCHAR(30))+') OR ('+CAST(@rClassId AS NVARCHAR(50))+'= 0))
	          AND ((SA.BatchId=' + CAST(@rBatchId AS NVARCHAR(30))+') OR ('+CAST(@rBatchId AS NVARCHAR(50))+'= 0))
	          AND ((SA.DepartmentId=' + CAST(@rDepartmentId AS NVARCHAR(30))+') OR ('+CAST(@rDepartmentId AS NVARCHAR(50))+'= 0))
	          AND ((SA.Code  like  '''+ convert(varchar,@rCode )+''') OR ('''+convert(varchar,@rCode )+'''= ''''))
	          AND ((SA.Suid  like  '''+ ISNULL(@rSUId,'') +''') OR ('''+@rSUId +'''= ''''))
	         AND ((SA.StatusId=' + CAST(@rStatusId AS NVARCHAR(30))+') OR ('+CAST(@rStatusId AS NVARCHAR(50))+'= 0))
              ) x
            pivot 
            (
                MIN(DocumentId)
                for DocumentName in (' + isnull(@cols,0) + ')  
            ) p order by RollNo'
            
  print @query
 execute(@query)
END
GO
PRINT N'Altering [sStudent].[pStudentDocumentSubmitGet]...';


GO
 

ALTER PROCEDURE [sStudent].[pStudentDocumentSubmitGet]
	 
        @rStudentId bigint,
		@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN
			SELECT DISTINCT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN  S.SubmitDocumentMasterId Is null THEN 'False' ELSE 'True'END AS IsCheck
		 	FROM sCommon.tSubmitDocumentMaster D
			INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id
			INNER JOIN sStudent.tAcademic A ON A.ClassId = DS.SourceId AND A.StudentId = @rStudentId
			LEFT Join sStudent.tStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND S.StudentId=@rStudentId
			WHERE D.OrgId=@rOrgId AND SubmitDocumentFunctionalityId='1'

			UNION ALL

			SELECT DISTINCT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,
			CASE WHEN  S.SubmitDocumentMasterId Is null THEN 'False' ELSE 'True'END AS IsCheck
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id
			LEFT JOIN sStudent.tAcademic A ON A.ClassId = DS.SourceId AND A.StudentId = @rStudentId
			LEFT Join sStudent.tStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND S.StudentId=@rStudentId
			WHERE D.OrgId=@rOrgId AND SubmitDocumentFunctionalityId='1' AND DS.SubmitDocumentId is null


END
GO
PRINT N'Altering [sStudent].[pStudentFullProfileGet]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentFullProfileGet]
	 
	 @rBatchId int,
	 @rStudentId bigint,
	 @rReportId int=0,
	 @rOrgId int,
	 @rStrCode nvarchar(max)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rStatusId int=0,
	 @rClassStatusId int=0,
	 @rDateOfBirth int=0,
	 @rDepartmentId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgGroupBatchId int,
	 @rFromAdmissionDate date = '',
	 @rToAdmissionDate date = ''
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @lAcademicId bigint
	SELECT @lAcademicId = Id from sStudent.tAcademic Where StudentId = @rStudentId AND BatchId = @rBatchId
	
	SELECT 
			--Academic
			@rBuilder1 As Builder1,
			SA.StudentId AS Id,
			--SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			SA.Name AS StudentName,
			SA.FirstName as FirstName,
			SA.MiddleName as MiddleName,
			SA.LastName as LastName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,' - ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			SA.RollNo,
			ISNULL(SM.Title,'-') AS House,
			--Other
			CASE WHEN @rReportId=0 THEN ISNULL(SA.DateOfBirth,'0001/01/01')  
			WHEN @rReportId=1 THEN  SA.DateOfBirth END  AS DateOfBirth,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			ISNULL(SA.Religion,'') AS Religion,
			--Admission			
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,
			--ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.AdmissionDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.AdmissionDate END AS AdmissionDate,
	
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.LeftDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LeftDate END AS LeftDate,
						 
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			--ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.InactiveDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.InactiveDate END AS InactiveDate,		
			ISNULL(SA.LCNumber,'') AS LCNumber,
			--ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			 CASE WHEN @rReportId=0 THEN ISNULL(SA.LCDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LCDate END AS LCDate,
			--Communication
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			
			--Parent Information
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			ISNULL(SF.FatherDesignation,'') AS FatherDesignation,
			ISNULL(SF.FatherOrganization,'') AS FatherOrganization,
			ISNULL(SF.FatherIncome,'') AS FatherIncome,

			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			ISNULL(SF.MotherDesignation,'') AS MotherDesignation,
			ISNULL(SF.MotherOrganization,'') AS MotherOrganization,
			ISNULL(SF.MotherIncome,'') AS MotherIncome,

			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			ISNULL(SF.RelativeDesignation,'') AS RelativeDesignation,
			ISNULL(SF.RelativeOrganization,'') AS RelativeOrganization,
			ISNULL(SF.RelativeIncome,'') AS RelativeIncome,
			
			--Health Information
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			
			ISNULL(SH.IsPysicalDeformity,0) AS IsPysicalDeformity,
			ISNULL(SH.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			ISNULL(SH.IsMajorIllness,0) AS IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			ISNULL(SH.IsAllergy,0) AS IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			ISNULL(SH.IsPastHistory,0) As IsPastHistory ,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			--Hostel
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,
					
	   	    --ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentPhoto,
	   	   -- ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
	   	   -- ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
	   	    --ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
	   	   CASE WHEN @rReportId=0
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS StudentPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS MotherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS FatherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), ''))
			END AS RelativePhoto,
		   -- Transport Details
		    A.VehicleName AS VehicleName,
		    A.VehicleRegistrationNumber AS VehicleRegistrationNumber,
		    A.TypeOfVehicle AS TypeOfVehicle,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    A.DriverName,
		    A.DriverMobileNo,
		    A.ConductorName,
		    A.ConductorMobileNo,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,
		    
		    A.DropVehicleName AS DropVehicleName,
		    A.DropVehicleRegistrationNumber AS DropVehicleRegistrationNumber,
		    A.DropTypeOfVehicle AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    A.DropRouteDriverName AS DropRouteDriverName,
		    A.DropRouteDriverMobileNo AS DropRouteDriverMobileNo,
		    A.DropRouteConductorName AS DropRouteConductorName,
		    A.DropRouteConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		    
		    --ClassTeacher Details
		    ISNULL(EMT.Id,0) AS TeacherId,
		    EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName AS TeacherFullName,
		    EDM.Title AS TeacherDesignation,
		    EPD.Qualification AS TeacherQualification,
		    ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS TeacherPhoto,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,
		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
			ISNULL(DF.IsDisplayClassTeacherDetail,0) AS IsDisplayClassTeacherDetail,
		    --Sibling Detail
		    isnull(SS.SiblingName1,'') AS SiblingName1,
	        ISNULL (SS.SiblingInstitue1,'') AS SiblingInstitue1,
	        ISNULL(SS.SiblingClass1,'')AS SiblingClass1,
	        ISNULL(SS.SiblingAge1,'')AS SiblingAge1,
	        ISNULL(SS.SiblingRelation1,'')AS SiblingRelation1,
	        isnull(SS.SiblingName2,'') AS SiblingName2,
	        ISNULL(SS.SiblingInstitue2,'')AS SiblingInstitue2,
	        ISNULL(SS.SiblingClass2,'')AS SiblingClass2,
	        ISNULL(SS.SiblingAge2,'') AS SiblingAge2,
	        ISNULL(SS.SiblingRelation2,'')AS SiblingRelation2,
	        isnull(SS.SiblingName3,'') AS SiblingName3,
	        ISNULL( SS.SiblingInstitue3,'')AS SiblingInstitue3,
	        ISNULL(SS.SiblingClass3,'')AS SiblingClass3,
	        ISNULL(SS.SiblingAge3,'')AS SiblingAge3,
	        ISNULL(SS.SiblingRelation3,'')AS SiblingRelation3,
	        ISNULL(SAD.BankAccountNumber,'')AS BankAccountNumber,
	        ISNULL(SAD.BankName,'')AS BankName,
	        ISNULL(SAD.BankBranch,'') AS BankBranch,
	        ISNULL(SAD.BankIFSCCode,'')AS BankIFSCCode,
	        ISNULL(SAD.Class9BoardRegistrationNumber,'') AS Class9BoardRegistrationNumber,
	        ISNULL(SAD.Class11BoardRegistrationNumber,'')AS Class11BoardRegistrationNumber,
	        ISNULL(SAD.PassportNumber,'')AS PassportNumber, 
	        ISNULL(SAD.PassportType,'') AS PassportType,
	       ISNULL( SAD.PassportCountryCode,'') AS PassportCountryCode,
	        CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportIssueDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportIssueDate END AS PassportIssueDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportExpiryDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportExpiryDate END AS PassportExpiryDate,
	        ISNULL(SA.UIDNumber,'')AS UIDNumber,
	        ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
	       ISNull(SA.StatusId,0) AS StatusId,
	       ISNUll(SA.IsTransfer,0)AS IsTransfer,
	       ISNULL(SA.TransferFrom,'') AS TransferFrom,
	       ISNULL(SA.CertificateName,'') AS CertificateName,
	       ISNUll(SA.IsTFWS,0)AS IsTFWS,
	       ISNUll(SA.IsCertificateHolder,0)AS IsCertificateHolder,
	       ISNULL(CD.SSCBoard,'') AS SSCBoard,
	       ISNULL(CD.SSCSchool,'') AS SSCSchool,
	       ISNULL(CD.SSCPassingYear,'') AS SSCPassingYear,
	       ISNULL(CD.SSCObtainMarks,0) AS SSCObtainMarks,
	       ISNULL(CD.SSCOutOfMarks,0) AS SSCOutOfMarks,
	       ISNULL(CD.SSCPercentage,0) AS SSCPercentage,
	       ISNULL(CD.SSCMathMarks,0) AS SSCMathMarks,
	       ISNULL(CD.SSCMathOutOfMarks,0) AS SSCMathOutOfMarks,
	       ISNULL(CD.SSCPercentile,0) AS SSCPercentile,
	       ISNULL(CD.SSCGrade,0) AS SSCGrade,
	       ISNULL(CD.HSCBoard,'') AS HSCBoard,
	       ISNULL(CD.HSCSchool,'') AS HSCSchool,
	       ISNULL(CD.HSCPassingYear,0) AS HSCPassingYear,
	       ISNULL(CD.HSCObtainMarks,0) AS HSCObtainMarks,
	       ISNULL(CD.HSCOutOfMarks,0) AS HSCOutOfMarks,
	       ISNULL(CD.HSCPercentage,0) AS HSCPercentage,
	       ISNULL(CD.HSCPhysicsMarks,0) AS HSCPhysicsMarks,
	       ISNULL(CD.HSCPhysicsOutOfMarks,0) AS HSCPhysicsOutOfMarks,
	       ISNULL(CD.HSCChemistryMarks,0) AS HSCChemistryMarks,
	       ISNULL(CD.HSCChemistryOutOfMarks,0) AS HSCChemistryOutOfMarks,
	       ISNULL(CD.HSCMathMarks,0) AS HSCMathMarks,
	       ISNULL(CD.HSCMathOutOfMarks,0) AS HSCMathOutOfMarks,
	       ISNULL(CD.HSCBiologyMarks,0) AS HSCBiologyMarks,
	       ISNULL(CD.HSCBiologyOutOfMarks,0) AS HSCBiologyOutOfMarks,
	       ISNULL(CD.PCMMarks,0) AS PCMMarks,
	       ISNULL(CD.PCBMarks,0) AS PCBMarks,
	       ISNULL(CD.JEERollNo,'') AS JEERollNo,
	       ISNULL(CD.JEEMeritNo,'') AS JEEMeritNo,
	       ISNULL(CD.JEEMeritMarks,0) AS JEEMeritMarks,
	       ISNULL(CD.JEEOutOfMarks,0) AS JEEOutOfMarks,
	       ISNULL(CD.DiplomaBoard,'') AS DiplomaBoard,
	       ISNULL(CD.DiplomaCollege,'') AS DiplomaCollege,
	       ISNULL(CD.DiplomaPassingYear,'') AS DiplomaPassingYear,
	       ISNULL(CD.DiplomaObtainMarks,0) AS DiplomaObtainMarks,
	       ISNULL(CD.DiplomaOutOfMarks,0) AS DiplomaOutOfMarks,
	       ISNULL(CD.DiplomaPercentage,0) AS DiplomaPercentage,
	       ISNULL(CD.ApplicationNo,'') AS ApplicationNo,
	       ISNULL(CD.AdmissionRound,0) AS AdmissionRound,
	       ISNULL(CD.MaritalStatusId,0) AS MaritalStatusId,
	       ISNULL(MS.Title,'') AS MaritalStatus,
	       ISNULL(ACD.RepeatCount,1)AS RepeatCount,
	       ISNULL(SA.MotherTongue,'') As MotherTongue,
	       ISNULL(SA.FamilyCast,'') AS FamilyCast,
	      ISNULL(CM.Nationality,'') AS Nationality,
	       ISNULL(CT.Title,'') AS CasteCategory,
	       ISnull(SA.ClassName,'') AS ClassName ,
	       ISnull( SA.DivisionName,'') AS DivisionName,
	      ISNULL( SF.IsFatherExStudent,0) AS IsFatherExStudent,
	       ISnull(SF.FatherPassOutYear,'') AS FatherPassOutYear,
	       Isnull(SF.IsMotherExStudent,0) AS IsMotherExStudent,
	       Isnull(SF.MotherPassOutYear,'') AS MotherPassOutYear,
	       ISNULL(SF.IsRelativeExStudent,0) AS IsRelativeExStudent,
	       ISNULL(SF.RelativePassOutYear,'') AS RelativePassOutYear,
	       ISNULL(Sa.PresentDistanceFromSchool,0) AS PresentDistanceFromSchool,
	        SA.StudentId,
	        SA.ClassId,
	        SA.DivisionId,
	        SA.BirthState,
	        SA.BirthCountry,
	         ISNULL(SA.PreviousStandard,'')AS PreviousStandard
	        ,ISNULL(CGG.Title,'') AS CustomGroup
			,ISNULL(SGM.Title,'') As StudentGroup
			,ISNULL(SOGM.Title,'') As StudentOtherGroup
			,ISNULL([sStudent].[fAssignedClubGet](@lAcademicId),'') AS ClubName
			,ISNULL([sStudent].[fAssignedCustomTagGet](@lAcademicId),'') AS CustomTag 
	        ,SA.ClassStatusId
	        ,SA.ClassStatusName
	        ,PDCM.Title As PhysicalDisabilityCategory
	       --[sHostel].[fHostelWardenGet](HM.Id) As WardenName
  FROM 
           sStudent.vStudentAllDetail SA
          -- LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
          -- LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId   
            LEFT JOIN
            (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 		   
		 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1       
           --LEFT JOIN sHostel.tHostelWarden HW ON HW.HostelId=HM.Id
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id AND  ISNULL(EMW.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id AND  ISNULL(EMA.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN 
           ( SElect AR1.SourceId,
           VM.Title AS VehicleName,
		    VM.RegistrationNumber AS VehicleRegistrationNumber,
		    TV.Title AS TypeOfVehicle,
		    ISNULL(BRM.Title,'') AS BusRoute,
		    BRM.DriverName,
		    BRM.DriverMobileNo,
		    BRM.ConductorName,
		    BRM.ConductorMobileNo,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    VM.Title AS DropVehicleName,
		    VM.RegistrationNumber AS DropVehicleRegistrationNumber,
		    TV1.Title AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		    BRM1.DriverName AS DropRouteDriverName,
		    BRM1.DriverMobileNo AS DropRouteDriverMobileNo,
		    BRM1.ConductorName AS DropRouteConductorName,
		    BRM1.ConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination
		      FROM
             sTransport.tAssignRoute AR1   
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId) A ON A.SourceId=SA.StudentId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId AND  ISNULL(EMT.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
           INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
           LEFT JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = SA.StudentId AND CGM.SourceTypeId = 2003
           LEFT JOIN sCommunication.tCustomGroup CGG ON CGG.Id = CGM.CustomGroupId
           LEFT JOIN sStudent.tStudentMaster SMM ON SMM.Id = SA.StudentId
           LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SMM.StudentGroupId
           LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id = SMM.StudentOtherGroupId
  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.BatchId=@rBatchId) OR(@rBatchId=0))
			AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
			AND ((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
			AND ((SA.AdmissionDate >= @rFromAdmissionDate) OR (ISNULL(@rFromAdmissionDate,'') = ''))
			AND ((SA.AdmissionDate <= @rToAdmissionDate) OR (ISNULL(@rToAdmissionDate,'') = ''))
			--AND(SA.OrgId=@rOrgId)
			
END
GO
PRINT N'Creating [sAdmission].[pAdmissionInquiryCriteriaAdd]...';


GO
CREATE PROCEDURE sAdmission.pAdmissionInquiryCriteriaAdd

@rClassId int = 0,
@rBatchId int = 0,
@rIsPublish bit = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

IF EXISTS (SELECT 1 FROM sAdmission.tAdmissionInquiryCriteria WHERE ClassId = @rClassId AND BatchId = @rBatchId) 
	BEGIN  
		UPDATE sAdmission.tAdmissionInquiryCriteria 
		SET IsPublish = @rIsPublish
		WHERE ClassId = @rClassId AND BatchId = @rBatchId 
	END  
ELSE 
	BEGIN 
		INSERT INTO sAdmission.tAdmissionInquiryCriteria 
		(
			ClassId,
			BatchId,
			IsPublish
		)
		VALUES 
		(
			@rClassId,
			@rBatchId,
			@rIsPublish
		)  
	END
END
GO
PRINT N'Creating [sAlert].[pAssignedTaskStatusGet]...';


GO
CREATE PROCEDURE [sAlert].[pAssignedTaskStatusGet]

	@rTemplate nvarchar(max),
	@rSourceId bigint,
	@rSourceTypeId smallint,
	@rOrgId int,
	@rSubject nvarchar(max),
	@rId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rSourceTypeId = 2003)
	BEGIN
		SELECT 
				SC.AcademicId,
				SC.Code,
				SC.Name,
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
				ISNULL(SC.StudentEmail,'') AS StudentEmail,
				ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
				ISNULL(SC.FatherMail,'') AS FatherMail,
				ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
				ISNULL(SC.MotherMail,'') AS MotherMail,
				replace(
				replace (					
				replace (
				replace (
				replace(@rTemplate,'[StartDate]',AT.AssignedDate),
				'[DueDate]',AT.DueDate),
				'[AssignedBy]',ISNULL(CASE WHEN U.SourceTypeId = 2003 THEN (SELECT Name FROM sStudent.vStudentName WHERE StudentId = U.SourceId)
					 ELSE (SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId) END,'')),
				'[IsCompleted]',(CASE WHEN AT.IsCompleted = 1 THEN 'Completed' ELSE 'Not Completed' END)),
				'[Remark]',AT.Remark)
				 AS MsgText,
				 @rSubject AS Subject,
				 2003 AS ReceiverSourceTypeId,
				 SC.StudentId AS ReceiverSourceId,
				 2003 AS SourceTypeId,
				 SC.StudentId AS SourceId,
				 SC.OrgGroupId,
				 SC.OrgId

		FROM 
				sStudent.vStudentCommunication SC
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgId = OM.Id
				INNER JOIN sCommunication.tAssignTask AT ON AT.AssignedToSourceId = SC.StudentId AND AT.AssignedToSourceTypeId = 2003
				INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId

		WHERE AT.Id = @rId
		AND (SC.OrgId=@rOrgId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	END
	ELSE IF (@rSourceTypeId = 95)
	BEGIN 
		SELECT 
			EM.EmployeeId AS EmployeeId,
			EM.Code,
			EM.EmployeeName AS Name,
			EM.MobileNumber AS MobileNo,	
			EM.CompanyEmail AS EmailId,
			replace(
			replace (					
			replace (
			replace (
			replace(@rTemplate,'[StartDate]',AT.AssignedDate),
			'[DueDate]',AT.DueDate),
			'[AssignedBy]',ISNULL(CASE WHEN U.SourceTypeId = 95 THEN (SELECT Name FROM sStudent.vStudentName WHERE StudentId = U.SourceId)
					ELSE (SELECT ShortName FROM sHrm.vExtEmployeeMaster WHERE EmployeeId = U.SourceId) END,'')),
			'[IsCompleted]',(CASE WHEN AT.IsCompleted = 1 THEN 'Completed' ELSE 'Not Completed' END)),
			'[Remark]',AT.Remark)
				AS MsgText,
			@rSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EM.EmployeeId AS ReceiverSourceId,
			95 AS SourceTypeId,
			EM.EmployeeId AS SourceId,
			OM.OrgGroupId,
			EM.OrgID

		FROM 
				sHrm.vExtEmployeeMaster EM
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id
				INNER JOIN sCommunication.tAssignTask AT ON AT.AssignedToSourceId = EM.EmployeeId AND AT.AssignedToSourceTypeId = 95
				INNER JOIN sSecurity.tUser U ON U.Id=AT.CreatedUserId

		WHERE AT.Id = @rId
		AND (EM.OrgId=@rOrgId)
		AND (EM.StatusId=7) 
		AND EM.IsOtherUser = 0
	END
END
GO
PRINT N'Creating [sCommon].[pSubmitDocumentScopeAdd]...';


GO
CREATE PROCEDURE sCommon.pSubmitDocumentScopeAdd

	 @rSubmitDocumentId bigint = 0
	,@rSourceTypeId smallint = 0
	,@rSourceId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		INSERT INTO [sCommon].[tSubmitDocumentScope]
		(
			SubmitDocumentId
		   ,SourceTypeId
		   ,SourceId
		)
		VALUES
		(
		    @rSubmitDocumentId
		   ,@rSourceTypeId
		   ,@rSourceId
		)
END
GO
PRINT N'Creating [sEExam].[pTestParticipantAnswerDetailAdd]...';


GO
CREATE PROCEDURE [sEExam].[pTestParticipantAnswerDetailAdd]
			@rTestId int
           ,@rQuestionId bigint
           ,@rQuestionOptionId bigint
           ,@rScoredMark decimal(6,2)
           ,@rAnswerStatusId smallint
           ,@rOrderIndex smallint
           ,@rTestParticipantId bigint
           ,@rQuestionAnswer nvarchar(max)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 IF EXISTS (SELECT 1 FROM sEExam.tTestParticipantAnswer WHERE TestId = @rTestId AND TestParticipantId = @rTestParticipantId)
	 BEGIN
		UPDATE sEExam.tTestParticipantAnswer 
		SET
            [TestId] = @rTestId
           ,[QuestionId] = @rQuestionId
           ,[QuestionOptionId] = @rQuestionOptionId
           ,[ScoredMark] = @rScoredMark
           ,[AnswerStatusId] = @rAnswerStatusId
           ,[OrderIndex] = @rOrderIndex
           ,[TestParticipantId] = @rTestParticipantId
           ,[QuestionAnswer] = @rQuestionAnswer
		WHERE TestId = @rTestId AND TestParticipantId = @rTestParticipantId
	 END
	 ELSE
	 BEGIN
		INSERT INTO sEExam.tTestParticipantAnswer  
		(
			[TestId]
           ,[QuestionId]
           ,[QuestionOptionId]
           ,[ScoredMark]
           ,[AnswerStatusId]
           ,[OrderIndex]
           ,[TestParticipantId]
           ,[QuestionAnswer]
		)
		Values
		(
			@rTestId 
           ,@rQuestionId 
           ,@rQuestionOptionId 
           ,@rScoredMark 
           ,@rAnswerStatusId 
           ,@rOrderIndex 
           ,@rTestParticipantId 
           ,@rQuestionAnswer 
		)
	 END

END
GO
PRINT N'Creating [sEExam].[pTestParticipantDetailAdd]...';


GO
 
CREATE PROCEDURE [sEExam].[pTestParticipantDetailAdd]
	
		@rTestParticipantDetailXml nvarchar(max),
		@rTestparticipantAnswerDetailXml nvarchar(max)

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
	
	BEGIN TRANSACTION

	--TestParticipant

	DECLARE @TestParticipantDetail XML  
    SET @TestParticipantDetail = CAST(@rTestParticipantDetailXml AS XML) 
	 
	CREATE TABLE #TempTestParticipant 
	(  
	RowIndex INT IDENTITY(1, 1), 
	TestId int,
    SourceTypeId smallint,
    SourceId bigint,
    TestDate date,
    StartTime time(7),
    EndTime time(7),
    TestStatusId smallint,
    TotalMarks decimal(6,2),
    ScoredMarks decimal(6,2),
    TotalQuestions int,
    RightQuestions int,
    WrongQuestions int,
    SkippQuestions int,
    NotAttemptedQuestions int,
    Id bigint,
    TimeTaken time(7)
	)
	 
	INSERT INTO #TempTestParticipant  
    SELECT           
            T.c.value('@TestId', 'int') AS TestId,
            T.c.value('@SourceTypeId', 'smallint') AS SourceTypeId, 
            T.c.value('@SourceId', 'bigint') AS SourceId,
			T.c.value('@TestDate', 'date') AS TestDate,
			T.c.value('@StartTime', 'time(7)') AS StartTime,
			T.c.value('@EndTime', 'time(7)') AS EndTime,
			T.c.value('@TestStatusId', 'smallint') AS TestStatusId,
			T.c.value('@TotalMarks', 'decimal(6,2)') AS TotalMarks,
			T.c.value('@ScoredMarks', 'decimal(6,2)') AS ScoredMarks,
			T.c.value('@TotalQuestions', 'int') AS TotalQuestions,
			T.c.value('@RightQuestions', 'int') AS RightQuestions,
			T.c.value('@WrongQuestions', 'int') AS WrongQuestions,
			T.c.value('@SkippQuestions', 'int') AS SkippQuestions,
			T.c.value('@NotAttemptedQuestions', 'int') AS NotAttemptedQuestions,
			T.c.value('@Id', 'bigint') AS Id,
			T.c.value('@TimeTaken', 'time(7)') AS TimeTaken
    FROM   
            @TestParticipantDetail.nodes('/Table/TestParticipantDetail')T(c)  
	
	 
	Declare @lCount int=1
	WHILE(@lCount <= (SELECT count(*) FROM #TempTestParticipant))                
	BEGIN
		DECLARE @TestId int,@Id bigint

		SELECT @TestId = TestId , @Id = Id FROM #TempTestParticipant WHERE RowIndex = @lCount

		IF EXISTS (SELECT 1 FROM sEExam.tTestParticipant WHERE TestId = @TestId AND Id = @Id)
		 BEGIN
			UPDATE sEExam.tTestParticipant 
			SET
			    [SourceTypeId] = A.SourceTypeId
			   ,[SourceId] = A.SourceId
			   ,[TestDate] = A.TestDate
			   ,[StartTime] = A.StartTime
			   ,[EndTime] = A.EndTime
			   ,[TestStatusId] = A.TestStatusId
			   ,[TotalMarks] = A.TotalMarks
			   ,[ScoredMarks] = A.ScoredMarks
			   ,[TotalQuestions] = A.TotalQuestions
			   ,[RightQuestions] = A.RightQuestions
			   ,[WrongQuestions] = A.WrongQuestions
			   ,[SkippQuestions] = A.SkippQuestions
			   ,[NotAttemptedQuestions] = A.NotAttemptedQuestions
			   ,[TimeTaken] = A.TimeTaken
			FROM
			#TempTestParticipant A
			WHERE sEExam.tTestParticipant.Id = A.Id AND sEExam.tTestParticipant.TestId = A.TestId AND A.Id = @Id AND A.TestId = @TestId
		 END
		 ELSE
		 BEGIN
			INSERT INTO sEExam.tTestParticipant  
			(
				[TestId]
			   ,[SourceTypeId]
			   ,[SourceId]
			   ,[TestDate]
			   ,[StartTime]
			   ,[EndTime]
			   ,[TestStatusId]
			   ,[TotalMarks]
			   ,[ScoredMarks]
			   ,[TotalQuestions]
			   ,[RightQuestions]
			   ,[WrongQuestions]
			   ,[SkippQuestions]
			   ,[NotAttemptedQuestions]
			   ,[Id]
			   ,[TimeTaken]
			)
			SELECT 
				[TestId]
			   ,[SourceTypeId]
			   ,[SourceId]
			   ,[TestDate]
			   ,[StartTime]
			   ,[EndTime]
			   ,[TestStatusId]
			   ,[TotalMarks]
			   ,[ScoredMarks]
			   ,[TotalQuestions]
			   ,[RightQuestions]
			   ,[WrongQuestions]
			   ,[SkippQuestions]
			   ,[NotAttemptedQuestions]
			   ,[Id]
			   ,[TimeTaken]
			 FROM #TempTestParticipant WHERE Id = @Id AND TestId = @TestId 
		 END

		 SET @lCount = @lCount + 1
	END
  
  --TestParticipantAnswer

	  DECLARE @TestParticipantAnswerDetail XML  
	  SET @TestParticipantAnswerDetail = CAST(@rTestParticipantAnswerDetailXml AS XML) 

	  CREATE TABLE  #TempTestParticipantAnswer 
	  (  
		RowIndex INT IDENTITY(1, 1), 
		TestId int,
		QuestionId bigint,
		QuestionOptionId bigint,
		ScoredMark decimal(6,2),
		AnswerStatusId smallint,
		OrderIndex smallint,
		TestParticipantId bigint,
		QuestionAnswer nvarchar(max)
	  )

	INSERT INTO #TempTestParticipantAnswer
    SELECT           
            T.c.value('@TestId', 'int') AS TestId,
            T.c.value('@QuestionId', 'bigint') AS QuestionId,
            T.c.value('@QuestionOptionId', 'bigint') AS QuestionOptionId,
			T.c.value('@ScoredMark', 'decimal(6,2)') AS ScoredMark,          
			T.c.value('@AnswerStatusId', 'smallint') AS AnswerStatusId,
			T.c.value('@OrderIndex', 'smallint') AS OrderIndex,
			T.c.value('@TestParticipantId', 'bigint') AS TestParticipantId,
			T.c.value('@QuestionAnswer', 'nvarchar(max)') AS QuestionAnswer
    FROM   
            @TestParticipantAnswerDetail.nodes('/Table/TestParticipantAnswerDetail')T(c)  

	SET @lCount = 1
	WHILE(@lCount <= (SELECT count(*) FROM #TempTestParticipantAnswer))                
	BEGIN

		DECLARE @TestParticipantId bigint , @QuestionId  bigint

		SELECT @TestId = TestId , @TestParticipantId = TestParticipantId , @QuestionId = QuestionId FROM #TempTestParticipantAnswer WHERE RowIndex = @lCount

		IF EXISTS (SELECT 1 FROM sEExam.tTestParticipantAnswer WHERE TestId = @TestId AND TestParticipantId = @TestParticipantId AND QuestionId = @QuestionId)
		 BEGIN
			UPDATE sEExam.tTestParticipantAnswer
			SET
			    [TestId] = A.TestId
			   ,[QuestionId] = A.QuestionId
			   ,[QuestionOptionId] = A.QuestionOptionId
			   ,[ScoredMark] = A.ScoredMark
			   ,[AnswerStatusId] = A.AnswerStatusId
			   ,[OrderIndex] = A.OrderIndex
			   ,[TestParticipantId] = A.TestParticipantId
			   ,[QuestionAnswer] = A.QuestionAnswer
			FROM
				#TempTestParticipantAnswer A
			WHERE sEExam.tTestParticipantAnswer.TestParticipantId = A.TestParticipantId AND sEExam.tTestParticipantAnswer.TestId = A.TestId AND sEExam.tTestParticipantAnswer.QuestionId = A.QuestionId
			AND A.TestParticipantId = @TestParticipantId AND A.TestId = @TestId AND A.QuestionId = @QuestionId
		 END
		 ELSE
		 BEGIN
			INSERT INTO sEExam.tTestParticipantAnswer
			(
				[TestId]
			   ,[QuestionId]
			   ,[QuestionOptionId]
			   ,[ScoredMark]
			   ,[AnswerStatusId]
			   ,[OrderIndex]
			   ,[TestParticipantId]
			   ,[QuestionAnswer]
			)
			SELECT 
				[TestId]
			   ,[QuestionId]
			   ,[QuestionOptionId]
			   ,[ScoredMark]
			   ,[AnswerStatusId]
			   ,[OrderIndex]
			   ,[TestParticipantId]
			   ,[QuestionAnswer]
			 FROM #TempTestParticipantAnswer WHERE TestParticipantId = @TestParticipantId AND TestId = @TestId AND QuestionId = @QuestionId
		 END
		 SET @lCount = @lCount + 1
	END

	DROP TABLE #TempTestParticipant
	DROP TABLE #TempTestParticipantAnswer

	SELECT 1 AS RESULT
COMMIT TRANSACTION

		END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Creating [sLibrary].[pBookListGet]...';


GO

CREATE PROCEDURE [sLibrary].[pBookListGet]
	
	 @rName nvarchar(500),
	 @rResourceTypeId int,
	 @rStatusId smallint,
	 @rLibraryId int
	 	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--DECLARE @lpaging
BEGIN 


	  --BEGIN
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
					
	  --END
	 declare @quer varchar(max)=''
	declare @lOrgId int,@lName nvarchar(200),@lResourceTypeId int,@lStatusId smallint,@lLibraryId int

	
	select 
	@lName = isnull(@rName,''),
	@lResourceTypeId = isnull(@rResourceTypeId,0),@lStatusId = isnull(@rStatusId,0),@lLibraryId = isnull(@rLibraryId,0)

	 
	SELECT @quer='SELECT BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'''')AS Publisher,
	ISNULL(BM.Supplier,'''')AS Supplier,
	ISNULL(BM.Author,'''')AS Author,
	ISNULL(BM.BookSubject,'''') AS BookSubject,
	ISNULL(BM.BookLanguage,'''') AS BookLanguage,
	ISNULL(BM.Location,'''') AS Location,
	ISNULL(BM.Edition,'''')AS Edition,
	ISNULL(BM.ISBNNumber,'''') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'''') AS Currency,
	ISNULL(BM.BookTag,'''')AS BookTag,
	ISNULL(BM.BookCustomTag,'''') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'''') AS BookDepartment,
	ISNULL(BM.ClassNumber,'''') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	SM.Title AS StatusName,
	BM.Id,
	ISNULL(AGM.Id,0)AS BookAgeGroupId,
	ISNULL(RTM.Id,0) AS ResourceTypeId,
	BM.CreatedUserId,
	BM.CreatedDateTime,
	ISNULL(BM.UpdatedUserId,0) AS UpdatedUserId,
	ISNULL(BM.UpdatedDateTime,'''') AS UpdatedDateTime,
	BM.LibraryId,
	SM.Id AS StatusId,
	BM.ClassificationNo,
	BM.AccessionNo,
	ISNUll(BM.NoOfPages,0) AS NoOfPages,
	 ISNULL(BM.PurchaseDate,''0001/01/01'') AS PurchaseDate,
    ISNUll(BM.BookRemark,'''') AS BookRemark,
    ISNULL(BM.BillNumber,'''') AS BillNumber,
    BM.YearOfPublication,
    ISNULL(BM.BookEntryDate,''0001/01/01'') AS BookEntryDate,
    ISNULL(BM.BookGroup1Id,0) AS BookGroup1Id,
    ISNULL(BM.BookGroup2Id,0) AS BookGroup2Id,
	ISNULL(BL.ReaderSourceId,0)AS ReaderSourceId
 
	FROM 
         sLibrary.tBookMaster BM
         LEFT JOIN sLibrary.tBookAgeGroupMaster AGM ON BM.BookAgeGroupId=AGM.Id
         INNER JOIN sLibrary.tResourceTypeMaster RTM ON BM.ResourceTypeId=RTM.Id
         INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
         INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId 
         
         WHERE  
	 ((BM.Publisher like ''' + @lName + ''') OR (''' + @lName + ''' = '''')
	 OR (BM.Title like ''' + @lName + ''') OR (''' + @lName + ''' = '''')
	 OR (BM.Code like ''' + @lName + ''') OR (''' + @lName + ''' = '''')
	 OR (BM.Author like ''' + @lName + ''') OR (''' + @lName + ''' = '''')) 
	AND ((BM.ResourceTypeId = ' + convert(varchar,@lResourceTypeId) + ') OR (' + convert(varchar,@lResourceTypeId) + ' = 0))
	AND ((BL.StatusId = ' + convert(varchar,@lStatusId) + ') OR (' + convert(varchar,@lStatusId) + '=0))
	AND BM.LibraryId = ' + convert(varchar,@lLibraryId)
	
	print(@quer);
	exec (@quer)

END
GO
PRINT N'Creating [sLibrary].[pMyBookLogAdd]...';


GO

CREATE PROCEDURE [sLibrary].[pMyBookLogAdd]
		--@rId bigint,
        @rReaderSourceTypeId smallint,
		@rReaderSourceId bigint,
		@rResourceSourceTypeId smallint,
		@rResourceSourceId bigint,
		@rLogDate date,
		@rDueDate date,
		@rStatusId smallint,
		@rRemark nvarchar(150),
		@rIsCurrentStatus bit,
		@rOrgId smallint,
		@rBatchId int,
		@rCreatedUserId bigint,
		@rLibraryId int,
		@rBookActionStatusId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	--IF (@rId = 0)
	--BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sLibrary.tBookLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	UPDATE sLibrary.tBookLog
	    SET
			IsCurrentStatus=0,			
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE ResourceSourceTypeId = @rResourceSourceTypeId AND ResourceSourceId = @rResourceSourceId
		--AND LibraryId = @rLibraryId
		      
		
	INSERT INTO sLibrary.tBookLog
		(
			Id,
			ReaderSourceTypeId,
			ReaderSourceId,
			ResourceSourceTypeId,
			ResourceSourceId,
			LogDate,
			DueDate,
			StatusId,
			Remark,
			IsCurrentStatus,
			OrgId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			LibraryId,
			BookActionStatusId
		)
	VALUES
		(
			@lNextNumber,
			@rReaderSourceTypeId,
			@rReaderSourceId,
			@rResourceSourceTypeId,
			@rResourceSourceId,
			ISNULL(@rLogDate,sCommon.fGetDate()),
			ISNULL(@rDueDate,sCommon.fGetDate()),
			@rStatusId,
			@rRemark,
			@rIsCurrentStatus,
			@rOrgId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLibraryId,
			@rBookActionStatusId
		)
		    SELECT @lNextNumber AS Result
	      
	--END	
	--ELSE
	-- BEGIN
	-- SET @lNextNumber = @rId
	--    UPDATE sLibrary.tBookLog
	--    SET
	--		ReaderSourceTypeId=@rReaderSourceTypeId,
	--		ReaderSourceId=@rReaderSourceId,
	--		ResourceSourceTypeId=@rResourceSourceTypeId,
	--		ResourceSourceId=@rResourceSourceId,
	--		LogDate=@rLogDate,
	--		DueDate=@rDueDate,
	--		StatusId=@rStatusId,
	--		Remark=@rRemark,
	--		IsCurrentStatus=@rIsCurrentStatus,
	--		UpdatedUserId=@rCreatedUserId,
	--		UpdatedDateTime=sCommon.fGetDate()
	      
	--      WHERE Id = @rId
	--      SELECT @lNextNumber AS Result
	
	-- END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sLibrary].[pReaderMyBookLogListGet]...';


GO

CREATE PROCEDURE [sLibrary].[pReaderMyBookLogListGet]
	 @rReaderSourceTypeId smallint=0,
	 @rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
If(@rReaderSourceTypeId=2003)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId 
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005 AND IS1.LibraryId=@rLibraryId
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		--AND  SA.IsActiveBatch = 1
		AND (BL.LibraryId=@rLibraryId)
END
ELSE If(@rReaderSourceTypeId=95)
BEGIN
	SELECT 
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId   
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId	
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004 AND IS1.LibraryId=@rLibraryId
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		AND (BL.ReaderSourceId=@rReaderSourceId)
		AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=522) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		AND (BL.LibraryId=@rLibraryId)
		AND ISNULL(EM.IsOtherUser,0) = 0
END
END
GO
PRINT N'Creating [sLibrary].[pViewMyBookDetailGet]...';


GO

CREATE PROCEDURE [sLibrary].[pViewMyBookDetailGet]
	 @rResourceSourceId bigint,
	 @rIsCurrentStatus bit,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @rReaderSourceTypeId smallint 
	Select @rReaderSourceTypeId=ReaderSourceTypeId from sLibrary.tBookLog WHERE ResourceSourceId=@rResourceSourceId AND IsCurrentStatus=@rIsCurrentStatus
	IF(@rReaderSourceTypeId IS NOT NULL)
	BEGIN
	SELECT 
			BM.Id AS ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			SA.Name AS ReaderName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDept,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId != 521 THEN BL.LogDate END AS LogDate,
			CASE WHEN BL.StatusId != 521 THEN BL.DueDate END AS DueDate
			
	FROM 
			sLibrary.tBookMaster BM 
			INNER JOIN sLibrary.tBookLog BL ON BM.Id=BL.ResourceSourceId AND BL.IsCurrentStatus=@rIsCurrentStatus AND BL.ReaderSourceTypeId=2003
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId 
	WHERE 
			((BM.Id=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
		
		UNION ALL
		
		SELECT 
			BM.Id AS ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			EM.FirstName+' '+EM.LastName AS ReaderName,
			ODM.Title as ClassDept,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId != 521 THEN BL.LogDate END AS LogDate,
			CASE WHEN BL.StatusId != 521 THEN BL.DueDate END AS DueDate
			
	FROM 
			sLibrary.tBookMaster BM 
			INNER JOIN sLibrary.tBookLog BL ON BM.Id=BL.ResourceSourceId AND BL.IsCurrentStatus=@rIsCurrentStatus AND BL.ReaderSourceTypeId=95
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
	WHERE 
			((BM.Id=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
		AND  ISNULL(EM.IsOtherUser,0) = 0
	END
	ELSE
	BEGIN
	
		SELECT 
			BM.Id AS ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			'' AS ReaderName,
			'' AS ClassDept,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId != 521 THEN BL.LogDate END AS LogDate,
			CASE WHEN BL.StatusId != 521 THEN BL.DueDate END AS DueDate
			
	FROM 
			sLibrary.tBookMaster BM 
			INNER JOIN sLibrary.tBookLog BL ON BM.Id=BL.ResourceSourceId AND BL.IsCurrentStatus=@rIsCurrentStatus
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			((BM.Id=@rResourceSourceId) OR (@rResourceSourceId=0))
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
	END
END
GO




GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('21.01.15',210115,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO