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


GO
PRINT N'Dropping UK_tEventAssign...';


GO
ALTER TABLE [sActivity].[tEventAssign] DROP CONSTRAINT [UK_tEventAssign];


GO
PRINT N'Altering [sAcademic].[tClasswork]...';


GO
ALTER TABLE [sAcademic].[tClasswork] ALTER COLUMN [Homework] NVARCHAR (1000) NULL;


GO
PRINT N'Altering [sAssessment].[tResultDetailOther]...';


GO
ALTER TABLE [sAssessment].[tResultDetailOther]
    ADD [TotalCount]   SMALLINT NULL,
        [PresentCount] SMALLINT NULL;


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


GO
ALTER TABLE [sErp].[tCustomerMaster]
    ADD [PlugIn] NVARCHAR (200) NULL,
        [Tag]    NVARCHAR (200) NULL;


GO
PRINT N'Altering [sHrm].[tEmployeeCustomSearch]...';


GO
ALTER TABLE [sHrm].[tEmployeeCustomSearch]
    ADD [LeftFromDate] DATE DEFAULT ('') NOT NULL,
        [LeftToDate]   DATE DEFAULT ('') NOT NULL;


GO
PRINT N'Creating [sErp].[tCustomerPlugInLog]...';


GO
CREATE TABLE [sErp].[tCustomerPlugInLog] (
    [AutoId]          INT            IDENTITY (1, 1) NOT NULL,
    [OrgGroupId]      INT            NOT NULL,
    [PlugInId]        SMALLINT       NOT NULL,
    [LogDate]         DATE           NOT NULL,
    [StatusRemark]    NVARCHAR (200) NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [PlugInStatusId]  TINYINT        NULL
);


GO
PRINT N'Creating [sErp].[tPlugInMaster]...';


GO
CREATE TABLE [sErp].[tPlugInMaster] (
    [Id]         TINYINT        NOT NULL,
    [Code]       NVARCHAR (50)  NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL
);


GO
PRINT N'Creating PK_tPlugInMaster...';


GO
ALTER TABLE [sErp].[tPlugInMaster]
    ADD CONSTRAINT [PK_tPlugInMaster] 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
PRINT N'Creating [sErp].[tTagMaster]...';


GO
CREATE TABLE [sErp].[tTagMaster] (
    [Id]         TINYINT        NOT NULL,
    [Code]       NVARCHAR (50)  NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL
);


GO
PRINT N'Creating PK_tTagMaster...';


GO
ALTER TABLE [sErp].[tTagMaster]
    ADD CONSTRAINT [PK_tTagMaster] 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'Creating [sSetup].[fMonthYearForBatchLeaveGet]...';


GO
CREATE FUNCTION [sSetup].[fMonthYearForBatchLeaveGet](@rBatchId int)
RETURNS  @List TABLE (
		 MonthNumber tinyint,
		 YearNumber smallint,
		 MonthTitle nvarchar(20),
		 NoOfDays tinyint,
		 BatchId int 
)  WITH EXECUTE AS CALLER
AS 
BEGIN

	declare @rFromDate DATE
    declare @rToDate DATE 
	Select @rFromDate=LeaveYearFromDate,@rToDate=LeaveYearToDate FROM sSetup.tBatchMaster WHERE Id=@rBatchId 
		 
	WHILE (@rFromDate <= @rToDate)
	BEGIN	
	INSERT INTO @List 
	SELECT 
			DATEPART(MONTH,@rFromDate) AS MonthNumber,
			DATENAME(YEAR,@rFromDate) AS YearNumber,
			DATENAME(MONTH,@rFromDate) AS MonthTitle,
			DATEDIFF(DAY, 
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rFromDate), 0),
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rFromDate) + 1, 0)),
			@rBatchId AS BatchId
			SET @rFromDate = DATEADD(M,1,@rFromDate)  
	END 
	 
IF NOT EXISTS(SELECT * FROM @List WHERE MonthNumber = DATEPART(MONTH,@rToDate) AND 
YearNumber = DATENAME(YEAR,@rToDate)
AND BatchId  = @rBatchId)
BEGIN
INSERT INTO @List 
	  SELECT 
			DATEPART(MONTH,@rToDate) AS MonthNumber,
			DATENAME(YEAR,@rToDate) AS YearNumber,
			DATENAME(MONTH,@rToDate) AS MonthTitle,
			DATEDIFF(DAY, 
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rToDate), 0),
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @rToDate) + 1, 0)),
			@rBatchId AS BatchId 
END
			  

		  
	
	--;with tMonth_Year (CurrentDate,BatchId)
 --   AS
 --   (
 --       SELECT @rFromDate,@rBatchId
 --       UNION ALL
 --       SELECT DATEADD(MONTH,1,CurrentDate),@rBatchId
 --       from tMonth_Year
 --       where DATEADD(MONTH,1,CurrentDate)<= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@rToDate)+1,0))
 --   )
    
 --   INSERT INTO @List 
 --   SELECT 
	--		DATEPART(MONTH,CurrentDate) AS MonthNumber,
	--		DATENAME(YEAR,CurrentDate) AS YearNumber,
	--		DATENAME(MONTH,CurrentDate) AS MonthTitle,
	--		@rBatchId AS BatchId
	--FROM 
	--	tMonth_Year 
    
    RETURN  
    
END
GO



GO
PRINT N'Altering [sAcademic].[pClassworkAdd]...';


GO
 
ALTER PROCEDURE [sAcademic].[pClassworkAdd]
	 
	 	@rBatchId int,
        @rId bigint,
        @rSubjectId int,
        @rClassId int,
        @rDivisionId int,
		@rClasswork nvarchar(max),
		@rHomework nvarchar(1000),
		@rClassWorkDate date,
		@rHomeWorkEndDate date,
		@rEmployeeId bigint,
		@rCreatedUserId bigint,
		@rOrgId int,
		@rClassworkStatusId smallint = 1,
		@rHomeWorkStatusId smallint = 1
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lNextNumber BIGINT 
	
	-- Temp Basis Update due to Wrong OrgId,BatchId paseed from Mobile End
	DECLARE @lOrgId smallint, @lOrgGroupBatchId int, @lBatchId int
	SELECT @lOrgId = OrgId from sSetup.tSubjectMaster Where Id = @rSubjectId
	SELECT @lOrgGroupBatchId =  OrgGroupBatchId from sSetup.tBatchMaster Where Id = @rBatchId
	SELECT @lBatchId = Id from sSetup.tBatchMaster Where OrgId = @lOrgId AND OrgGroupBatchId = @lOrgGroupBatchId 
	
	SET @rBatchId = @lBatchId
	SET @rOrgId = @lOrgId
	-- Ends
	
	SELECT @rId = Id FROM sAcademic.tClasswork WHERE	
	        BatchId=@rBatchId AND
			SubjectId=@rSubjectId AND
			ClassId=@rClassId AND
			DivisionId=@rDivisionId AND
			EmployeeId = @rEmployeeId AND
			ClassWorkDate = @rClassWorkDate
	        
	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tClasswork', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tClasswork
		(
			BatchId,
			Id,
			SubjectId,
			ClassId,
			DivisionId,
			Classwork,
			Homework,
			ClassWorkDate,
			HomeWorkEndDate,
			EmployeeId,
			CreatedUserId,
			CreatedDateTime,
			ClassworkStatusId,
			HomeWorkStatusId
		)
	VALUES
		(
			@rBatchId,
			@lNextNumber,
			@rSubjectId,
			@rClassId,
			@rDivisionId,
			CASE WHEN @rClassworkStatusId=1 THEN @rClasswork ELSE 'NA' END,
			CASE WHEN @rHomeWorkStatusId=1 THEN @rHomework ELSE 'NA' END,
			@rClassWorkDate,
			@rHomeWorkEndDate,
			@rEmployeeId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rClassworkStatusId,
		    @rHomeWorkStatusId
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 
			If @rClassworkStatusId=2 SET @rClasswork='NA'
			If @rHomeWorkStatusId=2 SET  @rHomework='NA'
	 --SET @lNextNumber = @rId
	    UPDATE  sAcademic.tClasswork
	    SET
			BatchId=@rBatchId,
			SubjectId=@rSubjectId,
			ClassId=@rClassId,
			DivisionId=@rDivisionId,
			Classwork=@rClasswork,
			Homework=@rHomework,
			ClassWorkDate=@rClassWorkDate,
			HomeWorkEndDate=@rHomeWorkEndDate,
			EmployeeId=@rEmployeeId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ClassworkStatusId=@rClassworkStatusId,
			HomeWorkStatusId=@rHomeWorkStatusId
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAcademic].[pClassworkGet]...';


GO
ALTER PROCEDURE [sAcademic].[pClassworkGet]

	 @rId bigint,	 
	 @rSubjectId int,
	 @rClassId int,
	 @rEmployeeId bigint,
	 @rDivisionid int,
	 @rFromDate datetime,
     @rToDate datetime,
     @rOrgId int,
     --@rBatchId int
     @rOrgGroupBatchId int,
    @rUserId bigint =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
	order by 
			AC.HomeWorkEndDate DESC
END
GO
PRINT N'Altering [sAcademic].[pLessonPlanGet]...';


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanGet]

	 @rId bigint=0,
	 @rClassId int=0,
	 @rSubjectId int=0,
	 @rDivisionId int=0,
	 @rIsCompleted bit=0,
	 @rBatchId int=0,
	 @rEmployeeId bigint=0,
	 @rDepartmentid int=0,
	 @rFromDate datetime='',
     @rToDate datetime=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId   

			--sAcademic.tLessonPlan LP
			--INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
		((LP.BatchId = @rBatchId) OR (LP.BatchId = 0))
		 AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))		
		AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
	ORDER BY
		LP.id 
END
GO
PRINT N'Altering [sAcademic].[pTaskConsolidatedDashboardGet]...';


GO

ALTER PROCEDURE [sAcademic].[pTaskConsolidatedDashboardGet]

     @rOrgGroupId smallint,
     @rTypeId int,
     @rDate date,
     @rType nvarchar(20),
     @rCommonOrgGroupBatchId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	---Attendance Task Wise 
	IF( @rType = 'Attendance')
		BEGIN
			IF(@rTypeId = 1)
				BEGIN
				SELECT 				
			OGM.Id AS OrgGroupId,
			OGM.Title AS OrgGroupName,
			 (
				 SELECT ISNULL(Count(StudentCount),0) AS DoneAttendance FROM
				(SELECT 
				(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
				FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				WHERE  OGM.Id = O.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  NOT in 
				( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
				) Temp WHERE rowno=1
			 ) AS Pending,
			 (SELECT
					COUNT(DISTINCT DM.Id) AS TotalDivision
			  FROM
					sSetup.tDivisionMaster DM
					INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				   
			  WHERE OGM.Id =OGMR.Id
			  AND DM.IsObsolete=0 AND OGMR.IsObsolete = 0 --AND BM.IsActive = 1 
					AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGMR.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
			
			) AS Total,
			(
			SELECT ISNULL(Count(StudentCount),0) AS DoneAttendance FROM
				(SELECT 
				(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
				FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				WHERE  OGM.Id = O.Id AND COGBM.Id=1 AND    A.Id   in 
				( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
				) Temp WHERE rowno=1) AS Complated
      FROM 
			sSetup.tOrgGroupMaster OGM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
			
			INNER JOIN sStudent.tAcademic SA ON SA.OrgId = OM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				
					 WHERE 
		    OGM.IsObsolete = 0 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) 
	 GROUP BY
			OGM.Id, OGM.Title
	 ORDER BY
			OGM.Id	
				
				
		--			  SELECT 				
		--	OGM.Id AS OrgGroupId,
		--	OGM.Title AS OrgGroupName,
		--	 CONVERT(nvarchar(10),ISNULL(AT1.DivisionPresent,0)) AS Pending
		--	,CONVERT(nvarchar(10),ISNULL(AT2.TotalDivision,0)) AS Total
		--	,CONVERT(nvarchar(10),ISNULL(AT3.DoneAttendance,0)) AS Complated
  --    FROM 
		--	sSetup.tOrgGroupMaster OGM
		--	INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
			
		--	INNER JOIN sStudent.tAcademic SA ON SA.OrgId = OM.Id
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		--    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		    
		--	LEFT JOIN --Attendance Pending
		--	(
		--	SELECT ISNULL(Count(StudentCount),0) AS DivisionPresent,OrgGroupId FROM
		--		(SELECT 
		--		(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
		--		ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
		--		FROM sStudent.tAcademic A
		--		INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		--		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
		--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		--		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--		WHERE  COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  not in 
		--		( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
		--		) Temp WHERE rowno=1  GROUP BY OrgGroupId
		--		) AT1 ON AT1.OrgGroupId = OGM.Id
		--	  --SELECT
		--		 --  COUNT(DISTINCT DM.Id) AS DivisionPresent,
		--		 --  OGM.Id AS OrgGroupId
		--	  --FROM
		--		 -- sSetup.tDivisionMaster DM
		--		 -- INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
		--		 -- INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--		 -- INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--		 -- INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
		--		 -- INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--		 -- INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		--		 -- INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.Id 
		--	  --WHERE
		--		 -- SR.IsPresent = 1 AND SR.AttendanceDate = @rDate 
		--		 -- --AND BM.IsActive=1 
		--		 -- AND DM.IsObsolete=0 AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
		--	  --GROUP BY
		--		 -- OGM.Id
		--	--) AT1 ON AT1.OrgGroupId = OGM.Id
		--	LEFT JOIN  --Attendance Total
		--	(
		--	  SELECT
		--			COUNT(DISTINCT DM.Id) AS TotalDivision,
		--			OGM.Id AS OrgGroupId
		--	  FROM
		--			sSetup.tDivisionMaster DM
		--			INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
		--			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		--			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
		--			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				   
		--	  WHERE
		--			DM.IsObsolete=0 AND OGM.IsObsolete = 0 --AND BM.IsActive = 1 
		--			AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
		--	  GROUP BY
		--			OGM.Id
		--	) AT2 ON AT2.OrgGroupId = OGM.Id
		--	LEFT JOIN --Attendance Done
		--	(
		--	SELECT ISNULL(Count(StudentCount),0) AS DoneAttendance,OrgGroupId FROM
		--		(SELECT 
		--		(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,O.Id  AS OrgGroupId,
		--		ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
		--		FROM sStudent.tAcademic A
		--		INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
		--		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		--		INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
		--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		--		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		--		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--		WHERE  COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id   in 
		--		( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rDate,126))
		--		) Temp WHERE rowno=1  GROUP BY OrgGroupId
		--		) AT3 ON AT3.OrgGroupId = OGM.Id

			
	 --WHERE 
		--    OGM.IsObsolete = 0 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) 
	 --GROUP BY
		--	OGM.Id, OGM.Title,DivisionPresent,TotalDivision,DoneAttendance
	 --ORDER BY
		--	OGM.Id	
				END
				ELSE IF( @rTypeId = 11)
					BEGIN
						
		SELECT OrgGroupId,OrgGroupName,DivisionId,ClassDivision,EmployeeCode,ISNULL(EmployeeName,'') AS EmployeeName,ISNULL(EmployeeContact,'')AS EmployeeContact
		FROM(SELECT 
						O.Id as OrgGroupId,
						O.Title As OrgGroupName,
						OMEL.Id As OrgId,
						(OMEL.Title) As Organization,
						A.ClassId,
						DM.Id AS DivisionId,
						DM.Code AS ClassDivision,
						(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
						A.Id As AcademicId,
						EM.Code As EmployeeCode,
						(EM.FirstName+' '+Em.LastName) AS EmployeeName,
						(EC.MobileNumber) AS EmployeeContact,
						ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
			FROM sStudent.tAcademic A
						INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			WHERE  O.id = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
						--AND A.Id not in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rDate,126))
						) Temp 
		WHERE 
						rowno=1
					END
				ELSE IF( @rTypeId = 12)
					BEGIN
						
		SELECT OrgGroupId,OrgGroupName,DivisionId,ClassDivision,EmployeeCode,ISNULL(EmployeeName,'') AS EmployeeName,ISNULL(EmployeeContact,'')AS EmployeeContact
		FROM(SELECT 
						O.Id as OrgGroupId,
						O.Title As OrgGroupName,
						OMEL.Id As OrgId,
						(OMEL.Title) As Organization,
						A.ClassId,
						DM.Id AS DivisionId,
						DM.Code AS ClassDivision,
						(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
						A.Id As AcademicId,
						EM.Code As EmployeeCode,
						(EM.FirstName+' '+Em.LastName) AS EmployeeName,
						(EC.MobileNumber) AS EmployeeContact,
						ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
			FROM sStudent.tAcademic A
						INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			WHERE  O.id = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
						AND A.Id not in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rDate,126))
						) Temp 
		WHERE 
						rowno=1
					END
				ELSE IF (@rTypeId = 13)
					BEGIN
						
		SELECT OrgGroupId,OrgGroupName,DivisionId,ClassDivision,EmployeeCode,ISNULL(EmployeeName,'') AS EmployeeName,ISNULL(EmployeeContact,'')AS EmployeeContact
		FROM(SELECT 
						O.Id as OrgGroupId,
						O.Title As OrgGroupName,
						OMEL.Id As OrgId,
						(OMEL.Title) As Organization,
						A.ClassId,
						DM.Id AS DivisionId,
						DM.Code AS ClassDivision,
						(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
						A.Id As AcademicId,
						EM.Code As EmployeeCode,
						(EM.FirstName+' '+Em.LastName) AS EmployeeName,
						(EC.MobileNumber) AS EmployeeContact,
						ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
			FROM sStudent.tAcademic A
						INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
						LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			WHERE  O.id = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
						AND A.Id  in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rDate,126))
						) Temp 
		WHERE 
						rowno=1
					END
		END
	IF(@rType = 'CW/HW')
			IF(@rTypeId=2)
				BEGIN
					SELECT 				
						OGM.Id AS OrgGroupId,
						OGM.Title AS OrgGroupName,
						ISNULL((
-- ClassworkAssigned								
					SELECT COUNT( AC.SubjectId) AS Classwork
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
					 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 1 
						AND (Classwork != '' OR  Classwork = NULL) 
						AND OGM.Id = OGM1.Id),0) 
					AS ClassworkAssigned,
					ISNULL((
--ClassworkNotAssigned
					SELECT COUNT(*)
					FROM sAcademic.tTeacherSubjectDivision TSD1 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId 
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
					INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
					Where 
					OGM1.Id= OGM.Id
					AND 
					NOT EXISTS(SELECT  *
					FROM sAcademic.tTeacherSubjectDivision TSD 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
					INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
					Where TSD.DivisionId = TSD1.DivisionId AND ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) AND TSD.SubjectId = TSD1.SubjectId AND AC.ClassWorkDate=@rDate)),0) 
					AS ClassworkNotAssigned,
					ISNULL((
--ClassworkNotApplicable
					SELECT COUNT( AC.SubjectId) AS Classwork 
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM1.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 2 
						AND COGBM.Id=@rCommonOrgGroupBatchId  
						AND OGM.Id = OGM1.Id),0) 
					AS ClassworkNotApplicable,
					ISNULL((
--HomeWorkAssigned
					SELECT COUNT( AC.SubjectId) AS Classwork
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
					 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 1 
						AND (HomeWork != '' OR HomeWork=NULL) 
						AND OGM.Id = OGM1.Id),0) 
					AS HomeWorkAssigned,
					ISNULL((
--HomeWorkNotAssigned
					SELECT COUNT(*)
					FROM sAcademic.tTeacherSubjectDivision TSD1 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId 
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
					INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
					Where 
					OGM1.Id= OGM.Id
					AND 
					NOT EXISTS(SELECT  *
					FROM sAcademic.tTeacherSubjectDivision TSD 
					INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
					INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
					INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
					Where TSD.DivisionId = TSD1.DivisionId AND ((OGM1.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) AND TSD.SubjectId = TSD1.SubjectId 
					AND AC.ClassWorkDate=@rDate)),0) 
					AS HomeWorkNotAssigned,
					ISNULL((
--HomeWorkNotApplicable
					SELECT COUNT( AC.SubjectId) AS Classwork 
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM1.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE
						AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 2
						AND COGBM.Id=@rCommonOrgGroupBatchId  
						AND OGM.Id = OGM1.Id),0) 
					AS HomeWorkNotApplicable
						 FROM 
								sSetup.tOrgGroupMaster OGM
								INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id
								INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
								INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
								INNER JOIN sStudent.tAcademic A ON A.OrgId = OM.Id
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
								--LEFT JOIN 
								--(
								--  SELECT 
								--		COUNT(DISTINCT AC.SubjectId) AS Classwork,
								--		OGM.Id AS OrgGroupId
								--  FROM sAcademic.tClasswork AC
								--		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
								--		INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
								--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
								--		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
								--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
								--		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
								--  WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
								--		AND AC.ClassWorkDate=@rDate AND ClassworkStatusId = 1 AND (Classwork != '' OR  Classwork = NULL)
								--  GROUP BY 
								--		OGM.Id
								--) CW1 ON CW1.OrgGroupId = OGM.Id
				--				LEFT JOIN(
				--					  SELECT
				--							COUNT(DISTINCT SM.Id) AS ClassWork,
				--							OGM.Id AS OrgGroupId
				--					  FROM
				--							sSetup.tSubjectMaster SM
				--							INNER JOIN sSetup.tClassSubject CS ON CS.SubjectId = SM.Id
				--							INNER JOIN sStudent.tAcademic SA ON SA.ClassId = CS.ClassId
				--							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				--							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--							INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
				--							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--							INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				    
				--					  WHERE
				--							--BM.IsActive=1 AND 
				--							SM.IsObsolete=0 AND OGM.IsObsolete = 0 AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
				--					  GROUP BY
				--							OGM.Id
				--						) CW2 ON CW2.OrgGroupId = OGM.Id

				--				--LEFT JOIN 
				--				--(
				--				--  SELECT 
				--				--		COUNT(DISTINCT AC.SubjectId) AS Classwork,
				--				--		OGM.Id AS OrgGroupId
				--				--  FROM sAcademic.tClasswork AC
				--				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--				--	   INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
				--				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				--				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				--				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
				--				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				--				--  WHERE 
				--				--	   AC.ClassWorkDate=@rDate AND (Classwork = NULL OR Classwork='') AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
				--				--  GROUP BY 
				--				--		OGM.Id
				--				--) CW2 ON CW2.OrgGroupId = OGM.Id
				--				LEFT JOIN 
				--				(
				--				  SELECT 
				--						COUNT(DISTINCT AC.SubjectId) AS Classwork,
				--						OGM.Id AS OrgGroupId
				--				  FROM sAcademic.tClasswork AC
				--					   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--					   INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
				--					   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				--					   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
				--					   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
				--					   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				--				  WHERE 
				--					   AC.ClassWorkDate=@rDate AND ClassworkStatusId = 2 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
				--				  GROUP BY 
				--						OGM.Id
				--				) CW3 ON CW3.OrgGroupId = OGM.Id
				--				LEFT JOIN 
				--(
				--  SELECT 
				--		COUNT(DISTINCT AC.SubjectId) AS Homework,
				--		OGM.Id AS OrgGroupId
				--  FROM sAcademic.tClasswork AC
				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--	   INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
				--	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					   
				--  WHERE 
				--	   AC.ClassWorkDate=@rDate AND HomeWorkStatusId = 1 AND (HomeWork != '' OR HomeWork=NULL)
				--	   --AND BM.IsActive = 1 
				--	   AND COGBM.Id=@rCommonOrgGroupBatchId 
				--  GROUP BY 
				--		OGM.Id
				--) HW1 ON HW1.OrgGroupId = OGM.Id
				--LEFT JOIN 
				--(
				--  SELECT 
				--		COUNT(DISTINCT AC.SubjectId) AS Homework,
				--		OGM.Id AS OrgGroupId
				--  FROM sAcademic.tClasswork AC
				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--	   INNER JOIN sStudent.tAcademic SA ON SA.DivisionId = DM.Id
				--	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					   
				--  WHERE 
				--	   AC.ClassWorkDate=@rDate AND HomeWorkStatusId = 1 AND(HomeWork = NULL OR HomeWork='')
				--	   --AND BM.IsActive = 1 
				--	   AND COGBM.Id=@rCommonOrgGroupBatchId 
				--  GROUP BY 
				--		OGM.Id
				--) HW2 ON HW2.OrgGroupId = OGM.Id
				--LEFT JOIN 
				--(
				--  SELECT 
				--		COUNT(DISTINCT AC.SubjectId) AS Homework,
				--		OGM.Id AS OrgGroupId
				--  FROM sAcademic.tClasswork AC
				--	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
				--	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id= AC.BatchId
				--	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				--	   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id =  OGBM.OrgGroupId		    
				--	   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					 
				--  WHERE 
				--	   AC.ClassWorkDate=@rDate AND HomeWorkStatusId = 2 AND BM.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId 
				--  GROUP BY 
				--		OGM.Id
				--) HW3 ON HW3.OrgGroupId = OGM.Id
						 WHERE 
								OGM.IsObsolete = 0  AND Bm.IsActive = 1 AND COGBM.Id=@rCommonOrgGroupBatchId  AND((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
						 GROUP BY OGM.Id, OGM.Title
							--	OGM.Id, OGM.Title,CW1.Classwork,CW2.Classwork, CW3.Classwork,HW1.HomeWork,HW2.HomeWork, HW3.HomeWork
						 ORDER BY
								OGM.Id
				END
				ELSE IF( @rTypeId = 21)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 1 
						AND (Classwork != '' OR  Classwork = NULL) 
					Order By DM.OrderIndex
					END
				ELSE IF( @rTypeId = 22)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,
						EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact
						FROM sAcademic.tTeacherSubjectDivision TSD1 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD1.EmployeeId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
						Where ((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
						AND 
						NOT EXISTS(SELECT  *
						FROM sAcademic.tTeacherSubjectDivision TSD 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
						INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						Where TSD.DivisionId = TSD1.DivisionId AND((OGM1.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) AND TSD.SubjectId = TSD1.SubjectId AND AC.ClassWorkDate=@rDate )
						Order By DM.OrderIndex
					END
				ELSE IF (@rTypeId = 23)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND ClassworkStatusId = 2 
						AND (Classwork != '' OR  Classwork = NULL) 
						Order By DM.OrderIndex
					END
					ELSE IF (@rTypeId = 24)
						BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 1 
						AND (HomeWork != '' OR HomeWork=NULL) 
					Order By DM.OrderIndex
									
					END
				ELSE IF( @rTypeId = 25)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,
						EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact
						FROM sAcademic.tTeacherSubjectDivision TSD1 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD1.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD1.DivisionId
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD1.EmployeeId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
						Where ((OGM.Id= @rOrgGroupId)OR(@rOrgGroupId=0))
						AND 
						NOT EXISTS(SELECT  *
						FROM sAcademic.tTeacherSubjectDivision TSD 
						INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId=SM.Id 
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=TSD.DivisionId 
						INNER JOIN sAcademic.tClasswork AC ON TSD.SubjectId=AC.SubjectId and  TSD.DivisionId=AC.DivisionId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.Orgid
						INNER JOIN sSetup.tOrgGroupMaster OGM1 ON OGM1.Id = OM.OrgGroupId
						Where TSD.DivisionId = TSD1.DivisionId AND((OGM1.Id= @rOrgGroupId)OR(@rOrgGroupId=0)) AND TSD.SubjectId = TSD1.SubjectId AND AC.ClassWorkDate=@rDate )
						Order By DM.OrderIndex
					END
				ELSE IF (@rTypeId = 26)
					BEGIN
						SELECT OGM.Id AS OrgGroupId, OGM.Title AS OrgGroupName,DM.Code AS ClassDivision,SM.Title AS SubjectName,EM.Code AS EmployeeCode,EM.FirstName +' '+EM.LastName AS EmployeeName,EC.PresentContactNo AS EmployeeContact
					FROM sAcademic.tClasswork AC
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = AC.DivisionId
						INNER JOIN sSetup.tSubjectMaster SM ON AC.SubjectId=SM.Id 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = AC.EmployeeId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
						INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMM ON OMM.Id = BM.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OMM.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE ((OGM.Id = @rOrgGroupId) OR(@rOrgGroupId = 0)) 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						AND AC.ClassWorkDate=@rDate 
						AND HomeWorkStatusId = 2 
						AND (HomeWork != '' OR HomeWork=NULL)
						Order By DM.OrderIndex
					END
END
GO
PRINT N'Altering [sActivity].[pMyEventGet]...';


GO
ALTER PROCEDURE [sActivity].[pMyEventGet]
	 
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rFromDate date='',
	 @rTodate date=''
	 --@rSyncedEventScheduleId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	IF(@rSourceTypeId=2003)
	BEGIN
	
	DECLARE @DivisionId int
	
	SELECT @DivisionId = DivisionId  FROM sStudent.tAcademic WHERE StudentId=@rSourceId 
					AND OrgId=@rOrgId AND BatchId=@rBatchId 
	
		SELECT
				ISNULL(EE.Id,0) AS Id,
				ES.Id AS EventScheduleId,
				ES.Title,
				ES.FromDate,
				ES.ToDate,
				ES.IsCommonForAll,
				ES.IsHoliday,
				ES.IsEnrollment,
				ES.CreatedDateTime,
				ES.Remark AS Remark,
				EE.Remark AS EventEnrollmentRemark
		FROM 
			sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventEnrollment EE ON EE.EventScheduleId=ES.Id AND EE.SourceId=@rSourceId AND EE.SourceTypeId=2003
		WHERE 
	        
			 ((ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2005 AND 
				SourceId= @DivisionId )) OR ES.ISCommonForAll = 1)
					
		AND (ES.BatchId=@rBatchId) 
		AND ((Convert(date,ES.FromDate)<=@rFromDate) OR ISNULL(@rFromDate,'')='')
		AND ((Convert(date,ES.Todate)>=@rTodate) OR ISNULL(@rTodate,'')='')
		--AND (ES.Id > @rSyncedEventScheduleId OR @rSyncedEventScheduleId = 0)
		ORDER BY ES.FromDate DESC
		
		
		
	END
	ELSE
	BEGIN
		SELECT
				ISNULL(EE.Id,0) AS Id,
				ES.Id AS EventScheduleId,
				ES.Title,
				ES.FromDate,
				ES.ToDate,
				ES.IsCommonForAll,
				ES.IsHoliday,
				ES.IsEnrollment,
				ES.CreatedDateTime,
				ES.Remark AS Remark,
				EE.Remark AS EventEnrollmentRemark
		FROM 
				sActivity.tEventSchedule ES
			LEFT JOIN sActivity.tEventEnrollment EE ON EE.EventScheduleId=ES.Id AND EE.SourceId=@rSourceId AND EE.SourceTypeId=95
		WHERE 
	  
			 (ES.Id IN(SELECT EventScheduleId FROM sActivity.tEventAssign WHERE SourceTypeId=2004 AND 
				SourceId=(SELECT OrganizationDepartmentId FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId))) 
		AND (ES.BatchId=@rBatchId)
	   AND ((Convert(date,ES.FromDate)<=@rFromDate) OR ISNULL(@rFromDate,'')='')
		AND ((Convert(date,ES.Todate)>=@rTodate) OR ISNULL(@rTodate,'')='')
		--AND (ES.Id > @rSyncedEventScheduleId OR @rSyncedEventScheduleId = 0)
		ORDER BY ES.FromDate DESC
	END
END
GO
PRINT N'Altering [sAlert].[pAllBirthdayWishListGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pAllBirthdayWishListGet]
	 	 
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrStudentId nvarchar(max),
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rDayOfBirth int=0,
	 @rTemp int=0,
	 @rIsStudent bit=0,
	 @rIsEmployee bit=0,
	 @rMother bit=0,
	 @rFather bit=0,
	 @rReletive bit=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		
	Select 
			
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			A.Id AS AcademicId,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
			A.RollNo,
			SC.ParentContactNo AS MobileNo,			 
			'Student' AS CategoryName,
			'' AS PersonName,
			SO.DateOfBirth,
			MONTH(SO.DateOfBirth),
			ISNULL(SI.StudentPhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
		    CM.DisplayTitle+' '+DM.DisplayTitle AS ClassName
	From 
	
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--sStudent.vStudentAllDetail SC
		
	WHERE
			((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (A.OrgId=@rOrgId)
			AND (A.BatchId=@rBatchId)
			AND ((MONTH(SO.DateOfBirth) = @rDateOfBirth) OR (@rDateOfBirth=0))
			AND ((DAY(SO.DateOfBirth) = @rDayOfBirth) OR (@rDayOfBirth = 0 ))
			AND (SM.StatusId=1)
			AND (@rIsStudent=1)
			AND SO.DateOfBirth!=''
	 	
			
UNION ALL

Select 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			A.Id AS AcademicId,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
			A.RollNo,
			SF.FatherContactNo AS MobileNo,			 
			'Father' AS CategoryName,
			SF.FatherName AS PersonName,
			SF.FatherDateOfBirth AS DateOfBirth,
			MONTH(SF.FatherDateOfBirth),
			SI.FatherPhoto AS Photo,
			 CM.DisplayTitle+' '+DM.DisplayTitle AS ClassName
	From 
			--sStudent.vStudentAllDetail SC
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sStudent.tStudentFamily SF ON SC.StudentId = SF.StudentId
	WHERE
			((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (A.OrgId=@rOrgId)
			AND (A.BatchId=@rBatchId)
			--AND (DAY(SF.FatherDateOfBirth) = DAY(@rDateOfBirth))
			AND  (@rDayOfBirth = 0)
			AND ((MONTH(SF.FatherDateOfBirth) = @rDateOfBirth) OR (@rDateOfBirth=0))
			AND (SM.StatusId=1)		
			AND(@rFather=1)
			AND SF.FatherDateOfBirth != ''
	
	UNION ALL

	Select 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,			
			A.Id AS AcademicId,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
			A.RollNo,
			SF.MotherContactNo AS MobileNo,			 
			'Mother' AS CategoryName,
			SF.MotherName AS PersonName,
			SF.MotherDateOfBirth AS DateOfBirth,
			MONTH(SF.MotherDateOfBirth),
			ISNULL(SI.MotherPhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassName
	From 
			--sStudent.vStudentAllDetail SC
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sStudent.tStudentFamily SF ON SC.StudentId = SF.StudentId
	WHERE
			((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (A.OrgId=@rOrgId)
			AND (A.BatchId=@rBatchId)
			--AND (DAY(SF.MotherDateOfBirth) = DAY(@rDateOfBirth))
			AND  (@rDayOfBirth = 0)
			AND  ((MONTH(SF.MotherDateOfBirth) = @rDateOfBirth) OR (@rDateOfBirth=0))
			AND (SM.StatusId=1)		
			AND(@rMother=1)
			AND SF.MotherDateOfBirth != ''	
			
	UNION ALL

	Select 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			A.Id AS AcademicId,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
			A.RollNo,
			SF.RelativeContactNo AS MobileNo,			 
			--SF.RelationshipName AS CategoryName,
			'Relative' AS CategoryName,
			SF.RelativeName AS PersonName,
			SF.RelativeDateOfBirth AS DateOfBirth,
			MONTH(SF.RelativeDateOfBirth),
			ISNULL(SI.RelativePhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassName
			
	From 
			--sStudent.vStudentAllDetail SC
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sStudent.tStudentFamily SF ON SC.StudentId = SF.StudentId
	WHERE
			((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (A.OrgId=@rOrgId)
			AND (A.BatchId=@rBatchId)
			--AND (DAY(SF.RelativeDateOfBirth) = DAY(@rDateOfBirth))
			AND  (@rDayOfBirth = 0)
			AND ((MONTH(SF.RelativeDateOfBirth) = @rDateOfBirth) OR (@rDateOfBirth=0))
			AND (SM.StatusId=1)	
			AND(@rReletive=1)
			AND SF.RelativeDateOfBirth != ''	
	
	UNION ALL
		
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS AcademicId,
			EM.Code,
			EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName AS Name,
	        '' AS RollNo,
	        EC.MobileNumber AS MobileNo,
	        'Employee' AS CategoryName,
	        '' AS PersonName,
			EPD.DateOfBirth,
			MONTH(EPD.DateOfBirth) ,
			ISNULL(EI.EmployeePhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
			ISNULL(ODM.Title,'') AS ClassName
	FROM 
			--[sHrm].[vExtEmployeeMaster] EM	
			sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId	
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.Id = EC.EmployeeId 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId 
			LEFT JOIN sHrm.tEmployeeImages EI ON EM.Id=EI.EmployeeId
			LEFT JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 	
	WHERE  	    
			(EM.OrgId = @rOrgId)
			AND ((MONTH(EPD.DateOfBirth) = @rDateOfBirth) or (@rDateOfBirth=0) )
			AND ((DAY(EPD.DateOfBirth) = @rDayOfBirth) OR (@rDayOfBirth = 0 ))
			AND (@rIsEmployee=1)
			AND EPD.DateOfBirth!=''
		

END
GO
PRINT N'Altering [sAlert].[pFeeDueGet]...';


GO
ALTER PROCEDURE [sAlert].[pFeeDueGet]

		 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rToDate date,
	 	 @rMailSubject nvarchar(500)='',
	 	 @rAdmissionCategoryId int=0,
	 	 @rIdNos nvarchar(500)='',
		 @rDepartmentId int=0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	CREATE TABLE #TempOptional (
		Id int,
		Amount decimal(12,2),
		StartDate date,
		EndDate date,
		ReceiptBookId int,
		AcademicId bigint
	)
	
	CREATE TABLE #TempReceipt (
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint
	)
	
	INSERT INTO #TempOptional
	SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			
			UNION ALL

			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	
	INSERT INTO #TempReceipt
	SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,
				RD.FeeSetupId,
				R.SourceId
			FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0) 
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			GROUP BY 
				FeeSetupId,R.SourceId
	
	SELECT 
		D.AcademicId,
		D.RollNo,
		D.Name,
		D.Code,
		D.MobileNo,	
		D.EmailId,
		D.StudentContactNo,
		D.StudentEmail,
		D.FatherContactNo,
		D.FatherMail,
		D.MotherContactNo,
		D.MotherMail,
		SUM(D.PendingAmount) As PendingAmount,
		REPLACE (
		REPLACE(REPLACE(REPLACE(@rTemplate,'[Name]',D.Name),
		'[Class]',D.ClassName),
		'[Division]',D.DivisionName),
		'[PendingAmount]',CONVERT(int,(SUM(D.PendingAmount))))
		AS Template,
		@rMailSubject AS [Subject]
	FROM
	(
	SELECT
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.ClassName,
		SA.DivisionName,
		SA.Code,
		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,
		SA.DivisionOrder,
		(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00)-(ISNULL(FA.NotApplicableAmount,0.00) + ISNULL(FA.DiscountAmount,0.00)+ISNULL(R.PaidAmount,0.00)))  AS PendingAmount
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN  #TempOptional FS ON FS.AcademicId=SA.AcademicId 
		LEFT JOIN sFee.tFeeAllocation FA
		ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #TempReceipt	R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN  sStudent.vStudentCommunication SC ON SC.AcademicId = SA.AcademicId
	WHERE	
		SA.StatusId = 1 AND SC.IsBlockAllAlert=0 
		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
		AND ((FS.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)		 
		AND (SA.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		AND (SC.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		) D
	GROUP BY 
		D.AcademicId,D.RollNo,D.Name,D.ClassName,D.DivisionName,D.Code,
		D.MobileNo,D.EmailId,D.StudentContactNo,D.StudentEmail,D.FatherContactNo,D.FatherMail,D.MotherContactNo,D.MotherMail,D.DivisionOrder
	ORDER BY 
		D.DivisionOrder,D.Rollno	

	DROP TABLE #TempOptional
	DROP TABLE #TempReceipt
END
GO
PRINT N'Altering [sAlert].[pFeeReceiptEntryGet]...';


GO
ALTER PROCEDURE [sAlert].[pFeeReceiptEntryGet]
	 	 
	 	 @rReceiptId bigint,
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rAdmissionCategoryId int=0,
	 	 @rIdNos nvarchar(500)='',
	 	 @rIsObsolete bit=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
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,
			@rSubject AS Subject,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ReceiptNumber]',R.ReceiptNumber),
			'[ReceiptDate]',R.ReceiptDate),
			'[PaidAmount]',convert(int,R.ReceiptAmount))
			 AS MsgText,
			 
			 SC.OrgId,
			 SC.OrgGroupId,
			 SC.AcademicId AS SourceId,
			 2001 AS SourceTypeId
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sFee.tReceipt R ON R.SourceId=SC.AcademicId AND R.SourceTypeId=2001 AND R.IsObsolete=@rIsObsolete
			AND ((R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((R.Id=@rReceiptId) OR (@rReceiptId=0))
		
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (SC.StatusId=1)
		AND (SC.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		AND (SC.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
		AND SC.IsBlockAllAlert=0
		ORDER BY R.ReceiptNumber
END
GO
PRINT N'Altering [sAssessment].[pCopyExamAdd]...';


GO
ALTER PROCEDURE [sAssessment].[pCopyExamAdd]
	 
	      @rFromBatchId int,
	      @rClassId int,
	      @rOrgId int,
	      @rToBatchId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 BEGIN TRANSACTION	
	 
	 
	DECLARE @lNextNumber BIGINT,@lExamdetailNextNumber BIGINT,@lExamCombineNextNumber bigint,@lCombineNextNumber bigint
	Declare @lCount int,@lExamDetailCount int,@lExamCombineCount int,@lCombineCount int ,
	@lClass nvarchar(50)
	 
	
		
	if exists (Select 1  from sAssessment.tExamMaster  WHere BatchId = @rToBatchId And ((ClassID=@rClassId) OR (@rClassId=0)))
	BEGIN
		Select @lClass=CM.Title from sAssessment.tExamMaster EM INNER JOIN sSetup.tClassMaster CM ON CM.Id= EM.ClassID Where EM.BatchId = @rToBatchId
		Select 1 as REsult,@lClass As Class
		COMMIT TRANSACTION		
	
		Return
		
	END


	Select @lCount = Count(Id) from sAssessment.tExamMaster where BatchId = @rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0))
	  EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	
	Insert into sAssessment.tExamMaster
	( 
		Id,BatchId,ExamSubGroupId,ClassId,IsRankNo,IsGrade,IsPercentile,IsPercentage,IsSubjectPercentile,
		GradeSetId,RankSetId,LevelSetId,UpdatedUserId,UpdatedDateTime,IsProcessResult,IsMarksInDecimal,
		IsNegativeMarks,IsIncludeCoScholastic,IsOnPrePrinted,ReportId,DisplayTitle,Remark1,Remark2,
		Remark3,IsDisplayPhoto,FooterAdjustment,IsDisplayBirthDate,IsLockForEdit,
		IsDisplaySchoolName,DetailAdjustment,IsDisplayHeightWeight,IsDisplayAttendance,TermScopeId,
		IsResultStatus,ExamMaximum,IsDisplayGradeString,IsIncludeGradeSubject,GradeSubjectGradeSetId,
		IsIncludeSubExam,IsCoScholasticGrade,IsCoScholasticGradeIndicator,
		IsCoScholasticGradeDesIndicator,IsCoScholasticCombine,OldExamId,IsPublished,IsDisplayHighestDivisionMark,
		IsDisplayHighestDivisionGrade,IsDisplayParentName,CoScholasticScopeId,SubjectGroupPerPage,
		IsDisplayTeacherSign,IsDisplayPrincipalSign,PercentileScopeId,CoScholasticGradeSetId,IsExcludeAbsentTotal,
		CoScholasticTitle,IsDisplayMonthlyAttendance,IsDisplayImageHeader,DecimalFormat,IsDisplayTotalMark,
		IsDisplayResultIndicator,IsRemovePercentageForFail,Remark1Caption,Remark2Caption,Remark3Caption,
		TeacherSignCaption,PrincipalSignCaption,ParentSignCaption,IsSubjectWeightage,OldImportExamId,IsDisplayActivityGrade,IsAllExamPassRequired
	)
	 Select  
		@lNextNumber + ROW_NUMBER() OVER(ORDER BY Id) ,@rToBatchId,ExamSubGroupId,@rClassId,IsRankNo,IsGrade,IsPercentile,IsPercentage,
		IsSubjectPercentile,GradeSetId,RankSetId,LevelSetId,UpdatedUserId,sCommon.fGetDate(),IsProcessResult,
		IsMarksInDecimal,IsNegativeMarks,IsIncludeCoScholastic,IsOnPrePrinted,ReportId,DisplayTitle,Remark1,
		Remark2,Remark3,IsDisplayPhoto,FooterAdjustment,IsDisplayBirthDate,IsLockForEdit,
		IsDisplaySchoolName,DetailAdjustment,IsDisplayHeightWeight,IsDisplayAttendance,TermScopeId,
		IsResultStatus,ExamMaximum,IsDisplayGradeString,IsIncludeGradeSubject,GradeSubjectGradeSetId,
		IsIncludeSubExam,IsCoScholasticGrade,IsCoScholasticGradeIndicator,
		IsCoScholasticGradeDesIndicator,IsCoScholasticCombine,OldExamId,IsPublished,IsDisplayHighestDivisionMark,
		IsDisplayHighestDivisionGrade,IsDisplayParentName,CoScholasticScopeId,SubjectGroupPerPage,IsDisplayTeacherSign,
		IsDisplayPrincipalSign,PercentileScopeId,CoScholasticGradeSetId,IsExcludeAbsentTotal,CoScholasticTitle,
		IsDisplayMonthlyAttendance,IsDisplayImageHeader,DecimalFormat,IsDisplayTotalMark,IsDisplayResultIndicator,
		IsRemovePercentageForFail,Remark1Caption,Remark2Caption,Remark3Caption,TeacherSignCaption,
		PrincipalSignCaption,ParentSignCaption,IsSubjectWeightage,Id,IsDisplayActivityGrade,IsAllExamPassRequired
	from sAssessment.tExamMaster Where BatchId = @rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0))
	
	 SET @lNextNumber  = @lCount + @lNextNumber 
	  EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tExamMaster', @rCurrentNumber = @lNextNumber 

	
	
	
	select @lExamDetailCount =count (Ed.id) from sAssessment.tExamDetail Ed INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId Where ((Em.ClassId=@rClassId) OR (@rClassID=0)) and Em.batchId=@rFromBatchId
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamDetail', 0, 1, 1,@outNextNumber = @lExamdetailNextNumber output

	
	--Delete EC from sAssessment.tExamDetail EC INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamID where ((Em.ClassId = @rClassId) OR (@rClassID=0)) AND EM.BatchId=@rToBatchID
	
	Insert into sAssessment.tExamDetail
	( 
		Id,ExamId,ClassSubjectId,Maximum,Minimum,IsIncludeInTotal,IsDisplayInMarksheet,IsShowSubjectGrade,DisplayOrder,GradeSetId,ExamDate,ExamTime,ExamTopic,UpdatedUserId,UpdatedDateTime,NoOfQuestion,IsShowSubjectMark
	)  
	Select
		@lExamdetailNextNumber+ ROW_NUMBER() OVER(ORDER BY ClassSubjectId),
		ExamId = (SELECT Id FROM sAssessment.tExamMaster E1 WHERE E1.OldImportExamId = Ed.ExamId and E1.ClassId=@rClassId)
		,ClassSubjectId,Maximum,Minimum,IsIncludeInTotal,IsDisplayInMarksheet,IsShowSubjectGrade,DisplayOrder,ED.GradeSetId,ExamDate,ExamTime,ExamTopic,ED.UpdatedUserId,sCommon.fGetDate(),NoOfQuestion,IsShowSubjectMark
	from sAssessment.tExamDetail Ed INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
	Where ((Em.ClassId=@rClassId) OR (@rClassID=0)) and Em.batchId=@rFromBatchId
	
	SET @lExamdetailNextNumber  = @lExamDetailCount + @lExamdetailNextNumber 
	EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tExamDetail', @rCurrentNumber = @lExamdetailNextNumber 
	
	Select  @lExamCombineCount = count(EC.id) from sAssessment.tExamCombine Ec INNER JOIN sAssessment.tExamMaster EM ON EM.Id= EC.ExamId
	WHere ((Em.ClassId =@rClassId) OR (@rClassID=0)) ANd BatchId =@rFromBatchId
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamCombine', 0, 1, 1,@outNextNumber = @lExamCombineNextNumber output
	
	--Delete EC from sAssessment.tExamCombine EC INNER JOIN sAssessment.tExamMaster EM ON EM.Id= EC.ExamId Where Em.batchId=@rToBatchId AND ((Em.ClassId=@rClassID) OR (@rClassID=0))  
	
	Insert into sAssessment.tExamCombine
	(
		Id,ExamId,SubExamId,weightage,ExamOrder,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
	)
	Select
		@lExamCombineNextNumber+ROW_NUMBER() OVER(ORDER BY ExamId),ExamId = (Select Id from sAssessment.tExamMaster E1 where E1.OldImportExamId = Ec.ExamId  and E1.ClassId=@rClassId),
		SubExamId = (Select Id from sAssessment.tExamMaster E1 where E1.OldImportExamId = Ec.SubExamId and E1.ClassId=@rClassId),weightage,ExamOrder,EC.CreatedUserId,SCommon.fGetdate(),EC.UpdatedUserId,sCommon.fGetDate()
	From sAssessment.tExamCombine EC INNER JOIN sAssessment.tExamMaster EM on EM.Id =EC.ExamId where EM.BatchId=@rFromBatchId and ((EM.ClassId=@rClassId) OR (@rClassID=0))
	
	SET @lExamCombineNextNumber  = @lExamCombineCount + @lExamCombineNextNumber 
	EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tExamCombine', @rCurrentNumber = @lExamCombineNextNumber 

	
	--DElete EC From sAssessment.tExamCombineSubject EC INNER JOIN sAssessment.tExamMaster  EM ON EM.Id=EC.ExamId WHere ((Em.ClassID =@rClassId) OR (@rClassId=0)) AND EM.BatchId=@rToBatchId
	Insert into sAssessment.tExamCombineSubject
	(
		ExamId,SubExamId,ClassSubjectId,SubjectWeightage
	)
	Select 
		ExamId = (Select Id from sAssessment.tExamMaster E1  Where E1.OldImportExamId = Ec.ExamId),
		
		SubExamId =(select Id from sAssessment.tExamMaster E1 Where  E1.OldImportExamId= ec.SubExamId),
		ClassSubjectId,SubjectWeightage
	from sAssessment.tExamCombineSubject EC INNER JOIN sAssessment.tExamMaster EM ON EM.Id= EC.ExamId where ((EM.ClassId =@rClassId) OR (@rClassId=0)) and Em.BatchID=@rFromBatchId
	
	select 11 as result
COMMIT TRANSACTION		
	 
END
GO
PRINT N'Altering [sAssessment].[pExamDetailAdd]...';


GO
ALTER PROCEDURE [sAssessment].[pExamDetailAdd]
	 
	        @rId int
           ,@rExamId int
		   ,@rClassSubjectId int
		   ,@rMinimum decimal(10,2)
		   ,@rMaximum Decimal(10,2)
		   ,@rIsIncludeInTotal bit
		   ,@rIsDisplayInMarkSheet bit
		   ,@rIsShowSubjectGrade bit
		   ,@rDisplayOrder tinyint
		   ,@rGradeSetDetailId int
		   ,@rExamDate date
		   ,@rExamTime nvarchar(50)
		   ,@rExamTopic nvarchar(100)
		   ,@rCreatedUserId bigint
		   ,@rOrgId int
		   ,@rIsObsolete bit,
		   @rIsShowSubjectMark bit=1
		 
		   
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	
	 DECLARE @lNextNumber BIGINT 

IF NOT EXISTS(SELECT 1 FROM sAssessment.tExamMaster E INNER JOIN sSetup.tClassSubject CS ON E.ClassId = CS.ClassId 
WHERE E.Id = @rExamId AND CS.Id = @rClassSubjectId)
BEGIN
SELECT -111 AS Result -- Other Class Subject Selected
RETURN
END 
--IF(@rId = 0)
 BEGIN TRANSACTION		
IF NOT EXISTS (SELECT 1 FROM [sAssessment].[tExamDetail] WHERE ExamId = @rExamId
				AND ClassSubjectId = @rClassSubjectId )
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO [sAssessment].[tExamDetail]
			   (
			    [Id]
			   ,ExamId 
			   ,ClassSubjectId 
			   ,Minimum 
			   ,Maximum 
			   ,IsIncludeInTotal 
			   ,IsDisplayInMarkSheet 
			   ,IsShowSubjectGrade 
			   ,DisplayOrder 
			   ,GradeSetId 
			   ,ExamDate 
			   ,ExamTime 
			   ,ExamTopic 
			   ,UpdatedUserId
			   ,UpdatedDateTime,
			   IsShowSubjectMark
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rExamId 
			   ,@rClassSubjectId 
			   ,@rMinimum 
			   ,@rMaximum 
			   ,@rIsIncludeInTotal 
			   ,@rIsDisplayInMarkSheet 
			   ,@rIsShowSubjectGrade 
			   ,@rDisplayOrder 
			   ,@rGradeSetDetailId 
			   ,@rExamDate 
			   ,@rExamTime 
			   ,@rExamTopic 
			   ,0
			   ,sCommon.fGetDate(),
			   @rIsShowSubjectMark 
			   )
		    SELECT @lNextNumber AS Result
			
		--COMMIT TRANSACTION         
	END	 
ELSE
    BEGIN


IF @rIsObsolete = 1 
	  
	BEGIN
	IF EXISTS (SELECT R.Id FROM sAssessment.tResultDetail R INNER JOIN  [sAssessment].[tExamDetail] ED ON R.ExamDetailId = ED.Id and R.ExamDetailId=@rId AND R.Obtain > @rMaximum) 
    BEGIN
		SELECT -104 AS Result
		RETURN
    END
			
			 SET @lNextNumber = @rId
		 
				UPDATE  [sAssessment].[tExamDetail]
				SET
						ExamId =@rExamId 
					   ,ClassSubjectId =@rClassSubjectId 
					   ,Minimum=@rMinimum 
					   ,Maximum=@rMaximum 
					   ,IsIncludeInTotal =@rIsIncludeInTotal 
					   ,IsDisplayInMarkSheet =@rIsDisplayInMarkSheet 
					   ,IsShowSubjectGrade =@rIsShowSubjectGrade 
					   ,DisplayOrder =@rDisplayOrder 
					   ,GradeSetId =@rGradeSetDetailId 
					   ,ExamDate =@rExamDate 
					   ,ExamTime=@rExamTime 
					   ,ExamTopic =@rExamTopic 
					   ,UpdatedUserId=@rCreatedUserId
					   ,UpdatedDateTime=sCommon.fGetDate(),
					   IsShowSubjectMark=@rIsShowSubjectMark 
				  WHERE Id = @rId 	   
				  SELECT @lNextNumber AS Result
			
				--COMMIT TRANSACTION
			 END 
	ELSE
		BEGIN
		
			IF EXISTS (SELECT R.Id FROM sAssessment.tResultDetail R INNER JOIN  [sAssessment].[tExamDetail] ED ON R.ExamDetailId = ED.Id and R.ExamDetailId=@rId) 
			AND @rIsObsolete = 0
			BEGIN
				SELECT -105 AS Result
				RETURN
			END
		
			DELETE FROM [sAssessment].[tExamDetail] WHERE ID = @rId
			SELECT @rId AS Result
		END		  
	END 

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


GO
ALTER PROCEDURE [sAssessment].[pGeneralExamCustomSearchGet]
(
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rPageIndex int = null,
	@rDivisionId nvarchar(max) = '',
	@rExamId nvarchar(max) = '',
	@rFromMarks decimal(5,2),
	@rToMarks decimal(5,2),
	@rFromGradePoint decimal(6,2),
	@rToGradePoint decimal(6,2),
	@rFromRankNumber int,
	@rToRankNumber int,
	@rFromPercentage decimal(5,2),
	@rToPercentage decimal(5,2),
	@rFromPercentile decimal(5,2),
	@rToPercentile decimal(5,2),
	@rResultGrade nvarchar(10),
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownExamSubGroupId int,
	@rDepartmentId int=0
 )
AS
SET NOCOUNT ON
BEGIN
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rResultGrade = sCommon.fSearchStringGet(@rResultGrade)
	
	
	SELECT * into #TempExam11
	FROM sAssessment.vGeneralExamCustomSearch ECS
	WHERE (ECS.OrgId = @rOrgId) AND (ECS.BatchId = @rBatchId)
	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ECS.TotalObtain >= @rFromMarks) OR (@rFromMarks=0))
	AND ((ECS.TotalObtain <= @rToMarks) OR (@rToMarks=0))
	AND ((ECS.ResultGradePoint >= @rFromGradePoint) OR (@rFromGradePoint=0))
	AND ((ECS.ResultGradePoint <= @rToGradePoint) OR (@rToGradePoint=0))
	AND ((ECS.RankNumber >= @rFromRankNumber) OR (@rFromRankNumber=0))
	AND ((ECS.RankNumber <= @rToRankNumber) OR (@rToRankNumber=0))
	AND ((ECS.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
	AND ((ECS.Percentage <= @rToPercentage) OR (@rToPercentage=0))
	AND ((ECS.Percentile >= @rFromPercentile) OR (@rFromPercentile=0))
	AND ((ECS.Percentile <= @rToPercentile) OR (@rToPercentile=0))
	AND ((ECS.ResultGrade Like @rResultGrade + '%')OR(@rResultGrade = ''))
	AND (ECS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
	AND (ECS.ExamId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamId,','))OR @rExamId='')
	AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((ECS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
	AND ((ECS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	AND ((ECS.ExamSubGroupId = @rDropDownExamSubGroupId) OR (@rDropDownExamSubGroupId=0))
	AND ((ECS.DepartmentId =@rDepartmentId) OR (@rDepartmentId =0))
	
	SET @sql='SELECT Code AS Code,Name,ClassName,RollNo,TotalMarks,TotalObtain,
	ResultStatus,ResultGrade,ResultGradePoint,RankNumber,Percentage,Percentile,
	ResultReMark,OtherRemark1,ExamName FROM #TempExam11 ORDER BY ' + @rOrderBy
	
	exec(@Sql)
	
	create table #TEMPExam
	(
		tid int identity(1,1),t_AcedemicId bigint
	)
	SET @sql='insert into #TEMPExam SELECT AcademicId FROM #TempExam11 ORDER BY ' + @rOrderBy
	
	exec (@sql)
	
	declare @lTotalRecords int,@lPageSize int = 10,@lPaging varchar(max)='',@lResult varchar(max)=''
	
	select @lTotalRecords = count(*) from #TEMPExam
	select @lPaging = @lPaging + dbo.fnc_searchpagingformat(@rPageIndex,@lTotalRecords,@lPageSize)
	
	select @lResult = @lResult + '<tr><td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td>
	<td>' + isnull(convert(varchar,RollNo),'') + '</td><td>' + isnull(ExamName,'') + '</td>
	<td>' + isnull(convert(varchar,TotalMarks),'') + '</td><td>' + isnull(convert(varchar,TotalObtain),'') + '</td>
	<td>' + isnull(ResultStatus,'') + '</td><td>' + isnull(ResultGrade,'') + '</td>

	<td>' + isnull(convert(varchar,RankNumber),'') + '</td>
	<td>' + isnull(convert(varchar,Percentage),'') + '</td><td>' + isnull(convert(varchar,Percentile),'') + '</td>
	<td>' + isnull(ResultReMark,'') + '</td><td>' + isnull(OtherRemark1,'') + '</td></tr>'
	from #TempExam11,#TEMPExam
	where AcademicId = t_AcedemicId  and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	
	select @lResult as StudentList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP table #TEMPExam
	DROP Table #TempExam11
	
		--<td>' + isnull(convert(varchar,ResultGradePoint),'') + '</td>
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryAllExamSubjectGet]...';


GO
ALTER PROCEDURE [sAssessment].[pMarkEntryAllExamSubjectGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId nvarchar(Max),
	 @rBatchId int,
	 @rClassSubjectId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

DECLARE @ExamIDTable TABLE (ExamID BIGINT)
INSERT INTO @ExamIDTable(ExamID)
SELECT item FROM sCommon.fnSplit(@rExamId,',')

DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(E.Id) 
					  From sAssessment.vExamMaster  E
					  --INNER JOIN sAssessment.tExamDetail Ed ON Ed.ExamId =E.Id 
					   Where ClassId = @rClassId AND E.Id in (SELECT ExamID FROM @ExamIDTable)
					   Order by E.ExamSubGroupId
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        --select @cols
set @query = 'SELECT  AcademicId, Name,RollNo,Code,ClassName, ' + @cols + '
FROM
(
Select ISNULL(RD.Obtain,0) AS Obtain, A.AcademicId,ED.ExamId,A.Name,A.RollNo,
A.Code,CM.Title ClassName 
FROM sStudent.vStudentAcademic A 
INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id 
INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND A.DivisionId=DM.Id
INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=A.AcademicId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectID
LEFT JOIN sAssessment.tOptionalSubject OP ON OP.AcademicId=A.AcademicId ANd CS.Id=OP.ClassSubjectId  
WHERE A.StatusId =1   AND A.BatchId = '+ CONVERT(nvarchar(15),@rBatchId) + ' AND A.ClassId= ' + convert(nvarchar(15),@rClassId) +  '  And A.DivisionId= ' + convert(nvarchar(15),@rDivisionId) + ' And  ED.ExamId in( ' + convert(nvarchar(Max),@rExamId) + ') And ED.ClassSubjectId='+convert(nvarchar(14),@rClassSubjectId)+'  AND ((CS.IsOptional = 1 AND  isnull(oP.AcademicId,0) <> 0) OR (CS.IsOptional = 0)) 
 ) MAIN

PIVOT
(
	MAX(obtain )
FOR ExamID IN (' + @cols + ')
)pvt Order by RollNo'
  --print @query
execute(@query)
		
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryGet]...';


GO
 
ALTER PROCEDURE [sAssessment].[pMarkEntryGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rExamDetailId int,
	 @rBatchId int,
	 @rIsWithPhoto bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

if(@rIsWithPhoto=1)
BEGIN
SELECT 
	
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,ISNULL(RD.Id,0) AS ResultDetailId
	,ISNULL(R.Id,0) AS ResultId  
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,ISNULL(RD.Obtain,0) AS Obtain
	,ISNULL(RD.IsPresent,'true') as IsPresent
	,ED.Id AS ExamDetailId
	,CONVERT(INT,ISNULL(ED.Maximum,0)) AS MaximumMark
	,ISNULL(EM.IsMarksInDecimal,0) AS IsMarkInDecimal,
	ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
	ISNULL(ED.ExamTopic,'') as ExamTopic,
	0 AS PresentTotal,
	0 AS TotalCount
from sStudent.vStudentAcademic SA 
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
	LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
	LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicId and o.ClassSubjectId=V.ClassSubjectId

Where  (DM.Id=@rDivisionId OR @rDivisionId = 0)
	   AND (EM.ClassId = @rClassId OR @rClassId = 0)  
	   AND (ED.Id=@rExamDetailId OR @rExamDetailId = 0 )
	   AND (EM.Id=@rExamId OR @rExamId = 0)
	   AND SA.StatusId=1 AND SA.BatchId=@rBatchId
	   AND ((V.IsOptional = 1 AND    isnull(o.AcademicId,0) <> 0) OR (V.IsOptional = 0))	  
	Order By SA.RollNo
END
ELse
BEGIN
	SELECT 
	
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,ISNULL(RD.Id,0) AS ResultDetailId
	,ISNULL(R.Id,0) AS ResultId  
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,ISNULL(RD.Obtain,0) AS Obtain
	,ISNULL(RD.IsPresent,'true') as IsPresent
	,ED.Id AS ExamDetailId
	,CONVERT(INT,ISNULL(ED.Maximum,0)) AS MaximumMark
	,ISNULL(EM.IsMarksInDecimal,0) AS IsMarkInDecimal,
	CONVERT(VARBINARY(MAX), 0) AS  StudentPhoto,
	ISNULL(ED.ExamTopic,'') as ExamTopic,
	0 AS PresentTotal,
	0 AS TotalCount
from sStudent.vStudentAcademic SA 
	--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
	LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
	LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicId and o.ClassSubjectId=V.ClassSubjectId

Where  (DM.Id=@rDivisionId OR @rDivisionId = 0)
	   AND (EM.ClassId = @rClassId OR @rClassId = 0)  
	   AND (ED.Id=@rExamDetailId OR @rExamDetailId = 0 )
	   AND (EM.Id=@rExamId OR @rExamId = 0)
	   AND SA.StatusId=1 AND SA.BatchId=@rBatchId
	   AND ((V.IsOptional = 1 AND    isnull(o.AcademicId,0) <> 0) OR (V.IsOptional = 0))	  
Order By SA.RollNo
END

END
GO
PRINT N'Altering [sAssessment].[pObtainMarksUpdate]...';


GO
ALTER PROCEDURE [sAssessment].[pObtainMarksUpdate]
	 
	@rResultDetailsId bigint,
	@rObtainMarks decimal(8,2)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
BEGIN TRY
BEGIN TRANSACTION	
		UPDATE sAssessment.tResultDetail SET Obtain=@rObtainMarks WHERE Id=@rResultDetailsId
		SELECT 1 Result
		
COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
		
END


--select *From sAssessment.tResultDetail
GO
PRINT N'Altering [sAssessment].[pResultGenerateListGet]...';


GO
ALTER PROCEDURE [sAssessment].[pResultGenerateListGet]
	 @rExamSubGroupId int,
	 @rClassId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
					 
	SELECT 
		EM.ClassId,
		EM.Id AS ExamId,
		ISNULL(DM.Id,0) as DivisionId,
		ISNULL(CM.DisplayTitle + ' - ' + DM.Displaytitle,'') as Class,
		CM.DisplayTitle AS ClassName,
		ESGM.Title AS Exam,	
		isnull(SM.Title,'Process Schedule') AS Status,
		ISNULL(ES.Id,0) AS ExamStatusId,
		ISNULL(EM.ReportId,0) as ReportId

FROM  				[sAssessment].[tExamGroupMaster] EGM			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ExamGroupId = EGM.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.ExamSubGroupId = ESGM.Id 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id
			LEFT JOIN sAssessment.tExamStatus ES ON EM.Id=ES.ExamId AND ES.DivisionId=DM.Id
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=ES.StatusId
			
  WHERE		(ESGM.Id = @rExamSubGroupId Or @rExamSubGroupId=0) AND
			(EM.ClassId=@rClassId OR @rClassId =0) AND ISProcessREsult = 1 AND EM.BatchId=@rBatchId
			ORDER BY DM.OrderIndex, ESGM.Title ASC
		 
		
END
GO
PRINT N'Altering [sAssessment].[pResultSheetStandardMultiExamGet]...';


GO
ALTER PROCEDURE [sAssessment].[pResultSheetStandardMultiExamGet]	 	 	
	 @rExamId int,	
	 @rAcademicId bigint=0	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam
 
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

Select @GradeStringHtml = GradeStringHtml from sAssessment.tGradeSetMaster where Id =@GradeSetId
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
	    SRNO INT IDENTITY(1,1) PRIMARY KEY, 
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(500),
		Remark2 nvarchar(500),
		Remark3 nvarchar(500),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays smallint,
		PresentDays smallint,
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		
--		ResultDetailId int,
		ResultDetailId1 bigint,
		ResultDetailId2 bigint,
		ResultDetailId3 bigint,
		ResultDetailId4 bigint,
		ResultDetailId5 bigint,
		ResultDetailId6 bigint,
		ResultDetailId7 bigint,
		ResultDetailId8 bigint,
		ResultDetailId9 bigint,
		ResultDetailId10 bigint,
		ResultDetailId11 bigint,
		ResultDetailId12 bigint,
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(200),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		--IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(20),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 smallint,
		PresentDays1 smallint,
		TotalDays2 smallint,
		PresentDays2 Smallint,
		TotalDays3 smallint,
		PresentDays3 smallint,
		TotalDays4 smallint,
		PresentDays4 smallint,
		TotalDays5 smallint,
		PresentDays5 smallint,
		TotalDays6 smallint,
		PresentDays6 smallint,
		TotalDays7 smallint,
		PresentDays7 smallint, 
		TotalDays8 smallint,
		PresentDays8 smallint,
		TotalDays9 smallint,
		PresentDays9 smallint,
		TotalDays10 smallint,
		PresentDays10 smallint,
		TotalDays11 smallint,
		PresentDays11 smallint,
		TotalDays12 smallint,
		PresentDays12 smallint,
		BatchIdText nvarchar(20),
		--IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(200),
		AchievementsTerm2 nvarchar(200),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 smallint,
		SR_PresentDaysTerm2 smallint,
		SR_TotalDaysTerm1 smallint,
		SR_TotalDaysTerm2 smallint
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	--ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	
	ExamCode,
	
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	Batch,
	ClassTeacherName,
	FirstName,
	LastName,
	IsDisplayMonthlyAttendance,
	MarksheetHeaderA4,
	IsImageHeader,
	MyGoal,
	AreaOfInterest,
	Responsibility,
	MyInterestHobby,
	MyStrength,
	Achievements, 
	
	DentalHygiene,
	VisionLeft,
	VisionRight,
	--IsDetail,
	SubjectGroupId,
	SubjectGroupTitle,
	SubjectGroupCode,
	DecimalFormat,
	SubjectRemark,
	GraceMark,
	KrupaMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	--BatchIdText,
    --IsShowWithDetail,
    IsPresent,
    GradeTitle,
	
	SubjectHighestDivisionGrade,
	SubjectHighestDivisionMark,
	
	AchievementsTerm1,
	AchievementsTerm2,
	GeneralRemarkTerm1,
	GeneralRemarkTerm2,
	ResultRemark1Term1,
	ResultRemark2Term1,
	ResultRemark1Term2,
	ResultRemark2Term2,
	SR_HeightTerm1,
	SR_WeightTerm1,
	SR_HeightTerm2,
	SR_WeightTerm2,
	SR_PresentDaysTerm1,
	SR_PresentDaysTerm2,
	SR_TotalDaysTerm1,
	SR_TotalDaysTerm2	
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		--Convert(nvarchar(50),@rClassId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		ISNULL(R.ResultStatus,'') AS ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		ISNULL(R.Percentage,0) As Percentage,
		R.RankNumber,
		ISNULL(R.ResultGrade,'') AS ResultGrade,


		EM.IsMarksInDecimal,
		
				
		1,
		--RD.Obtain,
		R.Percentile,
		--SM.Title AS ClassSubject,
		RD.Id AS ResultDetailId,
		R.Id AS ResultId,

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END)AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.TotalDays,
		SR.PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		ISNULL(ESGM.Code,'') AS ExamCode,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		 
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		--@rIsDetail AS IsDetail,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark,
		RD.GraceMark,
		RD.KrupaMark,
		@GradeStringHtml,
		SR.ResultRemark3,
		EM.IsDisplayTotalMark,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		--Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		--@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		
		'' AS AchievementsTerm1,
		'' AS AchievementsTerm2,
		'' AS GeneralRemarkTerm1,
		'' AS GeneralRemarkTerm2,
		'' AS ResultRemark1Term1,
		'' AS ResultRemark2Term1, 
		'' AS ResultRemark1Term2,
		'' AS ResultRemark2Term2,
		SR.StudentHeight AS SR_HeightTerm1,
		SR.StudentWeight AS SR_WeightTerm1,
		SR.StudentHeight AS SR_HeightTerm2,
		SR.StudentWeight AS SR_WeightTerm2,
		SR.PresentDays AS SR_PresentDaysTerm1,
	    SR.PresentDays AS SR_PresentDaysTerm2,
	    SR.TotalDays AS SR_TotalDaysTerm1,
	    SR.TotalDays AS SR_TotalDaysTerm2	
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	--LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = AR.OrgGroupBatchId)) 
 --   LEFT JOIN
	--(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
 --   INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
 --   INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
 --   ON RT.SourceId = StuM.Id 
			  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		R.ExamId = @rExamId 		
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))			    
	Order By ED.DisplayOrder
 
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
    
	Select @lCount = MAX(Id) from #tempcombineExam
	--print @lCount
	--SET @lCount1 = @lCount+1
	DECLARE @ExamTitle nvarchar(150)
	
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.Obtain,0),
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 --ExamDetailId' + convert(nvarchar(15),@lCount)+'=RD.ExamDetailId,
					  ResultDetailId' + convert(nvarchar(15),@lCount)+'=RD.Id,
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND  EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
				--print @lSubExamId							
	   execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.ExamSubGroupDisplayTitle,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code,
					AchievementsTerm1 = SR.Achievements,
					GeneralRemarkTerm1 = SR.GeneralRemark,
					ResultRemark1Term1 = SR.ResultRemark1,
					ResultRemark2Term1 = SR.ResultRemark2,
					SR_HeightTerm1 = SR.StudentHeight,
					SR_WeightTerm1 = SR.StudentWeight,
					SR_PresentDaysTerm1 = SR.PresentDays,
					SR_TotalDaysTerm1 = SR.TotalDays
					
					From
					 
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		 	
						
		execute(@query)
		
					select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum,
					AchievementsTerm2 = SR.Achievements,
					GeneralRemarkTerm2 = SR.GeneralRemark,
					ResultRemark1Term2 = SR.ResultRemark1,
					ResultRemark2Term2 = SR.ResultRemark2,
					SR_HeightTerm2 = SR.StudentHeight,
					SR_WeightTerm2 = SR.StudentWeight,
					SR_PresentDaysTerm2 = SR.PresentDays,
					SR_TotalDaysTerm2 = SR.TotalDays
									 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END		
	
	SELECT T.*
	FROM #TempAllExam T  where 
	T.ExamId=@rExamId AND 
	AcademicId= @rAcademicId
	
	
	--Declare @Count AS Integer
    --SET @Count=(SELECT  count(ClassSubjectID) FROM #TempAllExam T)
    DECLARE @lCounter INT
    SET @lCounter = 1
    DECLARE @lMAXID INT=0
    
    SELECT @lMAXID = COUNT(*) FROM #TempAllExam
    Declare @FinalHtml nvarchar(max)=''
	Declare @tdHtml nvarchar(max)
	Declare @trHtml nvarchar(max)
	Declare @HeaderHtml nvarchar(max)
	Declare @HeaderCounter int=0
	Declare @thHtml nvarchar(max)
	
	WHILE (@lCounter <= @lMAXID)
	BEGIN 
	     Declare @ClassSubject nvarchar(max)
	     Declare @ResultDetailId1 nvarchar(max)
	     Declare @ResultDetailId2 nvarchar(max)
	     Declare @ResultDetailId3 nvarchar(max)
	     Declare @ResultDetailId4 nvarchar(max)
	     Declare @ResultDetailId5 nvarchar(max)
	     Declare @ResultDetailId6 nvarchar(max)
	     Declare @ResultDetailId7 nvarchar(max)
	     Declare @ResultDetailId8 nvarchar(max)
	     Declare @ResultDetailId9 nvarchar(max)
	     Declare @ResultDetailId10 nvarchar(max)
	     Declare @ResultDetailId11 nvarchar(max)
	     Declare @ResultDetailId12 nvarchar(max)
	     
	     Declare @Obtain1 decimal(10,2)
	     Declare @Obtain2 decimal(10,2)
	     Declare @Obtain3 decimal(10,2)
	     Declare @Obtain4 decimal(10,2)
	     Declare @Obtain5 decimal(10,2)
	     Declare @Obtain6 decimal(10,2)
	     Declare @Obtain7 decimal(10,2)
	     Declare @Obtain8 decimal(10,2)
	     Declare @Obtain9 decimal(10,2)
	     Declare @Obtain10 decimal(10,2)
	     Declare @Obtain11 decimal(10,2)
	     Declare @Obtain12 decimal(10,2)
	     
	     
	     Declare @ExamMaximumMarks1 decimal(10,2)
	     Declare @ExamMaximumMarks2 decimal(10,2)
	     Declare @ExamMaximumMarks3 decimal(10,2)
	     Declare @ExamMaximumMarks4 decimal(10,2)
	     Declare @ExamMaximumMarks5 decimal(10,2)
	     Declare @ExamMaximumMarks6 decimal(10,2)
	     Declare @ExamMaximumMarks7 decimal(10,2)
	     Declare @ExamMaximumMarks8 decimal(10,2)
	     Declare @ExamMaximumMarks9 decimal(10,2)
	     Declare @ExamMaximumMarks10 decimal(10,2)
	     Declare @ExamMaximumMarks11 decimal(10,2)
	     Declare @ExamMaximumMarks12 decimal(10,2)
	     
	     
	     Declare @Exam1Name nvarchar(max)
	     Declare @Exam2Name nvarchar(max)
	     Declare @Exam3Name nvarchar(max)
	     Declare @Exam4Name nvarchar(max)
	     Declare @Exam5Name nvarchar(max)
	     Declare @Exam6Name nvarchar(max)
	     Declare @Exam7Name nvarchar(max)
	     Declare @Exam8Name nvarchar(max)
	     Declare @Exam9Name nvarchar(max)
	     Declare @Exam10Name nvarchar(max)
	     Declare @Exam11Name nvarchar(max)
	     Declare @Exam12Name nvarchar(max)
	     Declare @IsMarksInDecimal bit
	     
	     
	     SET @ClassSubject=(SELECT SubjectName from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId1=(SELECT ResultDetailId1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId2=(SELECT ResultDetailId2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId3=(SELECT ResultDetailId3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId4=(SELECT ResultDetailId4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId5=(SELECT ResultDetailId5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId6=(SELECT ResultDetailId6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId7=(SELECT ResultDetailId7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId8=(SELECT ResultDetailId8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId9=(SELECT ResultDetailId9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId10=(SELECT ResultDetailId10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId11=(SELECT ResultDetailId11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId12=(SELECT ResultDetailId12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     SET @Obtain1=(SELECT Obtain1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain2=(SELECT Obtain2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain3=(SELECT Obtain3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain4=(SELECT Obtain4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain5=(SELECT Obtain5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain6=(SELECT Obtain6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain7=(SELECT Obtain7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain8=(SELECT Obtain8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain9=(SELECT Obtain9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain10=(SELECT Obtain10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain11=(SELECT Obtain11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain12=(SELECT Obtain12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     
	     
	     SET @Exam1Name=(SELECT Exam1Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam2Name=(SELECT Exam2Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam3Name=(SELECT Exam3Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam4Name=(SELECT Exam4Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam5Name=(SELECT Exam5Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam6Name=(SELECT Exam6Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam7Name=(SELECT Exam7Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam8Name=(SELECT Exam8Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam9Name=(SELECT Exam9Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam10Name=(SELECT Exam10Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam11Name=(SELECT Exam11Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam12Name=(SELECT Exam12Name from #TempAllExam WHERE SRNO=@lCounter)
	     
	     SET @ExamMaximumMarks1=(SELECT MaximumMark1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks2=(SELECT MaximumMark2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks3=(SELECT MaximumMark3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks4=(SELECT MaximumMark4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks5=(SELECT MaximumMark5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks6=(SELECT MaximumMark6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks7=(SELECT MaximumMark7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks8=(SELECT MaximumMark8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks9=(SELECT MaximumMark9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks10=(SELECT MaximumMark10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks11=(SELECT MaximumMark11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks12=(SELECT MaximumMark12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     
	     SET @IsMarksInDecimal=(SELECT IsMarksInDecimal from #TempAllExam WHERE SRNO=@lCounter)
	     --print @IsMarksInDecimal
	  
	     IF(@HeaderCounter=0)
	     BEGIN
	      SET @thHtml='<th>Subjects</th>'
	      if(@Exam1Name<>'' OR @Exam1Name IS NOT NULL)	    
	      SET @thHtml=@thHtml+'<th>'+@Exam1Name+'</th>';   
	      if(@Exam2Name<>'' OR @Exam2Name IS NOT NULL)	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam2Name+'</th>';  
	       if(@Exam3Name<>'' OR @Exam3Name IS NOT NULL)	    	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam3Name+'</th>';   
	       if(@Exam4Name<>'' OR @Exam4Name IS NOT NULL)	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam4Name+'</th>';  
	      if(@Exam5Name<>'' OR @Exam5Name IS NOT NULL)	  	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam5Name+'</th>';  
	       if(@Exam6Name<>'' OR @Exam6Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam6Name+'</th>';  
	        if(@Exam7Name<>'' OR @Exam7Name IS NOT NULL)	  	  	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam7Name+'</th>';  
	        if(@Exam8Name<>'' OR @Exam8Name IS NOT NULL)	  	  	    		    
	      SET @thHtml=@thHtml+'<th>'+@Exam8Name+'</th>';  
	       if(@Exam9Name<>'' OR @Exam9Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam9Name+'</th>';  
	          if(@Exam10Name<>'' OR @Exam10Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam10Name+'</th>'; 
	       if(@Exam11Name<>'' OR @Exam11Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th>'+@Exam11Name+'</th>';  
	      if(@Exam12Name<>'' OR @Exam12Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th>'+@Exam12Name+'</th>';  
	     END   
	     SET @HeaderCounter=@HeaderCounter+1;
	    
	     
	     SET @tdHtml='<td class=Sub width=200>'+@ClassSubject+'</td>';
	     
	     Declare @SetDecimalFunction nvarchar(max)
	    --print @IsMarksInDecimal
	     IF(@IsMarksInDecimal=1)
			 BEGIN
			  SET @SetDecimalFunction='onblur="javascript:return fnValidateDecimal(this,10,2)" onKeypress="javascript:return MaskDecimal(event,10,2)"';
			  
		 if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),@Obtain1)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks1)+' value='+CONVERT(varchar(20),@Obtain1)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),@Obtain2)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks2)+' value='+CONVERT(varchar(20),@Obtain2)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),@Obtain3)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks3)+' value='+CONVERT(varchar(20),@Obtain3)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),@Obtain4)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks4)+' value='+CONVERT(varchar(20),@Obtain4)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),@Obtain5)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks5)+' value='+CONVERT(varchar(20),@Obtain5)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),@Obtain6)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks6)+' value='+CONVERT(varchar(20),@Obtain6)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),@Obtain7)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks7)+' value='+CONVERT(varchar(20),@Obtain7)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),@Obtain8)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks8)+' value='+CONVERT(varchar(20),@Obtain8)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),@Obtain9)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks9)+' value='+CONVERT(varchar(20),@Obtain9)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),@Obtain10)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks10)+' value='+CONVERT(varchar(20),@Obtain10)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	     SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),@Obtain11)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks11)+' value='+CONVERT(varchar(20),@Obtain11)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),@Obtain12)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks12)+' value='+CONVERT(varchar(20),@Obtain12)+' '+@SetDecimalFunction+' MaxLength="100"/></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
			  
			  
			  
			 END
	     ELSE
			 BEGIN
			   
			  SET @SetDecimalFunction='onblur="javascript:return fnValidateDecimal(this,10,0)" onKeypress="javascript:return MaskDecimal(event,10,0)"';
			  
			  
		if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain1 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks1)+' value='+CONVERT(varchar(20),CAST(@Obtain1 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain2 AS int))+'</div><input class=numbersOnly type=text   ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks2)+' value='+CONVERT(varchar(20),CAST(@Obtain2 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain3 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks3)+' value='+CONVERT(varchar(20),CAST(@Obtain3 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain4 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks4)+' value='+CONVERT(varchar(20),CAST(@Obtain4 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain5 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks5)+' value='+CONVERT(varchar(20),CAST(@Obtain5 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain6 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks6)+' value='+CONVERT(varchar(20),CAST(@Obtain6 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain7 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks7)+' value='+CONVERT(varchar(20),CAST(@Obtain7 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain8 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks8)+' value='+CONVERT(varchar(20),CAST(@Obtain8 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain9 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks9)+' value='+CONVERT(varchar(20),CAST(@Obtain9 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain10 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks10)+' value='+CONVERT(varchar(20),CAST(@Obtain10 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	     SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain11 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks11)+' value='+CONVERT(varchar(20),CAST(@Obtain11 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark><div>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div><div>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain12 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks12)+' value='+CONVERT(varchar(20),CAST(@Obtain12 AS int))+' '+@SetDecimalFunction+' MaxLength="100"/></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
			  
			  
			 END
	     
	    SET @trHtml= '<tr>'+@tdHtml+'</tr>';
	    SET @FinalHtml=@FinalHtml+@trHtml;
        
	     SET @lCounter = @lCounter + 1
	END
	 --print @thHtml
	select '<table id="ExamDataTbl" class="table table-striped table-bordered table-hover"><tr class="sub_exam_width">'+@thHtml+'</tr>'+@FinalHtml+'</table>' AS Html; 
	--if(@FinalHtml IS NOT NULL and @FinalHtml <> '')	    
 --   select '<table id="ExamDataTbl" class="table table-striped table-bordered table-hover"><tr>'+@thHtml+'</tr>'+@FinalHtml+'</table>' AS Html; 
 --   ELSE
 --   select '<table id="ExamDataTbl" class="table table-striped table-bordered table-hover"><tr>No record found.</tr></table>' AS Html; 
			
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

--	SELECT @rBuilder1,@rBuilder2, T.* FROM sAssessment.tTempAllExam T
--end
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0
	
	 --,@rcolumn_visible bit
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam
 
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

Select @GradeStringHtml = GradeStringHtml from sAssessment.tGradeSetMaster where Id =@GradeSetId
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(500),
		Remark2 nvarchar(500),
		Remark3 nvarchar(500),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays smallint,
		PresentDays smallint,
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(200),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(20),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 smallint,
		PresentDays1 smallint,
		TotalDays2 smallint,
		PresentDays2 Smallint,
		TotalDays3 smallint,
		PresentDays3 smallint,
		TotalDays4 smallint,
		PresentDays4 smallint,
		TotalDays5 smallint,
		PresentDays5 smallint,
		TotalDays6 smallint,
		PresentDays6 smallint,
		TotalDays7 smallint,
		PresentDays7 smallint, 
		TotalDays8 smallint,
		PresentDays8 smallint,
		TotalDays9 smallint,
		PresentDays9 smallint,
		TotalDays10 smallint,
		PresentDays10 smallint,
		TotalDays11 smallint,
		PresentDays11 smallint,
		TotalDays12 smallint,
		PresentDays12 smallint,
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(200),
		AchievementsTerm2 nvarchar(200),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 smallint,
		SR_PresentDaysTerm2 smallint,
		SR_TotalDaysTerm1 smallint,
		SR_TotalDaysTerm2 smallint
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	
	ExamCode,
	
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	Batch,
	ClassTeacherName,
	FirstName,
	LastName,
	IsDisplayMonthlyAttendance,
	MarksheetHeaderA4,
	IsImageHeader,
	MyGoal,
	AreaOfInterest,
	Responsibility,
	MyInterestHobby,
	MyStrength,
	Achievements, 
	
	DentalHygiene,
	VisionLeft,
	VisionRight,
	IsDetail,
	SubjectGroupId,
	SubjectGroupTitle,
	SubjectGroupCode,
	DecimalFormat,
	SubjectRemark,
	GraceMark,
	KrupaMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText,
    IsShowWithDetail,
    IsPresent,
    GradeTitle,
	
	SubjectHighestDivisionGrade,
	SubjectHighestDivisionMark,
	
	AchievementsTerm1,
	AchievementsTerm2,
	GeneralRemarkTerm1,
	GeneralRemarkTerm2,
	ResultRemark1Term1,
	ResultRemark2Term1,
	ResultRemark1Term2,
	ResultRemark2Term2,
	SR_HeightTerm1,
	SR_WeightTerm1,
	SR_HeightTerm2,
	SR_WeightTerm2,
	SR_PresentDaysTerm1,
	SR_PresentDaysTerm2,
	SR_TotalDaysTerm1,
	SR_TotalDaysTerm2	
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		Convert(nvarchar(50),@rClassId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		ISNULL(R.ResultStatus,'') AS ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		ISNULL(R.Percentage,0) As Percentage,
		R.RankNumber,
		ISNULL(R.ResultGrade,'') AS ResultGrade,


		EM.IsMarksInDecimal,
		
				
		1,
		--RD.Obtain,
		R.Percentile,
		--SM.Title AS ClassSubject,
		RD.Id AS ResultDetailId,
		R.Id AS ResultId,

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END)AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.TotalDays,
		SR.PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		ISNULL(ESGM.Code,'') AS ExamCode,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		 
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		@rIsDetail AS IsDetail,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark,
		RD.GraceMark,
		RD.KrupaMark,
		@GradeStringHtml,
		SR.ResultRemark3,
		EM.IsDisplayTotalMark,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		
		'' AS AchievementsTerm1,
		'' AS AchievementsTerm2,
		'' AS GeneralRemarkTerm1,
		'' AS GeneralRemarkTerm2,
		'' AS ResultRemark1Term1,
		'' AS ResultRemark2Term1, 
		'' AS ResultRemark1Term2,
		'' AS ResultRemark2Term2,
		SR.StudentHeight AS SR_HeightTerm1,
		SR.StudentWeight AS SR_WeightTerm1,
		SR.StudentHeight AS SR_HeightTerm2,
		SR.StudentWeight AS SR_WeightTerm2,
		SR.PresentDays AS SR_PresentDaysTerm1,
	    SR.PresentDays AS SR_PresentDaysTerm2,
	    SR.TotalDays AS SR_TotalDaysTerm1,
	    SR.TotalDays AS SR_TotalDaysTerm2	
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = StuM.Id 
			  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    ) 
	    
	Order By ED.DisplayOrder
 
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--SET @lCount1 = @lCount+1
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.Obtain,0),
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.ExamSubGroupDisplayTitle,
					--Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code,
					AchievementsTerm1 = SR.Achievements,
					GeneralRemarkTerm1 = SR.GeneralRemark,
					ResultRemark1Term1 = SR.ResultRemark1,
					ResultRemark2Term1 = SR.ResultRemark2,
					SR_HeightTerm1 = SR.StudentHeight,
					SR_WeightTerm1 = SR.StudentWeight,
					SR_PresentDaysTerm1 = SR.PresentDays,
					SR_TotalDaysTerm1 = SR.TotalDays
					
					From
					 
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		 	
						
		execute(@query)
		
					select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum,
					AchievementsTerm2 = SR.Achievements,
					GeneralRemarkTerm2 = SR.GeneralRemark,
					ResultRemark1Term2 = SR.ResultRemark1,
					ResultRemark2Term2 = SR.ResultRemark2,
					SR_HeightTerm2 = SR.StudentHeight,
					SR_WeightTerm2 = SR.StudentWeight,
					SR_PresentDaysTerm2 = SR.PresentDays,
					SR_TotalDaysTerm2 = SR.TotalDays
									 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

--	SELECT @rBuilder1,@rBuilder2, T.* FROM sAssessment.tTempAllExam T
--end
GO
PRINT N'Altering [sAssessment].[pSubjectRemarkAdd]...';


GO

ALTER PROCEDURE [sAssessment].[pSubjectRemarkAdd]
	 
	       
		    @rSubjectRemark nvarchar(1000)
		   ,@rExamId int
		   ,@rAcademicId bigint
		   ,@rClassSubjectId int
		   ,@rPresentCount int
		   ,@rTotalCount int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	if exists (select 1 from sAssessment.tResultDetailOther where ExamId = @rExamid and AcademicId = @racademicid and classsubjectid= @rclasssubjectid)
	begin
		update sAssessment.tResultDetailOther
		Set 
			Remark =@rSubjectRemark,
			PresentCount=@rPresentCount,
			TotalCount = @rTotalCount
		Where  ExamId = @rExamid and AcademicId = @racademicid and classsubjectid= @rclasssubjectid
		Select 11 As Result
	end
	 
ELSE
	 BEGIN
	     
	INSERT INTO sAssessment.tResultDetailOther
			   (
			    ExamId
			   ,AcademicId 
			   ,ClassSubjectId
			   ,Remark
			   ,PresentCount
			   ,TotalCount
			   )
		 VALUES
			   (
				@rExamId
			   ,@rAcademicId
			   ,@rClassSubjectId
			   ,@rSubjectRemark
			   ,@rPresentCount
			   ,@rTotalCount
			   )
		    SELECT 1 AS Result
	 END  
		 
 
		
END
GO
PRINT N'Altering [sAssessment].[pSubjectRemarkGet]...';


GO
ALTER PROCEDURE [sAssessment].[pSubjectRemarkGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	  
	 @rClassSubjectId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		


SELECT 
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,ISNULL(RD.Remark,'') AS SubjectRemark
	,ISNULL(RD.TotalCount,0) As TotalCount
	,ISNULL(RD.PresentCount,0)As PresentCount
	 
from 
	sStudent.vStudentAcademic SA 
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id	
	LEFT JOIN sAssessment.tResultDetailOther RD ON  RD.ExamId = Em.Id AND SA.Academicid =RD.AcademicId AND ED.ClassSubjectId = RD.ClassSubjectId
	INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.Academicid AND o.ClassSubjectId=CS.ID
	 
Where  
	  (DM.Id=@rDivisionId OR @rDivisionId = 0)
	   AND (EM.ClassId = @rClassId OR @rClassId = 0)  
	   AND (EM.Id=@rExamId OR @rExamId = 0)
	   AND ED.ClassSubjectId = @rClassSubjectId
	   AND SA.StatusId=1 AND SA.BatchId=@rBatchId
	   AND ((CS.IsOptional = 1 AND    isnull(o.AcademicId,0) <> 0) OR (CS.IsOptional = 0))
Order By SA.RollNo


END
GO
PRINT N'Altering [sAttendance].[pAttenanceRegisterGet]...';


GO
 
ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0,
	 @rStatus int=0 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

--Select * from sAttendance.tTempAttendance

DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	
	
DECLARE @lOrgId  int
--DECLARE @lSchoolRemark1  nvarchar(500)
--DECLARE @lSchoolRemark2  nvarchar(500)
--DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

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=1 where RGM.Id=1
 
-- select @lSchoolRequiredSignature as sig
 	Declare @Days int 
 	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
BEGIN 
	 CREATE Table #AttendanceRegistertempTable
(
	TID int identity(1,1),
	ClassDivisionTitle Nvarchar(500),
	Code nvarchar(500),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(500),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(500),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(500),
	DivisionName nvarchar(500),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	EmployeeName nvarchar(500),
	DateOfBirth date,
	Religion nvarchar(500),
	MotherName nvarchar(500),
	FamilyCast nvarchar(100)
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId,
	EmployeeName,
	DateOfBirth,
	Religion,
	MotherName,
	FamilyCast
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	@lSchoolRequiredSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 EM.FirstName+' ' + EM.LastName AS EmployeeName,
	 SO.DateOfBirth,
	 RE.Title As Religion,
	 Sf.MotherName,
	 SO.FamilyCast
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN  sStudent.tStudentFamily SF ON Sf.StudentId=Sa.StudentID
            LEFT JOIN sCommon.tReligionMaster RE On RE.Id=SO.ReligionId
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	           AND ((SA.StatusId=@rStatus)OR (@rStatus=0))

				
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=@Days
BEGIN
INSERT INTO #TempDaysTempTable
(
	DayPart ,
   Value
)

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffGet](@rForYear,@rForMonth,@li,@rBatchId,@rClassId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

 

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			ISNULL(ABU.AUCount,0) AS AbsentUpto,
			ISNULL(TC.TCount,0) AS AttendanceCount,
		    ISNULL(AC.ACount,0) As  AbsentCount,
		    ISNULL(PC.PCount,0) As  PresentUpto,	    
		    
		    ClassOrderIndex,
		    DivisionOrderIndex,
		    FooterSignature,
			(ISNULL(TotalPresent,0) + ISNULL(TC.TCount,0)) AS TotalPresent,
			 
			  [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,1 ,@rBatchId ,@rClassId,@rDivisionId , isnull([1],''),@rOrgId )  AS P1,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,2 ,@rBatchId ,@rClassId,@rDivisionId , isnull([2],''),@rOrgId )  AS P2,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,3 ,@rBatchId ,@rClassId,@rDivisionId , isnull([3],''),@rOrgId )  AS P3,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,4 ,@rBatchId ,@rClassId,@rDivisionId , isnull([4],''),@rOrgId )  AS P4,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,5 ,@rBatchId ,@rClassId,@rDivisionId , isnull([5],''),@rOrgId )  AS P5,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,6 ,@rBatchId ,@rClassId,@rDivisionId , isnull([6],''),@rOrgId ) AS P6,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,7 ,@rBatchId ,@rClassId,@rDivisionId , isnull([7],''),@rOrgId ) AS P7,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,8 ,@rBatchId ,@rClassId,@rDivisionId , isnull([8],''),@rOrgId ) AS P8,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,9 ,@rBatchId ,@rClassId,@rDivisionId , isnull([9],''),@rOrgId ) AS P9,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,10 ,@rBatchId ,@rClassId,@rDivisionId , isnull([10],''),@rOrgId ) AS P10,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,11 ,@rBatchId ,@rClassId,@rDivisionId , isnull([11],''),@rOrgId ) AS P11,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,12 ,@rBatchId ,@rClassId,@rDivisionId , isnull([12],''),@rOrgId ) AS P12,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,13 ,@rBatchId ,@rClassId,@rDivisionId , isnull([13],''),@rOrgId ) AS P13,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,14 ,@rBatchId ,@rClassId,@rDivisionId , isnull([14],''),@rOrgId ) AS P14,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,15 ,@rBatchId ,@rClassId,@rDivisionId , isnull([15],''),@rOrgId ) AS P15,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,16 ,@rBatchId ,@rClassId,@rDivisionId , isnull([16],''),@rOrgId ) AS P16,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,17 ,@rBatchId ,@rClassId,@rDivisionId , isnull([17],''),@rOrgId ) AS P17,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,18 ,@rBatchId ,@rClassId,@rDivisionId , isnull([18],''),@rOrgId ) AS P18,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,19 ,@rBatchId ,@rClassId,@rDivisionId , isnull([19],''),@rOrgId ) AS P19,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,20 ,@rBatchId ,@rClassId,@rDivisionId , isnull([20],''),@rOrgId ) AS P20,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,21 ,@rBatchId ,@rClassId,@rDivisionId , isnull([21],''),@rOrgId ) AS P21,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,22 ,@rBatchId ,@rClassId,@rDivisionId , isnull([22],''),@rOrgId ) AS P22,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,23 ,@rBatchId ,@rClassId,@rDivisionId , isnull([23],''),@rOrgId ) AS P23,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,24 ,@rBatchId ,@rClassId,@rDivisionId , isnull([24],''),@rOrgId ) AS P24,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,25 ,@rBatchId ,@rClassId,@rDivisionId , isnull([25],''),@rOrgId ) AS P25,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,26 ,@rBatchId ,@rClassId,@rDivisionId , isnull([26],''),@rOrgId ) AS P26,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,27 ,@rBatchId ,@rClassId,@rDivisionId , isnull([27],''),@rOrgId ) AS P27,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,28 ,@rBatchId ,@rClassId,@rDivisionId , isnull([28],''),@rOrgId ) AS P28,
			CASE WHEN @Days>=29 THEN  [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,29 ,@rBatchId,@rClassId ,@rDivisionId , isnull([29],''),@rOrgId ) end AS P29,
			CASE WHEN @Days>=30 THEN [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,30 ,@rBatchId ,@rClassId,@rDivisionId , isnull([30],''),@rOrgId ) end AS P30,
			CASE WHEN @Days>=31 THEN [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,31 ,@rBatchId ,@rClassId,@rDivisionId , isnull([31],''),@rOrgId )  end AS P31,
			
	 	--	 isnull([1],'') AS P1,
			--isnull([2],'') AS P2,
			--isnull([3],'') AS P3,
			--isnull([4],'') AS P4,
			--isnull([5],'') AS P5,
			--isnull([6],'') AS P6,
			--isnull([7],'') AS P7,
			--isnull([8],'') AS P8,
			--isnull([9],'') AS P9,
			--isnull([10],'') AS P10,
			--isnull([11],'') AS P11,
			--isnull([12],'') AS P12,
			--isnull([13],'') AS P13,
			--isnull([14],'') AS P14,
			--isnull([15],'') AS P15,
			--isnull([16],'') AS P16,
			--isnull([17],'') AS P17,
			--isnull([18],'') AS P18,
			--isnull([19],'') AS P19,
			--isnull([20],'') AS P20,
			--isnull([21],'') AS P21,
			--isnull([22],'') AS P22,
			--isnull([23],'') AS P23,
			--isnull([24],'') AS P24,
			--isnull([25],'') AS P25,
			--isnull([26],'') AS P26,
			--isnull([27],'') AS P27,
			--isnull([28],'') AS P28,
			--isnull([29],'') AS P29,
			--isnull([30],'') AS P30,
			--isnull([31],'') AS P31, 
			 EmployeeName ,
 
             sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth,
              DateOfBirth,Religion,MotherName,FamilyCast
--,
--AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LC' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'EL' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 3 THEN 'N' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 4 THEN 'G' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate
		,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,EmployeeName,
		DateOfBirth,Religion,MotherName,FamilyCast
      -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
            
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
		LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS AUCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 0	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) ABU ON ABU.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS TotalPresent  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
	        AND
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) AA ON AA.AcademicId = PivotTable.AcademicId
 
    ORDER BY RollNo;
 

select * from #TempDaysTempTable
 				
drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	
	
END
GO
PRINT N'Altering [sAttendance].[pAttenanceRegisterGetNew]...';


GO
ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGetNew]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0
	WITH EXECUTE AS CALLER
AS	
SET NOCOUNT ON
	DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	Declare @Days int 
	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	
BEGIN 
CREATE Table #AttendanceRegistertempTable
(
	 
	ClassDivisionTitle Nvarchar(500),
	Code nvarchar(500),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(500),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(500),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(500),
	DivisionName nvarchar(500),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int,
	AdmissionDate date 
	 
 
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId ,
	AdmissionDate 
	 
  
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	 OM.FooterSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 A.AdmissionDate 
	 
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
			 
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))

				
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=@Days 
BEGIN

INSERT INTO #TempDaysTempTable
(
	DayPart,
    Value
)
SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffGet](@rForYear,@rForMonth,@li,@rBatchId,@rClassId,@rDivisionId,'',@rOrgId) 
 
 
SET @li = @li + 1

END
 
 
--DECLARE @TotalRecords int,@lpaging varchar(max)='',@PageSize int =100
--SELECT @TotalRecords = count(*)	 from #AttendanceRegistertempTable
--SELECT @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@PageIndex,@TotalRecords,@PageSize)

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			 
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			 ISNULL(TC.TCount,0) AS AttendanceCount,
				
		      ISNULL(AC.ACount,0) As  AbsentCount,
		       ISNULL(PC.PCount,0) As  PresentUpto,
		       ISNULL(AAC.AACount,0) As  AbsentUpto,
		       
		       ClassOrderIndex,
		       DivisionOrderIndex,
		       FooterSignature,				 
			0 AS TotalPresent ,
	 			   sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),LeftDate,[1]) AS P1,
	 	 
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02'),LeftDate,[2]) AS P2,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03'),LeftDate,[3]) AS P3,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04'),LeftDate,[4]) AS P4,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05'),LeftDate,[5]) AS P5,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06'),LeftDate,[6]) AS P6,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07'),LeftDate,[7]) AS P7,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08'),LeftDate,[8]) AS P8,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09'),LeftDate,[9]) AS P9,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10'),LeftDate,[10]) AS P10,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11'),LeftDate,[11]) AS P11,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12'),LeftDate,[12]) AS P12,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13'),LeftDate,[13]) AS P13,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14'),LeftDate,[14]) AS P14,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15'),LeftDate,[15]) AS P15,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16'),LeftDate,[16]) AS P16,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17'),LeftDate,[17]) AS P17,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18'),LeftDate,[18]) AS P18,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19'),LeftDate,[19]) AS P19,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20'),LeftDate,[20]) AS P20,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21'),LeftDate,[21]) AS P21,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22'),LeftDate,[22]) AS P22,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23'),LeftDate,[23]) AS P23,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24'),LeftDate,[24]) AS P24,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25'),LeftDate,[25]) AS P25,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26'),LeftDate,[26]) AS P26,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27'),LeftDate,[27]) AS P27,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28'),LeftDate,[28]) AS P28,
			CASE WHEN @Days>=29 THEN  sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29'),LeftDate,[29])end AS P29,
			CASE WHEN @Days>=30 THEN sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30'),LeftDate,[30]) end AS P30,
		    CASE WHEN @Days>=31 THEN sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31'),LeftDate,[31]) end AS P31,
		 
 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth
,0 Ispresent,
0 AS AttendanceTagId 
  
--,AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE 
			 WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LA' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'ED' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 3 THEN 'N' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 4 THEN 'G' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,
		AdmissionDate 
 
		 -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
		
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount
		--,IsPresent,AttendanceTagId 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
			--,IsPresent,AttendanceTagId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
             --AND ( StatusId = 1)
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(
		SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			 AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
    LEFT JOIN
	(
		SELECT A.Id AS AcademicId, COUNT(1) AS AACount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
 
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			 AND SR.IsPresent = 0    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id 
    ) AAC ON AAC.AcademicId = PivotTable.AcademicId
    
    ORDER BY RollNo;
    
select * from #TempDaysTempTable
--select '' as paging

drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
END
GO
PRINT N'Altering [sAttendance].[pAttenanceRegisterGetNew1]...';


GO
 -- exec [sAttendance].[pAttenanceRegisterGetNew] '','',1,1001,7,2016,100100001,100100001,100100114,0,0,1
ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGetNew1]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
BEGIN 
CREATE Table #AttendanceRegistertempTable
(
	 
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(50),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(50),
	DivisionName nvarchar(50),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int 
 
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId 
  
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	 OM.FooterSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 NULL AS AttendanceTagId
	 
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            
			
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))

				
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=31
BEGIN
INSERT INTO #TempDaysTempTable
(
	DayPart ,
   Value
)

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffHolidayGet](@rForYear,@rForMonth,@li,@rBatchId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

--DECLARE @TotalRecords int,@lpaging varchar(max)='',@PageSize int =100
--SELECT @TotalRecords = count(*)	 from #AttendanceRegistertempTable
--SELECT @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@PageIndex,@TotalRecords,@PageSize)

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			 
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			 ISNULL(TC.TCount,0) AS AttendanceCount,
				
		      ISNULL(AC.ACount,0) As  AbsentCount,
		       ISNULL(PC.PCount,0) As  PresentUpto,
		       ClassOrderIndex,
		       DivisionOrderIndex,
		       FooterSignature,				 
			0 AS TotalPresent ,
	 		isnull([1],'') AS P1,
			isnull([2],'') AS P2,
			isnull([3],'') AS P3,
			isnull([4],'') AS P4,
			isnull([5],'') AS P5,
			isnull([6],'') AS P6,
			isnull([7],'') AS P7,
			isnull([8],'') AS P8,
			isnull([9],'') AS P9,
			isnull([10],'') AS P10,
			isnull([11],'') AS P11,
			isnull([12],'') AS P12,
			isnull([13],'') AS P13,
			isnull([14],'') AS P14,
			isnull([15],'') AS P15,
			isnull([16],'') AS P16,
			isnull([17],'') AS P17,
			isnull([18],'') AS P18,
			isnull([19],'') AS P19,
			isnull([20],'') AS P20,
			isnull([21],'') AS P21,
			isnull([22],'') AS P22,
			isnull([23],'') AS P23,
			isnull([24],'') AS P24,
			isnull([25],'') AS P25,
			isnull([26],'') AS P26,
			isnull([27],'') AS P27,
			isnull([28],'') AS P28,
			isnull([29],'') AS P29,
			isnull([30],'') AS P30,
			isnull([31],'') AS P31, 
 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth,Ispresent,
ISNULl(AttendanceTagId,0) AS AttendanceTagId
  
--,AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE 
			 WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LA' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'ED' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 3 THEN 'N' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 4 THEN 'G' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature 
		 -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
		
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount,IsPresent,AttendanceTagId 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId,IsPresent,AttendanceTagId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
             --AND ( StatusId = 1)
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(
		SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
    ORDER BY RollNo;
    
select * from #TempDaysTempTable
--select '' as paging

drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
END
GO
PRINT N'Altering [sAttendance].[pMonthlyRegisterStudentGet]...';


GO
ALTER PROCEDURE [sAttendance].[pMonthlyRegisterStudentGet]
	 	 
	 	 @rBatchId int,
	 	 @rAcademicId bigint,
	 	 --@rForMonth tinyint,
	 	 --@rForYear smallint,
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

declare @lAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid1 nvarchar(max)=''

IF NOT EXISTS(select 1 From sAttendance.tMonthlyRegister where AcademicId=@rAcademicId and ForMonth=Month(GETDATE()) and ForYear=Year(GETDATE()))
BEGIN

--CurreDECLARE @PresentCount DECIMAL(10,2)
		DECLARE @PresentCount DECIMAL(10,2)
		DECLARE @AbsentCount DECIMAL(10,2)
		DECLARE @AveragePresence DECIMAL(10,2)
		DECLARE @CurrentMonthDays DECIMAL(10,2)
		DECLARE @AttendanceCount INT 
		SET @CurrentMonthDays = (SELECT DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,getdate()),0))))
		DECLARE @YearNumber INT
		DECLARE @AbsentDays nvarchar(max)

		SET @YearNumber =Year(GETDATE())



		SET @PresentCount = (select count(AttendanceDate) AS PresentCount from sAttendance.tStudentRegister 
		where IsPresent=1 and AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()))		

		SET @AbsentCount = (select count(AttendanceDate) AS AbsentCount from sAttendance.tStudentRegister 
		where IsPresent=0 and AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()))		


		SET @AttendanceCount = (select count(AttendanceDate) AS PresentCount from sAttendance.tStudentRegister 
		where AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()))		

		SET @AveragePresence= (@PresentCount/@AttendanceCount)*100

		SET @AbsentDays=(SELECT SUBSTRING(
		(SELECT ',' + CONVERT(varchar(10), Day(AttendanceDate))
		FROM  sAttendance.tStudentRegister s
		where AcademicId=@rAcademicId and IsPresent=0 and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate())		

		ORDER BY AcademicId
		FOR XML PATH('')),2,200000) AS CSV
)
END



	SELECT *FROM (Select 
		SN.AcademicId,
		MY.MonthTitle AS ForMonthInWord,
		MY.MonthNumber AS ForMonth, 
		MY.YearNumber AS ForYear,
		ISNULL(MR.TotalCount,0) AS TotalCount,
		ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
		ISNULL(MR.PresentCount,0) AS PresentCount,
		ISNULL(MR.AbsentCount,0) AS AbsentCount,
		ISNULL(MR.AveragePresence,0) AS AveragePresence,
		ISNULL(MR.AbsentDays,'') AS AbsentDays
		
	From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	LEFT JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND (MR.AttendanceTypeId=@rAttendanceTypeId) 
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND MR.ForMonth=MY.MonthNumber 
		AND MR.ForYear=MY.YearNumber
	WHERE
		(SN.AcademicId=@rAcademicId) AND MY.MonthNumber<>MONTH(Getdate())
		
		
   UNION ALL
   
   SELECT 
           @rAcademicId AS AcademicId,
           Isnull(LEFT(DATENAME(MONTH,Getdate()),10),'') AS ForMonthInWord,
           MONTH(Getdate()) AS ForMonth,
           YEAR(Getdate()) AS ForYear,
           ISNULL(CAST(@AttendanceCount AS int),0) AS TotalCount,
           ISNULL(CAST(@AttendanceCount AS int),0) AS AttendanceCount,                    
           ISNULL(CAST(@PresentCount AS int),0) AS PresentCount,
           ISNULL(CAST(@AbsentCount AS int),0) AS AbsentCount,
           ISNULL(CAST(@AveragePresence AS int),0) AS AveragePresence,                     
           ISNULL(@AbsentDays,0) AS AbsentDays) 
           AS TempStudentAttendance ORDER BY ForYear,ForMonth
        
END
GO
PRINT N'Altering [sAttendance].[pStudentAttendaceDashboardGet]...';


GO
ALTER PROCEDURE [sAttendance].[pStudentAttendaceDashboardGet]
	 
	 @rTypeId smallint,
	 @rUptoDate date='',
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDivisionId int=0,
	 @rClassId int =0,
	 @rGenderType int=0,
	 @rCommonOrgGroupBatchId int=0,
	 @rSyncDate int =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

IF @rClassId=0
  BEGIN
--Orggroup wise Attendance
   IF @rTypeId=1 
   BEGIN
--Update Attendance
	IF(@rSyncDate =1) 
		BEGIN 
			DELETE  sAttendance.tTempStudentAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			INSERT INTO sAttendance.tTempStudentAttendance
--Total Student All Orggroup
				   SELECT 
					OGM.Id AS OrgGroupId,
					OGM.Title As OrgGroupTitle,
					0 As OrgId,'' As OrgTitle,       
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
						 ) AS Total,       
--PresentStudent All Orggroup
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id 
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
						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
					  WHERE 
						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						) AS PresentStudent,
--AbsentStudent All Orggroup
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						) AS AbsentStudent,
--LessThen70 % All Orggroup
				   (select Count(StudentID) from(
						select  
						 OGMEL.Id AS OrgGroupId,
						 OGMEL.Title AS OrgGroupTitle,
						 OMEL.Id AS OrgId,
						 (OMEL.Title) AS OrgTitle ,
						 DM.Code As DivisionCode,
						 (SMD.Id)StudentID,
						 (SMD.FirstName + ' ' + SMD.LastName) AS StudentName,
						 (SC.ParentContactNo) AS ContactNo,
						 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
						  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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
					where 
						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY 
						 OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
					)  As LessThen70,
--100% Attendance All Orggroup
				  (select Count(StudentID) from  (
					select  
						  OGMEL.Id AS OrgGroupId,
						  OGMEL.Title AS OrgGroupTitle,
						  OMEL.Id AS OrgId,
						  (OMEL.Title) As OrgTitle ,
						  DM.Code AS DivisionCode,
						  (SMD.Id)StudentID,
						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
						  (SC.ParentContactNo) AS ContactNo,
						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						   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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
					) AS HundredPer,
--Absent>3 All Orggroup
				   (SELECT COUNT(AcademicId) FROM(
					  SELECT 
						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
						AcademicId,AttendanceDate
					  FROM sAttendance.tStudentRegister d 		
						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						 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	
		
					  WHERE
						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
						 IsPresent IN(0) 
						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
						 and IsPresent=0
					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
					  ) AS AbsentCount,
--Leave Request All Orggroup
					(SELECT 
						COUNT(AcademicId) AS LeaveRequest
					 FROM sAttendance.tStudentLeaveRequest STSL
						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
					) AS LeaveRequest,
--AttnNotTakenClass All Orggroup
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
					 WHERE 
						 OGM.Id = OGMR.Id  and SM1.statusid =1 AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
					(select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126))) 
					As AttnNotTakenClass,

				@rUptoDate,@rCommonOrgGroupBatchId,GetDate()
				FROM sSetup.tOrgGroupMaster OGM 
				WHERE OGM.Id<>1 
				AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
			SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) ORDER BY OrgGroupId
		END
	ELSE
		BEGIN
			IF  Exists(select 1 from sAttendance.tTempStudentAttendance   where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND StudentAttendanceDate=  CONVERT(date,@rUptoDate,102) )
			BEGIN
			SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) ORDER BY OrgGroupId
			return
			END
ELSE
			
--Temp Atble Attendance
			BEGIN
			DELETE  sAttendance.tTempStudentAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId  AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			INSERT INTO sAttendance.tTempStudentAttendance
--Total Student All Orggroup Temp		
				   SELECT 
					OGM.Id AS OrgGroupId,
					OGM.Title As OrgGroupTitle,
					0 As OrgId,'' As OrgTitle,       
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
						 ) AS Total,       
--PresentStudent All Orggroup Temp
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
						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
					  WHERE 
						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						) AS PresentStudent,
--AbsentStudent All Orggroup Temp
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						) AS AbsentStudent,
--LessThen70 All Orggroup Temp
				   (select Count(StudentID) from(
						select  
						 OGMEL.Id AS OrgGroupId,
						 OGMEL.Title AS OrgGroupTitle,
						 OMEL.Id AS OrgId,
						 (OMEL.Title) AS OrgTitle ,
						 DM.Code As DivisionCode,
						 (SMD.Id)StudentID,
						 (SMD.FirstName + ' ' + SMD.LastName) AS StudentName,
						 (SC.ParentContactNo) AS ContactNo,
						 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						  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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
					where 
						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY 
						 OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
					)As LessThen70,
--100 % HundredPer All Orggroup Temp
				  (select Count(StudentID) from  (
					select  
						  OGMEL.Id AS OrgGroupId,
						  OGMEL.Title AS OrgGroupTitle,
						  OMEL.Id AS OrgId,
						  (OMEL.Title) As OrgTitle ,
						  DM.Code AS DivisionCode,
						  (SMD.Id)StudentID,
						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
						  (SC.ParentContactNo) AS ContactNo,
						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						   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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1					
						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
					) AS HundredPer,
--AbsentCount All Orggroup Temp
				   (SELECT COUNT(AcademicId) FROM(
					  SELECT 
						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
						AcademicId,AttendanceDate
					  FROM sAttendance.tStudentRegister d 		
						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						 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	
					  WHERE
						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
						 IsPresent IN(0) 
						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
						 and IsPresent=0
					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
					  ) AS AbsentCount,
--LeaveRequest All Orggroup Temp
					(SELECT COUNT(AcademicId) AS LeaveRequest
					FROM sAttendance.tStudentLeaveRequest STSL
						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
					) AS LeaveRequest,
--AttnNotTakenClass All Orggroup Temp
					(Select count(SM1.ID)
					FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  
						 and SM1.statusid =1 
						 AND COGBM.Id=@rCommonOrgGroupBatchId 
						 AND A.Id  not in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126))) 
					As AttnNotTakenClass,
					
					
					
					
					@rUptoDate,@rCommonOrgGroupBatchId,GetDate()
				FROM sSetup.tOrgGroupMaster OGM 
				WHERE OGM.Id<>1 AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			END
		END
	END

--Organization wise Attendance

ELSE IF @rTypeId=2
    BEGIN
    SELECT 
       OGMT.Id As OrgGroupId,
       OM.Id AS OrgId, 
       OM.Title AS OrgTitle,
       OGMT.Title As OrgGroupTitle,
       
--Total Organization wise
		   (Select count(SM1.ID)
			FROM sStudent.tStudentMaster SM1
				 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
				 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				 INNER JOIN sSetup.tOrganizationMaster OMR ON OM.Id = BM.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId		
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OMR.Id AND COGBM.Id=@rCommonOrgGroupBatchId
				 ) as Total,

--PresentStudent Organization wise
		 (SELECT count(*) 
			FROM sAttendance.tStudentRegister SME 
			   INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			   INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
			   INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
			   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
			WHERE OM.Id = OME.Id and SME.IsPresent=1 AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
			) AS PresentStudent,

--AbsentStudent Organization wise
		  (SELECT count(*) 
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OME.Id AND SME.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			) AS AbsentStudent,
        
--LessThen70 Organization wise
			(SELECT COUNT(StudentID) 
			   FROM (
				 SELECT   
				   OGMEL.Id as OrgGroupId,
				   OGMEL.Title As OrgGroupTitle,
				   OMEL.Id As OrgId,
				   (OMEL.Title) As OrgTitle ,
				   DM.Code As DivisionCode,
				   (SMD.Id)StudentID,
				   (SMD.FirstName+' '+SMD.LastName) AS StudentName,
					(SC.ParentContactNo) AS ContactNo,
					((COUNT(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
				 FROM sAttendance.tStudentRegister SMEL
					INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
					INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
					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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
					INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1					
					LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			     
				WHERE OM.Id = OMEL.Id AND SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
				GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
			   HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
			   ) AS Tmp)  
			   As LessThen70,
        
--HundredPer Organization wise
			 (SELECT COUNT(StudentID) from  (
				 SELECT  
				 OGMEL.Id as OrgGroupId,
				 OGMEL.Title As OrgGroupTitle,
				 OMEL.Id As OrgId,
				 (OMEL.Title) As OrgTitle ,
				 DM.Code As DivisionCode,
				 (SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				 (SC.ParentContactNo) AS ContactNo,
				 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
			 FROM sAttendance.tStudentRegister SMEL
				 INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				 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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
				 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1						
				 LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			     
			 WHERE OM.Id = OMEL.Id AND
				   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
			 GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
				
				
			 HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
			 ) AS Tmp)  
			 As HundredPer,
        
--AbsentCount Organization wise
			(SELECT COUNT(AcademicId) FROM(
				SELECT 
				  ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				  AcademicId,
				  AttendanceDate
				FROM sAttendance.tStudentRegister d 
				 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
				 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				 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				
				WHERE OM.Id = OMEL.Id AND
				IsPresent IN(0) 
				AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
				AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
				GROUP BY AcademicId,AttendanceDate
				) as sfsf
				WHERE rowno=3) 
				as AbsentCount,
        
--LeaveRequest Organization wise
			 (SELECT 
				COUNT(AcademicId) AS LeaveRequest
				FROM sAttendance.tStudentLeaveRequest STSL
				  INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
				  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				  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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
				  INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID

				WHERE OM.Id = OMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
				CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate) 
				As LeaveRequest,
        
--AttnNotTakenClass Organization wise
			(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
					 WHERE 
						 OM.Id = OMEL.Id  AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
					(select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126))) 
					As AttnNotTakenClass,
			getdate() AS UpdateDate		  
              
     FROM sSetup.tOrgGroupMaster OGMT 
        INNER join sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId 
         
     WHERE OGMT.Id=@rOrgGroupId
   
    END

ELSE IF @rTypeId=11
	BEGIN
     	SELECT OGMR.Id AS OrgGroupId,
			OGMR.Title AS OrgGroupTitle,
			OM.Id As OrgId,(OM.Title) AS OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			COUNT(A.StudentID) AS TotalStudent,
			COUNT(CASE WHEN SOD.GenderID=1 then 1 end) AS Male,
			COUNT(CASE WHEN SOD.GenderID=2 then 1 end) AS Female
		FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
		WHERE OGMR.Id=@rOrgGroupId
			AND COGBM.Id=@rCommonOrgGroupBatchId 
		GROUP BY OGMR.Id ,OGMR.Title,OM.Id ,OM.Title,CM.ID,CM.Code
    END

ELSE IF @rTypeId=21
    BEGIN
		SELECT OGMR.Id as OrgGroupId,
			OGMR.Title As OrgGroupTitle,
			OM.Id As OrgId,(OM.Title) As OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			COUNT(A.StudentID) AS TotalStudent,
			COUNT(case when SOD.GenderID=1 then 1 end) AS Male,
			COUNT(case when SOD.GenderID=2 then 1 end) AS Female
		FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
		WHERE OM.Id=@rOrgId
			AND COGBM.Id=@rCommonOrgGroupBatchId 
		GROUP BY OGMR.Id ,OGMR.Title,OM.Id ,OM.Title,CM.ID,CM.Code
     END
     
ELSE IF @rTypeId=12
    BEGIN
		SELECT OGME.Id as OrgGroupId,
			OGME.Title As OrgGroupTitle,
			OME.Id As OrgId,(OME.Title) As OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			COUNT(AE.StudentID) AS TotalStudent,
			COUNT(case when SOD.GenderID=1 then 1 end) AS Male,
			COUNT(case when SOD.GenderID=2 then 1 end) AS Female				 
		FROM sAttendance.tStudentRegister SME 
			INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
			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 sSetup.tClassMaster CM ON CM.ID=AE.ClassId
			INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		WHERE OGME.Id=@rOrgGroupId and SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId   
			and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
		GROUP BY OGME.Id,OGME.Title,OME.Id,OME.Title,CM.ID,CM.Code
         
    END
   
ELSE IF @rTypeId=22
	BEGIN
          SELECT 
				OGME.Id as OrgGroupId,OGME.Title As OrgGroupTitle,
				OME.Id As OrgId,(OME.Title) As OrgTitle,
				 CM.ID AS ClassId,CM.Code AS ClassCode,
				COUNT(AE.StudentID) AS TotalStudent,
				COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female
		  FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				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 sSetup.tClassMaster CM ON CM.ID=AE.ClassId
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		  WHERE OME.Id=@rOrgId and SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId  
				AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
		  GROUP BY OGME.Id,OGME.Title,OME.Id,OME.Title,CM.ID,CM.Code          
	END
   
ELSE IF @rTypeId=13
      BEGIN
      
          (SELECT 
				OGMEA.Id as OrgGroupId,
				OGMEA.Title As OrgGroupTitle,
				OME.Id As OrgId,
				(OME.Title) As OrgTitle,
				CM.ID As ClassId,
				CM.Code As ClassCode,
				COUNT(AE.StudentID) AS TotalStudent,
			    COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.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 sSetup.tClassMaster CM ON CM.ID=AE.ClassID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
				Left JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			WHERE OGMEA.Id=@rOrgGroupId and SME.IsPresent=0  AND COGBM.Id=@rCommonOrgGroupBatchId  
				 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			GROUP BY OGMEA.Id,OGMEA.Title,OME.Id,OME.Title,CM.ID,CM.Code
		 )
       END
       
ELSE IF @rTypeId=23
       BEGIN
          (SELECT 
				OGMEA.Id as OrgGroupId,
				OGMEA.Title As OrgGroupTitle,
				OME.Id As OrgId,
				(OME.Title) As OrgTitle,
				CM.ID AS ClassId,CM.Code AS ClassCode,
				COUNT(AE.StudentID) AS TotalStudent,
				COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female
		   FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.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 sSetup.tClassMaster CM ON CM.ID=AE.ClassId
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		   WHERE OME.Id=@rOrgId 
				AND SME.IsPresent=0 AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId  
		   GROUP BY OGMEA.Id,OGMEA.Title,OME.Id,OME.Title,CM.ID,CM.Code
		  )
    
       END       
       
ELSE IF @rTypeId=14  
      BEGIN
			
       (SELECT *FROM  (
           SELECT  
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DM.Code As DivisionCode,
              (SMD.Code)StudentID,
              AEL.Id AS SourceId,
              (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			  (SC.ParentContactNo) AS ContactNo
		   FROM sAttendance.tStudentRegister SMEL
				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
				LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		   WHERE OGMEL.Id=@rOrgGroupId 
				AND SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) 
		        AND COGBM.Id=@rCommonOrgGroupBatchId  
		   GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	   HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	   ) AS Tmp) 

      END
   
ELSE IF @rTypeId=24     
      BEGIN

      (SELECT *FROM  (
           SELECT 
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DM.Code As DivisionCode,
              (SMD.Code)StudentID,
              AEL.Id AS SourceId,
              (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			  (SC.ParentContactNo) AS ContactNo
	   FROM sAttendance.tStudentRegister SMEL
			   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
			   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
			   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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
			   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
			   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		WHERE OMEL.Id=@rOrgId AND
		      SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId  
		GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)

	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	 ) AS Tmp) 
		
          
      END   
   
ELSE IF @rTypeId=15
	   BEGIN	
		(SELECT *FROM(
              SELECT  
                  OGMEL.Id as OrgGroupId,
                  OGMEL.Title As OrgGroupTitle,
                  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
                  DM.Code As DivisionCode,
                  (SMD.Code)StudentID,
                  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				  (SC.ParentContactNo) AS ContactNo,
				  AEL.Id AS SourceId
		      FROM sAttendance.tStudentRegister SMEL
				   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
				   Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			   WHERE OGMEL.Id=@rOrgGroupId AND
				   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
			   GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	    ) AS Tmp) 
	   END
	   
ELSE IF @rTypeId=25
	BEGIN	
	 (SELECT *FROM(
           SELECT  
                OGMEL.Id as OrgGroupId,
                OGMEL.Title As OrgGroupTitle,
                OMEL.Id As OrgId,
                (OMEL.Title) As OrgTitle,
                DM.Code As DivisionCode,
                (SMD.Code)StudentID,
                (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
				AEL.Id AS SourceId
			FROM sAttendance.tStudentRegister SMEL
				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	
				Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		    WHERE OMEL.Id=@rOrgId AND
				  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
			GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	  ) AS Tmp) 

	   END
	   	   
ELSE IF @rTypeId=16   
   BEGIN
        
        (SELECT * FROM 
             (SELECT 
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
				DM.Code As DivisionCode,
				(SMD.Code)StudentID,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
						 AEL.Id AS SourceId
			  FROM sAttendance.tStudentLeaveRequest STSL
				INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	
			  WHERE OGMEL.Id=@rOrgGroupId 
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				AND CONVERT(char(10), @rUptoDate,126) between LeaveFromDate 
				AND LeaveToDate
		) as a) 
   END
      
ELSE IF @rTypeId=26   
   BEGIN
      
      (SELECT * FROM 
          (SELECT 
			  OGMEL.Id as OrgGroupId,
			  OGMEL.Title As OrgGroupTitle,
			  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
			  DM.Code As DivisionCode,(SMD.Code)StudentID,
			  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			  (SC.ParentContactNo) AS ContactNo,
			  AEL.Id AS SourceId
		   FROM sAttendance.tStudentLeaveRequest STSL 
			   INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
			   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
			   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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
			   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
			   INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID		 
		   WHERE OMEL.Id=@rOrgId 
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				AND CONVERT(char(10), @rUptoDate,126) between LeaveFromDate 
				AND LeaveToDate
		) as a) 
   END
   
ELSE IF @rTypeId=17   
   BEGIN
       
       (SELECT OrgGroupId,
                OrgGroupTitle,
                OrgId,
                OrgTitle,
                Code As DivisionCode,
                StudentID,
                SourceId,
                StudentName,
                ContactNo FROM( SELECT ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				AcademicId AS SourceId,
				AttendanceDate, 
				DM.Code,
				(SMD.Code)StudentID,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,(SC.ParentContactNo) As ContactNo
			 FROM sAttendance.tStudentRegister d 							
		 		INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		     WHERE
				OGMEL.Id=@rOrgGroupId AND
				IsPresent IN(0) 
				AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate   
				AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
			 Group By AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName),SC.ParentContactNo 
			 ) as T
		WHERE rowno=3) 
   END
      
ELSE IF @rTypeId=27   
   BEGIN
       
        (SELECT OrgGroupId,
                OrgGroupTitle,
                OrgId,OrgTitle, 
                Code As DivisionCode,SourceId,
                StudentID,StudentName,
                ContactNo  FROM(
			SELECT 
				ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
                AcademicId AS SourceId,AttendanceDate, 
                DM.Code,
                (SMD.Code)StudentID,
                (SMD.FirstName+' '+SMD.LastName) AS StudentName,
                (SC.ParentContactNo) As ContactNo		
			FROM sAttendance.tStudentRegister d 		
		 		INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID		
			WHERE
				OMEL.Id=@rOrgId AND
				IsPresent IN(0) 
				AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			    AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
			Group By AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName),SC.ParentContactNo
			) as sfsf
	   WHERE rowno=3) 
        
   END
   
ELSE IF @rTypeId=18
   BEGIN
			SELECT 
				OrgGroupId,
				OrgGroupTitle,
				OrgId,
				OrgTitle,
				ClassCode,
				StudentCount,
				SourceId,
				ISNULL(TeacherName,'') AS TeacherName,
				ISNULL(ContactNo,'')AS ContactNo  FROM(SELECT 
				O.Id as OrgGroupId,
				O.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				A.ClassId,
				DM.Code AS ClassCode,
				(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
				A.Id As SourceId,
				(EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.MobileNumber) AS ContactNo,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
			FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			WHERE  O.id = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  not in  ( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rUptoDate,126))
				) Temp 
		WHERE rowno=1  
		ORDER BY OrgId,ClassCode desc
   END
     
ELSE IF @rTypeId=28
   
   BEGIN

	SELECT 
				OrgGroupId,
				OrgGroupTitle,
				OrgId,
				OrgTitle,
				ClassCode,
				StudentCount,
				SourceId,
				ISNULL(TeacherName,'') AS TeacherName,
				ISNULL(ContactNo,'')AS ContactNo  FROM(SELECT 
				O.Id as OrgGroupId,
				O.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				A.ClassId,
				DM.Code AS ClassCode,
				(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
				A.Id As SourceId,
				(EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.MobileNumber) AS ContactNo,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
				FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				WHERE  OMEL.id = @rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  not in  ( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rUptoDate,126))
				) Temp 
				WHERE 
				rowno=1  
				ORDER BY OrgId,ClassCode desc
	   
   END

ELSE IF @rTypeId=1110
   BEGIN
	  SELECT 
	      (DM.Id) AS DivisionId,
	       SMD.Code As StudentId,
	       (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		   (SC.ParentContactNo) AS ContactNo
							
	  FROM sSetup.tDivisionMaster DM
			INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
			INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
			INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
	   WHERE DM.ID=@rDivisionId 
			 AND DM.OrgId=@rOrgId
	   ORDER BY A.StudentID														          
   END

ELSE IF @rTypeId=1111
	BEGIN
      SELECT 
         (DM.Id) AS DivisionId,
         SMD.Code As StudentId,
         (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		 (SC.ParentContactNo) AS ContactNo
								
	  FROM sSetup.tDivisionMaster DM
		 INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		 INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
	   WHERE DM.ID=@rDivisionId 
			AND SOD.GenderID=1 
	   ORDER BY A.StudentID            
	END
	
ELSE IF @rTypeId=1112
	BEGIN	  
	  SELECT 
	    (DM.Id) AS DivisionId,
	    SMD.Code As StudentId,
	    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		(SC.ParentContactNo) AS ContactNo								
	  FROM sSetup.tDivisionMaster DM
		INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID
		INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	
	  WHERE DM.ID=@rDivisionId 
		AND SOD.GenderID=2 
	  ORDER BY A.StudentID
	END 
	
  END
  ELSE
    BEGIN

     if @rTypeId=11 OR @rTypeId=21     
        BEGIN
			SELECT 
				(DM.Id) AS DivisionId,
				DM.Code AS ClassDivision,
				SM.Code As StudentId,
				(SM.FirstName+' '+SM.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo
			FROM sStudent.tStudentMaster SM 
				INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
				Left JOIN sStudent.tStudentCommunication SC on SM.Id=SC.StudentID
			WHERE 
				((@rOrgGroupId <>0 AND OGMR.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OM.Id=@rOrgId))
				AND DM.ClassId=@rClassId AND COGBM.Id=@rCommonOrgGroupBatchId
				AND ((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0))
        END
        
     ELSE IF @rTypeId=12 OR @rTypeId=22
      
        BEGIN
         
            SELECT 				
			   (DM.Id) AS DivisionId,
			   DM.Code AS ClassDivision,
			    SMD.Code As StudentId,
			    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			    (SC.ParentContactNo) AS ContactNo
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				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 sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
				INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
				Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			WHERE ((@rOrgGroupId <>0 AND OGME.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OME.Id=@rOrgId))
					AND SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
					AND SME.AttendanceDate=CONVERT(char(10), @rUpToDate,126)
					AND DM.ClassId=@rClassId AND COGBM.Id=@rCommonOrgGroupBatchId  
				    AND((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0))
       END  
    
     ELSE IF @rTypeId=13 OR @rTypeId=23
        BEGIN
         (select 
			(DM.Id) AS DivisionId,
			   DM.Code AS ClassDivision,
			    SMD.Code As StudentId,
			    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			    (SC.ParentContactNo) AS ContactNo
		  FROM sAttendance.tStudentRegister SME 
			 INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.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 sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
			 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
			 INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			 Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					
		   WHERE ((@rOrgGroupId <>0 AND OGMEA.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OME.Id=@rOrgId))
					AND SME.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId AND COGBM.Id=@rCommonOrgGroupBatchId  
					AND SME.AttendanceDate=CONVERT(char(10), @rUpToDate,126)--@rUptoDate
					AND DM.ClassId=@rClassId AND ((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0)))
        END
    END
END
GO
PRINT N'Altering [sCertificate].[pIncrementBulkGet]...';


GO
ALTER PROCEDURE [sCertificate].[pIncrementBulkGet]  
   @rId bigint = 0, 
  @rDesignationId int = 0,  
  @rDepartmentId int= 0,  
  @rOrgId int,  
  @rBatchId int,
  @rCertificateDate Date=''
    
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON   
    BEGIN   
  IF @rCertificateDate IS Null SET @rCertificateDate = ''
   --If @rFromDate IS Null Set @rFromDate = ''
 SELECT   
      
   isnull(CI.Id, 0)As Id,  
   EEM.EmployeeId,    
   EEM.FirstName+' '+EEM.LastName as Name,    
       
   isnull(CI.CertificateDate,'') AS CertificateDate ,    
   isnull(CI.Remark, '') As Remark,  
   EEM.Qualification As Qualification,   
   EEM.Code ,   
  CI.BatchId ,  
 isnull(CI.PayScale, 0)As PayScale, 
 isnull(CI.ExistingBasicPay, 0)As ExistingBasicPay, 
 isnull(CI.RevisedBasicPay,0)As RevisedBasicPay,   
 isnull(CI.RevisedBasicPayDate,'')As RevisedBasicPayDate,
 isnull(CI.GradePayInRevisedPayStructure,0)As GradePayInRevisedPayStructure,
 Isnull(CI.BasicPayInRevisedPayStructureBasicPayAndGradePay,0)As BasicPayInRevisedPayStructureBasicPayAndGradePay,  
 Isnull(CI.GrossSalaryAsPerExistingPayScale,0)As GrossSalaryAsPerExistingPayScale, 
 Isnull(CI.RevisedGrossSalaryAsOn,0)As RevisedGrossSalaryAsOn,   
 Isnull(CI.IncrementDate, '')As  IncrementDate,
 EEM.DepartmentId,
 EEM.DepartmentName as Department,  
 EEM.DesignationId ,
 EEM.Designation
     
  FROM   
  sHrm.vExtEmployeeMaster EEM 
  LEFT JOIN sHrm.tCertificateIncrement CI ON EEM.EmployeeId=CI.EmployeeId --AND EEM.OrgId=@rOrgId     
  AND ((CI.Id = @rId) OR (@rId = 0))    
  AND ((CI.CertificateDate = @rCertificateDate)OR(@rCertificateDate = ''))
  LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = CI.BatchId   AND ((BM.Id = @rBatchId) OR (@rBatchId = 0))       
  WHERE   
  ((EEM.DepartmentId = @rDepartmentId) OR ( @rDepartmentId=0))
  AND ((EEM.DesignationId = @rDesignationId) OR (@rDesignationId=0))	
 ORDER BY CI.Number  DESC 
END
GO
PRINT N'Altering [sCertificate].[pRptBonafiedCertificateGet]...';


GO
ALTER PROCEDURE [sCertificate].[pRptBonafiedCertificateGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rNumber nvarchar(20)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromDate date='',
     @rToDate date='',
     @rCode nvarchar(20)='',
     @rName nvarchar(20)='',
     @rOrgGroupBatchId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

DECLARE @lIsShowPhoto bit = 0
DECLARE @lIsOnPrePrinted bit = 0
DECLARE @lIsDisplayReligion bit=0
DECLARE @lIsDisplayImageHeader bit=0

DECLARE @lConfigValue nvarchar(50)
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0


	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 177 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 @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId
	--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,
			B.Id,
			B.Number,
			B.AcademicId,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			B.BonafideDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			--OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			--OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			ATM.Title AS AffiliationType,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			@lIsShowPhoto AS IsShowPhoto,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			B.Remark AS ReceiptNo,
			SF.FatherName,
			SA.AdmissionDate,
			DP.Title AS DepartmentName,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4,
			REPLICATE(',',OM.LetterHeadMargin)    AS LetterHeadMargin,
			ISNULL(B.BonafiedReason,'') AS BonafiedReason,
			CT.Title AS Category,
			SF.MotherName,
			C.PermanentStreetOne,
			C.PermanentStreetTwo,
			C.PermanentStreetThree,
			C.PermanentCountry,
			C.PermanentState,
			C.PermanentCity,
			C.PermanentZipCode,
			C.PermanentContactNo,
			C.PresentStreetOne,
			C.PresentStreetTwo,
			C.PresentStreetThree,
			C.PresentCountry,
			C.PresentState,
			C.PresentCity,
			C.PresentContactNo,
			C.PresentZipCode,
			SM.SUId,
			SO.AdhaarNumber,
			CM.DisplayTitle AS ClassName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			OM.PrincipalSignature,
			ISnull(AR.SourceId,0) AS StudentidForhostel,
			DM.DisplayTitle AS Divisionname,
			@lIDConfigValue AS ItemValue ,
			SM.RecordStatusId,
			SO.BirthState AS BirthState,
			CM1.Title AS AdmissionStandard,
			RRG.SchoolRemark1,
			RRG.SchoolRemark2,
			RRG.SchoolRemark3
			
	FROM 
			sCertificate.tBonafide B
			INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id = SA.AdmissionStandardId
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN SHostel.tAssignRoom Ar On Ar.SourceId=A.StudentId AND Ar.OrgGroupBatchId=@rOrgGroupBatchId 
			LEFT JOIN sCommon.tReportRemarkGroupOrg RRG ON RRG.OrgId = OM.Id AND ReportRemarkGroupId=6
			--INNER JOIN sSetup.tTermMaster TM ON  TM.ID=
	WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			--AND ((B.BonafideDate=@rBonafiedDate) OR (ISNULL(@rBonafiedDate,'')=''))
			AND ((B.Number=@rNumber) OR (@rNumber=''))
			AND ((B.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((B.Number <= @rToNo) OR (@rToNo=''))
			AND ((B.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((B.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--Group By B.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
			--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,B.BonafideDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,
			--OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering [sCommon].[pOrgGroupSetupRemove]...';


GO
 
ALTER PROCEDURE [sCommon].[pOrgGroupSetupRemove]
	 
	 @rOrgGroupId smallint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
	
	IF EXISTS(SELECT TOP 1 1 FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
	BEGIN
	SELECT -101 AS Result
	RETURN
	END
	
	
	BEGIN TRANSACTION
	 
	EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    




DELETE FROM sAccounting.tAccountingYearMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tAccountMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerGroupMaster  WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransaction WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sActivity.tActivityTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tClubMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tImmunizationChart WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryReferenceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAttendance.tAbsentReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingConductMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingProgressMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingRemarkMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAreaMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tBirthPlaceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCountryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tDistrictMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHobbyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tMotherTongueMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tNationalityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tOccupationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tPreviousSchoolMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tReligionMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tStateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tSurnameMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBehaviourTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlogComment WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogFavorite WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogScope WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircular WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCircularScope WHERE CAST(LEFT(CircularId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularView WHERE CAST(LEFT(CircularId, 4) AS BIGINT) =@rOrgGroupId
DELETE FROM sCommunication.tNews WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tNewsComment WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tNewsScope WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPhotoCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPoll WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPollAnswer WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollMember WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollResult WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQuery WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryAssignedTo WHERE CAST(LEFT(QueryCategoryId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryComment WHERE CAST(LEFT(QueryId, 4) AS BIGINT) =  @rOrgGroupId
DELETE FROM sEExam.tDataBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataSubjectMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionOption WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionParagraph WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateQuestion WHERE CAST(LEFT(TestTemplateId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tStockUomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sGSEB.tActivityGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityIndicatorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tRoomCategoryMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tRoomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tQualificationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tItemMainGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tItemSubGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemCategoryMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tStoreLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAgeGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAuthorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLanguageMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLocationMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookPublisherMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSupplierMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookTagMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tLibraryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tEsiProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tEsiSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayElement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcess WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessElement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessEmployee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetupDependent WHERE CAST(LEFT(PaySetupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcessCharge WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tProfessionalTaxRange WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sProcurement.tVendorCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrganizationTask WHERE CAST(LEFT(OrgGroupId, 4) AS SMALLINT) = @rOrgGroupId
DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRole WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

 
DELETE FROM sStudent.tAdmissionCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTax.tTaxGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteDestinationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tFamiliyCastMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sScholarship.tScholarshipTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgMainGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgSubGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tVisitorGatePass WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollYearMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sActivity.tEventTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRoleDashlet WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId


DELETE FROM sCommon.tFrequencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tRangeDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tRangeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFinanceCommon.tCurrencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierDispatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierReceive WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tBuildingMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tChangeRoom WHERE CAST(LEFT(RoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelAdmission WHERE CAST(LEFT(Hosteld, 4) AS INT) = @rOrgGroupId

DELETE FROM sLibrary.tLibraryAttendance WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineReceive WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tFuelLogs WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tFuelTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleDocumentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTransport.tVehicleDocuments WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenance WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenanceDetail WHERE CAST(LEFT(VehicleMaintenanceId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleTypeMaster WHERE OrgGroupId = @rOrgGroupId

--DELETE FROM sTimetable.tAssignSchoolRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tDivisionTimeOff WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolBuildingMaster WHERE  OrgGroupId = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomMaster WHERE  CAST(LEFT(SchoolBuildingId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tTeacherTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

DELETE FROM sCommunication.tEbook WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tEbookScope WHERE  CAST(LEFT(EbookId, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sActivity.tClubTypeMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tHouseGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryStatusMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroup WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroupMember WHERE  CAST(LEFT(CustomGroupId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sTally.tFeeLedgerMapping WHERE CAST(LEFT(FeeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptBookCompanyMapping WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptPosting WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoom WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoomTimeOff WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tSchoolBuilding WHERE  OrgGroupId = @rOrgGroupId
 DELETE FROM sCommon.tCastCategoryMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tTransportMaster WHERE  OrgGroupId = @rOrgGroupId

DELETE FROM sAlert.tOtherGroupDetail WHERE  CAST(LEFT(OtherGroupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tOtherGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAdmissionQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tCollectionGroupMaster WHERE  CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId

DELETE FROM sHrm.tWorkAreaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItem WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItemSize WHERE  CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sIp.tUniformStock WHERE  CAST(LEFT(UniformSizeId, 4) AS INT) = @rOrgGroupId

DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tReportOrgGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayConfiguration WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sTimetable.tDivisionClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tSubjectClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tTimeTableDetail WHERE CAST(LEFT(TimetableId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeDetail WHERE CAST(LEFT(ExemptionTypeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSecurity.tRoleModulePermission WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId

/* -- Date : 13/06/2016 -- */
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenIssueDetail WHERE CAST(LEFT(CanteenIssueId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tFoodItemMaster WHERE CAST(LEFT(CanteenId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFrontOffice.tLostFoundRegister WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sHostel.tAssetTypeMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tAssignRoomAsset WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tRoomAssetMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tLeaveReasonMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sSetup.tOrgGroupSetting WHERE OrgGroupId = @rOrgGroupId
 
DELETE FROM sStudent.tSUIdConfig WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTimetable.tAssignDivision WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

/* -- Date : 12/08/2016 -- */
DELETE FROM sHostel.tHostelDepositAdd WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositAdjustment WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositRefund WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSystem.tExceptionLog WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 17/09/2016 -- */
DELETE FROM sCommon.tReportClient WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tTempCircularScope WHERE CAST(LEFT(SourceID, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sErp.tCustomerMaster WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 05/10/2016 -- */
DELETE FROM sHostel.tAttendanceRegister WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateCommunications WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateImages WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidatePreviousEmployment WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateQualification WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateVacancyCriteriaScore WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tInterviewCriteria WHERE CAST(LEFT(VacancyId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tRecruitmentStatusLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tVacancy WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 24/11/2016 -- */

DELETE FROM siTax.tAssessmentYear WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16 WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16Detail WHERE CAST(LEFT(Form16Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxChallan WHERE CAST(LEFT(AssesmentYearId, 4) AS INT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSlab WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSubGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tPlacementCompanyMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAppraisal.tConductTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sErp.tCustomerActivationLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicyDetail WHERE  CAST(LEFT(IpPolicyId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tTimePolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserPolicy WHERE  CAST(LEFT(TimePolicyId, 4) AS int) = @rOrgGroupId


DELETE FROM sAppraisal.tKPATemplateDetail WHERE CAST(LEFT(KPATemplateId, 4) AS int) = @rOrgGroupId
DELETE FROM sAppraisal.tKPATemplateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayProduct WHERE CAST(LEFT(GatewayConfigurationId, 4) AS int) = @rOrgGroupId
DELETE FROM sOp.tGatewayProductReceiptBookMapping WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tSstockIssueTypeMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sFee.tFeeDepositExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelAttendanceTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseSubTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelGatePassReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformOrderItem WHERE CAST(LEFT(StockItemId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturn WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturnBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentOtherGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentUIdMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAssetManagement.tAssetCheck WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAssetManagement.tAssetInchargeUser WHERE CAST(LEFT(AssetId, 4) AS int) = @rOrgGroupId
DELETE FROM sCanteen.tBreakTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tDailyMenu WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId

DELETE FROM sAlert.tAdVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeAccountMapping WHERE CAST(LEFT(ChargeId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tChargeAccountPosting WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountMapping WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountPosting WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId

DELETE FROM sCommunication.tFeedback WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeDetail WHERE CAST(LEFT(FeedbackAnswerTypeId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAssign WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackFor WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackQuestionResponse WHERE CAST(LEFT(FeedbackResponseId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackResponse WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplate WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplateQuestion WHERE CAST(LEFT(FeedbackTemplateId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tStockReset WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockResetBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tBackupLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSystem.tPortalSync WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sAccounting.tBudget WHERE CAST(LEFT(LedgerId, 4) AS int) = @rOrgGroupId
DELETE FROM sAccounting.tTransactionApprove WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionApproveDetail WHERE CAST(LEFT(LedgerId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSetup.tScreenMandatoryFeild WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sCommunication.tPhotoCategoryScope WHERE CAST(LEFT(PhotoCategoryId, 4) AS int) = @rOrgGroupId
DELETE FROM sTool.tTestCase WHERE CAST(LEFT(Id, 4) AS int) = @rOrgGroupId

DELETE FROM sLibrary.tMagazineTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrgGroupMobileAppDetail WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sLibrary.tBookCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookSubCategoryMaster WHERE OrgGroupId = @rOrgGroupId


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

	-- special case will come orgwise and orggroupwise

DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgGroupId 
DELETE FROM sConfig.tConfigurationSetup WHERE SourceTypeId = 2010 AND SourceId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupBatchMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupMaster WHERE Id=@rOrgGroupId


DELETE FROM sCanteen.tGuestRequest WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tLimitLog WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sProcurement.tOtherStockBatch WHERE CAST(LEFT(StockBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockIssue WHERE CAST(LEFT(StoreLocationId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockIssueBatch WHERE CAST(LEFT(OtherStockBatchId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sVts.tvtsOrgGroupMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sLibrary.tBookGroup1Master WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookGroup2Master WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sHostel.tHostelEventAssign WHERE CAST(LEFT(HostelEventScheduleId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tHostelEventAttendance WHERE CAST(LEFT(HostelEventScheduleId, 4) AS int) = @rOrgGroupId

DELETE FROM sHostel.tHostelEventSchedule WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tHostelEventTypeMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId

DELETE FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @rOrgGroupId



DELETE FROM sCommon.tOrgGroupDepartmentMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sFee.tFeeExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserOrgGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupEIS WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteTripLog WHERE CAST(LEFT(BusRouteId, 4) AS int) = @rOrgGroupId
DELETE FROM sTransport.tBusRouteTripTemplate WHERE CAST(LEFT(BusRouteId, 4) AS int) = @rOrgGroupId


DELETE FROM sCommunication.tCircularTypeAssignedTo WHERE CAST(LEFT(CircularTypeId, 4) AS int) = @rOrgGroupId
DELETE FROM sErp.tSupportTicket WHERE OrgGroupId= @rOrgGroupId
DELETE FROM siTax.tTaxPlanning WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sStudent.tStudentCustomFieldMaster WHERE OrgGroupId= @rOrgGroupId

DELETE FROM sErp.tCustomerPlugInLog WHERE OrgGroupId= @rOrgGroupId


	
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].[pAllPhotoCategory_Get]...';


GO
ALTER PROCEDURE [sCommunication].[pAllPhotoCategory_Get]
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 @rBatchId int,
	 @rIsDivisionWise bit=true
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
    DECLARE @lOrgGroupId smallint,@lOrgGroupBatchID int,@lOrgId smallint
    
	SELECT @lOrgGroupId=OM.OrgGRoupId FROM sSetup.tOrganizationMaster OM
	INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id
	WHERE Bm.Id=@rBatchId
    IF(@rIsDivisionWise=0)
    BEGIN
		SELECT   
			PCM.[Id]
			,PCM.[Title]
			,PCM.[IsObsolete]
			,ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			,ISNULL(PCM.Remark,'') AS Remark,
			PCM.CreatedDateTime,
			CASE WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2021 THEN 'Organization'
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2017 THEN 'Department' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2016 THEN 'Class' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2005 THEN 'Division' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2014 THEN 'Hostel' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2029 THEN 'House' 
			END +' - '+ [sCommunication].[fPhotoCategoryScopeGet](PCM.Id,PCM.ScopeSourceTypeId) AS ScopeSourceType,
			U.DisplayTitle AS UserName
		FROM    
			[sCommunication].[tPhotoCategoryMaster]  PCM 
			INNER JOIN sSecurity.tUser U ON PCM.CreatedUserId = U.Id
		WHERE   
			((PCM.Id = @rId) OR (@rId = 0))
			AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
			AND OrgGroupId=@lOrgGroupId
			
		ORDER BY 
			PCM.CreatedDateTime DESC
	END		
	ELSE
	
	 BEGIN
		SELECT   
			PCM.[Id]
			,PCM.[Title]
			,PCM.[IsObsolete]
			,ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			,ISNULL(PCM.Remark,'') AS Remark,
			PCM.CreatedDateTime,
			CASE WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2021 THEN 'Organization'
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2017 THEN 'Department' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2016 THEN 'Class' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2005 THEN 'Division' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2014 THEN 'Hostel' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2029 THEN 'House' 
			END +' - '+ [sCommunication].[fPhotoCategoryScopeGet](PCM.Id,PCM.ScopeSourceTypeId) AS ScopeSourceType,
			U.DisplayTitle AS UserName
		FROM    
			[sCommunication].[tPhotoCategoryMaster]  PCM 
			INNER JOIN sSecurity.tUser U ON PCM.CreatedUserId = U.Id
		WHERE   
			((PCM.Id = @rId) OR (@rId = 0))
			AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
			AND OrgGroupId=@lOrgGroupId
			AND ScopeSourceTypeId=2005
		ORDER BY 
			PCM.CreatedDateTime DESC
	END		
END
GO
PRINT N'Altering [sCommunication].[pMyBookGet]...';


GO
ALTER PROCEDURE [sCommunication].[pMyBookGet]
	 
	 @rReaderSourceTypeId smallint,
	 @rReaderSourceId bigint,
	 @rBatchId int,
	 @rStatusId int
	 	 
	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 BL.IsCurrentStatus = 1 THEN 'Pending' ELSE 'Return' END AS IsReturnPending,
	BL.DueDate 
	--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
  ORDER BY BL.LogDate DESC

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


GO
 
ALTER PROCEDURE [sCommunication].[pOrgInfoAdd] 
	(
		@rXmlDoc nvarchar(MAX),	
		@rOrgId smallint
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
 DECLARE @lNextNumber smallint
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	--DECLARE @lOrgId smallint
	if exists (select OrgId from sSetup.tOrgInfo where OrgId=@rOrgId)
	begin
		delete from sSetup.tOrgInfo where OrgId=@rOrgId
	
		INSERT INTO sSetup.tOrgInfo
		(
			 OrgId,
			 Title,
			 Detail
		)
		SELECT
			@rOrgId,
			Title,
			Detail
			
		FROM OPENXML (@intDoc, '/Table/OrgInfo', 1)
		WITH
		(
			OrgId smallint '@rOrgId' ,
			Title nvarchar(200) '@Title',
			Detail nvarchar(1000) '@Detail'
			 
		) 
	 
		
		EXEC sp_xml_removedocument @intDoc
		SELECT 1 as result
	end
else
	 begin
			INSERT INTO sSetup.tOrgInfo
		(
			 OrgId,
			 Title,
			 Detail
		)
		SELECT
			OrgId,
			Title,
			Detail
			
		FROM OPENXML (@intDoc, '/Table/OrgInfo', 1)
		WITH
		(
			OrgId smallint '@OrgId' ,
			Title nvarchar(200) '@Title',
			Detail nvarchar(200) '@Detail'
			 
		) 
	 
		
		SELECT @lNextNumber = OrgId FROM sSetup.tOrgInfo Where OrgId=@rOrgId
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sSetup.tOrgInfo', @rCurrentNumber = @lNextNumber 
		SELECT 2 as result
	 end
	 
	
	COMMIT TRANSACTION
 
 
	 

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


GO

ALTER PROCEDURE [sCommunication].[pQueryQueueGet]
	 
	 @rQueryCategoryId int = 0,
	 --@rCreatedUserId bigint,
	 @rOrgGroupBatchId int,
	 @rOrgGroupId smallint,
	 @rQueryId bigint,
	 @rUserSourceId bigint,
	 @rMyList bit,
	 @rStatusId int = 0,
	 @rSourceId bigint = 0,
	 @rSubjectId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
IF(@rMyList=0)
BEGIN
	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code AS Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id  
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
        
	WHERE 
  
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId) 
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	    AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	    AND ((EJD.EmployeeId=@rSourceId) OR (@rSourceId=0))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
			sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		
		
	
		UNION
		SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId --AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = 120100101 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QCM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId
		
		UNION
		
		
		SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId  
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = QM.AssignedToEmployeeId 
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	
	 WHERE 
	 
	 ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
	 AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
	 AND (QCM.OrgGroupId=@rOrgGroupId)  
	 AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
	 AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	 
	 AND ((QM.AssignedToEmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
	 ORDER BY QM.CreatedDateTime DESC
	 --and QM.FromSourceTypeId=95
		
		
END
ELSE IF(@rMyList=1)
BEGIN

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId)
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	    AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId)
	    AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	    AND (( EJD.EmployeeId=@rSourceId) OR (@rSourceId=0))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId AND SourceTypeId <> 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
					AND SA.DivisionId IN (SELECT Id FROM sSetup.tDivisionMaster WHERE InchargeEmployeeId=@rUserSourceId)
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId			
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 24 AND SourceTypeId = 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		
		
		
		UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId --AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = 120100101 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QCM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId
		
		
   UNION
    
    
    
    
    
    SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId
        INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = SA.DivisionId AND (( TSD.EmployeeId = @rUserSourceId) OR (@rUserSourceId=0)) AND QM.SubjectId= TSD.SubjectId                  
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
        
  WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((TSD.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			--AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId      
        
	 
	 UNION
    
    SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate
			
	FROM 
		--	sCommunication.tQuery QM
		--INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
  --      INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
  --      INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
  --      INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
  --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
  --      INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
  --      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
	
	 --WHERE 
	 
	 --      ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		--    AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		--    AND (QCM.OrgGroupId = @rOrgGroupId)
	 --       AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	 --       AND (( EJD.EmployeeId=@rSourceId) OR (@rSourceId=0))
	        
		--	AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=95 and QM.OrgGroupBatchId=@rOrgGroupBatchId	
		
		
		sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId  
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = QM.AssignedToEmployeeId 
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	
	 WHERE 
	 
	 ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
	 AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
	 AND (QCM.OrgGroupId=@rOrgGroupId)  
	 AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
	 AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	 
	 AND ((QM.AssignedToEmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
	 ORDER BY QM.CreatedDateTime DESC	
	 
	 
	 
	 
	 
	 
	 
		
END
END


--SELECT Q.CreatedUserId FROM sCommunication.tQueryCategoryMaster QCM INNER JOIN sCommunication.tQuery Q ON Q.QueryCategoryId = QCM.Id
GO
PRINT N'Altering [sCommunication].[pRegisteredUsersGet]...';


GO
 
ALTER PROCEDURE [sCommunication].[pRegisteredUsersGet]

		@rSourceTypeId smallint = 0,
		@rSourceId bigint = 0,
		@rOSTypeId tinyint = 0,
		@rUserSourceTypeId smallint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			ISNULL(DeviceToken,'') AS DeviceToken
	FROM 
		sCommunication.tRegisteredUsers RU 
		INNER JOIN sStudent.tAcademic SA ON RU.UserSourceId = SA.StudentId AND RU.UserSourceTypeId=2003 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId AND BM.IsActive=1		
		INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId AND ISNULL(SC.IsBlockAllAlert,0) = 0
	WHERE 
		(
		(SA.Id=@rSourceId) AND (@rSourceTypeId=2001)
		OR (SA.StudentId=@rSourceId) AND (@rSourceTypeId=2003)
		OR (SA.DivisionId=@rSourceId) AND (@rSourceTypeId=2005)
		OR (SA.ClassId=@rSourceId) AND (@rSourceTypeId=2016)
		OR (CM.DepartmentId=@rSourceId) AND (@rSourceTypeId=2017)
		OR (SA.OrgId=@rSourceId) AND (@rSourceTypeId=2021)	
		) 
		AND RU.OSTypeId=@rOSTypeId AND RU.DeviceToken	IS NOT NULL AND RU.DeviceToken != '' 	
		AND ((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))
		
	UNION ALL		
		
	SELECT 
			ISNULL(DeviceToken,'') AS DeviceToken
	FROM 
		sCommunication.tRegisteredUsers RU
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON RU.UserSourceId = EJD.EmployeeId AND RU.UserSourceTypeId=95
	WHERE 
		(
		(EJD.EmployeeId=@rSourceId) AND (@rSourceTypeId=95)
		OR (EJD.OrganizationDepartmentId=@rSourceId) AND (@rSourceTypeId=2017)
		OR (EJD.OrgId=@rSourceId) AND (@rSourceTypeId=2021)	
		) AND RU.OSTypeId=@rOSTypeId AND RU.DeviceToken	IS NOT NULL AND RU.DeviceToken != '' 
		AND ((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))		
END
GO
PRINT N'Altering [sEExam].[pTestParticipantResultGet]...';


GO
ALTER PROCEDURE [sEExam].[pTestParticipantResultGet]
 
			@rTestId int,		 
			@rSourceTypeID int = 0,
			@rSourceId bigint = 0,
			@rBatchId int=0
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN   

DECLARE @1TestAssignStatusId int

 
IF(@rSourceTypeID = 2003)
   BEGIN
	 SELECT  
		 VSA.RollNo,
		 VSA.Name,
		 VSA.Code,
		 P.SourceId,
		 P.SourceTypeId,	
	     ISNULL(P.TotalMarks,0) AS TotalMarks,
		 ISNULL(P.ScoredMarks,0) AS ScoredMarks,
		 ISNULL(P.TotalQuestions,0) AS TotalQuestions,
		 ISNULL(P.RightQuestions,0) AS RightQuestions,
		 (ISNULL(P.WrongQuestions,0) - (ISNULL(P.NotAttemptedQuestions,0)+ ISNULL(P.SkippQuestions,0))) AS WrongQuestions,
		 ISNULL(P.NotAttemptedQuestions,0) AS NotAttemptedQuestions,
		 ISNULL(P.SkippQuestions,0) AS SkippQuestions,
		 'Student' AS TypeName,
		 VSA.ClassName+'-'+VSA.DivisionName As ClassName,
		 ISNULL(TM.IsMarkInDecimal,0) AS IsMarkInDecimal,
		 P.Id AS TestParticipantId,
		 VSA.AcademicId,
		 TM.Title As TestName
		 --TM.IsMarkInDecimal
		 FROM sEExam.tTestParticipant P INNER JOIN sEExam.tTestMaster TM ON TM.Id = P.TestId
		 INNER JOIN sStudent.vStudentAcademic VSA ON VSA.StudentId = P.SourceId AND P.SourceTypeId=2003
		 Where (SourceTypeId = @rSourceTypeID OR @rSourceTypeID = 0) AND TestId = @rTestId
		 AND TestStatusId != 0 AND (P.SourceId = @rSourceId or @rSourceId = 0)
		 AND TM.BatchId=@rBatchId AND VSA.BatchId=@rBatchId
		
		ORDER BY DivisionId, VSA.RollNo ASC
		END
		ELSE 
		     Select 			
			 ECD.Code AS RollNo,
			 ECD.EmployeeName AS Name,
			 ECD.Code,
			 P.SourceId,
			 P.SourceTypeId,			
			 ISNULL(P.TotalMarks,0) AS TotalMarks,
			 ISNULL(P.ScoredMarks,0) AS ScoredMarks,
			 ISNULL(P.TotalQuestions,0) AS TotalQuestions,
			 ISNULL(P.RightQuestions,0) AS RightQuestions,
			 ISNULL(P.WrongQuestions,0) AS WrongQuestions,
			 ISNULL(P.SkippQuestions,0) AS SkippQuestions,
			 ISNULL(P.NotAttemptedQuestions,0) AS NotAttemptedQuestions,
		     'Employee' AS TypeName,
		     ECD.DepartmentName AS ClassName,
		     ISNULL(TM.IsMarkInDecimal,0) AS IsMarkInDecimal,
		     P.Id AS TestParticipantId
		     --TM.IsMarkInDecimal
			 
			 FROM sEExam.tTestParticipant P INNER JOIN sEExam.tTestMaster TM ON TM.Id = P.TestId
			 INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId = P.SourceId 
			 AND TestStatusId != 0 
 
			 Where (SourceTypeId = @rSourceTypeID OR @rSourceTypeID = 0) AND TestId = @rTestId   
			  AND TestStatusId != 0  AND (P.SourceId = @rSourceId or @rSourceId = 0)
			  AND TM.BatchId=@rBatchId
END
GO
PRINT N'Altering [sErp].[pCustomerMasterAdd]...';


GO


ALTER PROCEDURE [sErp].[pCustomerMasterAdd]  	 	 
			@rId int, 
			@rOrgId smallint, 
			@rOrgGroupId smallint, 
			@rCRMLicenceId int, 
			@rTitle nvarchar(200), 
			@rShortTitle nvarchar(100), 
			@rStreetOne nvarchar(50), 
			@rStreetTwo nvarchar(50), 
			@rStreetThree nvarchar(50), 
			@rCityName nvarchar(100), 
			@rZipCode nvarchar(20),	
			@rHomePage nvarchar(100), 
			@rPhoneNo nvarchar(50), 
			@rMobileNo nvarchar(50), 
			@rContactPerson nvarchar(100),
			@rCreatedUserId bigint,       
			--@rUpdatedUserId bigint, 
			@rIsObsolete bit,
			@rCustomerStatusId tinyint,
			@rChannelId int, 
			@rInstallationTypeId tinyint,
			@rStateId int, 
			@rCountryId int, 
			@rDomain  nvarchar(200),
			@rDb nvarchar(100), 
			@rInstallationDate date,
			@rEmail nvarchar(100),
			@rAbsolutePath nvarchar(300)='',
			@rCampusType  int=0,
			--Remainder Perameter.--
			@rPaymentDueDate Date =null,
			@rIsPaymentReminder bit=0,
			@rPaymentRemainderRemark nvarchar(300) = '',
			@rstudentExtraCap int=0,
			@rLastStudentCapReminderDate date = null,
			@rStudentCapReminderCount smallint=0,
			@rStudentCapReminderDate date =null,
			@rIsStopServiceReminder bit=0,
			@rServiceStopRemark nvarchar(300)='',
			@rServiceStopDate date=null,
			@rIsAutoStopService bit=0,
			@rNoOfStudent int =0,
			@rPlugin nvarchar(200) = '',
			@rTag nvarchar(200) = ''
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--BEGIN
--	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sErp.tCustomerMaster where OrgGroupId=@rOrgGroupId AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	
		If Exists(select Id from sErp.tCustomerMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where ShortTitle=@rShortTitle AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where CRMLicenceId=@rCRMLicenceId AND OrgId=@rOrgId)
			BEGIN
			select -101 as Result
			RETURN
		END 
			If Exists(select Id from sErp.tCustomerMaster where Domain=@rDomain AND OrgId=@rOrgId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
			BEGIN
			select -105 as Result
			RETURN
		--END 
		--If Exists(select Id from sErp.tCustomerMaster where Db=@rDb AND OrgId=@rOrgId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
		--	BEGIN
		--	select -106 as Result
		--	RETURN
		END 
		
	END
	ELSE
	BEGIN
		If Exists(select Id from sErp.tCustomerMaster where OrgGroupId=@rOrgGroupId AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End
		If  Exists(select Id from sErp.tCustomerMaster where Title=@rTitle  AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
        If Exists(select Id from sErp.tCustomerMaster where ShortTitle=@rShortTitle AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where CRMLicenceId=@rCRMLicenceId AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where Domain=@rDomain AND OrgId=@rOrgId AND Id<>@rId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
			BEGIN
			select -105 as Result
			RETURN
		--END 
		--If Exists(select Id from sErp.tCustomerMaster where Db=@rDb AND OrgId=@rOrgId AND Id<>@rId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
		--	BEGIN
		--	select -106 as Result
		--	RETURN
		END 
	END
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tCustomerMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tCustomerMaster
		(
			Id ,
			OrgId ,
			OrgGroupId ,
			CRMLicenceId ,
			Title ,
			ShortTitle ,
			StreetOne,
			StreetTwo ,
			StreetThree ,
			CityName ,
			ZipCode,
			HomePage ,
			PhoneNo ,
			MobileNo ,
			ContactPerson ,
			CreatedUserId , 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			IsObsolete,
			CustomerStatusId ,
			ChannelId ,
			InstallationTypeId,
			StateId ,
			CountryId ,
			Domain ,
			Db ,
			InstallationDate ,
			Email,
			AbsolutePath,
			CampusTypeId,
			PaymentDueDate,
			IsPaymentReminder,
			PaymentReminderRemark,
			StudentExtraCap,
			LastStudentCapReminderDate,
			StudentCapReminderCount,
			StudentCapReminderDate,
			IsStopServiceReminder,
			ServiceStopRemark,
			ServiceStopDate,
			IsAutoStopService,
			PlugIn,
			Tag
			
        )
	VALUES
		(
			@lNextNumber , 
			@rOrgId,
			@rOrgGroupId , 
			@rCRMLicenceId , 
			@rTitle , 
			@rShortTitle, 
			@rStreetOne , 
			@rStreetTwo , 
			@rStreetThree , 
			@rCityName,
			@rZipCode,
			@rHomePage,
			@rPhoneNo,
			@rMobileNo,
			@rContactPerson,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rCustomerStatusId,
			@rChannelId,
			@rInstallationTypeId,
			@rStateId,
			@rCountryId,
			@rDomain,
			@rDb,
			@rInstallationDate,
			@rEmail,
			@rAbsolutePath,
			@rCampusType,
			@rPaymentDueDate,
			@rIsPaymentReminder,
			@rPaymentRemainderRemark,
			@rstudentExtraCap,	
			@rLastStudentCapReminderDate,
			@rStudentCapReminderCount	,
			@rStudentCapReminderDate,
			@rIsStopServiceReminder,
			@rServiceStopRemark,
			@rServiceStopDate,
			@rIsAutoStopService,
			@rPlugin,
			@rTag		
		)
			INSERT INTO sSetup.tOrgGroupSetting
		(OrgGroupId,NoOfStudent,PaymentDueDate,IsPaymentReminder,PaymentReminderRemark,StudentExtraCap,
		LastStudentCapReminderDate,
		StudentCapReminderCount,StudentCapReminderDate,IsStopServiceReminder,ServiceStopRemark,ServiceStopDate,
		IsAutoStopService)
		VALUES
		(@rOrgGroupId ,@rNoOfStudent,@rPaymentDueDate,
			@rIsPaymentReminder,
			@rPaymentRemainderRemark,
			@rstudentExtraCap,	
			@rLastStudentCapReminderDate,
			@rStudentCapReminderCount	,
			@rStudentCapReminderDate,
			@rIsStopServiceReminder,
			@rServiceStopRemark,
			@rServiceStopDate,
			@rIsAutoStopService )
		INSERT INTO sErp.tCustomerActivationLog
			(
			OrgGroupId,
			LogDate,
			StatusRemark,
			CreatedUserId,
			CreatedDateTime,
			CustomerStatusId
			)
			VALUES
			(
			@rOrgGroupID , 
			sCommon.fGetDate(),
			'',
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCustomerStatusId
			
			)
		
		
		    SELECT 1 AS Result
	END	 
	

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tCustomerMaster
	    SET		
			OrgGroupId= @rOrgGroupId,
			CRMLicenceId =@rCRMLicenceId,
			Title=@rTitle ,
			ShortTitle=@rShortTitle ,
			StreetOne=@rStreetOne,
			StreetTwo=@rStreetTwo ,
			StreetThree=@rStreetThree ,
			CityName= @rCityName,
			ZipCode=@rZipCode,
			HomePage= @rHomePage,
			PhoneNo=@rPhoneNo ,
			MobileNo= @rMobileNo,
			ContactPerson =@rContactPerson,

			UpdatedUserId=@rCreatedUserId, 
			UpdatedDateTime=sCommon.fGetDate(),
			IsObsolete=@rIsObsolete,
			CustomerStatusId= @rCustomerStatusId,
			ChannelId=@rChannelId ,
			InstallationTypeId=@rInstallationTypeId,
			StateId=@rStateId ,
			CountryId =@rCountryId,
			Domain =@rDomain,
			Db =@rDb,
			InstallationDate =@rInstallationDate,
			Email=@rEmail,
			AbsolutePath=@rAbsolutePath,
			CampusTypeId=@rCampusType,
			PaymentDueDate=@rPaymentDueDate,
			IsPaymentReminder=@rIsPaymentReminder,
			PaymentReminderRemark=@rPaymentRemainderRemark,
			StudentExtraCap=@rstudentExtraCap,	
			LastStudentCapReminderDate=@rLastStudentCapReminderDate,
			StudentCapReminderCount=@rStudentCapReminderCount	,
			StudentCapReminderDate=@rStudentCapReminderDate,
			IsStopServiceReminder=@rIsStopServiceReminder,
			ServiceStopRemark=@rServiceStopRemark,
			ServiceStopDate=@rServiceStopDate,
			IsAutoStopService=@rIsAutoStopService,
			PlugIn=@rPlugin,
			Tag=@rTag
	      WHERE Id = @rId
		  
		
	      SELECT 11 AS Result
	 --END  	

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


GO
ALTER PROCEDURE [sErp].[pCustomerMasterDelete]
	 @rOrgGroupId smallint, 
	  @rCustomerId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	IF EXISTS (SELECT  CustomerId  FROM sErp.tCustomerOrg WHERE  CustomerId=  @rCustomerId)
	BEGIN 
		SELECT -101 AS Result
	END
	IF EXISTS (SELECT  OrgGroupId   FROM sSecurity.tOrgGroupMobileApp WHERE  OrgGroupId =  @rOrgGroupId  )
	BEGIN 
		SELECT -102 AS Result
	END
	ELSE
		BEGIN 		
			DELETE  FROM sErp.tCustomerMaster WHERE Id = @rCustomerId AND OrgGroupId = @rOrgGroupId

			DELETE FROM sErp.tCustomerPlugInLog WHERE OrgGroupId = @rOrgGroupId
			SELECT 1 AS RESULT
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END
GO
PRINT N'Altering [sErp].[pCustomerMasterGet]...';


GO

ALTER PROCEDURE [sErp].[pCustomerMasterGet]

	  @rId int,
	  @rOrgId smallint=0,
	  @rOrgGroupId smallint=0,
	  @rTitle nvarchar(100),
	  @rShortTitle nvarchar(100),
	  @rCRMLicenceId int=0, 
	  @rCustomerStatusId tinyint,
      @rChannelId int, 
      @rInstallationTypeId nvarchar(max)='',
	  @rPlugIn int=0,
	  @rTag int=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rShortTitle = sCommon.fSearchStringGet(@rShortTitle)
	END
	
	IF (RIGHT(@rInstallationTypeId, 1) = ',')
        SET @rInstallationTypeId = LEFT(@rInstallationTypeId, LEN(@rInstallationTypeId) - 1)
	
	SELECT 
			CM.Id,
			CM.OrgId,
			CM.OrgGroupId,				
			CM.Title,
			CM.ShortTitle,
			CM.CRMLicenceId,
			CM.StreetOne,
			CM.StreetTwo,
			CM.StreetThree,
			ISNULL(CM.CountryId,0) AS CountryId,
			CM.StateId,
			CM.CityName,
			CM.ZipCode,
			CM.HomePage,
			CM.MobileNo,
			CM.PhoneNo,
			CM.ContactPerson,
			CM.CustomerStatusId AS CustomerStatusTypeId,
			CS.Title AS CustomerStatus,
			CM.ChannelId AS ChannelTypeId,
			CC.Title AS ChannelName,
			CM.InstallationTypeId AS InstallationId,
			IT.Title AS InstallationType,	
			CM.Domain,
			CM.Db,
			CM.InstallationDate,
			--CS.Id AS CustomerStatusTypeId,
			--CS.Title AS CustomerStatus,
			--CC.Id AS ChannelTypeId,
			--CC.Title AS ChannelName,
			--IT.Id AS InstallationId,
			--IT.Title AS InstallationType,	
			CM.IsObsolete ,
			Isnull(CM.Email,'') As Email,
			ISNULL(AbsolutePath,'') AS AbsolutePath,
			ISNULL(CampusTypeID,0) As CampusTypeID,
			ISNULL(CA.Title,'') As CampusType,
			PaymentDueDate,
			IsPaymentReminder,
			PaymentReminderRemark,
			StudentExtraCap,
			LastStudentCapReminderDate,
			StudentCapReminderCount,
			StudentCapReminderDate,
			IsStopServiceReminder,
			ServiceStopRemark,
			ServiceStopDate
	FROM 
			 sErp.tCustomerMaster CM
			 LEFT JOIN  sErp.tCustomerStatusMaster CS ON CM.CustomerStatusId=CS.Id
			 LEFT JOIN sErp.tChannelMaster CC ON CM.ChannelId=CC.Id
			 LEFT JOIN sErp.tInstallationTypeMaster IT ON CM.InstallationTypeId=IT.Id
			 LEFT JOIN sErp.tCampusTypeMaster CA ON CA.Id= CM.CampusTypeId
	WHERE 
	    ((CM.OrgId = @rOrgId)OR (@rOrgId=0))
		AND((CM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId=0))
		AND	((CM.Id = @rId) OR (@rId = 0))
		AND ((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))		
		AND	((CM.CRMLicenceId = @rCRMLicenceId) OR (@rCRMLicenceId = 0))
		AND ((CM.ShortTitle like @rShortTitle) OR (ISNULL(@rShortTitle,'') = ''))
		AND ((CM.CustomerStatusId like @rCustomerStatusId) OR (@rCustomerStatusId=0))
		AND ((CM.ChannelId like @rChannelId) OR (@rChannelId=0))
		--AND ((CM.InstallationTypeId like @rInstallationTypeId) OR (@rInstallationTypeId=0))
		AND ((CM.InstallationTypeId IN (SELECT item from sCommon.fnSplit(@rInstallationTypeId,',')))  OR (ISNULL(@rInstallationTypeId,'') = ''))
		AND ((CM.PlugIn like @rPlugIn) OR (@rPlugIn=0))
		AND ((CM.Tag like @rTag) OR (@rTag=0))
		ORDER BY CM.OrgGroupId DESC
END
GO
PRINT N'Altering [sErp].[pWorkStatusGet]...';


GO
 
 
 
ALTER PROCEDURE   [sErp].[pWorkStatusGet]

	@rEmployeeId bigint =0, 
	@rFromDate DATETIME='',
	@rToDate DATETIME='',
	@rOrgId smallint=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

------------- For Visit Type ---------------------------
		
	DECLARE @lTypeTotal table(
		FollowupTypeId int,
		FollowupCount int
		)
	DECLARE @lTypeEffective table(
		FollowupTypeId int,
		FollowupCount int
		)
	DECLARE @lTypeSchool table(
		FollowupTypeId int,
		FollowupCount int
		)
		DECLARE @lTypeNewSchool table(
		FollowupTypeId int,
		FollowupCount int
		)
		
		INSERT INTO @lTypeTotal		
		SELECT  LF.FollowupTypeId, ISNULL(count(LF.Id),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
		Group By FollowupTypeId
		 
		 
		INSERT INTO @lTypeEffective
				SELECT  LF.FollowupTypeId, ISNULL(count(LF.Id),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	     AND NonEffective = 1
		Group By FollowupTypeId
		
				
 		INSERT INTO @lTypeSchool
		SELECT  LF.FollowupTypeId, ISNULL(count(Distinct LF.LeadId),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	     AND NonEffective = 1
		Group By FollowupTypeId
	
	
INSERT INTO @lTypeNewSchool

SELECT LF.FollowupTypeId,ISNULL(Count(LF.LeadId),0) FROM sErp.tLeadFollowup LF INNER JOIN
(

	SELECT LF.LeadId FROM sErp.tLeadFollowup LF
	INNER JOIN
	(
	
	SELECT DISTINCT LF.LeadId
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		 (( LF.FollowupDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))	  
		  AND (( LF.FollowupDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	     ) L ON LF.LeadId = L.LeadId 
	     WHERE 
		 (( LF.FollowupDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))	  
		  AND (( LF.FollowupDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	     GROUP BY LF.LeadId Having count(LF.LeadId) = 1
	     )
	       A ON LF.LeadId = A.LeadId
	  WHERE 
		 (( LF.FollowupDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))	  
		  AND (( LF.FollowupDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))     
	       GROUP BY LF.FollowupTypeId
	
	 	
 SELECT Id AS FollowupTypeId, Title AS FollowupType,
 ISNULL(TT.FollowupCount,0) AS TypeTotal,
 ISNULL(TE.FollowupCount,0) AS TypeEffective,
 ISNULL(TS.FollowupCount,0) AS TypeSchool,
 ISNULL(TN.FollowupCount,0) AS TypenewSchool
 FROM sErp.tFollowupTypeMaster FTM
 LEFT JOIN @lTypeTotal TT ON  FTM.Id = 	TT.FollowupTypeId
 LEFT JOIN @lTypeEffective TE ON FTM.Id = 	TE.FollowupTypeId
 LEFT JOIN @lTypeSchool TS ON FTM.Id = 	TS.FollowupTypeId
 LEFT JOIN @lTypeNewSchool TN ON FTM.Id = 	TN.FollowupTypeId
 
 ------------- For Leave Status ---------------------------

	DECLARE @lStatusTotal table(
		LeadStatusId int,
		FollowupCount int
		)
	DECLARE @lStatusSchool table(
		LeadStatusId int,
		FollowupCount int
		)

		INSERT INTO @lStatusTotal		
		SELECT  LF.LeadStatusId, ISNULL(count(LF.Id),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
		Group By LeadStatusId


		INSERT INTO @lStatusSchool
		
		SELECT  LM.LeadStatusId, ISNULL(count(LM.Id),0) FROM
		(	
	
		SELECT DISTINCT LF.LeadId
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	     ) A INNER JOIN sErp.tLeadMaster LM on A.LeadId = LM.Id
	     Group By LM.LeadStatusId
	     


SELECT * FROM
(	
 SELECT Id AS LeadStatusId, Title AS LeadStatusType,
 ISNULL(TT.FollowupCount,0) AS StatusTotal, 
 ISNULL(TS.FollowupCount,0) AS StatusSchool
 
 FROM sErp.tLeadStatusMaster FTM
 LEFT JOIN @lStatusTotal TT ON  FTM.Id = 	TT.LeadStatusId  
 LEFT JOIN @lStatusSchool TS ON FTM.Id = 	TS.LeadStatusId
 ) A WHERE A.StatusTotal > 0
  

------------- For Leave ---------------------------
	    
	 SELECT  L.FromDate AS LeaveFromDate, L.ToDate AS LeaveToDate ,LPM.Title AS LeaveType
	 
	 FROM sHrm.tLeave L INNER JOIN sHrm.tLeavePeriodMaster LPM
	 ON L.LeavePeriodId = LPM.Id
	 WHERE
	 (( L.FromDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( L.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	    AND((L.EmployeeId = @rEmployeeId)OR(@rEmployeeId=0))

------------- For Manager ---------------------------

	CREATE TABLE #TempEmployeeId
	(
		EmployeeId bigint
	);
	
 
			WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeID
			 FROM sHrm.tEmployeeJobDetail EJD
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 WHERE ((EmployeeManagerId = @rEmployeeId) OR (@rEmployeeId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
			 AND EM.StatusId = 7
			-- AND EM.FirstName like '%'+@rEmpName+'%'
			 	
			 UNION ALL

			 SELECT
			  E.EmployeeID
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeID = E.EmployeeManagerId
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = E.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =E.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 AND EM.StatusId = 7
			) 
			INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.EmployeeID FROM EmployeeCTE E	    
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT @rEmployeeId
		
 
	    SELECT
	    EM.Id AS EmployeeId,
	    EM.FirstName + ' ' + EM.LastName AS EmployeeName,
	   (SELECT  ISNULL(count(Id),0) 
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		EM.Id = LF.FollowupEmployeeId
		AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND LF.WithManagerEmployeeId > 100
	    AND LF.FollowupTypeId = 1		 
	     ) AS PhysicalWithManager,
	     
	    (SELECT  ISNULL(count(Id),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		EM.Id = LF.FollowupEmployeeId
		AND(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	    AND LF.WithManagerEmployeeId > 100
	    AND LF.FollowupTypeId = 2		 
	     ) AS CallWithManager,	     
	     
	 --  	(SELECT  ISNULL(count(Id),0)
		--FROM		
		--sErp.tLeadFollowup LF
		--WHERE 
		--EM.Id = LF.FollowupEmployeeId
		--AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 --   AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	 --   AND LF.WithManagerEmployeeId IS NOT NULL
	 --   AND LF.FollowupTypeId = 3		 
	 --    ) AS MailWithManager,
	     
	   	(SELECT  ISNULL(count(LF.Id),0) 
		FROM		
		sErp.tLeadFollowup LF INNER JOIN sErp.tLeadMaster LM
		ON LF.LeadId = LM.Id
		WHERE 
		EM.Id = LM.LeadOwnerEmployeeId
		AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	    AND LF.FollowupEmployeeId <> LM.LeadOwnerEmployeeId AND LF.FollowupEmployeeId > 100
	    AND LF.FollowupTypeId = 1		 
	     ) AS PhysicalManager ,
	     
	    (SELECT  ISNULL(count(LF.Id),0) 
		FROM		
		sErp.tLeadFollowup LF INNER JOIN sErp.tLeadMaster LM
		ON LF.LeadId = LM.Id
		WHERE 
		EM.Id = LM.LeadOwnerEmployeeId
		AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	    AND LF.FollowupEmployeeId <> LM.LeadOwnerEmployeeId AND LF.FollowupEmployeeId > 100
	    AND LF.FollowupTypeId = 2		 
	     ) AS CallManager 
	     --,
	     
	 --   (SELECT  ISNULL(count(LF.Id),0) 
		--FROM		
		--sErp.tLeadFollowup LF INNER JOIN sErp.tLeadMaster LM
		--ON LF.LeadId = LM.Id
		--WHERE 
		--EM.Id = LM.LeadOwnerEmployeeId
		--AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 --   AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	 --   AND LF.FollowupEmployeeId <> LM.LeadOwnerEmployeeId
	 --   AND LF.FollowupTypeId = 3		 
	 --    ) AS MailManager	     
	    FROM
	    sHrm.tEmployeeMaster EM INNER JOIN #TempEmployeeId TE ON EM.Id = TE.EmployeeId
	   

END
GO
PRINT N'Altering [sFee].[pDepositAddDelete]...';


GO


ALTER PROCEDURE [sFee].[pDepositAddDelete]
	 
		@rId bigint,
		@rAcademicId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lStudentId bigint
BEGIN 



	BEGIN TRY
		BEGIN TRANSACTION	
			
	IF EXISTS (SELECT 1 FROM  sFee.tDepositAdjustment DA1 INNER JOIN sFee.tDepositAdd DA2 
							  ON DA1.AcademicId=DA2.AcademicId AND DA1.DepositHeadId=DA2.DepositHeadId WHERE DA2.Id=@rId AND DA2.AcademicId=@rAcademicId)
	BEGIN
		SELECT -101 AS RESULT
	END
	
	ELSE 
	
	BEGIN
		DELETE  sFee.tDepositAdd
		FROM sFee.tDepositAdd DA
		WHERE DA.Id=@rId AND DA.AcademicId=@rAcademicId
		SELECT 1 AS Result
	END		
COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END
GO
PRINT N'Altering [sFee].[pDepositAddGet]...';


GO

ALTER PROCEDURE [sFee].[pDepositAddGet]
          
		   @rOrgId int =0,          
           @rDepositHeadId int =0,
           @rFromAmount decimal(12,2) =0,
           @rToAmount decimal(12,2) =0,
           @rFromDepositDate date ='',
           @rToDepositDate date='',
           @rBatchId int =0,
           @rCode nvarchar(20) = '',
           @rOrgGroupBatchId int =0,
           @rClassId int=0,
           @rDivisionId int=0
           
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DA.Id,
		DA.DepositHeadId,
		--DA.StudentId AS StudentId,
		DA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(VSA.SUID,'') AS SUID,
        vSA.BatchId,
		Isnull(DA.DepositNumber,0) As DepositNumber
     
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdd DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId 
  WHERE  
		--vSA.BatchId = @rBatchId
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.DepositDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = ''))
		AND ((DA.DepositDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND((vSA.ClassId = @rClassId)OR(@rClassId=0))
		AND((vSA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
	--	AND DA.OrgGRoupBatchId=@rOrgGroupBatchId
		AND vSA.OrgGRoupBatchId=@rOrgGroupBatchId
		Order By DA.DepositDate
END
GO
PRINT N'Altering [sFee].[pDepositAdjustmentGet]...';


GO

ALTER PROCEDURE [sFee].[pDepositAdjustmentGet]
          
		   @rOrgId int=0,          
           @rDepositHeadId int=0,
           @rFromAmount decimal(12,2)=0,
           @rToAmount decimal(12,2)=0,
           @rFromAdjustmentDate date='',
           @rToAdjustmentDate date='',
           @rBatchId int=0,
           @rCode nvarchar(20)='',
           @rOrgGroupBatchId int=0,
           @rFeeDepositExpenseTypeId int=0,
           @rClassId int=0,
           @rDivisionId int=0
AS
SET NOCOUNT ON

BEGIN
SELECT  
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DA.Id,
		DA.DepositHeadId,
	--	DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(VSA.SUID,'') AS SUID,
        VSA.BatchId,
        Isnull(DA.FeeDepositExpenseTypeId,0) AS FeeDepositExpenseTypeId,
        ISNULL(EM.Title,'') As FeeDepositExpenseType,
        vSA.StudentId,
		ISNULL(AdjustmentNumber,0) AS AdjustmentNumber
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdjustment DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
		LEFT JOIN  sFee.tFeeDepositExpenseTypeMaster EM ON EM.Id=DA.FeeDepositExpenseTypeId
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
	    AND VSA.OrgGroupBatchId=@rOrgGroupBatchId
	    AND (DA.FeeDepositExpenseTypeId=@rFeeDepositExpenseTypeId OR @rFeeDepositExpenseTypeId=0)
	    AND((vSA.ClassId = @rClassId)OR(@rClassId=0))
		AND((vSA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
		Order By DA.AdjustmentDate
END
GO
PRINT N'Altering [sFee].[pDepositRefundGet]...';


GO

ALTER PROCEDURE [sFee].[pDepositRefundGet]
          
		   @rOrgId int=0,          
           @rDepositHeadId int=0,
           @rFromRefundAmount decimal(12,2)=0,
           @rToRefundAmount decimal(12,2)=0,
           @rFromRefundDate date='',
           @rToRefundDate date='',
           --@rBatchId int,
           @rCode nvarchar(20)='',
           @rOrgGroupBatchId int =0,
           @rId bigint =0,
           @rClassId int=0,
           @rDivisionId int=0
           
AS
SET NOCOUNT ON

BEGIN
SELECT 
		DHM.Title AS DepositHeadName,
		vSA.OrgId,
		DR.DepositHeadId,
		--DR.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DR.RefundDate,
		DR.PayTypeId,
		DR.ChequeNo,
		DR.BankName,
		DR.Remark,
		DR.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName, 
        DR.Id ,       
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        CASE  WHEN ISNULL(DR.RefundAmount,0) <> 0 THEN ISNULL(DR.RefundAmount,0) ELSE
        (SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D 
        INNER JOIN sFee.tDepositRefund DR1 ON DR1.DepositHeadId=D.DepositHeadId AND DR1.AcademicId=D.AcademicId AND D.AcademicId = DR.AcademicId
        WHERE D.DepositHeadId = DR1.DepositHeadId AND D.AcademicId=DR1.AcademicId )         
		 - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sFee.tDepositAdjustment DA 
		 INNER JOIN sFee.tDepositRefund DR2 ON DR2.DepositHeadId=DA.DepositHeadId AND DR2.AcademicId=DA.AcademicId AND DA.AcademicId= DR.AcademicId
		 WHERE DA.DepositHeadId = DR2.DepositHeadId AND DA.AcademicId=DR2.AcademicId ) END AS RefundAmount,
        ISNULL(VSA.SUID,'') AS SUID,
        vSA.BatchId,
		Isnull(RefundNumber,0) AS RefundNumber
        
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DR.DepositHeadId
		
  WHERE  
		--vSA.BatchId = @rBatchId 
	   (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DR.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=0)
		AND ((DR.RefundAmount >= @rFromRefundAmount) OR (@rFromRefundAmount = 0))
		AND ((DR.RefundAmount <= @rToRefundAmount) OR (@rToRefundAmount = 0))
		AND ((DR.RefundDate >= @rFromRefundDate) OR (ISNULL(@rFromRefundDate,'') = ''))
		AND ((DR.RefundDate <= @rToRefundDate) OR (ISNULL(@rToRefundDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND VSA.OrgGroupBatchId=@rOrgGroupBatchId
		AND( DR.Id=@rId OR @rId=0)
		AND((vSA.ClassId = @rClassId)OR(@rClassId=0))
		AND((vSA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
		--GROUP BY
		
		--DHM.Title,vSA.OrgId,DR.DepositHeadId,DR.StudentId,vSA.AcademicId,DR.RefundAmount,DR.RefundDate,DR.PayTypeId,
		--DR.ChequeNo,DR.BankName,DR.Remark,DR.CreatedDateTime,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName  
		Order By DR.RefundDate     
END
GO
PRINT N'Altering [sFee].[pFeeConsolidateDashBoardGet]...';


GO


ALTER PROCEDURE [sFee].[pFeeConsolidateDashBoardGet]
		
	@rType nvarchar(100)='',
	@rCount int =0 ,
	@rDivisionId int  =0,
	@rClassId int  =0,
	@rOrgId int  =0,
	@rOrgGroupId int=0,
	@rOrgGroupBatchId int  =0,
	@rCollectionGroupId int =0,
	@rReceiptBookId int =0,
	@rDays int=0,
	@rCommonOrgGroupBatchId int=0,
	@rFromDate varchar(10)='',
	@rToDate varchar(10)='',
	@rMonth int =0,
	@rSyncDate int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

IF(@rType ='FeeStatusOrganization')
	BEGIN 
	IF(@rSyncDate =1)
		BEGIN
			DELETE  sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			CREATE TABLE #tempFeeSetupDetailsSync (
	FeeId int,
	Id int,
	IsOptional bit,
	IsVariable bit,
	Amount decimal(12,2),
	StartDate date,
	EndDate date,
	BatchId int,
	ReceiptBookId int,
	AcademicId bigint,
	FeeName nvarchar(200),
	FeeHeadId int
	)
				INSERT INTO #tempFeeSetupDetailsSync
				SELECT 
					FS1.FeeId,
					FS1.Id, 
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.Id AS AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM 
					sFee.tFeeSetup FS1
					INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
					INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 	    
					INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId		
				WHERE 
					((FS1.IsOptional=0))
					--AND (BM.IsActive =1)  
					And COGBM.Id=@rCommonOrgGroupBatchId 
					And O.IsObsolete = 0
					--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
					--AND (StartDate>='2017-01-01' AND EndDate<='2019-01-31')
					 
					
				UNION ALL

				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.Id AS AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM 
					sFee.tFeeSetup FS1
					INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
					INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
					AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					((FS1.IsOptional=1))
					--AND (BM.IsActive =1) 
					And COGBM.Id=@rCommonOrgGroupBatchId 
					And O.IsObsolete = 0
					--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
					--AND (StartDate>='2017-01-01' AND EndDate<='2019-01-31')	
				CREATE TABLE #tempFeeReceiptSync (
				PaidAmount decimal(12,2),
				FeeSetupId int,
				SourceId bigint
				)
				INSERT INTO #tempFeeReceiptSync
				SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
					sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
					INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
				    
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) AND  COGBM.Id=@rCommonOrgGroupBatchId 
					And O.IsObsolete = 0
					--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
					--AND (StartDate>='2017-01-01' AND EndDate<='2019-01-31')
				GROUP BY FeeSetupId,R.SourceId	
				CREATE TABLE #tempOrganizationSync(
				PaidAmount DECIMAL(12,2),
				PendingAmount DECIMAL(12,2),
				OrgGroupName nvarchar(200),
				OrgGroupId int
				)
				INSERT INTO #tempOrganizationSync
				SELECT 
						SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
						O.Title AS OrgGroupName,
						O.Id AS OrgGroupId
					FROM 
						sStudent.tAcademic SA
						INNER JOIN #tempFeeSetupDetailsSync FS ON FS.AcademicId=SA.Id
						LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
						LEFT JOIN #tempFeeReceiptSync R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.ID = SA.OrgId
						--INNER JOIN sSetup.tBatchMaster BM ON BM.ID = SA.BatchId 
						--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
						INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
						INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
						
						WHERE	
						--(BM.IsActive =1) 
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  And O.IsObsolete = 0
						--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
						GROUP BY  o.Id,o.Title
				INSERT INTO sFee.tTempOrgGroupFeeStatus
				SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
				ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganizationSync T
				SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			
				DROP TABLE #tempFeeSetupDetailsSync
				DROP TABLE #tempFeeReceiptSync
				DROP TABLE #tempOrganizationSync			
		END
	ELSE
		BEGIN
			IF  Exists(select 1 from sFee.tTempOrgGroupFeeStatus where CONVERT(date,UpdatedDateTime) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId)
			BEGIN
	
				SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN
			DELETE  sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			CREATE TABLE #tempFeeSetupDetails (
			FeeId int,
			Id int,
			IsOptional bit,
			IsVariable bit,
			Amount decimal(12,2),
			StartDate date,
			EndDate date,
			BatchId int,
			ReceiptBookId int,
			AcademicId bigint,
			FeeName nvarchar(200),
			FeeHeadId int
			)
				INSERT INTO #tempFeeSetupDetails
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.Id AS AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM 
					sFee.tFeeSetup FS1
					INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
					INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 	    
					INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId		
				WHERE 
					((FS1.IsOptional=0))
					--AND (BM.IsActive =1)  
					And COGBM.Id=@rCommonOrgGroupBatchId 
					And O.IsObsolete = 0
					--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
					--AND (StartDate>='2017-01-01' AND EndDate<='2019-01-31')
					 
					
				UNION ALL

				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.Id AS AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM 
					sFee.tFeeSetup FS1
					INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
					INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
					AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					((FS1.IsOptional=1))
					--AND (BM.IsActive =1) 
					And COGBM.Id=@rCommonOrgGroupBatchId 
					And O.IsObsolete = 0
					--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
					--AND (StartDate>='2017-01-01' AND EndDate<='2019-01-31')	
				CREATE TABLE #tempFeeReceipt (
				PaidAmount decimal(12,2),
				FeeSetupId int,
				SourceId bigint
				)
				INSERT INTO #tempFeeReceipt
				SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
					sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
					INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
				    
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) AND  COGBM.Id=@rCommonOrgGroupBatchId 
					And O.IsObsolete = 0
					--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
					--AND (StartDate>='2017-01-01' AND EndDate<='2019-01-31')
				GROUP BY FeeSetupId,R.SourceId	
				CREATE TABLE #tempOrganization (
				PaidAmount DECIMAL(12,2),
				PendingAmount DECIMAL(12,2),
				OrgGroupName nvarchar(200),
				OrgGroupId int
				)
				INSERT INTO #tempOrganization
				SELECT 
						SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
						O.Title AS OrgGroupName,
						O.Id AS OrgGroupId
					FROM 
						sStudent.tAcademic SA
						INNER JOIN #tempFeeSetupDetails FS ON FS.AcademicId=SA.Id
						LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
						LEFT JOIN #tempFeeReceipt R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.ID = SA.OrgId
						--INNER JOIN sSetup.tBatchMaster BM ON BM.ID = SA.BatchId 
						--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
						INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
						INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
						
						WHERE	
						--(BM.IsActive =1) 
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  And O.IsObsolete = 0
						--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
						GROUP BY  o.Id,o.Title
						
						--select *from #tempOrganization
					
					INSERT INTO sFee.tTempOrgGroupFeeStatus
				SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
				ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganization T
				SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			
				DROP TABLE #tempFeeSetupDetails
				DROP TABLE #tempFeeReceipt
				DROP TABLE #tempOrganization
			END
		END
		
	
	END
ELSE IF(@rType = 'FeeStatusPaid&UnpaidDetilsClassWise')
	BEGIN 
		CREATE TABLE #tempPaidDetailsClassWise(
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(30),
	ClassId int,
	ClassName nvarchar(50),
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2)
)
CREATE TABLE #tempFSClassWise(
    Id int,
    Amount DECIMAL(12,2),
	AcademicId BIGINT
)
INSERT INTO #tempFSClassWise
SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		SA1.Id AS AcademicId
	FROM 
		sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId		
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA1.OrgId		
		
	WHERE 
		(FS1.IsOptional=0) 
		AND  ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		AND((OM.OrgGroupId) = @rOrgGroupId OR (@rOrgGroupId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
		--AND(BM.IsActive =1) 
UNION ALL				
SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		SA1.Id As AcademicId
	FROM 
	    sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA1.OrgId
		
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND COGBM.Id=1 
	WHERE
		(FS1.IsOptional=1)
		AND ((OM.OrgGroupId) = @rOrgGroupId OR (@rOrgGroupId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
		--AND(BM.IsActive =1)


CREATE TABLE #tempRClassWise(    
    PaidAmount DECIMAL(12,2),
	FeeSetupId int,
	SourceId BIGINT
)
INSERT INTO #tempRClassWise
SELECT
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
	    INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA1.OrgId
		
	WHERE		
		(R.SourceTypeId = 2001)
		AND (OM.OrgGroupId = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND(BM.IsActive =1) 
		AND((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate 
		
	GROUP BY FeeSetupId,R.SourceId 

INSERT INTO #tempPaidDetailsClassWise
SELECT 
		 ISNULL(SA.AcademicId,0) AS AcademicId,
		 ISNULL(SA.OrgId,0) AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 ISNULL(SA.ClassId,0)AS ClassId,
		 ISNULL(SA.ClassName,'') AS ClassName,
		 SUM(ISNULL(TR.PaidAmount,0)) AS PaidAmount,
		 SUM(ISNULL(TFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TR.PaidAmount,0.00))AS PendingAmount
		
	FROM 		
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempFSClassWise TFS ON TFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempRClassWise TR ON TR.FeeSetupId = TFS.Id AND SA.AcademicId = TR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
	WHERE
		(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
	GROUP by SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName,SA.AcademicId
	--HAVING SUM(ISNULL(TR.PaidAmount,0)) > 0 
	--AND SUM(ISNULL(TFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TR.PaidAmount,0.00)) >0
	IF(@rCount = 1)
		BEGIN
			SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount,COUNT(T.PaidAmount)AS StudentCount
			FROM #tempPaidDetailsClassWise T
			WHERE T.PaidAmount > 0
			GROUP BY T.OrgGroupId,T.ClassName,T.ClassId,T.OrgGroupName
			HAVING ISNULL(SUM(T.PaidAmount),0) > 0
			ORDER BY T.ClassId
			
		END
	IF(@rCount = 2)
		BEGIN
			SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS UnPaidAmount,COUNT(T.PendingAmount)AS StudentCount
			FROM #tempPaidDetailsClassWise T
				WHERE T.PendingAmount > 0
			GROUP BY T.OrgGroupId,T.ClassName,T.ClassId,T.OrgGroupName
			HAVING ISNULL(SUM(T.PendingAmount),0) > 0
			ORDER BY T.ClassId
		END
		DROP TABLE #tempPaidDetailsClassWise
	DROP TABLE #tempFSClassWise
	DROP TABLE #tempRClassWise
	END
ELSE IF(@rType ='FeeStatusPaid&UnpaidDetils')
BEGIN 
CREATE TABLE #tempPaidDetails(
	SourceId bigint,
	OrgGroupId int,
	ClassName nvarchar(50),
	DivisionId int,
	DivisionName nvarchar(50),
	Code nvarchar(20),
	Name nvarchar(200),
	ParentContactNo nvarchar(50),
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2),
	ClassOrderIndex int,
	DivisionOrder int,
	RollNo int
)
CREATE TABLE #tempFS(
    Id int,
    Amount DECIMAL(12,2),
	AcademicId BIGINT
)
INSERT INTO #tempFS
SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		SA1.Id AS AcademicId
	FROM 
		sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId		
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA1.OrgId		
		
	WHERE 
		(FS1.IsOptional=0) AND  COGBM.Id=@rCommonOrgGroupBatchId 
		AND((OM.OrgGroupId) = @rOrgGroupId OR (@rOrgGroupId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
		--AND(BM.IsActive =1) 
UNION ALL				
SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		SA1.Id As AcademicId
	FROM 
	    sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA1.OrgId
		
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND COGBM.Id=@rCommonOrgGroupBatchId 
	WHERE
		(FS1.IsOptional=1)
		AND ((OM.OrgGroupId) = @rOrgGroupId OR (@rOrgGroupId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
		--AND(BM.IsActive =1)


CREATE TABLE #tempR(    
    PaidAmount DECIMAL(12,2),
	FeeSetupId int,
	SourceId BIGINT
)
INSERT INTO #tempR
SELECT
         
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
	    INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA1.OrgId
		
	WHERE		
		(R.SourceTypeId = 2001)
		AND (OM.OrgGroupId = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		And O.IsObsolete = 0
		--AND(BM.IsActive =1) 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate 
		
	GROUP BY FeeSetupId,R.SourceId 

INSERT INTO #tempPaidDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		ISNULL(O.Id,0) AS OrgGroupId,
		ISNULL(SA.ClassName,'') AS ClassName,
		ISNULL(SA.DivisionId,0) AS DivisionId,
		ISNULL(SA.DivisionName,'') AS DivisionName,
		ISNULL(SA.Code,'') As Code,
		ISNULL(SA.Name,'') AS Name,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		SUM(ISNULL(TR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TR.PaidAmount,0.00))AS PendingAmount,
		 SA.ClassOrderIndex,  
		 SA.DivisionOrder,
		 SA.RollNo 
	FROM 		
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempFS TFS ON TFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempR TR ON TR.FeeSetupId = TFS.Id AND SA.AcademicId = TR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND((SA.ClassId = @rClassId)OR(@rClassId=0))
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
	And O.IsObsolete = 0
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.Code,SA.Name,SC.ParentContactNo,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
	--HAVING SUM(ISNULL(TR.PaidAmount,0)) > 0 
	--AND SUM(ISNULL(TFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TR.PaidAmount,0.00)) >0

	IF(@rCount = 1)
		BEGIN
			SELECT T.SourceId, T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,T.DivisionId,
				T.ParentContactNo AS ParentContactNo,T.PaidAmount AS PaidAmount,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
			FROM #tempPaidDetails T
			WHERE T.PaidAmount > 0
			--WHERE PendingAmount  = 0
			GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.Name,T.ParentContactNo,T.PaidAmount,T.Code,T.ClassOrderIndex,T.DivisionOrder,T.RollNo,T.DivisionId,T.SourceId
			HAVING T.PaidAmount > 0
			ORDER BY T.OrgGroupId,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
			
		END
	IF(@rCount = 2)
		BEGIN
			SELECT T.SourceId,T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,T.DivisionId,
				T.ParentContactNo AS ParentContactNo,T.PendingAmount AS UnPaidAmount,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
			FROM #tempPaidDetails T
			WHERE T.PendingAmount > 0
			--WHERE PendingAmount  != 0
			GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.Name,T.ParentContactNo,T.PendingAmount,T.Code,T.ClassOrderIndex,T.DivisionOrder,T.RollNo,T.DivisionId,T.SourceId
			HAVING T.PendingAmount > 0
			ORDER BY T.PendingAmount DESC
		END
	
	DROP TABLE #tempPaidDetails
	DROP TABLE #tempFS
	DROP TABLE #tempR
	

END

ELSE IF(@rType ='FeeStatusTotalHeadwiseAmount')
BEGIN 
	IF(@rSyncDate =1)
		BEGIN
		DELETE  sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			CREATE TABLE #tempTotalPaidDetailsSync (
	FeeHeadId bigint,
	FeeHeadName nvarchar(200),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	ReceiptBookId bigint,
	RecepitTitle nvarchar(100),
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2),
	OrderIndex int
	)
CREATE TABLE #tempHFSSync (
    Id INT,
    Amount DECIMAL(12,2),
    FeeHeadId INT,
    CollectionGroupId INT,
    ReceiptBookId INT,
    AcademicId BIGINT
    
)	
INSERT INTO #tempHFSSync	
SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		 SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		 INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	     INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	     INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	     INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	     INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId		 
		 INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	     
		 
	WHERE 
	     (FS1.IsOptional=0) --AND BM.IsActive=1 --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
	     AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		 And O.IsObsolete = 0
	      
				--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
UNION ALL
				
SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		 SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	WHERE
				
		(FS1.IsOptional=1) --AND BM.IsActive=1 --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
CREATE TABLE #tempHRSync (
    PaidAmount DECIMAL(12,2),
    FeeSetupId INT,
    SourceId BIGINT
 
)
INSERT INTO #tempHRSync	
SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId ,R.SourceId
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	  
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId
INSERT INTO #tempTotalPaidDetailsSync
SELECT 
		ISNULL(FHM.Id,0) AS FeeHeadId,
		ISNULL(FHM.code,'') AS FeeHeadName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Id,'')  AS ReceiptBookId,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		SUM(ISNULL(THR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(THFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(THR.PaidAmount,0.00))AS PendingAmount,
		FHM.OrderIndex
	FROM 
		sStudent.tAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempHFSSync THFS ON THFS.AcademicId=SA.Id
		
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=THFS.Id AND FA.SourceId=SA.Id
		LEFT JOIN #tempHRSync THR ON THR.FeeSetupId = THFS.Id AND SA.Id = THR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)		
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId		
	    INNER JOIN sFee.tReceiptBookMaster RBM ON THFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON THFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=THFS.FeeHeadId	
	WHERE
	 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(BM.IsActive =1) --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
	And O.IsObsolete = 0
	GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Code,RBM.Title,RBM.Id,FHM.OrderIndex

	INSERT INTO sFee.tTempTotalPaidDetails
	SELECT @rOrgGroupId,T.FeeHeadId,ISNULL(T.FeeHeadName,'') AS FeeHeadName,T.CollectionGroupId,
				ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
				ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
				ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
				T.OrderIndex,@rCommonOrgGroupBatchId,GETDATE() from #tempTotalPaidDetailsSync T
	GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId,T.OrderIndex
	ORDER BY T.OrderIndex
	SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))		

		--New Temp Table Create-------------
	CREATE TABLE #tempTotalStudentCountSync (
	AcademicId bigint,
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	EndDate date,
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2)
	)
	
	--Test
	
   CREATE TABLE #tempHFSSync1(
       Id INT,
       Amount DECIMAL(12,2),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT
	)
	INSERT INTO #tempHFSSync1
	SELECT 
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.FeeHeadId,
			FS1.CollectionGroupId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
			INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 	        
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
			(FS1.IsOptional=0) --AND BM.IsActive=1
			AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
			And O.IsObsolete = 0
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			UNION ALL
				
	SELECT 
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.FeeHeadId,
			FS1.CollectionGroupId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		    INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	        INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		    INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
		    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			    
		    INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
		    AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
		   (FS1.IsOptional=1) --AND BM.IsActive=1 --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
		    AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			And O.IsObsolete = 0

	CREATE TABLE #tempHRSync1(
	     PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT     
	)
	
	INSERT INTO #tempHRSync1 
	SELECT 
			ISNULL(SUM(RD.Amount),0) AS PaidAmount,
			RD.FeeSetupId ,
			R.SourceId
	   FROM
			sFee.tReceipt R 
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
		WHERE		
			(R.SourceTypeId = 2001)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND (R.IsObsolete = 0) --AND BM.IsActive=1 
			AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
			And O.IsObsolete = 0
			--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
		GROUP BY FeeSetupId,R.SourceId
	INSERT INTO #tempTotalStudentCountSync
	SELECT 
			ISNULL(SA.Id,0) AS AcademicId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Code,'') AS CollectionGroup,
			ISNULL(RBM.Title,'')  AS ReceiptTitle,
			ISNULL(RBM.Id,0) As ReceiptBookId,
			(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
			INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
			WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			 ORDER BY ReceiptDate DESC) EndDate,
			SUM(ISNULL(HR1.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(HFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(HR1.PaidAmount,0.00))AS PendingAmount
	FROM 
		sStudent.tAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 
		INNER JOIN #tempHFSSync1 HFS1 ON HFS1.AcademicId=SA.Id
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=HFS1.Id AND FA.SourceId=SA.Id
		LEFT JOIN #tempHRSync1 HR1 ON HR1.FeeSetupId = HFS1.Id AND SA.Id = HR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		INNER JOIN sFee.tReceiptBookMaster RBM ON HFS1.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON HFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=HFS1.FeeHeadId	
	WHERE
	 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
	 And O.IsObsolete = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(BM.IsActive =1) 
	AND COGBM.Id=@rCommonOrgGroupBatchId 
	GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	
	INSERT INTO sFee.tTempTotalStudentCount
			SELECT @rOrgGroupId,E.CollectionGroupId,E.CollectionGroup AS CollectionGroup,E.ReceiptBookId AS ReceiptId,E.ReceiptCollection AS ReceiptCollection,
			ISNULL(E.EndDate,'1900-01-01')AS EndDate,
			--E.EndDate AS EndDate,
			SUM(E.TotalStudentCount) AS TotalStudentCount,SUM(E.PaidStudentCount) AS PaidStudentCount,SUM(E.PendingStudentCount) AS PendingStudentCount,@rCommonOrgGroupBatchId,GETDATE() FROM (
			SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(T.CollectionGroup,'') As CollectionGroup,
				ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,T.CollectionGroupId AS CollectionGroupId,
				ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate from #tempTotalStudentCountSync T
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM #tempTotalStudentCountSync --CollectionGroupId,CollectionGroup,
						WHERE PendingAmount  = 0
						GROUP BY CollectionGroupId,ReceiptBookId
					) A ON A.CollectionGroupId = T.CollectionGroupId
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM #tempTotalStudentCountSync
						WHERE PendingAmount !=0
						GROUP BY CollectionGroupId,ReceiptBookId
					)B ON B.CollectionGroupId = T.CollectionGroupId 
					GROUP BY T.CollectionGroupId,T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
					)E
					GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate,E.CollectionGroupId
		 SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	


		-------------Create a New Temp Table For Pending date-----------------
	CREATE TABLE #tempPendingCountSync(
	AcademicId bigint,
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	EndDate date,
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2)
	)
	CREATE TABLE #tempHFSSync2(
	     Id INT,
	     Amount DECIMAL(12,2),
	     FeeHeadId INT,
	     CollectionGroupId INT,
	     ReceiptBookId INT,
	     AcademicId BIGINT
	)
	INSERT INTO #tempHFSSync2
	SELECT 
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.FeeHeadId,
			FS1.CollectionGroupId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId							
			INNER JOIN sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 			
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
			(FS1.IsOptional=0) --AND BM.IsActive=1 
			AND COGBM.Id=@rCommonOrgGroupBatchId 
			And O.IsObsolete = 0
			--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.FeeHeadId,
			FS1.CollectionGroupId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		    INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	        INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		    INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
		    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			    
		    INNER JOIN sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
		    AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId --AND BM.IsActive=1
	WHERE
				
		    (FS1.IsOptional=1) AND COGBM.Id=@rCommonOrgGroupBatchId 
			And O.IsObsolete = 0
			--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate   
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	CREATE TABLE #tempHRSync2(
	       PaidAmount DECIMAL(12,2),
	       FeeSetupId INT,
	       SourceId BIGINT
	       
	)
	INSERT INTO #tempHRSync2
	SELECT 
			ISNULL(SUM(RD.Amount),0) AS PaidAmount,
			RD.FeeSetupId ,
			R.SourceId
		FROM
		    sFee.tReceipt R 
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
		    INNER JOIN sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
	    WHERE		
			(R.SourceTypeId = 2001)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND (R.IsObsolete = 0) --AND BM.IsActive=1 
			AND COGBM.Id=@rCommonOrgGroupBatchId 
			And O.IsObsolete = 0
			--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
			--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
			GROUP BY FeeSetupId,R.SourceId
	
	
	INSERT INTO #tempPendingCountSync
	SELECT 
			ISNULL(SA.Id,0) AS AcademicId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Code,'') AS CollectionGroup,
			ISNULL(RBM.Title,'')  AS ReceiptTitle,
			ISNULL(RBM.Id,0) As ReceiptBookId,
				(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id 
			
			INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
			
	WHERE  
			(LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
			AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			And O.IsObsolete = 0
	ORDER BY ReceiptDate DESC) EndDate,
			SUM(ISNULL(HR2.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(HFS2.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(HR2.PaidAmount,0.00))AS PendingAmount
	FROM 
		sStudent.tAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 
		INNER JOIN #tempHFSSync2 HFS2 ON HFS2.AcademicId=SA.Id
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=HFS2.Id AND FA.SourceId=SA.Id
		LEFT JOIN #tempHRSync2 HR2 ON HR2.FeeSetupId = HFS2.Id AND SA.Id = HR2.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		
		--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		INNER JOIN sFee.tReceiptBookMaster RBM ON HFS2.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON HFS2.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=HFS2.FeeHeadId	
	WHERE
	 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
	 And O.IsObsolete = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(BM.IsActive =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
	GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	INSERT INTO sFee.tTempPendingCount
	SELECT @rOrgGroupId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,T.ReceiptBookId AS ReceiptId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount,@rCommonOrgGroupBatchId,GETDATE()
	FROM   #tempPendingCountSync T
	WHERE PendingAmount !=0
	 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()- @rDays) AND CONVERT(DATE,GETDATE())
	 GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup
	 SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	 
	 
	
	DROP TABLE #tempTotalPaidDetailsSync
	DROP TABLE #tempHFSSync
	DROP TABLE  #tempHRSync
	DROP TABLE #tempTotalStudentCountSync
	DROP TABLE #tempHFSSync1
	DROP TABLE #tempHRSync1
	DROP TABLE #tempPendingCountSync
	DROP TABLE #tempHFSSync2
	DROP TABLE #tempHRSync2
		END
	ELSE
		BEGIN
		IF  Exists(select 1 from sFee.tTempTotalPaidDetails where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
			BEGIN
	
				SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN

			DELETE  sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					CREATE TABLE #tempTotalPaidDetails (
				FeeHeadId bigint,
				FeeHeadName nvarchar(200),
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				ReceiptBookId bigint,
				RecepitTitle nvarchar(100),
				PaidAmount DECIMAL(12,2),
				PendingAmount DECIMAL(12,2),
				OrderIndex int
				)
			CREATE TABLE #tempHFS (
				Id INT,
				Amount DECIMAL(12,2),
				FeeHeadId INT,
				CollectionGroupId INT,
				ReceiptBookId INT,
				AcademicId BIGINT
    
			)	
			INSERT INTO #tempHFS	
			SELECT 
					 FS1.Id,
					 ISNULL(FS1.Amount,0)AS Amount,
					 FM.FeeHeadId,
					 FS1.CollectionGroupId,
					 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					 SA1.Id AS AcademicId
				FROM sFee.tFeeSetup FS1
					 INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
					 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					 INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
					 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId		 
					 INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	     
		 
				WHERE 
					 (FS1.IsOptional=0) --AND BM.IsActive=1 --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
					 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
	      And O.IsObsolete = 0
							--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
							--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
							--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
							--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			UNION ALL
				
			SELECT 
					 FS1.Id,
					 ISNULL(FS1.Amount,0)AS Amount,
					 FM.FeeHeadId,
					 FS1.CollectionGroupId,
					 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					 SA1.Id AS AcademicId
				FROM sFee.tFeeSetup FS1
					INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
					INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
					INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
					AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
				
					(FS1.IsOptional=1) --AND BM.IsActive=1 --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
					AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
					And O.IsObsolete = 0
			CREATE TABLE #tempHR (
				PaidAmount DECIMAL(12,2),
				FeeSetupId INT,
				SourceId BIGINT
 
			)
			INSERT INTO #tempHR	
			SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,
					RD.FeeSetupId ,R.SourceId
				FROM
					sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	  
				WHERE		
					(R.SourceTypeId = 2001)
					--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					AND (R.IsObsolete = 0) --AND BM.IsActive=1 
					AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
					And O.IsObsolete = 0
					--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
					--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
				GROUP BY FeeSetupId,R.SourceId
			INSERT INTO #tempTotalPaidDetails
			SELECT 
					ISNULL(FHM.Id,0) AS FeeHeadId,
					ISNULL(FHM.code,'') AS FeeHeadName,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Id,'')  AS ReceiptBookId,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					SUM(ISNULL(THR.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(THFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(THR.PaidAmount,0.00))AS PendingAmount,
					FHM.OrderIndex
				FROM 
					sStudent.tAcademic SA
					LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
					INNER JOIN #tempHFS THFS ON THFS.AcademicId=SA.Id
		
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=THFS.Id AND FA.SourceId=SA.Id
					LEFT JOIN #tempHR THR ON THR.FeeSetupId = THFS.Id AND SA.Id = THR.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)		
					--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId		
					INNER JOIN sFee.tReceiptBookMaster RBM ON THFS.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM ON THFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=THFS.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				And O.IsObsolete = 0
				GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Code,RBM.Title,RBM.Id,FHM.OrderIndex

				INSERT INTO sFee.tTempTotalPaidDetails
				SELECT @rOrgGroupId,T.FeeHeadId,ISNULL(T.FeeHeadName,'') AS FeeHeadName,T.CollectionGroupId,
				ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
				ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
				ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
				T.OrderIndex,@rCommonOrgGroupBatchId,GETDATE()from #tempTotalPaidDetails T
				GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId,T.OrderIndex
				ORDER BY T.OrderIndex
			SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	

					--New Temp Table Create-------------
				CREATE TABLE #tempTotalStudentCount (
				AcademicId bigint,
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				RecepitTitle nvarchar(100),
				ReceiptBookId bigint,
				EndDate date,
				PaidAmount DECIMAL(12,2),
				PendingAmount DECIMAL(12,2)
				)
	
				--Test
	
			   CREATE TABLE #tempHFS1(
				   Id INT,
				   Amount DECIMAL(12,2),
				   FeeHeadId INT,
				   CollectionGroupId INT,
				   ReceiptBookId INT,
				   AcademicId BIGINT
				)
				INSERT INTO #tempHFS1
				SELECT 
						FS1.Id,
						ISNULL(FS1.Amount,0)AS Amount,
						FM.FeeHeadId,
						FS1.CollectionGroupId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						SA1.Id AS AcademicId
				FROM sFee.tFeeSetup FS1
						INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
						INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 	        
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
						(FS1.IsOptional=0) --AND BM.IsActive=1
						AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
						And O.IsObsolete = 0
						--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
						--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
						--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
						--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
						--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
						UNION ALL
				
				SELECT 
						FS1.Id,
						ISNULL(FS1.Amount,0)AS Amount,
						FM.FeeHeadId,
						FS1.CollectionGroupId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						SA1.Id AS AcademicId
				FROM sFee.tFeeSetup FS1
						INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			    
						INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
						AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
				
					   (FS1.IsOptional=1) 
					   --AND BM.IsActive=1 --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
						AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
						And O.IsObsolete = 0

				CREATE TABLE #tempHR1(
					 PaidAmount DECIMAL(12,2),
					 FeeSetupId INT,
					 SourceId BIGINT     
				)
	
				INSERT INTO #tempHR1 
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,
						RD.FeeSetupId ,
						R.SourceId
				   FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
					WHERE		
						(R.SourceTypeId = 2001)
						--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
						AND (R.IsObsolete = 0) --AND BM.IsActive=1 
						AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
						And O.IsObsolete = 0
						--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
						--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
				INSERT INTO #tempTotalStudentCount
				SELECT 
						ISNULL(SA.Id,0) AS AcademicId,
						ISNULL(CGM.Id,0) AS CollectionGroupId,
						ISNULL(CGM.Code,'') AS CollectionGroup,
						ISNULL(RBM.Title,'')  AS ReceiptTitle,
						ISNULL(RBM.Id,0) As ReceiptBookId,
						(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
						INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
						INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
						WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
						 ORDER BY ReceiptDate DESC) EndDate,
						SUM(ISNULL(HR1.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(HFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(HR1.PaidAmount,0.00))AS PendingAmount
				FROM 
					sStudent.tAcademic SA
					LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 
					INNER JOIN #tempHFS1 HFS1 ON HFS1.AcademicId=SA.Id
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=HFS1.Id AND FA.SourceId=SA.Id
					LEFT JOIN #tempHR1 HR1 ON HR1.FeeSetupId = HFS1.Id AND SA.Id = HR1.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
					--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
					INNER JOIN sFee.tReceiptBookMaster RBM ON HFS1.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM ON HFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=HFS1.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				 And O.IsObsolete = 0
				-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	
			INSERT INTO sFee.tTempTotalStudentCount
			SELECT @rOrgGroupId,E.CollectionGroupId,E.CollectionGroup AS CollectionGroup,E.ReceiptBookId AS ReceiptId,E.ReceiptCollection AS ReceiptCollection,
			ISNULL(E.EndDate,'1900-01-01')AS EndDate,
			--E.EndDate AS EndDate,
			SUM(E.TotalStudentCount) AS TotalStudentCount,SUM(E.PaidStudentCount) AS PaidStudentCount,SUM(E.PendingStudentCount) AS PendingStudentCount,@rCommonOrgGroupBatchId,GETDATE() FROM (
			SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(T.CollectionGroup,'') As CollectionGroup,
				ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,T.CollectionGroupId AS CollectionGroupId,
				ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate from #tempTotalStudentCount T
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM #tempTotalStudentCount --CollectionGroupId,CollectionGroup,
						WHERE PendingAmount  = 0
						GROUP BY CollectionGroupId,ReceiptBookId
					) A ON A.CollectionGroupId = T.CollectionGroupId
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM #tempTotalStudentCount
						WHERE PendingAmount !=0
						GROUP BY CollectionGroupId,ReceiptBookId
					)B ON B.CollectionGroupId = T.CollectionGroupId 
					GROUP BY T.CollectionGroupId,T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
					)E
					GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate,E.CollectionGroupId
				 SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))


					-------------Create a New Temp Table For Pending date-----------------
				CREATE TABLE #tempPendingCount(
				AcademicId bigint,
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				RecepitTitle nvarchar(100),
				ReceiptBookId bigint,
				EndDate date,
				PaidAmount DECIMAL(12,2),
				PendingAmount DECIMAL(12,2)
				)
				CREATE TABLE #tempHFS2(
					 Id INT,
					 Amount DECIMAL(12,2),
					 FeeHeadId INT,
					 CollectionGroupId INT,
					 ReceiptBookId INT,
					 AcademicId BIGINT
				)
				INSERT INTO #tempHFS2
				SELECT 
						FS1.Id,
						ISNULL(FS1.Amount,0)AS Amount,
						FM.FeeHeadId,
						FS1.CollectionGroupId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						SA1.Id AS AcademicId
				FROM sFee.tFeeSetup FS1
						INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId							
						INNER JOIN sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 			
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
						(FS1.IsOptional=0) --AND BM.IsActive=1 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						And O.IsObsolete = 0
						--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
						--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
						--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
						--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
						--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
				SELECT 
						FS1.Id,
						ISNULL(FS1.Amount,0)AS Amount,
						FM.FeeHeadId,
						FS1.CollectionGroupId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						SA1.Id AS AcademicId
				FROM sFee.tFeeSetup FS1
						INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			    
						INNER JOIN sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
						AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId --AND BM.IsActive=1
				WHERE
				
						(FS1.IsOptional=1) AND COGBM.Id=@rCommonOrgGroupBatchId	
						And O.IsObsolete = 0
				CREATE TABLE #tempHR2(
					   PaidAmount DECIMAL(12,2),
					   FeeSetupId INT,
					   SourceId BIGINT
	       
				)
				INSERT INTO #tempHR2
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,
						RD.FeeSetupId ,
						R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
						INNER JOIN sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
					WHERE		
						(R.SourceTypeId = 2001)
						--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
						AND (R.IsObsolete = 0) --AND BM.IsActive=1 
						AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
						--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
						GROUP BY FeeSetupId,R.SourceId	
				INSERT INTO #tempPendingCount
				SELECT 
						ISNULL(SA.Id,0) AS AcademicId,
						ISNULL(CGM.Id,0) AS CollectionGroupId,
						ISNULL(CGM.Code,'') AS CollectionGroup,
						ISNULL(RBM.Title,'')  AS ReceiptTitle,
						ISNULL(RBM.Id,0) As ReceiptBookId,
							(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
						INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id 
			
						INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
			
				WHERE  
						(LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
						AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
						And O.IsObsolete = 0
				ORDER BY ReceiptDate DESC) EndDate,
						SUM(ISNULL(HR2.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(HFS2.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(HR2.PaidAmount,0.00))AS PendingAmount
				FROM 
					sStudent.tAcademic SA
					 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 
					INNER JOIN #tempHFS2 HFS2 ON HFS2.AcademicId=SA.Id
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=HFS2.Id AND FA.SourceId=SA.Id
					LEFT JOIN #tempHR2 HR2 ON HR2.FeeSetupId = HFS2.Id AND SA.Id = HR2.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
					INNER JOIN sFee.tReceiptBookMaster RBM ON HFS2.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM ON HFS2.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=HFS2.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
				And O.IsObsolete = 0
				GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
		
		INSERT INTO sFee.tTempPendingCount
				SELECT @rOrgGroupId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,T.ReceiptBookId AS ReceiptId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount,@rCommonOrgGroupBatchId,GETDATE()
				FROM   #tempPendingCount T
				WHERE PendingAmount !=0
				 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()- @rDays) AND CONVERT(DATE,GETDATE())
				 GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup
		SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	
				DROP TABLE #tempTotalPaidDetails
				DROP TABLE #tempHFS
				DROP TABLE  #tempHR
				DROP TABLE #tempTotalStudentCount
				DROP TABLE #tempHFS1
				DROP TABLE #tempHR1
				DROP TABLE #tempPendingCount
				DROP TABLE #tempHFS2
				DROP TABLE #tempHR2
			END

			

		END
	 
END

ELSE IF(@rType ='FeeStatusPaidSubPartAmount')
BEGIN 
	CREATE TABLE #tempPaidSubPart (
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(50),
	ClassId bigint,
	ClassName nvarchar(50),
	--DivisionId bigint,
	--DivisionName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2),
	ClassOrderIndex int,
	MonthName nvarchar(15)
	--,DivisionOrder int
	)
   
    CREATE TABLE #tempPFS (
       Id INT,
       Amount DECIMAL(12,2),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    
    INSERT INTO #tempPFS	
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
	   (FS1.IsOptional=0)
	   --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate   
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		And O.IsObsolete = 0
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))


     CREATE TABLE #tempPR (
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPR	
     SELECT 
		  ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 FROM
		  sFee.tReceipt R 
		  INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		  INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		  INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		  INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
		  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		  INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		  
		  INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		 
	WHERE		
		  (R.SourceTypeId = 2001)
		   AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		   AND (R.IsObsolete = 0) --AND BM.IsActive=1 
		   AND COGBM.Id=@rCommonOrgGroupBatchId 
		   And O.IsObsolete = 0
		   --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
		   --AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
 

IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPaidSubPart
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 --O.Id AS OrgGroupId,
		 --O.Title As OrgGroupName,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		 --SA.DivisionId AS DivisionId,
		 --SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR.PaidAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex,
		TPR.ReceiptDate
		--,SA.DivisionOrder
		 
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN #tempPFS TPFS ON TPFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=TPFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPR TPR ON TPR.FeeSetupId = TPFS.Id AND SA.AcademicId = TPR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN sFee.tReceiptBookMaster RBM ON TPFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON TPFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=TPFS.FeeHeadId	    	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
	And O.IsObsolete = 0
		GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.ClassId,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex,TPR.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex,DATENAME(month,T.MonthName)MonthName from #tempPaidSubPart T
		WHERE T.PaidAmount > 0
		group by T.OrgGroupId,T.PaidAmount,T.ClassName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex,T.OrgGroupName,DATENAME(month,T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		ORDER BY T.ClassOrderIndex
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempPFS1 (
       Id INT,
       Amount DECIMAL(12,2),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    INSERT INTO #tempPFS1
    SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		 SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		 INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	     INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	     INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	     INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	     INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			 
		 INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		 --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		 AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		 And O.IsObsolete = 0
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		 --AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		
	WHERE
				
		(FS1.IsOptional=1) AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
    
    CREATE TABLE #tempPR1(
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPR1
     SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		

	WHERE		
		(R.SourceTypeId = 2001)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		AND (R.IsObsolete = 0) 
		And O.IsObsolete = 0
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate  
   
	
	INSERT INTO #tempPaidSubPart
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 --O.Id AS OrgGroupId,
		 --O.Title As OrgGroupName,
		 SA.OrgId AS OrgGroupId,SA.OrganizationName As OrgGroupName,
		 SA.ClassId As ClassId,
		 SA.ClassName AS ClassName,
		 --SA.DivisionId AS DivisionId,
		 --SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR1.PaidAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex,TPR1.ReceiptDate
		--,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPFS1 TPFS1 ON TPFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TPFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPR1 TPR1 ON TPR1.FeeSetupId = TPFS1.Id AND SA.AcademicId = TPR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TPFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TPFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TPFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	And O.IsObsolete = 0
		GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.ClassId,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex,TPR1.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount,COUNT(T.AcademicId) As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex,DATENAME(month,T.MonthName)MonthName from #tempPaidSubPart T
		WHERE T.PaidAmount > 0
		group by T.OrgGroupId,T.ClassName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex,T.OrgGroupName,DATENAME(month,T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		ORDER BY T.ClassOrderIndex
	END
	
	DROP TABLE #tempPaidSubPart
	DROP TABLE #tempPFS
	DROP TABLE #tempPR
	DROP TABLE #tempPFS1
	DROP TABLE #tempPR1
	
END

ELSE IF(@rType ='FeeStatusPaidSubPartAmountMonthWise')
BEGIN 
	CREATE TABLE #tempPaidSubPartMonthWise (
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2),
	MonthName nvarchar(15),
	)
   
    CREATE TABLE #tempPFSMonthWise (
       Id INT,
       Amount DECIMAL(12,2),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    
    INSERT INTO #tempPFSMonthWise	
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
	   (FS1.IsOptional=0)
	   --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate   
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))


     CREATE TABLE #tempPRMonthWise (
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPRMonthWise	
     SELECT 
		  ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 FROM
		  sFee.tReceipt R 
		  INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		  INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		  INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		  INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
		  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		  INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		  
		  INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		 
	WHERE		
		  (R.SourceTypeId = 2001)
		   AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		   AND (R.IsObsolete = 0) --AND BM.IsActive=1 
		   AND COGBM.Id=@rCommonOrgGroupBatchId 
		   And O.IsObsolete = 0
		   --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
		   --AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
 

IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPaidSubPartMonthWise
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR.PaidAmount,0.00))AS PendingAmount,
		TPR.ReceiptDate		 
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN #tempPFSMonthWise TPFS ON TPFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=TPFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise TPR ON TPR.FeeSetupId = TPFS.Id AND SA.AcademicId = TPR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN sFee.tReceiptBookMaster RBM ON TPFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON TPFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=TPFS.FeeHeadId	    	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	And O.IsObsolete = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.PaidAmount,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempPFSMonthWise1 (
       Id INT,
       Amount DECIMAL(12,2),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    INSERT INTO #tempPFSMonthWise1
    SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		 SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		 INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	     INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	     INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	     INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	     INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			 
		 INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		 --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		 AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		 And O.IsObsolete = 0
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		 --AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		
	WHERE
				
		(FS1.IsOptional=1) AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
    
    CREATE TABLE #tempPRMonthWise1(
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPRMonthWise1
     SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		

	WHERE		
		(R.SourceTypeId = 2001)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		AND (R.IsObsolete = 0) 
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate  
   
	
	INSERT INTO #tempPaidSubPartMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,		
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR1.PaidAmount,0.00))AS PendingAmount,
		TPR1.ReceiptDate
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPFSMonthWise1 TPFS1 ON TPFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TPFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise1 TPR1 ON TPR1.FeeSetupId = TPFS1.Id AND SA.AcademicId = TPR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TPFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TPFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TPFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	And O.IsObsolete = 0
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR1.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount,COUNT(T.AcademicId) As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END
	
	DROP TABLE #tempPaidSubPartMonthWise
	DROP TABLE #tempPFSMonthWise
	DROP TABLE #tempPRMonthWise
	DROP TABLE #tempPFSMonthWise1
	DROP TABLE #tempPRMonthWise1
	
END

ELSE IF(@rType ='FeeStatusPendingSubPartAmount')
BEGIN 
CREATE TABLE #tempPendingSubPart(
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(50),
	ClassId bigint ,
	ClassName nvarchar(50),
	--DivisionId bigint,
	--DivisionName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2),
	ClassOrderIndex int
	--,DivisionOrder int
	)

   CREATE TABLE #tempSFS(
       Id INT,
       Amount DECIMAL(12,2),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT
    )
    INSERT INTO #tempSFS
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0)
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) 
		And O.IsObsolete = 0
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId --AND BM.IsActive=1 --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
		
    WHERE
				
	   (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		And O.IsObsolete = 0
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 

    
      CREATE TABLE #tempSR(
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT
     )
     INSERT INTO #tempSR
     SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
	  FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    

	  WHERE		
		(R.SourceTypeId = 2001)
		 AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		 AND COGBM.Id=@rCommonOrgGroupBatchId 
		 And O.IsObsolete = 0
		 --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		 AND (R.IsObsolete = 0) 
		 --AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	  GROUP BY FeeSetupId,R.SourceId 


IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPendingSubPart
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 --O.Id AS OrgGroupId,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		-- O.Title AS OrgGroupName,
		 SA.ClassId  AS ClassId,
		 SA.ClassName AS ClassName,
		 --SA.DivisionId AS DivisionId,
		 --SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TSR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TSFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TSR.PaidAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex
		--,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA 
		INNER JOIN #tempSFS TSFS ON TSFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TSFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempSR TSR ON TSR.FeeSetupId = TSFS.Id AND SA.AcademicId = TSR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TSFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TSFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TSFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	And O.IsObsolete = 0
		GROUP by SA.OrgId,SA.OrganizationName,SA.ClassId,SA.ClassName,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	
	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,COUNT(T.AcademicId)AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex from #tempPendingSubPart T
		WHERE T.PendingAmount >0
		group by T.OrgGroupId,T.OrgGroupName,T.PaidAmount,T.ClassName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex
		--HAVING ISNULL(SUM(T.PendingAmount),0) > 0
		ORDER BY T.ClassOrderIndex
		
    DROP TABLE #tempPendingSubPart
	DROP TABLE #tempSFS
	DROP TABLE #tempSR
		
		
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempSFS1(
       Id INT,
       Amount DECIMAL(12,2),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT
    )
	INSERT INTO #tempSFS1
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0)
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) 
		And O.IsObsolete = 0
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
	    INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	 
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	WHERE
				
		(FS1.IsOptional=1)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		And O.IsObsolete = 0
		 --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			
	CREATE TABLE #tempSR1(
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT
     )
	INSERT INTO #tempSR1
    SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    

	WHERE		
		(R.SourceTypeId = 2001)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId 	
		 
	
	INSERT INTO #tempPendingSubPart
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 --O.Id AS OrgGroupId,
		 --O.Title As OrgGroupName,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		 --SA.DivisionId AS DivisionId,
		 --SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TSR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TSFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TSR1.PaidAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex  
		--,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempSFS1 TSFS1 ON TSFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TSFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempSR1 TSR1 ON TSR1.FeeSetupId = TSFS1.Id AND SA.AcademicId = TSR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TSFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TSFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TSFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	And O.IsObsolete = 0 
		GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	
	SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount, COUNT(T.AcademicId) AS studentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex from #tempPendingSubPart T
		WHERE T.PendingAmount >0
		GROUP BY T.OrgGroupId,T.ClassName,T.OrgGroupName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex
		--HAVING ISNULL(SUM(T.PendingAmount),0) > 0
		ORDER BY T.ClassOrderIndex	
    DROP TABLE #tempSFS1
	DROP TABLE #tempSR1
		
	END
	
	
	
	
		
	END
  ELSE IF(@rType ='FeeStatusPendingSubPartDetails')
BEGIN 
CREATE TABLE #tempPendingSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2),
RollNo int
)

CREATE TABLE #tempPendingDFS(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

)

INSERT INTO #tempPendingDFS
	 SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
	   (FS1.IsOptional=1) --AND BM.IsActive=1 
	   AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And O.IsObsolete = 0
	   --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
	    --AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
	    --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
		


CREATE TABLE #tempPendingDR(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT
)
INSERT INTO #tempPendingDR
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
	WHERE		
		(R.SourceTypeId = 2001) 
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate     
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId 



IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPendingSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPendingDFS TDFS ON TDFS.AcademicId=SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPendingDR TDR ON TDR.FeeSetupId = TDFS.Id AND SA.AcademicId = TDR.SourceId
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And O.IsObsolete = 0
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPendingSubPartDetails T
		WHERE T.PendingAmount >0
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempPendingDFS1(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT  

    )
    
    INSERT INTO #tempPendingDFS1
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	
CREATE TABLE #tempPendingDR1(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT
)
INSERT INTO #tempPendingDR1
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId 
	
	
	
	insert into #tempPendingSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR1.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPendingDFS1 TDFS1 ON TDFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPendingDR1 TDR1 ON TDR1.FeeSetupId = TDFS1.Id AND SA.AcademicId = TDR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	And O.IsObsolete = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPendingSubPartDetails T
		WHERE T.PendingAmount >0
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.RollNo
	END
	
	DROP TABLE #tempPendingSubPartDetails
	DROP TABLE #tempPendingDFS
	DROP TABLE #tempPendingDR
	DROP TABLE #tempPendingDFS1
	DROP TABLE #tempPendingDR1
	
	
END	
	
ELSE IF(@rType ='FeeStatusTotalSubPartAmount')
BEGIN 
CREATE TABLE #tempTotalSubPart (
AcademicId bigint,
OrgGroupId int,
OrgGroupName nvarchar(50),
ClassId bigint,
ClassName nvarchar(50),
--DivisionId bigint,
--DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2),
ClassOrderIndex int
--,DivisionOrder int
)


CREATE TABLE #tempAFS(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT 

)
INSERT INTO #tempAFS
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	  
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
		(FS1.IsOptional=1)
		And O.IsObsolete = 0
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 


CREATE TABLE #tempAR(
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT
     )
    INSERT INTO #tempAR
		SELECT 
			ISNULL(SUM(RD.Amount),0) AS PaidAmount,
			RD.FeeSetupId,
			R.SourceId
		FROM
			sFee.tReceipt R 
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
		WHERE		
			(R.SourceTypeId = 2001)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND (R.IsObsolete = 0) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			And O.IsObsolete = 0
			--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate  
			--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
		GROUP BY FeeSetupId,R.SourceId  
     


IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempTotalSubPart
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		-- O.Id AS OrgGroupId,
		SA.OrgId AS OrgGroupId,
		SA.OrganizationName AS OrgGroupName,
		 --O.Title AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		 --SA.DivisionId AS DivisionId,
		 --SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TAR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TAFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TAR.PaidAmount,0.00))AS PendingAmount,
	SA.ClassOrderIndex
	--SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN #tempAFS TAFS ON TAFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TAFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempAR TAR ON TAR.FeeSetupId = TAFS.Id AND SA.AcademicId = TAR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TAFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TAFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TAFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	And O.IsObsolete = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
		GROUP by SA.OrgId,SA.OrganizationName, SA.ClassId,SA.ClassName--,SA.DivisionName
		,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex--,SA.DivisionOrder
	
	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from #tempTotalSubPart T
		--WHERE T.PaidAmount > 0  AND T.PendingAmount > 0
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount+PendingAmount) AS PaidCount  from @ltempTotalSubPart 
		--	--WHERE PendingAmount  != 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName,T.CollectionGroupId,T.ReceiptBookId
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		
		
		DROP TABLE #tempAFS
		DROP TABLE #tempAR
		
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempAFS1(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

    )

    INSERT INTO #tempAFS1
		SELECT 
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.FeeHeadId,
			FS1.CollectionGroupId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id As AcademicId
		FROM sFee.tFeeSetup FS1
		    INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		    
		    INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		WHERE 
			(FS1.IsOptional=0) AND   COGBM.Id=@rCommonOrgGroupBatchId 
			And O.IsObsolete = 0
			--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate   
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		UNION ALL
				
		SELECT 
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.FeeHeadId,
			FS1.CollectionGroupId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id As AcademicId
		FROM sFee.tFeeSetup FS1
		    INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	        INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		    INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
		    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		    
		    INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
		    AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		WHERE
				
		    (FS1.IsOptional=1)  AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
    
	CREATE TABLE #tempAR1(
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT
     )
     INSERT INTO #tempAR1		 
		SELECT 
			ISNULL(SUM(RD.Amount),0) AS PaidAmount,
			RD.FeeSetupId,
			R.SourceId
		FROM
			sFee.tReceipt R 
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
	    WHERE		
			(R.SourceTypeId = 2001)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND (R.IsObsolete = 0) AND   COGBM.Id=@rCommonOrgGroupBatchId 
			And O.IsObsolete = 0
			--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
			--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
		GROUP BY FeeSetupId,R.SourceId
		
		
		
	
	INSERT INTO #tempTotalSubPart
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		  SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		 --SA.DivisionId AS DivisionId,
		 --SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TAR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TAFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TAR1.PaidAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex--,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempAFS1 TAFS1 ON TAFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TAFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempAR1 TAR1 ON TAR1.FeeSetupId = TAFS1.Id AND SA.AcademicId = TAR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN sFee.tReceiptBookMaster RBM ON TAFS1.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON TAFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM 	ON FHM.Id=TAFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND  ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
	And O.IsObsolete = 0
		GROUP by SA.OrgId,SA.OrganizationName,SA.ClassId,SA.ClassName--,SA.DivisionName
		,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex--,SA.DivisionOrder

		 
	SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from #tempTotalSubPart T
		--WHERE T.PaidAmount > 0  AND T.PendingAmount > 0
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount+PendingAmount) AS PaidCount  from @ltempTotalSubPart T
		--	--WHERE PendingAmount  != 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		GROUP BY T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName--,T.ClassOrderIndex,T.DivisionOrder
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		--ORDER BY T.ClassOrderIndex,T.DivisionOrder
		
		DROP TABLE #tempAFS1
	    DROP TABLE #tempAR1
		
	END
	
	DROP TABLE #tempTotalSubPart
	
		
	
  END	
  ELSE IF(@rType ='FeeStatusTotalSubPartDetails')
BEGIN 
CREATE TABLE #tempTotalSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2),
RollNo int
)

CREATE TABLE #tempTotalDFS(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

)

INSERT INTO #tempTotalDFS
	 SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
	   (FS1.IsOptional=1) --AND BM.IsActive=1 
	   AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And O.IsObsolete = 0
	   --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
	    --AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
	    --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
		


CREATE TABLE #tempTotalDR(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT
)
INSERT INTO #tempTotalDR
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
	WHERE		
		(R.SourceTypeId = 2001) 
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate     
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId 



IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempTotalSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempTotalDFS TDFS ON TDFS.AcademicId=SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempTotalDR TDR ON TDR.FeeSetupId = TDFS.Id AND SA.AcademicId = TDR.SourceId
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	And O.IsObsolete = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempTotalSubPartDetails T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempTotalDFS1(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT  

    )
    
    INSERT INTO #tempTotalDFS1
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0

		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	
CREATE TABLE #tempTotalDR1(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT
)
INSERT INTO #tempTotalDR1
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId 
	
	
	
	insert into #tempTotalSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR1.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempTotalDFS1 TDFS1 ON TDFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempTotalDR1 TDR1 ON TDR1.FeeSetupId = TDFS1.Id AND SA.AcademicId = TDR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And O.IsObsolete = 0
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempTotalSubPartDetails T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.RollNo
	END
	
	DROP TABLE #tempTotalSubPartDetails
	DROP TABLE #tempTotalDFS
	DROP TABLE #tempTotalDR
	DROP TABLE #tempTotalDFS1
	DROP TABLE #tempTotalDR1
	 
	
END
  
ELSE IF(@rType ='FeeStatusPaidSubPartDetails')
BEGIN 
CREATE TABLE #tempPaidSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2),
RollNo int
)

CREATE TABLE #tempDFS(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

)

INSERT INTO #tempDFS
	 SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
	   (FS1.IsOptional=1) --AND BM.IsActive=1 
	   AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And O.IsObsolete = 0
	   --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
	    --AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
	    --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
		


CREATE TABLE #tempDR(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT
)
INSERT INTO #tempDR
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
	WHERE		
		(R.SourceTypeId = 2001) 
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate     
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId 



IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPaidSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFS TDFS ON TDFS.AcademicId=SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDR TDR ON TDR.FeeSetupId = TDFS.Id AND SA.AcademicId = TDR.SourceId
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And O.IsObsolete = 0
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetails T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempDFS1(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT  

    )
    
    INSERT INTO #tempDFS1
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	
CREATE TABLE #tempDR1(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT
)
INSERT INTO #tempDR1
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId 
	
	
	
	insert into #tempPaidSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR1.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFS1 TDFS1 ON TDFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDR1 TDR1 ON TDR1.FeeSetupId = TDFS1.Id AND SA.AcademicId = TDR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	And O.IsObsolete = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetails T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
	END
	
	DROP TABLE #tempPaidSubPartDetails
	DROP TABLE #tempDFS
	DROP TABLE #tempDR
	DROP TABLE #tempDFS1
	DROP TABLE #tempDR1
	
	
END

ELSE IF(@rType ='FeeStatusPaidSubPartDetailsMonthWise')
BEGIN 
CREATE TABLE #tempPaidSubPartDetailsMonthWise(
AcademicId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2),
RollNo int
)

CREATE TABLE #tempDFSMonthWise(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

)

INSERT INTO #tempDFSMonthWise
	 SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
	   (FS1.IsOptional=1) --AND BM.IsActive=1 
	   AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And O.IsObsolete = 0
	   --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
	    --AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
	    --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
		


CREATE TABLE #tempDRMonthWise(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT,
	   ReceiptDate DATE
)
INSERT INTO #tempDRMonthWise
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
		,R.ReceiptDate
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
	WHERE		
		(R.SourceTypeId = 2001) 
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate     
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate



IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPaidSubPartDetailsMonthWise
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise TDFS ON TDFS.AcademicId=SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDRMonthWise TDR ON TDR.FeeSetupId = TDFS.Id AND SA.AcademicId = TDR.SourceId
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	AND((DATEPART(M, TDR.ReceiptDate)  =@rMonth)OR(@rMonth=0))
	And O.IsObsolete = 0
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetailsMonthWise T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempDFSMonthWise1(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT  

    )
    
    INSERT INTO #tempDFSMonthWise1
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	
CREATE TABLE #tempDRMonthWise1(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT,
	   ReceiptDate DATE
)
INSERT INTO #tempDRMonthWise1
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId,
		R.ReceiptDate
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		And O.IsObsolete = 0
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
	
	
	
	insert into #tempPaidSubPartDetailsMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR1.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise1 TDFS1 ON TDFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDRMonthWise TDR1 ON TDR1.FeeSetupId = TDFS1.Id AND SA.AcademicId = TDR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND((DATEPART(M, TDR1.ReceiptDate)  =@rMonth)OR(@rMonth=0))
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	And O.IsObsolete = 0
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetailsMonthWise T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName
		--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
	END
	
	DROP TABLE #tempPaidSubPartDetailsMonthWise
	DROP TABLE #tempDFSMonthWise
	DROP TABLE #tempDRMonthWise
	DROP TABLE #tempDFSMonthWise1
	DROP TABLE #tempDRMonthWise1
	
	
END

ELSE IF(@rType='ReceiptOrganization')
  BEGIN
	IF(@rSyncDate =1)
		BEGIN
				DELETE  sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				CREATE TABLE #tempReceiptOrganizationSync(
				OrgGroupId int,
				OrgGroupName nvarchar(500),
				ReceiptId bigint,
				TotalReceiptAmount DECIMAL(12,2),
				IsObsolete bit
				)
				INSERT INTO #tempReceiptOrganizationSync
				SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,R.Id AS ReceiptCount,R.TotalReceiptAmount,R.IsObsolete
				FROM  sFee.tReceipt R
				INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
				WHERE R.SourceTypeId = 2001
				AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND (COGBM.Id=@rCommonOrgGroupBatchId )
				And O.IsObsolete = 0 
				AND (R.ReceiptDate between @rFromDate and @rToDate)    
			
			INSERT INTO sFee.tTempReceiptOrganization
				SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate() FROM #tempReceiptOrganizationSync T  
				LEFT JOIN (
				SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganization WHERE IsObsolete = 1
				GROUP BY OrgGroupId,OrgGroupName
				) A ON A.OrgGroupId=t.OrgGroupId
				WHERE IsObsolete = 0
				GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
				ORDER BY OrgGroupId
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId
		END 
	ELSE
		BEGIN
			IF  Exists(select 1 from sFee.tTempReceiptOrganization where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND CONVERT(date,ReceiptDate) =@rFromDate AND CONVERT(date,ReceiptDate) =@rToDate )
			BEGIN
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
	ELSE
			BEGIN 
			DELETE  sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				CREATE TABLE #tempReceiptOrganization(
				OrgGroupId int,
				OrgGroupName nvarchar(500),
				ReceiptId bigint,
				TotalReceiptAmount DECIMAL(12,2),
				IsObsolete bit
				)
				INSERT INTO #tempReceiptOrganization
				SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,R.Id AS ReceiptCount,R.TotalReceiptAmount,R.IsObsolete
				FROM  sFee.tReceipt R
				INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
				WHERE R.SourceTypeId = 2001
				AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND (COGBM.Id=@rCommonOrgGroupBatchId ) 
				AND (R.ReceiptDate between @rFromDate and @rToDate)    
			
				INSERT INTO sFee.tTempReceiptOrganization
				SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate() FROM #tempReceiptOrganization T  
				LEFT JOIN (
				SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganization WHERE IsObsolete = 1
				GROUP BY OrgGroupId,OrgGroupName
				) A ON A.OrgGroupId=t.OrgGroupId
				WHERE IsObsolete = 0
				GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
				ORDER BY OrgGroupId
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		
			END
		END
  END
ELSE IF(@rType='ReceiptBookCollectionGroup')
  BEGIN
	CREATE TABLE #tempReceiptBookCollection (
	RecepitTitle nvarchar(200),
	CollectionTitle nvarchar(200),
	ReceiptCount int,
	ReceiptAmount DECIMAL(12,2),
	ReceiptId bigint,
	CollectionGroupId bigint,
	IsObsolete bit
)

INSERT INTO #tempReceiptBookCollection
 SELECT ISNULL(RBM.Title,'')  AS RecepitTitle ,ISNULL(CGM.Code,'') AS CollectionTitle,
			ISNULL(COUNT(DISTINCT R.Id),0) AS ReceiptCount,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount,
			ISNULL(RBM.Id,0) AS ReceiptId,ISNULL(CGM.Id,0) AS CollectionGroupId,R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					
			INNER JOIN  sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id 			
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId 
			AND FS.AdmissionCategoryId=SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id 
			AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND (R.IsObsolete = 1) 
			--AND(BM.IsActive =1) 
			AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))AND R.ReceiptDate between @rFromDate and @rToDate 
			And O.IsObsolete = 0   
			GROUP BY RBM.Title,CGM.Code,RBM.Id,CGM.Id, R.ReceiptBookId,R.IsObsolete
			
			 
			SELECT  TRC.RecepitTitle +'-'+ TRC.CollectionTitle AS ReceictCollection,TRC.ReceiptId AS ReceiptId,TRC.CollectionGroupId AS CollectionGroupId,TRC.ReceiptCount,SUM(ReceiptAmount) AS ReceiptAmount ,
			ISNULL(A.CancelReceiptCount,0)AS CancelAmount FROM #tempReceiptBookCollection TRC 
			LEFT JOIN (
			SELECT ReceiptId,CollectionGroupId,SUM(ReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptBookCollection WHERE IsObsolete = 1
			GROUP BY ReceiptId,CollectionGroupId
			) A ON A.ReceiptId=TRC.ReceiptId AND A.CollectionGroupId=TRC.CollectionGroupId
			
			WHERE IsObsolete = 0
			GROUP BY TRC.RecepitTitle,TRC.CollectionTitle,A.ReceiptId,A.CancelReceiptCount,TRC.ReceiptId,TRC.CollectionGroupId,TRC.ReceiptCount 
		
  END
ELSE IF(@rType='ReceiptBookCollectionGroupDetail')
  BEGIN
  CREATE TABLE #tempReceiptBookCollectionDetail(
  SourceId bigint,
Code nvarchar(200),
Name nvarchar(200),
ReceiptNumber bigint,
ReceiptAmount DECIMAL(12,2),
ReceiptId bigint,
IsObsolete bit
)
IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempReceiptBookCollectionDetail
 SELECT ISNULL(SA.Id,0) AS SourceId,SM.Code AS Code,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) As Name,R.ReceiptNumber AS ReceiptNumber,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount,R.Id AS ReceiptId,R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
			INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId=SM.Id	
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.AdmissionCategoryId =  SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			AND  ISNULL(CGM.Id,0)=0
			--AND (R.IsObsolete = 0) 
			--AND(BM.IsActive =1) 
			And O.IsObsolete = 0
			AND COGBM.Id=@rCommonOrgGroupBatchId AND R.ReceiptDate between @rFromDate and @rToDate 
			GROUP BY SA.Id,SM.Code,R.ReceiptNumber,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId), R.ReceiptBookId,CGM.Id,R.Id,R.IsObsolete 
	END
ELSE
	BEGIN
	INSERT INTO #tempReceiptBookCollectionDetail
 SELECT ISNULL(SA.Id,0) AS SourceId,SM.Code AS Code,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) As Name,R.ReceiptNumber AS ReceiptNumber,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount,R.Id AS ReceiptId,R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId=SM.Id	
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.AdmissionCategoryId =  SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND (R.IsObsolete = 0) 
			--AND(BM.IsActive =1) 
			And O.IsObsolete = 0
			AND COGBM.Id=@rCommonOrgGroupBatchId AND R.ReceiptDate between @rFromDate and @rToDate     
			GROUP BY SA.Id,SM.Code,R.ReceiptNumber,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId), R.ReceiptBookId,CGM.Id,R.Id,R.IsObsolete 
			--ORDER BY 
	END
  SELECT *  FROM #tempReceiptBookCollectionDetail ORDER BY ReceiptNumber
  END
END
GO
PRINT N'Altering [sFee].[pRptFeeInvoiceGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeInvoiceGet]
		
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rReportId int,
		@rIsFilter bit,
	    @rIsDisplayOrgGroup bit,
	    @rIsFeeInvoiceHeadwise bit,
		@rOrgGroupBatchId int,
		@rCommonBatch nvarchar(100),
		@rReceiptBookId int,
		@rOrgId int,
		@rBatchId int,
		@rDepartmentId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rStatusId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rCollectionGroupId int=0,
	    @rFeeHeadId nvarchar(max) = '',
	    @rFeeId nvarchar(max) = '',
	    @rFilterId int=0,
	    @rOrgIds nvarchar(max) = ''    
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		FS.AcademicId,
		FS.Name,
		FS.ClassId,
		FS.ClassName,
		FS.DivisionId,
		FS.DivisionName,
		FS.DivisionOrder,
		FS.RollNo,
		FS.Code,
		FS.DepartmentId,
		FS.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		--ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) AS FeeAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) AS FeeAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		FS.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		RBM.GroupTitle AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		ISNULL(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
		ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
			        
	         CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader
  FROM 
		sFee.tFeeMaster FM 
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			    FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
				WHERE FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = SA.BatchId AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
				AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
			INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=SA.AcademicId) AND(FO.SourceTypeId=2001)
			WHERE FS1.BatchId = SA.BatchId AND FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=1 
			AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId 
		AND FS.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=FS.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = FS.StudentId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=FS.AcademicId) AND(FA.SourceTypeId=2001)
		
         LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=FS.StudentId AND AR.SourceTypeId=2003 AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = FS.StudentId AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
    
    LEFT  JOIN
	(
	    SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,
				RD.FeeSetupId,
				R.SourceId
	    FROM
				sFee.tReceipt R 
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = R.PayTypeId
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			--AND (R.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId=0)
			--AND (R.CollectionGroupId=@rCollectionGroupId OR @rCollectionGroupId=0)
		WHERE		
			(R.SourceTypeId = 2001)
			AND (R.IsObsolete = 0) 
			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				GROUP BY FeeSetupId,R.SourceId,R.ReceiptNumber,R.ReceiptDate,PTM.Title,R.ChequeNo,R.BankName,R.ChequeDate
	) R ON R.FeeSetupId = FS.Id AND FS.AcademicId = R.SourceId
    
WHERE 
		(FS.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((FS.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((FS.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((FS.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((FS.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((FS.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((FS.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((FS.Code=@rCode) OR (@rCode=''))
		AND ((FS.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		--AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) > 0  
		AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0  
         AND (
			 (@rFilterId = 0) -- All
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			 ) 
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) = ''    

	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,
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) 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  
			      THEN				
				  [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Month name in detail
			ELSE '' END) 
			AS MonthDetail,    
			
			--FS.FeeDuration 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
			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,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign
	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 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
	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='')
	  
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC

END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptListGet]...';


GO
   
ALTER PROCEDURE [sFee].[pRptFeeReceiptListGet]  
  @rReportId int=0,  
  @rReceiptBookId int=0,  
  @rAdmissionCategoryId int=0,  
  @rClassId int=0,  
  @rDivisionId int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rFromReceiptNo int=0,  
  @rToReceiptNo int=0,  
  @rBatchId int,  
  @rUserId bigint=0,  
  @rBuilder1 nvarchar(max)=0,  
  @rBuilder2 nvarchar(max)=0,  
  @rIsDetail bit=0,  
  @rIsCancel bit=0,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int=0,  
  @rPaytypeId int=0,  
  @rCommonBatch nvarchar(100)='',  
  @rDepartmentId int=0,  
  @rFromRollNo int=0,  
     @rToRollNo int=0,  
     @rCode nvarchar(20),  
     @rIsFilter bit=0,  
     @rIsHeader bit=0,  
     @rCreatedUserName nvarchar(100)='',  
     @rFeeHeadId nvarchar(max) = '',  
     @rIsDisplayOrgGroup bit=0,  
     @rIsDiscount bit = 0,  
     @rFeeId nvarchar(max) = '',  
     @rFilterId int=0,  
     @rCustomGroupId smallint = 0,  
     @rOrgGroupId int=0,  
     @rFeeStatusId int=0,  
     @rFromChequeDate date='',      
  @rToChequeDate date='',      
     @rBankName nvarchar(100)='',  
     @rOrgIds nvarchar(max) = '',  
     @rBankNames nvarchar(max) = '',  
  
  @rFromChequeClearDate Date = '',  
  @rToChequeClearDate Date = ''  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   
  BEGIN      
  SET @rBankName = sCommon.fSearchStringGet(@rBankName)      
    END   
  
 SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsDetail AS IsDetail,  
  (CASE @rReportId WHEN 20456 THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
  --@rIsCancel AS IsCancel,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  --SA.ClassName,  
  SA.DivisionId,  
  --SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.Code,  
  SA.Name,  
  ISNULL(PTM.Title,'') AS PayType,  
  ISNULL(R.ChequeNo,'') AS ChequeNo,  
  ISNULL(R.BankName,'') AS BankName,  
  R.ReceiptAmount,  
  --R.ReceiptDate,  
  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
  R.CreatedUserId,  
  ISNULL(U.LoginTitle,'') AS UserName,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
   ELSE '' END),'') AS FeeDetail,  
   R.Remark,  
   R.DiscountAmount,  
   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
   SA.OrgId,  
   SA.OrganizationName,  
   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
   @rCustomGroupId AS CustomGroupId,  
   SA.OrgGroupBatchId AS BatchId,  
   SA.BatchName,  
   R.ChequeDate,  
   R.ChequeClearDate   
  FROM   
   sFee.tReceipt R  
  --INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
  --INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
  --INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
    
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  LEFT JOIN sSecurity.tUser U  
   ON U.Id=R.CreatedUserId  
 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
    LEFT JOIN  
 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
    ON RT.SourceId = SA.StudentId   
    AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
    AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND ((R.IsObsolete =@rIsCancel  AND @rReportId != 20456)  OR   
  ((@rReportId = 20456) AND ((@rFeeStatusId = 0) -- All  
  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
  )))  
 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
  AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
    )  
    AND ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
 AND ((R.ChequeClearDate>=@rFromChequeClearDate OR R.ReceiptDate>=@rFromChequeClearDate )OR(ISNULL(@rFromChequeClearDate,'')=''))      
 AND ((R.ChequeClearDate<=@rToChequeClearDate OR R.ReceiptDate>=@rToChequeClearDate )OR(ISNULL(@rToChequeClearDate,'')=''))   
  
  
 ORDER BY R.ReceiptNumber  
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END
GO
PRINT N'Altering [sFee].[pRptTransportFeePendingWithFeeNameGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptTransportFeePendingWithFeeNameGet]
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rUptoDate date='',
		@rBatchId int=0,
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rRouteId int=0,
		@rDestinationId int = 0,
		@rTransportId int =0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	


--CREATE TABLE #TempStudent
--	(
--	AcademicId bigint,
--	ClassId int,
--	BatchId int,
--	a
--	)
--	SELECT AcademicId

 
	--CREATE TYPE  TempPendingFee AS TABLE
	--(
	--AcademicId bigint
	--,
	--RollNo int,
	--Name nvarchar(200),
	--Code nvarchar(20),
	--ClassId int,
	--DivisionId int,
	--ClassName nvarchar(100),
	--DivisionName nvarchar(100),
	--ClassDivision nvarchar(100),
	--FeeSetupId int,
	--IsVariable int,
	--Amount Decimal(12,2),
	--StartDate date,
	--EndDate date,
	--FAAmount Decimal(12,2),
	--DiscountAmount Decimal(12,2),
	--AdditionalAmount Decimal(12,2),
	--PaidAmount Decimal(12,2),
	--PendingAmount Decimal(12,2),
	--Remark nvarchar(200),
	--ReceiptBookId int,
	--FeeName nvarchar(100),
	--FeeCode nvarchar(100),
	--OrgId int,
	--OrgName nvarchar(200),
	--OrgOrderIndex int,
	--ReceiptBookTitle nvarchar(200),
	--ReceiptOrderIndex int 
	--)
	 
	DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId
		,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName, 
		'' AS Pickup,
		'' AS DRoppoint,
		'' AS PresentContactNo	
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				SA1.StudentId AS StudentId
				
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
			--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				SA1.StudentId AS StudentId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
		--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId 
				INNER JOIN sfEe.tFeeMaster FM ON FM.Id = FS.FeeId 
				INNER JOIN sFee.tFeeHeadMaster FH ON FM.FeeHeadId = FH.Id AND FH.Number = 1001
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		INNER JOIN sTransport.tAssignRoute AR 
			ON  SA.StudentId = AR.SourceId AND AR.SourceTypeId = 2003	
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM 
			ON BRDM.Id = AR.PickupDestinationId
	 INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
			AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
			AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
			Order by SA.RollNo

			SELECT
			P.OrgId,			 
			P.ReceiptBookId,
			P.AcademicId,
			P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,ReceiptBookTitle,OrgName,
			SUM(P.PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](P.AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			P.ReceiptOrderIndex,
			BR.Id AS BusRouteId,
			BR.Title AS BusRoute,
			BD.Title AS BusDestination,
			isnull(SC.ParentContactNo,'') AS ParentContactNo
			
			FROM @p P INNER JOIN sStudent.vStudentAcademic VA ON p.AcademicId=VA.AcademicId
			INNER JOIN sTransport.tAssignRoute AR oN VA.StudentId = AR.SourceId AND SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BD ON BD.Id = AR.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster BR ON BR.Id = BD.BusRouteId 
			AND BR.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =  VA.StudentId
			GROUP By P.ReceiptBookId,P.OrgId,P.AcademicId,P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,
			P.ReceiptBookTitle,P.OrgName,P.ReceiptOrderIndex,BR.Title,BD.Title,BR.Id,SC.ParentContactNo	
			ORDER BY P.AcademicId
 
END
GO
PRINT N'Altering [sFrontOffice].[pStudentGatePassGet]...';


GO
ALTER PROCEDURE [sFrontOffice].[pStudentGatePassGet]
          
           @rId int,
           @rOrgId int=0,
           @rFromGatePassDate datetime='',
           @rToGatePassDate datetime='',
           @rEntryModeStatusId smallint=0,
           @rCode nvarchar(20)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0,
           @rUserId bigint= 0 
AS
SET NOCOUNT ON
BEGIN
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId
		
		SELECT  
			SGP.Id,
			vSA.Code,
			vSA.FirstName+' '+vSA.MiddleName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			SGP.AcademicId,
			ISNULL(SGP.RelationshipId,0) AS RelationshipId,
			RM.Title AS Relationship,
			SGP.Relation,
			SGP.VisitorName,
			ISNULL(SGP.VisitorMobile,0) As VisitorMobile,
			SGP.ReasonOfGatePass,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SGP.VisitorPhoto		
			ELSE ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			ISNULL(SGP.GatePassDate,'') As GatePassDate,
			ISNULL(SGP.ReturnGatePassDate,'') As ReturnGatePassDate,
			ISNULL(SGP.GatePassTime,'') As GatePassTime,
			ISNULL(SGP.ReturnGatePassTime,'') As ReturnGatePassTime,
			ISNULL(SGP.EntryModeStatusId,0) AS EntryModeStatusId,
			ISNULL(SM.Title,'')  AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.OrgLogo,
			OM.DisplayTitle AS Organization,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.StudentPhoto		
			ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS StudentPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.FatherPhoto		
			ELSE ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS FatherPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.MotherPhoto		
			ELSE ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS MotherPhoto,
			
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.RelativePhoto		
			ELSE ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) END) AS RelativePhoto,
			
			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			vSA.SUId,
			Remark,
			@GatePassConfig AS ConfigValue,
				
			SF.FatherContactNo,
			SF.MotherContactNo,
			SF.RelativeContactNo,
			SF.FatherName,
			SF.MotherName,
			SF.RelativeName
		FROM 
		    sStudent.vStudentAcademic vSA
			INNER JOIN sFrontOffice.tStudentGatePass SGP ON SGP.AcademicId = vSA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id=SGP.RelationshipId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=SGP.EntryModeStatusId			
			INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId = SGP.OrgId AND UO.UserId = @rUserId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SI.StudentId
			LEFT JOIN sSecurity.tUser U	ON U.Id=SGP.CreatedUserId
			
		WHERE 
		  ((SGP.Id=@rId) OR (@rId=0))
			AND ((SGP.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((SGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((SGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			AND (OM.OrgGroupId=@rOrgGroupId)
			--AND vSA.IsActiveBatch=1
			ORDER BY SGP.GatePassDate,SGP.GatePassTime DESC
			
END
GO
PRINT N'Altering [sHrm].[pEmployeeAttendanceGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pEmployeeAttendanceGet]
	 
	@rForYear  bigint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	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))
BEGIN 
	SELECT  
		EM.Code AS EmployeeCode,
		EM.EmployeeName,
		EM.EmployeeId,
		ISNULL(EM.EmployeeGrade,'') AS EmployeeGrade,
		ISNULL(WD.TotalDays,0) AS TotalDays,
		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate) + 1 
		--	ELSE ISNULL(WD.TotalDays,0) 
		--END AS TotalDays,
		ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays,
		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate)  + 1 
		--	ELSE ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) 
		--END AS WorkingDays,
		(ISNULL(AT.TotalWorkingDays,0) - ((ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)))) AS PresentDays,
		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate) - (ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)) + (1) 
		--	ELSE (ISNULL(AT.TotalWorkingDays,0) - (ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0))) 
		--END AS PresentDays,
		(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS PayrollDays,
		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate) - ISNULL(AT.LWP,0) + (1)
		--	ELSE (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) 
		--END AS PayrollDays,
		(ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)) AS LWP,   -- Absent Days
		ISNULL(AT.PaidLeave,0) AS PaidLeave,
		ISNULL(AT.LWP,0) AS UnPaidLeave,
		ISNULL(AT.LateCount,0) AS LateCount,
		ISNULL(AT.LateDeductionDays,0) AS LateDeductionDays,
		ISNULL(AT.SandwichDeductionDays,0) AS SandwichDeductionDays
	FROM 
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId		 
		AND AT.ForMonth=@rForMonth AND AT.ForYear=@rForYear AND AT.BatchId = @rBatchId
	WHERE 
		EM.OrgID = @rOrgId 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
		AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		--AND  Code='E158'
	ORDER BY 
		EM.Code
END
GO
PRINT N'Altering [sHrm].[pEmployeeAttendanceRegisterGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeAttendanceRegisterGet]
	 	 
	 	 @rDepartmentId int=0,
	 	 @rAttendanceDate date='',
	 	 @rCode nvarchar(20)='',
	 	 @rBatchId int=0,
	 	 @rOrgId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  BEGIN
	SELECT 
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			EM.DepartmentName,
			ISNULL(EAR.IsPresent,'true') as IsPresent,
			ISNULL(EAR.AbsentReasonId,0) as AbsentReasonId,
			CASE WHEN EAR.UpdatedUserId IS NULL THEN cast(0 as bit) ELSE cast(1 as bit) END AS IsDeleted,
			ISNULL(EAR.LeaveTypeId,0) AS LeaveTypeId,
			ISNULL(EAR.LeavePeriodId,0) AS LeavePeriodId
  FROM 
			sHrm.vExtEmployeeMaster EM
			LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId=EM.EmployeeId
			 --AND (( convert(DATE,EAR.AttendanceDate,102) = @rAttendanceDate) OR (@rAttendanceDate='')) 	
			AND EAR.AttendanceDate =@rAttendanceDate
			AND (EAR.BatchId = @rBatchId)
    WHERE 
		  ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		  AND ((EM.Code like @rCode) OR (ISNULL(@rCode,'')=''))
		  AND (EM.OrgId = @rOrgId)
		   --AND ((convert(DATE,EM.DateOfleaving,102) >= @rAttendanceDate) OR (@rAttendanceDate=''))
		   -- AND ((convert(DATE,EM.DateOfleaving,102) <= @rAttendanceDate) OR (@rAttendanceDate='')) 
		  AND ((EM.DateOfleaving >= @rAttendanceDate) OR ISNULL(EM.DateOfleaving,'') = '')
          AND ((EM.DateOfJoining <= @rAttendanceDate) OR ISNULL(EM.DateOfJoining,'') = '') 
		  --AND (EM.StatusId = 7)
          ORDER BY EM.Code
  END
END
GO
PRINT N'Altering [sHrm].[pEmployeeAttendanceSummaryDashboard]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeAttendanceSummaryDashboard]
	@rType nvarchar(50)='',
	@rBatchId int=0,
	@rOrgGroupBatchId int=0,
	@rOrgId smallint=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 

	IF(@rType = 'EmployeePresentDetails')
		BEGIN
		    
		    SELECT 
		    (SELECT ISNULL(COUNT(EAT.EmployeeId),0) AS AbsentCount FROM sHrm.tEmployeeAttendanceRegister EAT  WHERE EAT.AttendanceDate=CONVERT(char(10), GetDate(),126) AND EAT.BatchId= @rBatchId) AS TotalCount,
		    (SELECT ISNULL(COUNT(EAT.EmployeeId),0) AS AbsentCount FROM sHrm.tEmployeeAttendanceRegister EAT  WHERE EAT.IsPresent=1 AND  EAT.AttendanceDate=CONVERT(char(10), GetDate(),126) AND EAT.BatchId= @rBatchId ) AS PresentCount,
		    (SELECT ISNULL(COUNT(EAT.EmployeeId),0) AS AbsentCount FROM sHrm.tEmployeeAttendanceRegister EAT  WHERE EAT.IsPresent=0 AND EAT.AttendanceDate=CONVERT(char(10), GetDate(),126) AND EAT.BatchId= @rBatchId) AS AbsentCount,		    
             (SELECT COUNT(Id) From sHrm.tEmployeeMaster EM WHERE ORGId=@rOrgId AND ID NOT IN (SELECT EmployeeId FROM sHrm.tEmployeeAttendanceRegister EAT WHERE EAT.AttendanceDate=CONVERT(char(10), GetDate(),126) AND EAT.BatchId= @rBatchId)) AS PendingAttendance
		    
		END
		
	 ELSE IF(@rType = 'EmployeeLeaveDetails')
	 
	  BEGIN
	  
	   SELECT 		
		--(SELECT ISNULL(SUM(NoOfLeave),0) AS ApprovedLeaves FROM sHrm.tLeave HL1 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL1.BatchId where HL1.StatusId=550 AND HL1.ToDate  >= DATEADD(day,-30, getdate()) AND HL1.FromDate  <= getdate() AND HL1.BatchId= @rBatchId AND BM.OrgGroupBatchId = 110100111) AS ApprovedLeaves,
		(SELECT ISNULL(SUM(NoOfLeave),0) AS PendingLeaves FROM sHrm.tLeave HL2 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL2.BatchId where HL2.StatusId=549 AND HL2.ToDate  >= DATEADD(day,-30, getdate()) AND HL2.FromDate  <= getdate() AND  BM.OrgGroupBatchId = @rOrgGroupBatchId ) AS PendingLeaves,
		(SELECT ISNULL(SUM(NoOfLeave),0) AS ApprovedLeaves FROM sHrm.tLeave HL1 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL1.BatchId where HL1.StatusId=550 AND HL1.ToDate  >= DATEADD(day,-30, getdate()) AND HL1.FromDate  <= getdate() AND BM.OrgGroupBatchId = @rOrgGroupBatchId) AS ApprovedLeaves,						
		(SELECT ISNULL(SUM(NoOfLeave),0) AS PendingLeaves FROM sHrm.tLeave HL3 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL3.BatchId where HL3.StatusId=551 AND HL3.ToDate  >= DATEADD(day,-30, getdate()) AND HL3.FromDate  <= getdate() AND BM.OrgGroupBatchId = @rOrgGroupBatchId) AS RejectedLeaves
		
	  END
	  
	 ELSE IF(@rType = 'EmployeeCurrentYearLeaveDetails')
	 
	  BEGIN
	  
	   SELECT 	
	   (SELECT ISNULL(SUM(NoOfLeave),0) AS PendingLeaves 
	            FROM sHrm.tLeave HL2 
	               INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL2.BatchId 	               
				   INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = HL2.EmployeeId
				   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = HL2.EmployeeId 
	               where HL2.StatusId=549 AND HL2.FromDate  >= convert(date, DATEADD(yy, DATEDIFF(yy, 0,  DATEadd(day, -1,getdate())), 0), 103 ) AND HL2.ToDate  <= convert(date, DATEADD(yy, DATEDIFF(yy, 0, DATEDIFF(day, -1,getdate()))+1, -1), 103 ) AND  BM.OrgGroupBatchId = @rOrgGroupBatchId) AS PendingLeaves,	
		(SELECT ISNULL(SUM(NoOfLeave),0) AS ApprovedLeaves 
		      FROM sHrm.tLeave HL1 
		         INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL1.BatchId 
		         INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = HL1.EmployeeId
			     INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = HL1.EmployeeId 
		      where HL1.StatusId=550 AND HL1.FromDate  >= convert(date, DATEADD(yy, DATEDIFF(yy, 0,  DATEadd(day, -1,getdate())), 0), 103 ) AND HL1.ToDate  <= convert(date, DATEADD(yy, DATEDIFF(yy, 0, DATEDIFF(day, -1,getdate()))+1, -1), 103 ) AND   BM.OrgGroupBatchId = @rOrgGroupBatchId) AS ApprovedLeaves,		
		(SELECT ISNULL(SUM(NoOfLeave),0) AS PendingLeaves 
		      FROM sHrm.tLeave HL3 		         
		          INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL3.BatchId 
		          INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = HL3.EmployeeId
			      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = HL3.EmployeeId 
		          where HL3.StatusId=551 AND HL3.FromDate  >= convert(date, DATEADD(yy, DATEDIFF(yy, 0,  DATEadd(day, -1,getdate())), 0), 103 ) AND HL3.ToDate  <= convert(date, DATEADD(yy, DATEDIFF(yy, 0, DATEDIFF(day, -1,getdate()))+1, -1), 103 ) AND   BM.OrgGroupBatchId = @rOrgGroupBatchId) AS RejectedLeaves
	  
	  END   
	  
	  
	   ELSE IF(@rType = 'EmployeeMonthWiseAbsentPIChartDetails')
	   
	    BEGIN
	        Select M.Id,M.Title, ISNULL(COUNT(AttendanceDate),0) AS AbsentCount  From sCommon.tMonthMaster M
			 LEFT JOIN  sHrm.tEmployeeAttendanceRegister ER ON MONTH(ER.AttendanceDate) =M.Id AND BatchId=@rBatchId AND IsPresent=0
			 GROUP BY M.Id,M.Title
			 ORDER BY M.Id
 
	    END
	  	
	  ELSE IF(@rType = 'EmployeeMonthWiseLeavePIChartDetails')	
	  	
	  	BEGIN
	       
          Select M.Id,M.Title, ISNULL(SUM(NoOfLeave),0) AS LeaveCount  From sCommon.tMonthMaster M
			 LEFT JOIN  sHrm.tLeave HL ON MONTH(HL.FromDate) =M.Id AND BatchId=@rBatchId 
			 GROUP BY M.Id,M.Title
			 ORDER BY M.Id
 
	    END		
END
GO
PRINT N'Altering [sHrm].[pEmployeeCustomSearchGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeCustomSearchGet]
(
	@rPageIndex int = null,
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'Code',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName[nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',
	@rEmployeeGroupId[nvarchar](50)='',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rDropDownStatusId int,
	@rLeftFromDate Date = '0001-01-01',
	@rLeftToDate Date = '9999-12-31'
	
 )
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Sql nvarchar(MAX)
	
	if @rDOBToDate = '9999-12-31'
	begin
		select @rDOBToDate = null
	end
	
	if @rLeftToDate = '9999-12-31'
	begin
		select @rLeftToDate = null
	end
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	
	SELECT * into sHrm.tTempEmployee1
	FROM sHrm.vEmployeeCustomSearch ECS
	WHERE ECS.OrgId = @rOrgId
	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
	AND ((ECS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
	AND ((ECS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
	AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
	AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
	AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='')
	AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
	AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='')
	AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='')
	AND (ISNULL(ECS.EmployeeGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeGroupId,','))OR @rEmployeeGroupId='')
	AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
	AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
	AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='')
	AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
	--AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))
	AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
	
	
	SET @rOrderBy=Replace(@rOrderBy,'Code','Code')
	SET @sql='SELECT EmployeeId,Code AS Code,Name,EmployeeType,OrganizationDepartment AS OrganizationDepartment,
	StatusName FROM sHrm.tTempEmployee1 ORDER BY '+@rOrderBy
	exec(@Sql)
	
	create table #STUDENTTEMP
	(
		tid int identity(1,1),t_StudentId bigint
	)
	select @Sql = 'insert into #STUDENTTEMP
	SELECT EmployeeId FROM sHrm.tTempEmployee1 ORDER BY ' + @rOrderBy
	
	exec (@Sql)
	
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	declare @lTotalRecords int,@lPageSize int = 10,@lResult varchar(max) = '',@lPaging varchar(max) = ''
	
	select @lTotalRecords = COUNT(*) FROM #STUDENTTEMP
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex, @lTotalRecords, @lPageSize)
	
	select @lResult = @lResult + '<tr><td><a style="cursor:pointer;" onclick="SelectEmp(' + convert(varchar,EmployeeId) + ',''' + isnull(Code,'') + ''')">Select</a></td>
	<td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td><td>' + isnull(EmployeeType,'') + '</td>
	<td>' + isnull(StatusName,'') + '</td><td>' + isnull(OrganizationDepartment,'') + '</td></tr>'	
	from sHrm.tTempEmployee1,#STUDENTTEMP
	where t_StudentId = EmployeeId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	order by tid
	
	select @lResult as EmpList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP TABLE #STUDENTTEMP
	DROP Table sHrm.tTempEmployee1
END
GO
PRINT N'Altering [sHrm].[pEmployeeGenerateReport]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeGenerateReport]	
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'Code',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',	 
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rIsCommonForOrg bit,
	@rLeftFromDate Date = '0001-01-01',
	@rLeftToDate Date = '9999-12-31'
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION	
	
	--if @rColumnName <> ''
	--begin
	--	select @rColumnName = left(@rColumnName,len(@rColumnName)-1)
	--end
	
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate='0001-01-01'
	IF(@rDOJFromDate IS NULL)
		SET @rDOJFromDate='0001-01-01'
	IF(@rLeftFromDate IS NULL)
		SET @rLeftFromDate='0001-01-01'
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate='9999-12-31'
	IF(@rDOJToDate IS NULL)
		SET @rDOJToDate='9999-12-31'
	IF(@rLeftToDate IS NULL)
		SET @rLeftToDate='9999-12-31'

	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
		DECLARE @lNextNumber BIGINT 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		INSERT INTO sHrm.tEmployeeCustomSearch
			(
				Id,Title,ColumnName,OrgId,Code,FirstName,LastName,EmployeeTypeId,StatusId,OrganizationDepartmentId,ReligionId,
				MaritalStatusId,Qualification,GenderId,EmployeeDesignationId,BloodGroupId,DOBFromDate,DOBToDate,DOJFromDate,
				DOJToDate,IsCommon,CreatedUserId,CreatedDateTime,IsCommonForOrg)
		VALUES
			(
				@lNextNumber,@rTitle,@rColumnName,@rOrgId,@rCode,@rFirstName,@rLastName,@rEmployeeTypeId,@rStatusId,@rOrganizationDepartmentId,@rReligionId,
				@rMaritalStatusId,@rQualification,@rGenderId,@rEmployeeDesignationId,@rBloodGroupId,@rDOBFromDate,@rDOBToDate,@rDOJFromDate,
				@rDOJToDate,@rIsCommon,@rCreatedUserId,sCommon.fGetDate(),@rIsCommonForOrg)
			--SELECT @lNextNumber AS Result
	END
	
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rEmployeeTypeId=EmployeeTypeId,
				@rStatusId=StatusId,
				@rOrganizationDepartmentId=OrganizationDepartmentId,
				@rReligionId=ReligionId,
				@rMaritalStatusId=MaritalStatusId,
				@rQualification=Qualification,
				@rGenderId=GenderId,
				@rEmployeeDesignationId=EmployeeDesignationId,
				@rBloodGroupId=BloodGroupId,	 
				@rDOBFromDate=DOBFromDate,
				@rDOBToDate=DOBToDate,
				@rDOJFromDate=DOJFromDate,
				@rDOJToDate=DOJToDate
		FROM
			sHrm.tEmployeeCustomSearch
		WHERE
			Id=@rId
	END
	
	DECLARE @Sql nvarchar(MAX)
	SET @rColumnName=Replace(@rColumnName,',ID No',',Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')

	SET @rColumnName=Replace(@rColumnName,',GR No',',Code')
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
 
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	
		SELECT 
			* 
			into sHrm.tTempEmployee
		FROM 
			sHrm.vEmployeeCustomSearch ECS
		WHERE 
			ECS.OrgId = @rOrgId 
			AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
			AND ((ECS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
			AND ((ECS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
			AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
			AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))	
			
			AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
			
			AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
			
		    AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 

			
		    AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
			
		    AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
			   
		    AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
			        
		    AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
			 
		    AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
	
			--AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			
			AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))
			
			AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
			
		
		--SELECT * FROM 
		--	sHrm.vEmployeeCustomSearch ECS
		--WHERE 
		--	ECS.OrgId = @rOrgId 
		--	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
		--	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
		
--	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		--	AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
		--	AND ((ECS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		--	AND ((ECS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
		--	AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
		--	AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))	
			
		--	AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
			

		--	AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
			
		--    AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 
			
		--    AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
			
		--    AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
			   
		--    AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
			        
		--    AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
			 
		--    AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
	
		--	AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sHrm.tTempEmployee ORDER BY '+@rOrderBy
		--SELECT @sql
		exec(@Sql)
		
		DROP Table sHrm.tTempEmployee
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sHrm].[pEmployeeMonthWiseLeaveGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pEmployeeMonthWiseLeaveGet]
	 
	@rEmployeeId bigint,	 
	@rForMonth int,
	@rForYear int,
	@rBatchId int,
	@rIsConsiderBiometricRule bit=0,
	@rIsSandwichRuleApplicable bit=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	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))
  
 SELECT 
			
		CASE 
			WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
			THEN DATEDIFF(day, @lFirstDate , EJD.DateOfJoining) 
			ELSE ISNULL(SUM(ISNULL([sHrm].[fMonthWiseNoOfLeave](1,L.FromDate,L.ToDate,@rForMonth,@rForYear,L.LeavePeriodId,L.LeaveTypeId),0)),0)
		END AS NoOfLeave,	
   
        --ISNULL(SUM(ISNULL([sHrm].[fMonthWiseNoOfLeave](1,L.FromDate,L.ToDate,@rForMonth,@rForYear,L.LeavePeriodId,L.LeaveTypeId),0)),0) AS NoOfLeave,
        ISNULL(SUM(ISNULL([sHrm].[fMonthWiseNoOfLeave](0,L.FromDate,L.ToDate,@rForMonth,@rForYear,L.LeavePeriodId,L.LeaveTypeId),0)),0) AS PaidLeave,
        
        CASE WHEN @rIsConsiderBiometricRule = 1 THEN ISNULL([sBiometric].[fEmployeeLateCountGet](@rEmployeeId, @rForMonth,@rForYear),0) ELSE 0 END AS LateCount
        FROM 
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		LEFT JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId	 AND L.BatchId = @rBatchId 	AND L.StatusId = 550 -- apporved 
    	WHERE EM.EmployeeId = @rEmployeeId  
    	GROUP BY EJD.DateOfJoining
    	
    	IF(@rIsSandwichRuleApplicable=1)
    		EXEC [sHrm].[pEmployeeMonthWiseSandwichDaysCountGet] @rEmployeeId,@rForMonth,@rForYear,@rBatchId
    	ELSE
    		SELECT 0 AS SandwichDayCount
    		
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,
		
		----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)
			 
END
GO
PRINT N'Altering [sHrm].[pEmployeeStatutoryDetailAdd]...';


GO

ALTER PROCEDURE [sHrm].[pEmployeeStatutoryDetailAdd]

	       @rEmployeeId bigint,
	       @rAccountNumber nvarchar(20),
	       @rBankName nvarchar(200),
           @rBranch nvarchar(50),          
           @rEPFNumber nvarchar(50),
           @rPanNumber nvarchar(20),
           @rIsVPFDeduction bit,
           @rVPFContributionId tinyint,
           @rVPFContributionEffectiveFrom date,
           @rVPFPercentage decimal(5,2),
           @rVPFAmount decimal(22,6),
           @rESINumber nvarchar(20),        
           @rIFSCNumber nvarchar(50),           
           @rIncomeTaxStatusId int,
           @rUpdatedUserId bigint,            
           @rIncrementDate date,
           @rBasicPay decimal(12,2),
           @rPayrollId int,
           @rPayrollGroupId int,
           @rPayscale nvarchar(150)='',
           @rEPFJoinDate date = NULL,
           @rUAN nvarchar(20)='',
           @rRetirementDate date
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
BEGIN TRANSACTION
	DECLARE @lNextNumber BIGINT 
 	  
IF NOT EXISTS(Select 1 From sHrm.tEmployeeStatutoryAndOther Where EmployeeId = @rEmployeeId)
   BEGIN
	INSERT INTO sHrm.tEmployeeStatutoryAndOther
           (
            [EmployeeId]
           ,[EPFNumber]
           ,[IsVPFDeduction]
           ,[VPFContributionId]
           ,[VPFContributionEffectiveFrom]
           ,[VPFPercentage]
           ,[VPFAmount]
           ,[ESINumber]
           ,[BankName]
           ,[Branch]
           ,[AccountNumber]
           ,[IFSCNumber]
           ,[PanNumber]
           ,[IncomeTaxStatusId]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[IncrementDate]
           ,[BasicPay]
           ,[PayrollId]
           ,[PayrollGroupId]
           ,[Payscale]
           ,[EPFJoinDate]
           ,[UAN]
           ,[RetirementDate]
           )
     VALUES
           (
           @rEmployeeId,
           @rEPFNumber,
           @rIsVPFDeduction,
           @rVPFContributionId,
           @rVPFContributionEffectiveFrom,
           @rVPFPercentage,
           @rVPFAmount,
           @rESINumber,
           @rBankName,
           @rBranch,
           @rAccountNumber,
           @rIFSCNumber,
           @rPanNumber,
           @rIncomeTaxStatusId,
           @rUpdatedUserId,
           sCommon.fGetDate(),
           @rIncrementDate,
           @rBasicPay,
           @rPayrollId,
           @rPayrollGroupId,
           @rPayscale,
           @rEPFJoinDate,
           @rUAN,
           @rRetirementDate
           )
     END
     ELSE
     BEGIN
      UPDATE sHrm.tEmployeeStatutoryAndOther
      SET 
		  [EPFNumber] = @rEPFNumber,
		  [IsVPFDeduction] = @rIsVPFDeduction, 
		  [VPFContributionId] = @rVPFContributionId, 
		  [VPFContributionEffectiveFrom] = @rVPFContributionEffectiveFrom, 
		  [VPFPercentage] = @rVPFPercentage, 
		  [VPFAmount] = @rVPFAmount, 
		  [ESINumber] = @rESINumber, 
		  [BankName] = @rBankName, 
		  [Branch] = @rBranch, 
		  [AccountNumber] = @rAccountNumber, 
		  [IFSCNumber] = @rIFSCNumber, 
		  [PanNumber] = @rPanNumber, 
		  [IncomeTaxStatusId] = @rIncomeTaxStatusId, 
		  [UpdatedUserId] = @rUpdatedUserId, 
		  [UpdatedDateTime] = sCommon.fGetDate(), 
		  [IncrementDate] = @rIncrementDate, 
		  [BasicPay] = @rBasicPay,
		  [PayrollId]=@rPayrollId,
          [PayrollGroupId]=@rPayrollGroupId,
          [Payscale]=@rPayscale,
          [EPFJoinDate]=@rEPFJoinDate,
          [UAN]=@rUAN,
          [RetirementDate]=@rRetirementDate
	  WHERE 
			EmployeeId = @rEmployeeId
     END    
     
	SELECT 1 AS RESULT
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH				
END
GO
PRINT N'Altering [sHrm].[pIncrementCertificateAdd]...';


GO
    
ALTER PROCEDURE [sHrm].[pIncrementCertificateAdd]    
    
@rId bigint = 0,    
  @rCode nvarchar(20)='',    
  @rName nvarchar(200)='',    
  @rFromNo int = 0,    
  @rToNo int =0,    
  @rFromDate date='',    
  @rToDate date='',    
  @rOrgId smallint =0,    
  @rIsSearch bit = 1,    
  @rEmployeeId bigint=0,    
  @rBatchId int = 0,    
  @rNumber int = 0,    
  @rEmployeeDesignationId int= 0,    
  @rQualification nvarchar(150)='',    
  @rPayScale nvarchar(200)='',    
  @rExistingBasicPay decimal(12,2)= 0,    
  @rRevisedBasicPay decimal(12,2)= 0,    
  @rRevisedBasicPayDate DATE='',    
  @rGradePayInRevisedPayStructure decimal(12,2)= 0,    
  @rBasicPayInRevisedPayStructureBasicPayAndGradePay decimal(12,2)= 0.00,    
  @rGrossSalaryAsPerExistingPayScale decimal(12,2)= 0.00,    
  @rRevisedGrossSalaryAsOn decimal(12,2)= 0.00,    
  @rIncrementDate DATE = '',    
  @rRemark nvarchar(200)='',    
  @rCertificateDate DATE= '',    
  @rCreatedUserId bigint =0,    
  @rCreatedDateTime DATE=''    
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
BEGIN    
 --BEGIN TRY     
 -- BEGIN TRANSACTION     
      
  IF(@rNumber = 0)    BEGIN    SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sHrm.tCertificateIncrement WHERE OrgId=@rOrgId   END     
       
  IF(@rId = 0)     
  BEGIN    IF EXISTS(SELECT 1 FROM sHrm.tCertificateIncrement WHERE Number=@rNumber AND OrgId=@rOrgId)    
   BEGIN    
    SELECT -103 AS Result    
    RETURN    
   END   
   END     
   DECLARE @lNextNumber BIGINT   
   DECLARE @lQualification nvarchar(150)
   
    IF(@rId = 0)     
  BEGIN    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tCertificateIncrement', 0, 1, 1,@outNextNumber = @lNextNumber output     
  SELECT @lQualification= Qualification FROM  sHrm.vExtEmployeeMaster WHERE EmployeeId = @rEmployeeId
 
  INSERT INTO sHrm.tCertificateIncrement     
  (      Id    
       ,EmployeeId    
       ,Number    
       ,CertificateDate        ,OrgId        ,Remark        ,BatchId     
       ,EmployeeDesignationId     
       ,Qualification     
     ,PayScale    
     ,ExistingBasicPay    
     ,RevisedBasicPay     
     ,RevisedBasicPayDate    
     ,GradePayInRevisedPayStructure    
     ,BasicPayInRevisedPayStructureBasicPayAndGradePay    
     ,GrossSalaryAsPerExistingPayScale    
     ,RevisedGrossSalaryAsOn     
     ,IncrementDate    
     ,CreatedUserId    
     ,CreatedDateTime     )    
      VALUES     
      ( @lNextNumber    
       ,@rEmployeeId    
       ,@rNumber    
       ,@rCertificateDate        ,@rOrgId        ,@rRemark        ,@rBatchId     
       ,@rEmployeeDesignationId    
       ,@lQualification     
     ,@rPayScale    
     ,@rExistingBasicPay    
     ,@rRevisedBasicPay     
     ,@rRevisedBasicPayDate    
     ,@rGradePayInRevisedPayStructure    
     ,@rBasicPayInRevisedPayStructureBasicPayAndGradePay    
     ,@rGrossSalaryAsPerExistingPayScale    
     ,@rRevisedGrossSalaryAsOn     
     ,@rIncrementDate    
     ,@rCreatedUserId    
     ,@rCreatedDateTime     )    
     SELECT 1 AS Result 
  END    
      
  ELSE    
      
  BEGIN    
  
   SET @lNextNumber = @rId 
    UPDATE  sHrm.tCertificateIncrement    
    SET    
     EmployeeId=@rEmployeeId,    
     CertificateDate=@rCertificateDate,      
     UpdatedUserId=@rCreatedUserId,      
     UpdatedDateTime=sCommon.fGetDate(),    
     Remark=@rRemark,         
     BatchId=@rBatchId,    
      EmployeeDesignationId=@rEmployeeDesignationId,    
      Qualification= @rQualification ,    
      PayScale=@rPayScale,     
      ExistingBasicPay=@rExistingBasicPay,    
      RevisedBasicPay=@rRevisedBasicPay,    
      RevisedBasicPayDate=@rRevisedBasicPayDate,    
      GradePayInRevisedPayStructure=@rGradePayInRevisedPayStructure,    
      BasicPayInRevisedPayStructureBasicPayAndGradePay=@rBasicPayInRevisedPayStructureBasicPayAndGradePay,    
      GrossSalaryAsPerExistingPayScale=@rGrossSalaryAsPerExistingPayScale,    
      RevisedGrossSalaryAsOn=@rRevisedGrossSalaryAsOn,    
      IncrementDate=@rIncrementDate    
    WHERE Id = @rId    
   END
     SELECT 11 AS Result 
      
  SELECT @lNextNumber AS Result    
     
 --COMMIT TRANSACTION    
 --END TRY    
     
 --BEGIN CATCH     
 -- ROLLBACK TRANSACTION    
 -- SELECT -1 AS Result    
 --END CATCH     
     
END
GO
PRINT N'Altering [sHrm].[pLeaveListGet]...';


GO
 

ALTER PROCEDURE [sHrm].[pLeaveListGet]
(
	@rOrgId int ,
    @rId bigint = 0,
    @rEmployeeId  bigint ,   
    @rFromDate date = '',
    @rLeaveTypeId int = 0,
    @rTodate date = '',
    @rBatchId int ,
    @rEmployeeCode nvarchar(100) = '',
    @rEmployeeName nvarchar(100) = '',
    @rStatusId int=0
 )
AS
SET NOCOUNT ON

BEGIN
    
	SELECT 
		   L.Id AS LeaveId
		  ,L.EmployeeId
		  ,L.ReportDate
		  ,L.FromDate
		  ,L.ToDate
		  ,LeavePeriodId
		  ,L.LeaveTypeId
		  ,CASE WHEN LeaveReason = '- Select -' THEN 'NA' ELSE LeaveReason END AS LeaveReason
		  ,LPM.Title AS LeavePeriod
		  ,LTM.Title AS LeaveType
		  ,EM.EmployeeName
		  ,EM.Code AS EmployeeCode
		  ,ISNULL(L.StatusId,0) AS StatusId
		  ,ISNULL(SM.Title,'Pending') AS StatusName
		  ,L.NoOfLeave      
		  ,ISNULL(L.FromTime,'') AS FromTime
          ,ISNULL(L.ToTime,'') AS ToTime
          ,ISNULL(L.LeaveRemark,'') AS LeaveRemark
		  --,(ISNULL((Select NoOfLeave FROM sHrm.tLeaveTypeGradeSettings LGS WHERE LGS.EmployeeGradeId = EM.EmployeeGradeId AND LGS.LeaveTypeId = L.LeaveTypeId),0) - L.NoOfLeave) AS AvailableLeave
      
  FROM 
		  sHrm.tLeave L 
		  INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id = L.LeavePeriodId
		  INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
		  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId 
		  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId
	  --INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.EmployeeGradeId = EM.EmployeeGradeId AND LTGS.LeaveTypeId = L.LeaveTypeId 
  WHERE 
		  (L.Id = @rId OR @rId = 0)
      AND (L.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND ((L.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
      AND ((L.FromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
      AND (L.LeaveTypeId = @rLeaveTypeId OR @rLeaveTypeId = 0)      
      AND BatchId = @rBatchId AND L.OrgId = @rOrgId 
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
      AND (L.StatusId = @rStatusId OR @rStatusId = 0)
  Order By L.FromDate DESC
END
GO
PRINT N'Altering [siTax].[pRptEmployeeChallanList]...';


GO
ALTER PROCEDURE [siTax].[pRptEmployeeChallanList]
	@rEmployeeID bigint,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rAssessmentYearId bigint,
	@rBuilder1 VARCHAR(MAX)=null,
	@rBuilder2 VARCHAR(MAX)=null,
	@rStatusId smallint=0
WITH EXECUTE AS CALLER
AS

BEGIN 



--DECLARE @rOrgId INT =3333
--DECLARE @rEmployeeID BIGINT=3333000000046
--DECLARE @rOrgGroupId smallINT=1001
--DECLARE @rAssessmentYearId bigINT=1001000000009




	SELECT @rBuilder1 AS Builder1
		,@rBuilder2 AS Builder2
		,ROW_NUMBER() OVER (PARTITION BY EMP.id   ORDER BY EMP.Code ,PT.YearFor,PT.MonthFor) AS RowNumber
		,EMP.id AS EmployeeID
		,ISNULL(FirstName,'') +' '+ISNULL(MiddleName,'')+' '+ ISNULL(LastName,'') +' - '+ ISNULL(EMP.Code,'') as EmpName
		,PT.[ChallanNo]
		--,CONVERT(VARCHAR(20), PT.[ChallanDate],103) as  [ChallanDate]
		,REPLACE(CONVERT(VARCHAR(20), PT.[ChallanDate],106),' ','-') as  [ChallanDate]
		,PT.[BankCode]
		,DateName(month,DateAdd(month,PT.[MonthFor],-1))  +'-'+ CAST(PT.[YearFor] as VARCHAR)  AS [MonthName]
		,PT.[Amount]
	FROM sHrm.tEmployeeMaster                      AS EMP 
		INNER JOIN sHrm.tEmployeeStatutoryAndOther AS EMO ON EMO.EmployeeId=EMP.Id
		INNER JOIN sHrm.tEmployeeCommunications    AS ECM ON ECM.EmployeeId=EMP.Id
		INNER JOIN sHrm.tEmployeeJobDetail         AS EJD ON EMP.Id = EJD.EmployeeId 
	    INNER JOIN sHrm.tEmployeePersonalDetail    AS EPD ON EMP.Id = EPD.EmployeeId	
		LEFT JOIN  sSetup.tOrganizationMaster      AS OMD ON OMD.Id=EMP.OrgID
		LEFT JOIN  sSetup.tOrganizationOtherDetail AS OOD ON OOD.OrgId=OMD.id
		INNER JOIN [siTax].[tIncomeTaxChallan]     AS PT  ON PT.EmployeeId=EMP.Id
	WHERE EMP.OrgID=@rOrgId AND 
		  ((EMP.StatusId=@rStatusId) OR (@rStatusId=0)) AND 
	      ((EMP.id=@rEmployeeID) OR (@rEmployeeID=0)) AND 
		  PT.AssesmentYearId=@rAssessmentYearId
	ORDER by  EMP.Code ,PT.YearFor,PT.MonthFor
END
GO
PRINT N'Altering [siTax].[pRptForm16PartB]...';


GO
ALTER PROCEDURE [siTax].[pRptForm16PartB]
	@rEmployeeID bigint,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rAssessmentYearId bigint,
	@rBuilder1 VARCHAR(MAX)=null,
	@rBuilder2 VARCHAR(MAX)=null,
	@rStatusId smallint=0
WITH EXECUTE AS CALLER
AS

BEGIN 



--DECLARE @rOrgId INT =3333
--DECLARE @rEmployeeID BIGINT=3333000000046
--DECLARE @rOrgGroupId smallINT=1001
--DECLARE @rAssessmentYearId bigINT=1001000000009




	DECLARE @year INT,@AssessmentYear VARCHAR(1000),@FromDate Date,@ToDate Date,@Place VARCHAR(1000)
	DECLARE @Quarter1 DECIMAL(18,2),@Quarter2 DECIMAL(18,2),@Quarter3 DECIMAL(18,2),@Quarter4 DECIMAL(18,2),@Total DECIMAL(18,2),@AmountWord  VARCHAR(500)

	SELECT @year=SUBSTRING(Title,0,5),@AssessmentYear=Title 
	FROm [siTax].[tAssessmentYear] 
	WHERE id=@rAssessmentYearId 

	SET @year=ISNULL(@year,2000)
	SET @FromDate= CONVERT(DATE, CAST( CAST((@year-1) AS varchar(10)) +'-'+  '4' +'-'+ '1' AS VARCHAR(100)))
	SET @ToDate= CONVERT(DATE, CAST( CAST(@year AS varchar(10)) +'-'+  '3' +'-'+ '31' AS VARCHAR(100)))

	

	DECLARE @EmployeeMaster  TABLE 		(			RowID INT Identity(1,1),			EmployeeID bigINT		)


	

	DECLARE @QuarterDetails	 TABLE 
		(
			RowID INT Identity(1,1),
			EmployeeID bigINT,
			GroupID INT ,SubGroupID INT,
			GroupCount INT,
			GroupHeader VARCHAR(200),
			SubGroupName VARCHAR(200),
			GrossAmount DECIMAL(18,2),
			QualifyingAmount DECIMAL(18,2),
			DeductibleAmount DECIMAL(18,2),
			OrderIndex1 INT,
			OrderIndex2 INT
		)

	INSERT INTO @EmployeeMaster(EmployeeID)
	SELECT EMP.ID 
	FROM sHrm.vExtEmployeeMaster  AS EMP
	INNER JOIN [siTax].[tForm16] AS F16 ON f16.EmployeeId=EMP.ID
	WHERE EMP.OrgID=@rOrgId AND  ((EMP.StatusId=@rStatusId) OR (@rStatusId=0)) AND F16.AssesmentYearId=@rAssessmentYearId

	DECLARE @Count INT = (SELECT COUNT(0) FROM   @EmployeeMaster)
	DECLARE @EmpID BigINT=null


	While (@Count<>0) 
		BEGIN
		
			SELECT @EmpID=EmployeeID 
			FROM @EmployeeMaster 
			WHERE RowID=@Count
	
			INSERT INTO @QuarterDetails
			(
				EmployeeID,
				GroupID,
				SubGroupID,
				GroupCount,
				GroupHeader,
				SubGroupName,
				GrossAmount,
				QualifyingAmount,
				DeductibleAmount,
				OrderIndex1,
				OrderIndex2
			)
	
			SELECT  
				@EmpID,
				ITG.Id,
				ITSG.Id,
				cnt.GroupCount,
				ISNULL(ITG.GroupCode,'') +'  '+ ISNULL(ITG.DisplayName,'') +'  '+ ISNULL(ITG.ActionName,''),
				ITSG.SubGroupName,
				d.GrossAmount,
				d.QualifyingAmount,
				d.DeductibleAmount,
				ITG.OrderIndex,
				ITSG.OrderIndex
			FROm [siTax].[tStaticIncomeTaxGroup] AS ITG 
			LEFT JOIN [siTax].[tStaticIncomeTaxSubGroup] AS ITSG on ITG.Id=ITSG.StaticIncomeTaxGroupId
			LEFT JOIN (
							SELECT StaticIncomeTaxGroupId,count(1) as GroupCount 
							FROm [siTax].[tStaticIncomeTaxSubGroup] 
							GROUP by StaticIncomeTaxGroupId
					  ) AS cnt on cnt.StaticIncomeTaxGroupId=ITG.id
			LEFT JOIN  (
							SELECT FD.IncomeTaxSubgroupId,FD.GrossAmount,FD.QualifyingAmount,FD.DeductibleAmount 
							FROM  [siTax].[tForm16Detail]  AS fd 
							INNER JOIN [siTax].[tForm16] as f on f.id =fd.Form16Id AND  f.EmployeeId=@EmpID and AssesmentYearId=@rAssessmentYearId
					   ) AS d on d.IncomeTaxSubgroupId=ITSG.id
			ORDER by ITG.OrderIndex,ITSG.OrderIndex
			SET @Count=@Count-1
	END

	--SELECT q.GroupID,q.SubGroupID,q.GroupCount,q.GroupHeader,q.SubGroupName,q.GrossAmount,q.QualifyingAmount,q.DeductibleAmount  FROM ##QuarterDetails AS q
	
	SELECT 
		q.GroupID,q.SubGroupID,q.GroupCount,q.GroupHeader,q.SubGroupName
		, CASE WHEN  q.GrossAmount =0 THEN NULL ELSE q.GrossAmount END AS GrossAmount
		, CASE WHEN  q.QualifyingAmount =0 THEN NULL ELSE q.QualifyingAmount END AS QualifyingAmount
		, CASE WHEN  q.DeductibleAmount =0 THEN NULL ELSE q.DeductibleAmount END AS DeductibleAmount
		,ISNULL(FirstName,'') +' '+ISNULL(MiddleName,'')+' '+ ISNULL(LastName,'') as EmpName
		,ISNULL(EMO.PanNumber,'') AS PANNumberEmp
		,ISNULL(ECM.PresentStreetOne,'') +' '+ ISNULL(ECM.PresentStreetTwo,'')+' '+ ISNULL(ECM.PresentStreetThree,'') AS EmpAddLine1
		,ISNULL(ECM.PresentCity,'') +'-'+ISNULL(ECM.PresentZipCode,'') +' '+ISNULL(ECM.PresentState,'') +' '+ ISNULL(ECM.PresentCountry,'')   AS EmpAddLine2
		,ISNULL(oo.TaxCertifyAuthorityName,'') AS Name
		,ISNULL(oo.TaxCertifyAuthorityFatherName,'') AS FatherName
		,ISNULL(oo.TaxCertifyAuthorityDesignation,'') as Designation
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityName,'')+ '</U>' AS NameHTML
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityFatherName,'')+ '</U>' AS FatherNameHTML
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityDesignation,'')+ '</U>' AS DesignationHTML
		,ISNULL(oo.TaxCertifyAuthorityRelation,'') as Relation
		,ISNULL(StreetThree,'') +' - '+ISNULL(CityName,'') AS Place
		,ISNULL(@AssessmentYear,'') AS AssessmentYear
		,REPLACE(CONVERT(VARCHAR,@FromDate,106),' ','-')AS FromDate
		,REPLACE(CONVERT(VARCHAR,@ToDate,106),' ','-') as ToDate
		,REPLACE(CONVERT(VARCHAR,sCommon.fGetDate(),106),' ','-')AS Date
		,EMP.id  as EmployeeID	
		,@rOrgGroupId as OrgGroupId	
		,@rOrgId AS OrgId
		,@rAssessmentYearId AS AssessmentYearId
		,CAST(@rOrgGroupId AS VARCHAR(50)) as OrgGroupIdText
		,CAST(@rOrgId AS VARCHAR(50)) AS OrgIdText
		,CAST(EMP.id AS VARCHAR(50))  as EmployeeIDText
		,CAST(@rAssessmentYearId AS VARCHAR(50))   AS AssessmentYearIdText
	FROM sHrm.tEmployeeMaster  AS EMP 
		INNER JOIN sHrm.tEmployeeStatutoryAndOther AS EMO on EMO.EmployeeId=EMP.Id
		INNER JOIN sHrm.tEmployeeCommunications AS ECM on ECM.EmployeeId=EMP.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EMP.Id = EJD.EmployeeId 
	    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EMP.Id = EPD.EmployeeId	
		LEFT JOIN sSetup.tOrganizationMaster  AS OM ON OM.Id=EMP.OrgID
		LEFT JOIN sSetup.tOrganizationOtherDetail AS oo ON oo.OrgId=om.id
		INNER JOIN @QuarterDetails AS Q ON Q.EmployeeID=EMP.Id
	WHERE EMP.OrgID=@rOrgId 
	AND ((EMP.StatusId=@rStatusId) OR (@rStatusId=0))
	AND ((EMP.id=@rEmployeeID) OR (@rEmployeeID=0))
	ORDER by Q.EmployeeID,OrderIndex1,OrderIndex2
END
GO
PRINT N'Altering [siTax].[pRptTDSReport]...';


GO
ALTER PROCEDURE [siTax].[pRptTDSReport]
	@rEmployeeID bigint,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rAssessmentYearId bigint,
	@rBuilder1 VARCHAR(MAX)=null,
	@rBuilder2 VARCHAR(MAX)=null,
	@rStatusId smallint=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	--DECLARE @rOrgId int =1001
	--DECLARE @rEmployeeID BIGINT=3333000000044,1001000000160
	--DECLARE @rOrgGroupId smallint=1001
	--DECLARE @rAssessmentYearId bigint=1001000000009




	DECLARE @year int,@AssessmentYear VARCHAR(1000),@FromDate Date,@ToDate Date,@Place VARCHAR(1000),@rItemValue NVARCHAR(50)
	DECLARE @Quarter1 Decimal(18,2),@Quarter2 Decimal(18,2),@Quarter3 Decimal(18,2),@Quarter4 Decimal(18,2),@Total Decimal(18,2),@AmountWord  VARCHAR(500)

	SELECT @year=SUBSTRING(Title,0,5),@AssessmentYear=Title 
	FROm [siTax].[tAssessmentYear] 
	WHERE id=@rAssessmentYearId 
	
	SET @year=ISNULL(@year,2000)
	SET @FromDate= CONVERT(DATE, CAST( CAST((@year-1) AS varchar(10)) +'-'+  '4' +'-'+ '1' AS VARCHAR(100)))
	SET @ToDate= CONVERT(DATE, CAST( CAST(@year AS varchar(10)) +'-'+  '3' +'-'+ '31' AS VARCHAR(100)))





	
	
	DECLARE   @EmployeeMaster TABLE(RowID int Identity(1,1),EmployeeID bigint)
	
	
	
	DECLARE	 @QuarterDetails TABLE 
		(
			RowID int Identity(1,1),
			EmployeeID bigint,
			Quarter1 Decimal(18,2),
			Quarter2 Decimal(18,2),
			Quarter3 Decimal(18,2),
			Quarter4 Decimal(18,2),
			Total Decimal(18,2),
			AmountWord NVARCHAR(500),
			TotalHTML NVARCHAR(500)
		)

	INSERT INTO @EmployeeMaster(EmployeeID)
	SELECT EMP.ID 
	FROM sHrm.vExtEmployeeMaster  AS EMP
	INNER JOIN [siTax].[tForm16] AS F16 ON f16.EmployeeId=EMP.ID
	WHERE EMP.OrgID=@rOrgId AND ((EMP.StatusId=@rStatusId) OR (@rStatusId=0)) AND F16.AssesmentYearId=@rAssessmentYearId

	
	select @rItemValue=ISNULL(CGS.ItemValue,CNF.ItemValue) from [sConfig].[tConfigurationMaster] AS CNF
	LEFT JOIN [sConfig].[tConfigurationSetup] AS CGS ON CGS.ConfigurationId=CNF.Id AND CGS.SourceTypeId = 2010 AND CGS.SourceId = @rOrgGroupId
	WHERE CNF.id=211 

	PRINT @rItemValue
		

	DECLARE @Count int = (SELECT COUNT(0) FROM   @EmployeeMaster)
	DECLARE @EmpID Bigint=null


	While (@Count<>0) 
	BEGIN

		SELECT @EmpID=EmployeeID FROM @EmployeeMaster WHERE RowID=@Count
	
		SELECT 
			@Quarter1=ISNULL(SUM(amount),0) 
		FROM [siTax].[tIncomeTaxChallan] 
		WHERE IsObsolete=0 AND   
			  EmployeeId =@EmpID AND 
			  OrgGroupId=@rOrgGroupId AND 
			  AssesmentYearId=@rAssessmentYearId AND 
			  YearFor=(@year-1) AND 
			  MonthFor IN (4,5,6)
		
		SELECT 
			@Quarter2=ISNULL(SUM(amount),0) 
		FROM [siTax].[tIncomeTaxChallan] 
		WHERE IsObsolete=0 AND   
			EmployeeId =@EmpID AND 
			OrgGroupId=@rOrgGroupId AND 
			AssesmentYearId=@rAssessmentYearId AND 
			YearFor=(@year-1) AND -- updated by Kundan : Assessment year is next year for current Finanacial Year
			MonthFor IN (7,8,9)
		
		SELECT 
			@Quarter3=ISNULL(SUM(amount),0) 
		FROM [siTax].[tIncomeTaxChallan] 
		WHERE IsObsolete=0 AND   
			  EmployeeId =@EmpID AND 
			  OrgGroupId=@rOrgGroupId AND 
			  AssesmentYearId=@rAssessmentYearId AND 
			  YearFor=(@year-1) AND 
			  MonthFor IN (10,11,12)
		
		SELECT 
			@Quarter4=ISNULL(SUM(amount),0) 
		FROM [siTax].[tIncomeTaxChallan] 
		WHERE IsObsolete=0 AND   
			  EmployeeId =@EmpID AND 
			  OrgGroupId=@rOrgGroupId AND 
			  AssesmentYearId=@rAssessmentYearId AND 
			  YearFor=(@year) AND 
			  MonthFor IN (1,2,3)
		
		SET @Total=@Quarter1+@Quarter2+@Quarter3+@Quarter4
		SET @AmountWord = [sFinanceCommon].[fNumberToWordsWithDecimal](@Total,0,2,0)+ ' Only'
		
		INSERT INTO 
		@QuarterDetails 
		(
			EmployeeID,
			Quarter1,
			Quarter2,
			Quarter3,
			Quarter4,
			Total,
			AmountWord,
			TotalHTML
		)
		SELECT 
			@EmpID, 
			@Quarter1,
			@Quarter2,
			@Quarter3,
			@Quarter4,
			@Total,
			@AmountWord,
			'<U>'+ CAST(@Total AS NVARCHAR(50)) + '</U>'
	
	
		PRINT @Count 
		PRINT @EmpID 
		SET @Count=@Count-1
	END

	SELECT 
		 CASE WHEN @rItemValue='False' THEN  ISNULL(OM.Title,'') ELSE OG.Title END AS OrgName
		,ISNULL(OM.StreetOne,'') +', '+ISNULL(OM.StreetTwo,'') AS OrgAddLine1
		,ISNULL(OM.CityName,'')+'-'+ISNULL(OM.ZipCode,'')   +' ,'+ISNULL(OM.StateName,'') +' ,'+ISNULL(OM.CountryName,'') AS OrgAddLine2
		,ISNULL(OM.PhoneNo,'') AS PhoneNo
		,ISNULL(OM.Email,'')  AS EmailID
		,ISNULL(oo.PANNumber,'') AS PANNumber
		,ISNULL(oo.TANNumber,'') AS TANNumber
		,ISNULL(oo.TaxOfficeDetail,'') AS TaxOfficeDetail
		,ISNULL(FirstName,'') +' '+ISNULL(MiddleName,'')+' '+ ISNULL(LastName,'') as EmpName
		,ISNULL(EMO.PanNumber,'') AS PANNumberEmp
		,ISNULL(ECM.PresentStreetOne,'') +' '+ ISNULL(ECM.PresentStreetTwo,'')+' '+ ISNULL(ECM.PresentStreetThree,'') AS EmpAddLine1
		,ISNULL(ECM.PresentCity,'') +'-'+ISNULL(ECM.PresentZipCode,'') +' '+ISNULL(ECM.PresentState,'') +' '+ ISNULL(ECM.PresentCountry,'')   AS EmpAddLine2
		,ISNULL(oo.TaxCertifyAuthorityName,'') AS Name
		,ISNULL(oo.TaxCertifyAuthorityFatherName,'') AS FatherName
		,ISNULL(oo.TaxCertifyAuthorityDesignation,'') as Designation
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityName,'')+ '</U>' AS NameHTML
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityDesignation,'')+ '</U>' AS DesignationHTML
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityFatherName,'')+ '</U>' AS FatherNameHTML
		,ISNULL(oo.TaxCertifyAuthorityRelation,'') as Relation
		,ISNULL(StreetThree,'') +' - '+ISNULL(CityName,'') AS Place
		,ISNULL(@AssessmentYear,'') AS AssessmentYear
		,REPLACE(CONVERT(VARCHAR,@FromDate,106),' ','-')AS FromDate
		,REPLACE(CONVERT(VARCHAR,@ToDate,106),' ','-') as ToDate
		,QD.Quarter1 as Quarter1
		,QD.Quarter2 as Quarter2	
		,QD.Quarter3 as Quarter3
		,QD.Quarter4 as Quarter4
		,EMP.id  as EmployeeID	
		,@rOrgGroupId as OrgGroupId	
		,@rAssessmentYearId AS AssessmentYearId
		,REPLACE(CONVERT(VARCHAR,sCommon.fGetDate(),106),' ','-')AS Date
		,QD.Total as Total
		,QD.TotalHTML as TotalHTML
		,'<U>'+  QD.AmountWord +'</U>' as AmountWord
		,ISNULL(ITC.Amount,0) as Amount
		,ITC.BankCode as BankCode
		,ISNULL(CONVERT(VARCHAR(20),ITC.ChallanDate ,103),'') AS ChallanDate
		,ITC.ChallanNo as ChallanNo
		,ROW_NUMBER() OVER (PARTITION BY EMP.id ORDER BY EMP.id, ITC.YearFor, ITC.MonthFor) AS RowNumber
		,CAST(EMP.id AS VARCHAR)  as EmployeeIDText	
		,CAST(@rOrgGroupId AS VARCHAR) as OrgGroupIdText	
		,CAST(@rOrgId	 AS VARCHAR) as OrgIdText		
		,CAST (@rAssessmentYearId AS VARCHAR) AS AssessmentYearIdText	
	FROM sHrm.tEmployeeMaster  AS EMP 
		INNER JOIN sHrm.tEmployeeStatutoryAndOther                         AS EMO ON EMO.EmployeeId=EMP.Id
		INNER JOIN sHrm.tEmployeeCommunications                            AS ECM ON ECM.EmployeeId=EMP.Id
		INNER JOIN sHrm.tEmployeeJobDetail                                 AS EJD ON EMP.Id = EJD.EmployeeId 
	    INNER JOIN sHrm.tEmployeePersonalDetail							   AS EPD ON EMP.Id = EPD.EmployeeId	
		LEFT JOIN sSetup.tOrganizationMaster                               AS OM  ON OM.Id=EMP.OrgID
		LEFT JOIN sSetup.tOrganizationOtherDetail                          AS oo  ON oo.OrgId=om.id
		LEFT JOIN [siTax].[tIncomeTaxChallan]                              AS ITC ON ITC.EmployeeId=EMP.id  AND ITC.IsObsolete=0 AND  ITC.AssesmentYearId=@rAssessmentYearId 
		INNER JOIN @QuarterDetails                                         AS QD  ON QD.EmployeeID=EMP.Id
		LEFT JOIN [sSetup].[tOrgGroupMaster] OG ON  OG.id=OM.OrgGroupId
	WHERE EMP.OrgID=@rOrgId 
		AND ((EMP.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((EMP.id=@rEmployeeID) OR (@rEmployeeID=0))
	ORDER BY EMP.id,ITC.YearFor, ITC.MonthFor,ISNULL(FirstName,'') +' '+ISNULL(MiddleName,'')+' '+ ISNULL(LastName,'')

END
GO
PRINT N'Altering [sLibrary].[pRptBookListCirculationGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptBookListCirculationGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	--@rReaderSourceTypeId smallint,
	 --@rReaderSourceId bigint,
	 --@rOrgId smallint,
	 --@rBatchId int,
	 --@rClassId int,
	 --@rDivisionId int,
	 @rFromLogDate date,
	 @rToLogDate date,
	 @rLibraryId int,
	 @rTopFrequency  smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		SELECT Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2 FROM sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		WHERE (BL.LibraryId=@rLibraryId)
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			GROUP  by BM.Id,BM.Code,BM.Title
			ORDER BY COUNT(BL.Id) desc

END
GO
PRINT N'Altering [sLibrary].[pRptBookListNotIssueGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptBookListNotIssueGet]
@rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rReaderSourceTypeId smallint=0,
	 --@rReaderSourceId bigint,
	 --@rOrgId smallint,	
	
	 @rFromLogDate date,
	 @rToLogDate date,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	SELECT 
	     
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BM.Code AS Code,
			BM.Title AS Title
			
			
	FROM sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			
	--WHERE ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
	--	AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))		
	--	AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	--	AND BL.ReaderSourceTypeId IS NULL AND  BL.ReaderSourceId IS NULL
	--	AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
	--	AND (BL.LibraryId=@rLibraryId)
		WHERE BL.ResourceSourceId  IN (
			SELECT BM.Id FROM sLibrary.tBookLog  BL
			INNER JOIN   sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			WHERE((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))	
			AND BL.LibraryId=@rLibraryId 
			AND BL.ReaderSourceTypeId IS NULL AND  BL.ReaderSourceId IS NULL)
			AND BL.ReaderSourceTypeId IS NULL AND  BL.ReaderSourceId IS NULL
END
GO
PRINT N'Altering [sLibrary].[pRptBookListNotReturnGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptBookListNotReturnGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rReaderSourceTypeId smallint=0,
	 --@rReaderSourceId bigint,
	 @rOrgId smallint=0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 --@rFromLogDate date=,
	 --@rToLogDate date,
	 @rFromDueDate date='',
	 @rToDueDate date='',
	 @rLibraryId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
If(@rReaderSourceTypeId=2003)
BEGIN
	SELECT 
	     
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId ,
			SM.Title AS Status,
			SA.Name,
			SA.RollNo,
			SA.Code,
			SA.ClassName,
			SA.DivisionName,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2
			
			
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005
			INNER JOIN sSetup.tBatchMaster B ON SA.BatchId = B.Id --AND B.IsActive = 1
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		--AND (BL.ReaderSourceId=@rReaderSourceId OR @rReaderSourceId=0)
		AND (SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		--AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		--AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		AND ((BL.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,'') = ''))
		AND ((BL.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,'') = ''))
		AND (BL.StatusId=523) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
END
ELSE If(@rReaderSourceTypeId=95)
BEGIN
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BM.BookSubject,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,			
			BL.StatusId,
			SM.Title AS Status,
			BL.IsCurrentStatus ,
			EM.FirstName+' '+EM.LastName AS Name,
			EM.Code,
			ODM.Title AS EmpDept,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2
	FROM 
			sLibrary.tBookLog BL
			LEFT JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			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
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
				WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		--AND (BL.ReaderSourceId=@rReaderSourceId OR @rReaderSourceId=0)
		--AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		--AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		AND ((BL.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,'') = ''))
		AND ((BL.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,'') = ''))
		AND (BL.StatusId=523)
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
END
END
GO
PRINT N'Altering [sLibrary].[pRptBookLogRegisterGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptBookLogRegisterGet]
	 
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='',
           @rLibraryId int=0,
           @rSourceTypeId int=0,
           @rFromLogDate date='',
           @rToLogDate date='',
           @rOrgId smallint=0,
           @rBatchId int=0,
            @rFromDueDate date='',
	 @rToDueDate date=''
           
AS
SET NOCOUNT ON
BEGIN
SELECT   
	   @rBuilder1 AS Builder1,
	   @rBuilder2 AS Builder2,
	   BL.Id AS BookLogId,
	   BL.LibraryId,
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	'Employee'
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	'Student'
			 ELSE 'Other' END) AS TypeName,

		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.EmployeeName
			WHEN BL.ReaderSourceTypeId = 2003 THEN vSF.Name
			ELSE
			''
			END) AS Name,
			
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.DepartmentName
			WHEN BL.ReaderSourceTypeId = 2003 THEN (vSF.ClassName + ' - '+ vSF.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
		 
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	Emp.Code
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	vSF.Code
			 ELSE '' END) AS Code, 	
	   BL.ReaderSourceTypeId,
	   BL.ReaderSourceId,
	   BL.LogDate,
	   BL.DueDate,
	   BL.ReturnDate,
	   BM.Code AS BookCode,
	   BM.Title AS BookName,
	   OM.DisplayTitle AS OrganizationName,
	    LM.ReportOrgTitle,
	    LM.SmallAddress1,
	    LM.SmallAddress2
	   
  FROM  
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
		LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 95 
		LEFT JOIN sStudent.vStudentLastAcademic vSF
			ON vSF.StudentId = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 2003 
			AND (SELECT IsActive FROM sSetup.tBatchMaster WHERE Id=vSF.BatchId AND IsActive = 1) = 1	
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId			
 
  WHERE 
    BL.StatusId = 523 
	AND BL.LibraryId=@rLibraryId
	AND (BL.LogDate>=@rFromLogDate OR ISNULL(@rFromLogDate,'')='')
	AND (BL.LogDate<=@rToLogDate OR ISNULL(@rToLogDate,'')='')
	AND ((BL.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,'') = ''))
	AND ((BL.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,'') = ''))
	AND ((BL.ReaderSourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
END
GO
PRINT N'Altering [sLibrary].[pRptLibraryRegularUserGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptLibraryRegularUserGet]

		 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	--@rReaderSourceTypeId smallint,
	 --@rReaderSourceId bigint,
	 --@rOrgId smallint,
	 --@rBatchId int,
	 --@rClassId int,
	 --@rDivisionId int,
	 @rFromLogDate date,
	 @rToLogDate date,
	 @rLibraryId int,
	 @rTopFrequency  smallint
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	SELECT 
	     
	        
			 Top(@rTopFrequency) BM.Id,SA.Name,
		SA.RollNo,
		SA.Code,
		SA.ClassName,
		SA.DivisionName, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2 FROM sLibrary.tBookLog BL
INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
	WHERE ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		AND (BL.LibraryId=@rLibraryId)
		GROUP  by BM.Id,SA.Name,SA.RollNo,SA.Code,SA.ClassName,SA.DivisionName
ORDER BY COUNT(BL.Id) desc
		

END
GO
PRINT N'Altering [sLibrary].[pRptMonthlyNotIssuingBookStudentListGet]...';


GO

ALTER PROCEDURE [sLibrary].[pRptMonthlyNotIssuingBookStudentListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rReaderSourceId bigint,
	 @rOrgId smallint=0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromLogDate date='',
	 @rToLogDate date='',
	 @rLibraryId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT    
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BL.Id AS BookLogId,
		BM.Code AS ResourceCode,
		BM.Title AS ResourceName,
		BL.LogDate,
		BL.DueDate,
		--IS1.NoOfBookIssuable,
		BL.StatusId ,
		SM.Title AS Status,
		SA.Name,
		SA.RollNo,
		SA.Code,
		SA.ClassName,
		SA.DivisionName
		--LM.ReportOrgTitle,
  --      LM.SmallAddress1,
  --      LM.SmallAddress2
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
			--INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005
			--INNER JOIN sSetup.tBatchMaster B ON SA.BatchId = B.Id --AND B.IsActive = 1
			--LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE (BL.ReaderSourceTypeId=2003) 
		AND (SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		AND (BL.StatusId=523) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
		AND BL.ReaderSourceId NOT IN (SELECT Id FROM sStudent.tAcademic) 

END
GO
PRINT N'Altering [sPayroll].[pCopyPaySetupAdd]...';


GO
ALTER PROCEDURE [sPayroll].[pCopyPaySetupAdd]
	  
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rOrgGroupId int,
     @rCopyGradeId bigint,
     @rPayrollId int,
     @rPayrollYearId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       DELETE PSD FROM sPayroll.tPaySetup PS INNER JOIN  sPayroll.tPaySetupDependent PSD ON PSD.PaySetupId = PS.ID 
	   WHERE SourceId = @rCopyGradeId AND SourceTypeId = @rSourceTypeId AND PayrollId = @rPayrollId  AND PayrollYearId = @rPayrollYearId
		
	   DELETE FROM sPayroll.tPaySetup WHERE SourceId = @rCopyGradeId AND SourceTypeId = @rSourceTypeId AND PayrollId = @rPayrollId AND PayrollYearId = @rPayrollYearId
		
		DECLARE @1Count int
		DECLARE @1PaySetupId int
		DECLARE @lNextNumber BIGINT
		
		CREATE TABLE #TempTable
		(
		    ID INT IDENTITY(1,1),
		    PaySetupId INT,
		    PayElementId INT,
		    AMOUNT DECIMAL(22,2),
		    Percentage DECIMAL(22,2),
		    ProcessOrder int,
		    DefaultAmount decimal(22,2)
		 ) 
       		
       	INSERT INTO #TempTable 
        SELECT  ID, 
         PayElementId
		,[Amount]
		,[Percentage]
        ,[ProcessOrder]  
        
	   FROM [sPayroll].[tPaySetup] PS   
			  
	   WHERE PayrollId = @rPayrollId  AND PayrollYearId = @rPayrollYearId  AND  PS.SourceTypeId = @rSourceTypeId AND PS.SourceId = @rSourceId
	   
	   SELECT @1Count = COUNT(Id) FROM #TempTable
	   
	   WHILE @1Count > 0	     
	     BEGIN 
	        SET @1PaySetupId = 0
	        EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPaySetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	        
	        INSERT INTO sPayroll.tPaySetup   
	        SELECT @lNextNumber,
				   @rSourceTypeId,      
                   @rCopyGradeId,
	               PayElementId
				   ,[Amount]
				   ,[Percentage]
				   ,[ProcessOrder]     
	               ,@rPayrollId
	               ,NULL
	               ,@rPayrollYearId
	               ,[DefaultAmount]
	                
	        FROM #TempTable Where Id = @1Count				    
	        
	        SELECT @1PaySetupId = PaySetupId From #TempTable Where Id = @1Count
	        
	        IF EXISTS(SELECT 1 FROM sPayroll.tPaySetupDependent Where PaySetupId = @1PaysetupId)
	          BEGIN  
	          
	                --Select @1PaysetupId
	                INSERT INTO sPayroll.tPaySetupDependent
	                SELECT DependentPayElementId,@lNextNumber,IsDeduct FROM sPayroll.tPaySetupDependent Where PaySetupId = @1PaysetupId	               
	          END       
	          
	        SET @1Count = @1Count - 1
	     END
	     
	     DROP TABLE #TempTable
	     
	     SELECT @lNextNumber AS Result
       
END
GO
PRINT N'Altering [sProcurement].[pStockInward]...';


GO
ALTER PROCEDURE [sProcurement].[pStockInward]
	
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rStoreLocationId int,
	@rFromDate date='',
	@rToDate date='',
	@rVendorId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	  
	SELECT		
			SI.Id,
			SI.Number,
			isnull(SI.StockInwardRequestId,0) as StockInwardRequestId,
			isnull(SI.InwardByName,'') as InwardByName,
			SI.CreatedDateTime			AS TransactionDate,
			SLM.Code					AS ToStoreLocationCode,
			SIReq.Number				AS RequestNumber,	
			SI.TransactionDate AS InwardDate,
			SIReq.CreatedDateTime AS RequestedDate,		
			--Case when SI.TransactionDate is not null then SI.TransactionDate else isnull(SIReq.CreatedDateTime,'') end
			--AS RequestedDate,
			SI.VendorId,
			 SIM.Code AS StockItemCode,
					SIM.TItle As StockItemName
			
	FROM		
		    sProcurement.tStockInward SI
			INNER JOIN	sIp.tStoreLocationMaster SLM ON SLM.Id = SI.ToStoreLocationId 		
			LEFT JOIN	sProcurement.tStockInwardRequest SIReq ON SIReq.Id = SI.StockInwardRequestId
			
			Inner join sProcurement.tStockInwardDetail SIDE on SI.ID= SIDE.StockInwardId
			INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SIDE.StockItemID

	WHERE		
			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = '*'))
			AND        SI.OrgGroupId = @rOrgGroupId	
			AND ((SI.CreatedDateTime>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SI.CreatedDateTime<=DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
			AND SI.ToStoreLocationId =@rStoreLocationId
			AND ((SI.VendorId=@rVendorId) or (@rVendorId=0))
			order by SI.Number desc
 
END


--select *From  sProcurement.tStockInwardDetail
GO
PRINT N'Altering [sProcurement].[pStockIssGet]...';


GO
 
ALTER PROCEDURE [sProcurement].[pStockIssGet]
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0,
	@rItemCode nvarchar(100)='',
	@rItemName nvarchar(200)='',
	@rSearchType nvarchar(5)= '1'
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	  
SET @rNumber = sCommon.fSearchStringGet(@rNumber)
	if(@rSearchType='1')
		begin
				SELECT		
				SI.Id,SI.Number,isnull(SI.StockIssueRequestId,0) as StockIssueRequestId,
				SI.IssuedByName,
				case when SI.TransactionDate is not null  then SI.TransactionDate else  SI.CreatedDateTime End AS IssuedDate,
				 SI.CreatedDateTime as TranjactionDate,
				 '' StockItemCode,
				 '' StockItemName
				FROM sProcurement.tStockIssue SI 
				WHERE ((Number like @rNumber) OR (@rNumber = ''))
				AND  SI.OrgGroupId = @rOrgGroupId
				AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SI.FromStoreLocationId=@rStoreLocationId 
				Order by SI.CreatedDateTime desc
		end
	else
		begin
				SELECT		
					SI.Id,SI.Number,isnull(SI.StockIssueRequestId,0) as StockIssueRequestId,
					SI.IssuedByName,
					case when SI.TransactionDate is not null  then SI.TransactionDate else  SI.CreatedDateTime End	AS IssuedDate,
					 SI.CreatedDateTime as TranjactionDate,
					 SIM.Code AS StockItemCode,
					SIM.TItle As StockItemName
				FROM sProcurement.tStockIssue SI 
				Inner join sProcurement.tStockIssueDetail SIDE on SI.ID= SIDE.StockIssueId
				INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SIDE.StockItemID
				WHERE ((Number like @rNumber) OR (@rNumber = ''))
				AND  SI.OrgGroupId = @rOrgGroupId
				AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))

				AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SI.FromStoreLocationId=@rStoreLocationId 
				AND (SIM.Id = @rItemCode or @rItemCode='')
				AND (SIM.Id = @rItemName or @rItemName='')
				Order by SI.CreatedDateTime desc
		end
END
GO
PRINT N'Altering [sProcurement].[pStockIssueReturnSearchGet]...';


GO

ALTER PROCEDURE [sProcurement].[pStockIssueReturnSearchGet]

	@rIssueReturnNumber nvarchar(30) = '',
	@rStoreLocationId int,
	@rIssueToName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	    SELECT 
	          SIR.Id AS StockIssueReturnId,
			  SIR.Number AS IssueReturnNumber,
			  SIR.ToStoreLocationId,
			  SI.Number AS IssueNumber,
			  SIR.TransactionDate,
			  U.DisplayTitle AS UserName,
			  SI.IssueToName
		FROM 
			  sProcurement.tStockIssueReturn SIR 
			  INNER JOIN sProcurement.tStockIssue SI ON SI.Id=SIR.StockIssueId
			  LEFT JOIN sSecurity.tUser U ON U.Id = SIR.CreatedUserId
	   	WHERE 
	   	      ((SIR.Number = @rIssueReturnNumber) OR (@rIssueReturnNumber = ''))
	   	      AND ((SIR.ToStoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
	   		  AND ((SI.IssueToName like @rIssueToName+'%') OR (@rIssueToName = ''))
	   		  AND ((SIR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
	   		  
END
GO
PRINT N'Altering [sSecurity].[pAppPermissionGet]...';


GO
 
ALTER PROCEDURE [sSecurity].[pAppPermissionGet]
	@rOrgGroupId [int],
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@rOrgGroupId)

	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(20075,20086,20094,20107,20126,20171,20184,20538,20561,20983,30032,30502,30501,30505,30504,30508,30507,30506,30536,30546,30547,30550,30551,30560,30572,30573,20089,30607,30621,30630,30621,20555,30635)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(20075,20086,20094,20107,20126,20171,20184,20538,20561,20983,30032,30502,30501,30505,30504,30508,30507,30506,30536,30546,30547,30550,30551,30560,30572,30573,20089,30607,30621,30630,30621,20555,30635)
		) TP 
		GROUP BY TP.TaskId
	END
END
GO
PRINT N'Altering [sSecurity].[pStudentPasswordGet]...';


GO
ALTER PROCEDURE [sSecurity].[pStudentPasswordGet]
	
	@rOrgId smallint,
	@rBatchId int,
	@rClassId int,
	@rDivisionId int,
	@rIsPendingLogin  bit,
	@rIsCreatedLogin bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
			ISNULL(U.Id,0) AS Id,
			A.StudentId,
			SM.Code,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle + '-' + DM.DisplayTitle AS ClassName,
			A.RollNo,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword,
			STM.Title AS Status
	FROM 
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId			 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id	
	        LEFT JOIN sSecurity.tUser U ON U.SourceId=SC.StudentId AND U.SourceTypeId=2003 
	        INNER JOIN sStudent.tStatusMaster STM ON STM.Id = SM.StatusId 
	WHERE 
			((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND	(A.OrgId = @rOrgId)
		AND	(A.BatchId = @rBatchId)
		AND SM.StatusId = 1
		AND ((U.LoginPassWord is Null AND @rIsPendingLogin=1) OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1))
		Order By A.RollNo
END
GO
PRINT N'Altering [sSetup].[pBatchMasterAdd]...';


GO
ALTER PROCEDURE [sSetup].[pBatchMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rOrgId int,
	@rIsHistory bit,
	@rIsObsolete bit,
	@rOrderIndex smallint,
	@rFromDate date,
	@rToDate date,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupBatchId int,
	@rBatchGroupId int=0,
	@rLeaveYearFromDate date,
	@rLeaveYearToDate date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
	DECLARE @lBatchCount int,@lBatchCountActive int
	DECLARE @lTermPattern int
	DECLARE @lIsInContext bit,@lIsActive bit
	
	SELECT @lBatchCountActive = ISNULL(COUNT(ID),0) FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId
	
	SELECT @lBatchCount = ISNULL(COUNT(ID),0) FROM sSetup.tBatchMaster WHERE OrgGroupBatchId = @rOrgGroupBatchId AND OrgId = @rOrgId
	SELECT @lTermPattern = TermPatternId FROM sSetup.tOrganizationMaster WHERE  Id = @rOrgId
	
	IF (@lBatchCount >= @lTermPattern)
	BEGIN
	SELECT -101 AS Result
	RETURN
	END
	
	IF (@lBatchCountActive = 0)
	SET @lIsActive = 1
	ELSE
	SET @lIsActive = 0
	
	IF (@lTermPattern = 1)
		SET @lIsInContext = 1
	ELSE IF (@lTermPattern = 2 AND  @lBatchCount = 0)
		SET @lIsInContext = 1
	END
	--BEGIN
	--		IF EXISTS(SELECT 1 FROM sSetup.tBatchMaster WHERE OrgId=@rOrgId AND OrgGroupBatchId=@rOrgGroupBatchId)
	--		BEGIN
	--			SELECT -100 AS Result
	--			RETURN
	--		END
	--END
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sSetup.tBatchMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sSetup.tBatchMaster
		(
			Id,
			Code,
			Title,
			OrgId,
			IsHistory,
			IsObsolete,
			OrderIndex,
			FromDate,
			ToDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupBatchId,
			IsInContext,
			IsActive,
			BatchGroupId,
			LeaveYearFromDate,
			LeaveYearToDate
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rOrgId,
			@rIsHistory,
			@rIsObsolete,
			@rOrderIndex,
			@rFromDate,
			@rToDate,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupBatchId,
			@lIsInContext,
			@lIsActive,
			@rBatchGroupId,
			@rLeaveYearFromDate,
			@rLeaveYearToDate
		)
	
	-- Insert Batch Class
	INSERT INTO sSetup.tBatchClass
	SELECT @lNextNumber,Id
	FROM sSetup.tClassMaster
	WHERE OrgId = 	@rOrgId
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sSetup.tBatchMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			OrgId=@rOrgId,
			--IsHistory=@rIsHistory,
			IsObsolete=@rIsObsolete,
			OrderIndex=@rOrderIndex,
			BatchGroupId=@rBatchGroupId,
			FromDate=@rFromDate,
			ToDate=@rToDate,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			LeaveYearFromDate=@rLeaveYearFromDate,
			LeaveYearToDate=@rLeaveYearToDate
			
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pBatchMasterGet]...';


GO
ALTER PROCEDURE [sSetup].[pBatchMasterGet]
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rOrgId int,
	 @rIsSearch bit=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgGroupId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF(@rIsSearch=1)
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			BM.Id,
			BM.Code,
			BM.Title,
			BM.OrgId,
			BM.IsHistory,
			BM.IsObsolete,
			ISNULL(BM.IsActive,0) AS IsActive,
			BM.OrderIndex,
			BM.FromDate,
			BM.ToDate,
			BM.CreatedUserId,
			BM.CreatedDateTime,
			BM.UpdatedUserId,
			BM.UpdatedDateTime,
			ISNULL(BM.OrgGroupBatchId,0) AS OrgGroupBatchId,
			ISNULL(BM.IsInContext,0) AS IsInContext,
			OGBM.Title AS OrgGroupBatchTitle,
			OM.DisplayTitle AS OrganizationName,
			OGBM.Id AS OrgGroupBatchId,
			OGBM.OrgGroupId,
			ISNULL(BM.batchGroupId,0) AS BatchGroupId,
			ISNULL(BM.LeaveYearFromDate,'') AS LeaveYearFromDate,
			ISNULL(BM.LeaveYearToDate,'') AS LeaveYearToDate
			
  FROM 
            sSetup.tBatchMaster BM
            INNER JOIN sSetup.tOrgGroupBatchMaster OGBM
				ON OGBM.Id = BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OM.Id = BM.OrgId
			LEFT join sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.batchGroupId  
  WHERE 
  
    ((BM.Id = @rId) OR (@rId = 0))
    AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
	AND ((BM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))  
	AND ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))  
	--AND BM.IsActive=1
	--AND(BM.OrgId=@rOrgId)

ORDER BY OM.Id, BM.OrderIndex ASC
END
GO
PRINT N'Altering [sSetup].[pMastedDataModify]...';


GO
ALTER PROCEDURE [sSetup].[pMastedDataModify]	 
	@rCategoryId int,
	@rXML nvarchar(max),
	@rSubCategoryField nvarchar(100)--,
	--@rOrgId int = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
Declare @Sql nvarchar(max) 
DECLARE @loDoc INT

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'InchargeEmployee') 	
		SET @rSubCategoryField = @rSubCategoryField + 'Id'	
	
	
	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id int,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)  
		BEGIN
		
		insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
						
		select *from ListofData				
		UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tOrganizationMaster ) 
		
		set @sql='INSERT INTO sSetup.tOrganizationMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tOrganizationMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tOrganizationMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
	else IF(@rCategoryId= 2)     
	 
	 BEGIN
	 
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tClassMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tClassMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tClassMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tClassMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  END
	  
	  
	  else IF(@rCategoryId= 3)
	  BEGIN
	     
	     insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tDivisionMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tDivisionMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tDivisionMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tDivisionMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		--print @sql
		--return
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    
	  
	  END    
	  
	  else IF(@rCategoryId= 4)
	  BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tSubjectMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tSubjectMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tSubjectMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tSubjectMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  
	  END 
	    
	 else IF(@rCategoryId= 5)
	 
	 BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tOrgGroupBatchMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tOrgGroupBatchMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tOrgGroupBatchMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tOrgGroupBatchMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  
	  END 
	  
   else IF(@rCategoryId= 6)
	 BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tBatchMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tBatchMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tBatchMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tBatchMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	  
	else IF(@rCategoryId= 7)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tDepartmentMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tDepartmentMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tDepartmentMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tDepartmentMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	  
	  
 else IF(@rCategoryId= 8)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sCommon.tOrgGroupDepartmentMaster ) 
	    
	    set @sql='INSERT INTO sCommon.tOrgGroupDepartmentMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sCommon.tOrgGroupDepartmentMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sCommon.tOrgGroupDepartmentMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	    
	 	
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
GO
PRINT N'Altering [sSetup].[pPortalStudentAcademicMasterGet]...';


GO
ALTER PROCEDURE [sSetup].[pPortalStudentAcademicMasterGet]
	 
	 @rOrgId int,
	 @rDivisionId int = 0,
	 @rBatchId int,	
	 @rStudentAcademicCreatedDate DateTime,
	 @rStudentAcademicUpdatedDate DateTime,	 
	 @rStudentMaxId bigint
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	 
BEGIN 	
	SELECT  
		Id,
		StudentId,
		ClassId,
		DivisionId,
		RollNo,
		OrgId,
		BatchId,
		CreatedUserId,
		ISNULL(CreatedDateTime,sCommon.fGetDate()) AS CreatedDateTime,	
		ISNULL(UpdatedUserId,0) AS UpdatedUserId,
		ISNULL(UpdatedDateTime,sCommon.fGetDate()) AS UpdatedDateTime,
		ISNULL(IsCurrent,0) AS IsCurrent,
		ISNULL(BatchStatusId,0) AS BatchStatusId,
		ISNULL(ExemptionTypeId,0) AS ExemptionTypeId,
		ISNULL(FeeStructureId,0) AS FeeStructureId,
		ISNULL(AdmissionCategoryId,0) AS AdmissionCategoryId,
		ISNULL(ClassStatusId,0) AS ClassStatusId
  FROM 
           sStudent.tAcademic
             
  WHERE   oRGiD = @rOrgId and
   DivisionId = @rDivisionId 
  And BatchId=@rBatchId 
  --AND StudentId > @rStudentMaxId
  --AND ( Convert(datetime,CreatedDatetime,120) > @rStudentAcademicCreatedDate OR  Convert(datetime,UpdatedDatetime,120) > @rStudentAcademicUpdatedDate)
     AND  (CONVERT(DATETIME,CONVERT(VARCHAR(20),CONVERT(DATETIME,  CreatedDateTime), 120)) > @rStudentAcademicCreatedDate OR 
       CONVERT(DATETIME,CONVERT(VARCHAR(20),CONVERT(DATETIME,  UpdatedDateTime), 120)) > @rStudentAcademicUpdatedDate )
  
  END
GO
PRINT N'Altering [sSetup].[pPortalStudentAcademicMasterUpdate]...';


GO


ALTER PROCEDURE [sSetup].[pPortalStudentAcademicMasterUpdate]
	 
	
	@rStrXml [nvarchar](max),
	@rDivisionId int
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	--BEGIN TRY
	
	 BEGIN	
	 --DELETE FROM sStudent.tAcademic WHERE DivisionId = @rDivisionId
	
	 UPDATE sStudent.tAcademic
		SET
			StudentId = A.StudentId,
			ClassId = A.ClassId,
			DivisionId = A.DivisionId,
			RollNo = A.RollNo,
			OrgId = A.OrgId,
			BatchId = A.BatchId,
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime,
			CreatedDateTime = A.CreatedDateTime,
			IsCurrent=A.IsCurrent,
			BatchStatusId=A.BatchStatusId,
			ExemptionTypeId=A.ExemptionTypeId,
			FeeStructureId=A.FeeStructureId,
			AdmissionCategoryId=A.AdmissionCategoryId,
			ClassStatusId=A.ClassStatusId
		FROM
		(
		SELECT		
			Id,
			StudentId,
			ClassId,
			DivisionId,
			RollNo,
			OrgId,
			BatchId,
			UpdatedUserId,
			UpdatedDateTime,
			CreatedDateTime,
			IsCurrent,
			BatchStatusId,
			ExemptionTypeId,
			FeeStructureId,
			AdmissionCategoryId,
			ClassStatusId
						
		FROM OPENXML (@loDoc, '/Table/Academic', 1)
		WITH ( 
				Id bigint,
				StudentId bigint,
				ClassId int,					
				DivisionId int,
				RollNo int,
				OrgId int,
				BatchId int,
				UpdatedUserId bigint,
				UpdatedDateTime DateTime,
				CreatedDateTime DateTime,
				IsCurrent bit,
				BatchStatusId smallint,
				ExemptionTypeId int,
				FeeStructureId int,
				AdmissionCategoryId int,
				ClassStatusId smallint
			  )) A
			  Where sStudent.tAcademic.Id = A.Id
			  
			  
	   INSERT INTO sStudent.tAcademic
		(
			Id,
			StudentId,
			ClassId,
			DivisionId,
			RollNo,
			OrgId,
			BatchId,
			CreatedUserId,
			UpdatedUserId,
			UpdatedDateTime,
			CreatedDateTime,
			IsCurrent,
			BatchStatusId,
			ExemptionTypeId,
			FeeStructureId,
			AdmissionCategoryId,
			ClassStatusId
			)
		SELECT		
			A.Id,
			A.StudentId,
			A.ClassId,
			A.DivisionId,
			A.RollNo,
			A.OrgId,
			A.BatchId,
			A.CreatedUserId,
			A.UpdatedUserId,
			A.UpdatedDateTime,
			A.CreatedDateTime,
			A.IsCurrent,
			A.BatchStatusId,
			A.ExemptionTypeId,
			A.FeeStructureId,
			A.AdmissionCategoryId,
			1
						
		FROM OPENXML (@loDoc, '/Table/Academic', 1)
		WITH ( 
				Id bigint,
				StudentId bigint,
				ClassId int,					
				DivisionId int,
				RollNo int,
				OrgId int,
				BatchId int,
				CreatedUserId bigint,
				UpdatedUserId bigint,
				UpdatedDateTime DateTime,
				CreatedDateTime DateTime,
				IsCurrent bit,
				BatchStatusId smallint,
				ExemptionTypeId int,
				FeeStructureId int,
				AdmissionCategoryId int		
			  ) A LEFT JOIN sStudent.tAcademic AC ON A.Id = AC.Id
			  WHERE AC.Id IS NULL
			  
			  EXEC sp_xml_removedocument @loDoc
		
        SELECT 1 AS Result
	 END	
	
		
	--END TRY
	
	--BEGIN CATCH 
	
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pAcademicAdd]...';


GO
ALTER PROCEDURE [sStudent].[pAcademicAdd]
	 
	@rAcademicId bigint=0,
	@rStudentId bigint=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=0,
	@rOrgId int=0,
	@rBatchId int=0,
	@rCreatedUserId bigint=0,
	@rUpdatedUserId bigint=0,
	@rAdmissionCategoryId int = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	SET @rRollNo = ISNULL(@rRollNo,0)
	
	 BEGIN TRANSACTION	
 IF NOT EXISTS(Select Id from sStudent.tAcademic where StudentId=@rStudentId AND BatchId=@rBatchId)
BEGIN
	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tAcademic', 0, 1, 1,@outNextNumber = @lNextNumber output



--IF ISNULL(@rRollNo,0) <> 0
--BEGIN
--IF EXISTS(Select Id from sStudent.tAcademic where RollNo = @rRollNo AND DivisionId = @rDivisionId )
--BEGIN
--SET @rRollNo = 0
--END
--END
--ELSE
--BEGIN
--  SELECT @rRollNo =  (ISNULL(max(RollNo),0) + 1) FROM  sStudent.tAcademic where DivisionId=@rDivisionId AND BatchId=@rBatchId
--END
 
	INSERT INTO sStudent.tAcademic
		(
			Id,
			StudentId,
			ClassId,
			DivisionId,
			RollNo,
			OrgId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			IsCurrent,
			BatchStatusId,
			AdmissionCategoryId,
			ClassStatusId
		)
	VALUES
		(
			@lNextNumber,
			@rStudentId,
			@rClassId,
			@rDivisionId,
			@rRollNo,
			@rOrgId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate()
			,1
			,1
			,@rAdmissionCategoryId,
			1
		)	
		
	   INSERT INTO sStudent.tAcademicDetail
		(
		AcademicId,
		RepeatCount
		)
		VALUES
		(
		@lNextNumber,
		1
		)
			
        UPDATE sStudent.tAcademic SET IsCurrent = 0 WHERE StudentId = @rStudentId AND OrgId = @rOrgId AND BatchId <>  @rBatchId        
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rAcademicId
	 
	 
--if ISNULL(@rRollNo,0) <> 0
--BEGIN
--IF EXISTS(Select Id from sStudent.tAcademic where RollNo = @rRollNo AND DivisionId = @rDivisionId AND Id <> @rAcademicId )
--BEGIN
--SET @rRollNo = 0
--END
--END
	 
	    UPDATE sStudent.tAcademic
	    SET
			ClassId=@rClassId,
			DivisionId=@rDivisionId,
			RollNo=@rRollNo,
			OrgId=@rOrgId,
			BatchId=@rBatchId,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate() ,
			AdmissionCategoryId = @rAdmissionCategoryId
	      WHERE 
	       --Id = @rAcademicId  AND 
	       StudentId=@rStudentId  AND 
	       BatchId = @rBatchId
	      
	 END  			
		COMMIT TRANSACTION
		SELECT @lNextNumber AS Result
		
	--UPDATE sStudent.tAcademic SET BatchStatusId = 1 WHERE BatchStatusId is null
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pGetDropDownLists]...';


GO

ALTER proc [sStudent].[pGetDropDownLists]
@rBatchId int,
@rOrgId int,
@rUserId bigint,
@rDepartmentId int,
@rOrgGroupBatchId int=0,
@rOrgGroupId int=0
as
begin
	declare @lStatusRes nvarchar(max)='',@lClassRes Nvarchar(max)='',@lEnrollmentStatusRes nvarchar(max)=''
	declare @lDepartmentRes nvarchar(max)='',@lDivisionRes Nvarchar(max)='',@lAvailableRes nvarchar(max)=''
	declare @lReportList nvarchar(max)='',@lExamRes nvarchar(max)='',@lGeneralExamRes nvarchar(max)='',@lcastdropdown nvarchar(max)=''
	declare @lExamReportList nvarchar(max)=''
	declare @lclassdropdown nvarchar(max)='',@lStatusdropdown nvarchar(max)='',@lGenderdropdown nvarchar(max)='',@lReligiondropdown nvarchar(max)=''
	declare @lCitydropdown nvarchar(max)='',@lAreadropdown nvarchar(max)='',@lNationalitydropdown nvarchar(max)='',@lTranspotrmodedropdown nvarchar(max)='',@lbusrouedropdown nvarchar(max)=''
	declare @lbusrotedestinationdrop nvarchar(max)='',@lblooddropdown nvarchar(max)='',@lhousedropdown nvarchar(max)='',@lmothertoungedropdown nvarchar(max)='',@lpriviousschooldropdown nvarchar(max)=''
	declare @lfatherqadrop nvarchar(max)='',@lmotherqadropdown nvarchar(max)='',@lfatherocdropdown nvarchar(max)='',@lmotherocdropdown nvarchar(max)='',@lfeescategorydropdown nvarchar(max)=''
	declare @lCustomtagdrop nvarchar(max)='',@lcustomgroupdropdown nvarchar(max)='',@lclubdropdown nvarchar(max)='',@lhosteldropdown nvarchar(max)='',@lstudentgroupdropdown nvarchar(max)=''
	declare @lstudentothergroupdropdown nvarchar(max)='',@lExaminationtypedropdown nvarchar(max)=''
	declare @lSavedReport nvarchar(max)='',@lSavedReport1 nvarchar(max)=''

	
	select @lDivisionRes = @lDivisionRes + '<option value="0"> -- ALL -- </option>'
	
	select @lStatusRes = @lStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lStatusRes = @lStatusRes + '<option value="1">Active</option>'
	select @lStatusRes = @lStatusRes + '<option value="2">InActive</option>'
	select @lStatusRes = @lStatusRes + '<option value="3">Left</option>'
	
	select @lClassRes = @lClassRes + '<option value="0"> -- ALL -- </option>'
	select @lClassRes = @lClassRes + '<option value="' + convert(varchar,ClassId) + '">' + ClassName + '</option>'
	from sSetup.vBatchClass where IsObsolete = 0 and BatchId = @rBatchId order by OrderIndex
	
	select @lEnrollmentStatusRes = @lEnrollmentStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lEnrollmentStatusRes = @lEnrollmentStatusRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sStudent.tEnrollmentStatusMaster where IsObsolete = 0 order by Title
	
	select @lDepartmentRes = @lDepartmentRes + '<option value="0"> -- ALL -- </option>'
	select @lDepartmentRes = @lDepartmentRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sSetup.vDepartment where IsObsolete = 0 AND OrgId = @rOrgId and UserId = @rUserId
	and (Id = @rDepartmentId or @rDepartmentId = 0) order by Title
	
	select @lAvailableRes = @lAvailableRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sStudent' AND TABLE_NAME='vStudentColumnName' AND COLUMN_NAME <> 'GR No'
	
	
	DECLARE @lAvailableStudentColumns nvarchar(max)=''
	 DECLARE @lAvailableStudentCustomRes nvarchar(max)=''
	 Declare @Title as nvarchar(max)


	   SET @lAvailableStudentColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
						from sStudent.tStudentCustomFieldMaster PP WHERE PP.IsObsolete=0 AND PP.OrgGroupId =@rOrgGroupId
				FOR XML PATH(''), TYPE
				).value('.', 'NVARCHAR(MAX)') 
			,1,1,'')
	        
		DECLARE @lStudentCustomFields TABLE
		(
		  Title nvarchar(max)
		)
		 INSERT INTO  @lStudentCustomFields      
		select Item AS Title from sCommon.fnSplit(@lAvailableStudentColumns , ',')

	        
		select @lAvailableStudentCustomRes = @lAvailableStudentCustomRes +'<option class=StudentCustom value="|' + Title + '||">|' + Title + '||</option>'
		from @lStudentCustomFields
		
		--select @lAvailableStudentCustomRes = @lAvailableStudentCustomRes +'<option class=StudentCustom value="''[' + Title + ']''">''[' + Title + ']''</option>'
		--from @lStudentCustomFields  
		
		--print @lAvailableStudentCustomRes
	
	
	
	select @lGeneralExamRes = @lGeneralExamRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sAssessment' AND TABLE_NAME='vGeneralExamColumnName'
	
	--select @lReportList = @lReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	--<td style="width:670px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	--<td style="width:80px; word-wrap:break-word;"><a onclick="ViewReport(' + convert(varchar(20),SCS.Id) + ',''' + convert(varchar(20),SCS.Title) + ''',''' + convert(varchar(max),SCS.ColumnName) +''');">View</a></td>
	--<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	--<td style="width:50px; word-wrap:break-word;text-align: center;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><img src="../../Images/Del.png"></a></td></tr>'
	--from sStudent.tStudentCustomSearch SCS
	--INNER JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	--WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1)
	--AND SCS.IsCommonForOrg = 0 OR SCS.IsCommonForOrg IS NULL
	--AND SCS.OrgId = @rOrgId
	
	select @lReportList = @lReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:670px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:80px; word-wrap:break-word;"><a onclick="ViewReport(' + convert(varchar(20),SCS.Id) + ',''' + convert(varchar(20),SCS.Title) + ''',''' + convert(varchar(max),SCS.ColumnName) +''');">View</a></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;text-align: center;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><img src="../../Images/Del.png"></a></td></tr>'
	from sStudent.tStudentCustomSearch SCS
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	LEFT JOIN sSecurity.tUser U ON U.Id = SCS.CreatedUserId   
	WHERE SCS.CreatedUserId = @rUserId OR (SCS.IsCommon = 1) OR (SCS.IsCommonForOrg = 1)
	
	
	select @lExamReportList = @lExamReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"><a onclick="ViewReport(' + convert(varchar(20),SCS.Id) + ',''' + convert(varchar(20),SCS.Title) + ''',''' + convert(varchar(max),SCS.ColumnName) +''');">View</a></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><img src="/Images/Del.png"></i></a></td></tr>'
	from sAssessment.tGeneralExamCustomSearch SCS
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	LEFT JOIN sSecurity.tUser U ON U.Id = SCS.CreatedUserId 
	WHERE (SCS.CreatedUserId = @rUserId) OR (SCS.IsCommon = 1) OR ( SCS.IsCommonForOrg = 1)
		
	select @lExamRes = @lExamRes + '<option value="0"> -- ALL -- </option>'
	select @lExamRes = @lExamRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sAssessment.tExamSubGroupMaster where OrgId = @rOrgId
	
					--select @lclassdropdown=@lclassdropdown+'<option value="0"> -- ALL -- </option>'
					select @lclassdropdown = @lclassdropdown + '<option value="' + convert(varchar,DivisionId) + '">' + ClassDivisionName + '</option>'
					from sSetup.vBatchClassDivision where IsObsolete = 0 and BatchId = @rBatchId order by OrderIndex

					select @lStatusdropdown = @lStatusdropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
					from sStudent.tStatusMaster where IsObsolete = 0

					select @lGenderdropdown = @lGenderdropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
					from sCommon.tGenderMaster where IsObsolete = 0
					select @lReligiondropdown = @lReligiondropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
					from sCommon.tReligionMaster where IsObsolete = 0 
					and OrgGroupId = @rOrgGroupId

					select @lcastdropdown = @lcastdropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
					from sCommon.tCastCategoryMaster where IsObsolete = 0 
					and OrgGroupId = @rOrgGroupId
					order by OrderIndex

					select @lCitydropdown = @lCitydropdown + '<option value="' +convert(varchar,OrgId)+ '">' + City + '</option>'
					from sStudent.vCity where OrgId = @rOrgId

					select @lAreadropdown = @lAreadropdown + '<option value="' +convert(varchar,OrgId)+ '">' + Area + '</option>'
					from sStudent.vArea where OrgId = @rOrgId

					select @lNationalitydropdown = @lNationalitydropdown + '<option value="' +convert(varchar,Id)+ '">' + Nationality + '</option>'
					from sCommon.tCountryMaster where IsObsolete = 0 
					and OrgGroupId = @rOrgGroupId

					select @lTranspotrmodedropdown = @lTranspotrmodedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tTransportModeMaster where IsObsolete = 0

					select @lbusrouedropdown = @lbusrouedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sTransport.tBusRouteMaster where IsObsolete = 0  and OrgGroupBatchId = @rOrgGroupBatchId

					select @lbusrotedestinationdrop  = @lbusrotedestinationdrop  + '<option value="' +convert(varchar,BDM.Id)+ '">' + BDM.Title + '</option>'
					from sTransport.tBusRouteMaster BM inner join sTransport.tBusRouteDestinationMaster BDM ON BM.Id= BDM.BusRouteId
					where BDM.IsObsolete = 0  and OrgGroupBatchId = @rOrgGroupBatchId


					select @lblooddropdown = @lblooddropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tBloodGroupMaster where IsObsolete = 0

					select @lhousedropdown = @lhousedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sActivity.tHouseMaster where IsObsolete = 0 and OrgId = @rOrgId

					select @lmothertoungedropdown = @lmothertoungedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tMotherTongueMaster where IsObsolete = 0 and OrgGroupId = @rOrgGroupId

					select @lpriviousschooldropdown = @lpriviousschooldropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tPreviousSchoolMaster where IsObsolete = 0 and OrgGroupId = @rOrgGroupId

			
		
					select @lfatherqadrop = @lfatherqadrop + '<option value="' +convert(varchar,OrgId)+ '">' + Qualification + '</option>'
					from sStudent.vQualification where OrgId = @rOrgId

					select @lmotherqadropdown  = @lmotherqadropdown  + '<option value="' +convert(varchar,OrgId)+ '">' + Qualification + '</option>'
					from sStudent.vQualification where OrgId = @rOrgId
			
			
					select @lfatherocdropdown = @lfatherocdropdown + '<option value="' +convert(varchar,OrgId)+ '">' + Occupation + '</option>'
					from sStudent.vOccupation where OrgId = @rOrgId

					select @lmotherocdropdown = @lmotherocdropdown + '<option value="' +convert(varchar,OrgId)+ '">' + Occupation + '</option>'
					from sStudent.vOccupation where OrgId = @rOrgId


					select @lfeescategorydropdown = @lfeescategorydropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tAdmissionCategoryMaster where IsObsolete = 0 and OrgGroupId = @rOrgGroupId
			
			
					select @lCustomtagdrop  = @lCustomtagdrop  + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tCustomTagMaster where IsObsolete = 0  and OrgGroupId = @rOrgGroupId

					select @lcustomgroupdropdown  = @lcustomgroupdropdown  + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommunication.tCustomGroup where  OrgGroupId = @rOrgGroupId

					select @lclubdropdown   = @lclubdropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sActivity.tClubMaster where  OrgGroupId = @rOrgGroupId

					select @lhosteldropdown   = @lhosteldropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sHostel.tHostelMaster where  OrgGroupId = @rOrgGroupId

					select @lstudentgroupdropdown   = @lstudentgroupdropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tStudentGroupMaster  where  OrgGroupId = @rOrgGroupId

					select @lstudentothergroupdropdown   = @lstudentothergroupdropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tStudentOtherGroupMaster where  OrgGroupId = @rOrgGroupId

					select @lExaminationtypedropdown    = @lExaminationtypedropdown    + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sFee.tExemptionTypeMaster where  OrgGroupId = @rOrgGroupId
			
					select @lSavedReport = @lSavedReport + '<option value="0"> -- Select -- </option>'
					select @lSavedReport =  @lSavedReport + '<option value="' + convert(varchar,SCS.Id)+ '">' + SCS.Title + '</option>'
					from sStudent.tStudentCustomSearch SCS
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
					LEFT JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId 
					WHERE (SCS.CreatedUserId = @rUserId) OR (SCS.IsCommon = 1) OR (SCS.IsCommonForOrg = 1)
					
					select @lSavedReport1 = @lSavedReport1 + '<option value="0"> -- Select -- </option>'
					select @lSavedReport1 =  @lSavedReport1 + '<option value="' + convert(varchar,GES.Id)+ '">' + GES.Title + '</option>'
					from sAssessment.tGeneralExamCustomSearch GES
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = GES.OrgId AND OM.OrgGroupId = @rOrgGroupId
					LEFT JOIN sSecurity.tUser U ON U.Id=GES.CreatedUserId 
					where  (GES.CreatedUserId = @rUserId) OR (GES.IsCommon = 1) OR  (GES.IsCommonForOrg = 1)
								 

	select @lStatusRes as StatusRes,@lClassRes as ClassRes,@lDivisionRes as DivisionRes,
	@lEnrollmentStatusRes as EnrollStatusRes,@lDepartmentRes as DepartmentRes,
	@lAvailableRes as AvailableRes,@lAvailableStudentCustomRes as AvailableStudentCustomRes,@lReportList as ReportList,@lExamRes as ExamRes,
	@lGeneralExamRes as GeneralExamAvailRes,@lExamReportList as ExamReportList,@lclassdropdown as classChechboxlist,@lStatusdropdown As statusChechboxlist,
	@lGenderdropdown As Gendercheckboxlist,@lReligiondropdown As Religionchklist,@lcastdropdown as castcategorychklist,@lCitydropdown as Citychklist,
	@lAreadropdown AS Areachklist,@lNationalitydropdown As Nationalitychklist,@lTranspotrmodedropdown AS Transportmodechklist,@lbusrouedropdown AS busroutechklist,
	@lbusrotedestinationdrop AS Busroutedestinationchklist,@lblooddropdown AS bloodgrpchklist,@lhousedropdown AS Housechklist,
	@lmothertoungedropdown AS Mothertoungechklist,@lpriviousschooldropdown AS priviousschoolchklist,@lfatherqadrop  AS fatherqachklist,
	@lmotherqadropdown AS motherqachklist,@lfatherocdropdown AS fatherocuupationchklist,@lmotherocdropdown AS motherocuupationchklist,@lfeescategorydropdown AS feescategorychklist,
	@lCustomtagdrop AS customtaghklist,@lcustomgroupdropdown AS customgroupchklist,@lclubdropdown  AS clubchklist,@lhosteldropdown AS Hostelchklist,
	@lstudentgroupdropdown AS studentgroupchklist,@lstudentothergroupdropdown AS studentothergroupchklist,@lExaminationtypedropdown  as ExaminationTypechklist,
	@lSavedReport AS SavedReportList, @lSavedReport1 AS SavedReportList1
end
GO
PRINT N'Altering [sStudent].[pRptStudentRegisterGet]...';


GO
ALTER PROCEDURE [sStudent].[pRptStudentRegisterGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rClassStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rFromAdmissionDate date='', 
     @rToAdmissionDate date=''  
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassDivision,
			SD.Code,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,		
			SD.ClassName,
			SD.DivisionName,
			SD.StatusName,
			SD.StatusId,
			SD.LCProgress,
			SD.Religion,
			SD.FamilyCast,
			SD.FamilySubCast,
			SD.LCConduct,
			SD.BirthPlace,
			SD.BirthTaluka,
			SD.BirthDistrict,
			SD.LeftDate,
			SD.PreviousSchool,
			SD.DateOfBirth,
			SD.BirthDateInWord,
			SD.LeftReason,
			SD.AdmissionDate,
			SD.AdmissionStandard,
			SD.LeftStandard,
			SD.LCNumber,
			SD.LCDate,
			SD.StudentPhoto,
			SD.BloodGroup,
			SD.PresentAddress,
			SD.ContactNo,
			SD.Batch,
			SD.InactiveDate,
			OM.Title AS OrgName,
			SF.MotherName,
			SD.DivisionOrder,
			SD.Number AS StudentNumber,
			SF.FatherName,
			SD.Nationality,
			SD.MotherTongue,
			SD.BirthState,
			SD.BirthCountry,
			SD.SUId,
            SD.AdhaarNumber,
            SD.ClassStatusId,
            SD.ClassStatusName
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassID and BC.BatchId= @rBatchId
			LEFT JOIN sStudent.tStudentAdmission SAM ON SD.StudentId=SAM.StudentId
			AND ((SAM.AdmissionDate>=@rFromAdmissionDate)OR(ISNULL(@rFromAdmissionDate,'')=''))    
			AND ((SAM.AdmissionDate<=@rToAdmissionDate)OR(ISNULL(@rToAdmissionDate,'')=''))  
			AND	SAM.BatchId = @rBatchId   
	WHERE 
		SD.OrgId=@rOrgId
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SD.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND ((MONTH(SD.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=0))
	    AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	   
	 Order by
	 SD.RollNo
END
GO
PRINT N'Altering [sStudent].[pRptStudentStrengthDivisionWiseGet]...';


GO
 
ALTER PROCEDURE [sStudent].[pRptStudentStrengthDivisionWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rDepartmentId int,
	 @rStudentCode varchar(20)='',
	 @rReportId int=0,
	 @rOrggroupBatchID int=0
	 ,@rAsOnDate Date =''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
  DECLARE @lCount Int
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			A.ClassId,
			A.DivisionId,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			DM.OrderIndex AS DivisionOrder,
			Cm.OrderINdex AS ClassOrderIndex  ,
		    ISNUll(AR.SourceId,0) AS HostelStudent,
			ISNUll(RT.SourceId,0) AS TransportStudent,
			A.StudentId 
			FROM 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			LEFT JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=A.AdmissionCategoryId
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=A.StudentId AND AR.SourceTypeId=2003 
			AND  ((AR.OrggroupBatchID=@rOrggroupBatchID) OR (@rOrggroupBatchID=0))
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = A.StudentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
    
	WHERE 
		A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		--AND SM.StatusId = 1
		AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.LeftDate > @rAsOnDate) OR (SA.LeftDate Is null AND SM.StatusId = 1))
		
	   END
GO
PRINT N'Altering [sStudent].[pStudentAdmissionAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentAdmissionAdd]
	 
		   @rStudentId bigint,
		   @rPreviousSchool nvarchar(200),
           @rPreviousSchoolTypeId int,
           @rPreviousStudentId bigint,
           @rAdmissionFormId bigint,
           @rAdmissionFormNumber nvarchar(20),
           @rAdmissionStandardId int,
           @rAdmissionDate date,
           @rAdmissionYear nvarchar(10),
           @rLeftStandardId int,
           @rLeftDate date,
           @rLeftYear nvarchar(10),
           @rInactiveDate date,
           @rInActiveReason nvarchar(200),
           @rLeftReason nvarchar(200),
           @rLCProgress nvarchar(200),
           @rLCConduct nvarchar(200),
           @rLCBook nvarchar(20),
           @rLCNumber nvarchar(20),
           @rLCDate date,
           @rLCRemark nvarchar(200),
           @rLCCopy tinyint,
           @rLcId bigint,
           @rBatchId int,
           @rCreatedUserId bigint,
           @rUpdatedUserId bigint,
           @rIsGeneral bit,
           
           @rAdmissionNumber nvarchar(50)='',
           @rIsTransfer bit = 0,
           @rTransferFrom nvarchar(150)='',
           @rPassingYear nvarchar(20)='',
           @rIsTFWS bit = 0,
           @rIsCertificateHolder bit = 0,
           @rCertificateName nvarchar(100) = '',
           @rAdmissionQuotaId int =0,
           @rPreviousStandard nvarchar(50)='',
           @rAcademicId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
BEGIN TRANSACTION	

 


IF(@rIsGeneral=1)	
BEGIN 
	IF NOT EXISTS(SELECT * FROM sStudent.tStudentAdmission WHERE StudentId = @rStudentId)
	BEGIN

	INSERT INTO sStudent.tStudentAdmission
		(
			   StudentId,
			   PreviousSchool,
			   AdmissionStandardId,
			   AdmissionDate,
			   LeftStandardId,
			   LeftDate,
			   InactiveDate,
			   BatchId,
			   CreatedUserId,
			   CreatedDateTime,
			   PreviousStandard
			   
		)
	VALUES
		(
			   @rStudentId,
			   @rPreviousSchool,
			   @rAdmissionStandardId,
			   @rAdmissionDate,
			   @rLeftStandardId,
			   @rLeftDate,
			   @rInactiveDate,
			   @rBatchId,
			   @rCreatedUserId,
			   sCommon.fGetDate(),
			   @rPreviousStandard
		)
		
		
		SELECT 1 AS Result             
	END	 
	 ELSE
	 BEGIN
		UPDATE sStudent.tStudentAdmission
	    SET
			  
			  AdmissionStandardId = @rAdmissionStandardId, 
			  AdmissionDate = @rAdmissionDate, 
			  LeftStandardId = @rLeftStandardId,
			  LeftDate = @rLeftDate, 
			  InactiveDate = @rInactiveDate, 
			  UpdatedUserId = @rUpdatedUserId, 
			  UpdatedDateTime =sCommon.fGetDate()
	
	      WHERE StudentId = @rStudentId 
	      
	  
	 END  
		SELECT 11 AS Result
	END
ELSE
BEGIN
		IF(@rIsGeneral=0)
	    IF NOT EXISTS(SELECT * FROM sStudent.tStudentAdmission WHERE StudentId = @rStudentId)
BEGIN

	INSERT INTO sStudent.tStudentAdmission
		(
			   StudentId,
			   PreviousSchool,
			   PreviousSchoolTypeId,
			   PreviousStudentId,
			   AdmissionFormId,
			   AdmissionFormNumber,
			   AdmissionStandardId,
			   AdmissionDate,
			   AdmissionYear,
			   LeftStandardId,
			   LeftDate,
			   LeftYear,
			   InactiveDate,
			   InActiveReason,
			   LeftReason,
			   LCProgress,
			   LCConduct,
			   LCBook,
			   LCNumber,
			   LCDate,
			   LCRemark,
			   LCCopy,
			   LcId,
			   BatchId,
			   CreatedUserId,
			   CreatedDateTime,
			   
			   AdmissionNumber,
			   IsTransfer,
			   TransferFrom,
			   PassingYear,
			   IsTFWS,
			   IsCertificateHolder,
			   CertificateName,
			   AdmissionQuotaId,
			   PreviousStandard
		)
	VALUES
		(
			   @rStudentId,
			   @rPreviousSchool,
			   @rPreviousSchoolTypeId,
			   @rPreviousStudentId,
			   @rAdmissionFormId,
			   @rAdmissionFormNumber,
			   @rAdmissionStandardId,
			   @rAdmissionDate,
			   @rAdmissionYear,
			   @rLeftStandardId,
			   @rLeftDate,
			   @rLeftYear,
			   @rInactiveDate,
			   @rInActiveReason,
			   @rLeftReason,
			   @rLCProgress,
			   @rLCConduct,
			   @rLCBook,
			   @rLCNumber,
			   @rLCDate,
			   @rLCRemark,
			   @rLCCopy,
			   @rLcId,
			   @rBatchId,
			   @rCreatedUserId,
			   sCommon.fGetDate(),
			   
			   @rAdmissionNumber,
			   @rIsTransfer,
			   @rTransferFrom,
			   @rPassingYear,
			   @rIsTFWS,
			   @rIsCertificateHolder,
			   @rCertificateName,
			   @rAdmissionQuotaId,
			   @rPreviousStandard
		)
		SELECT 1 AS Result             
	END	 
	ELSE
	BEGIN
		UPDATE sStudent.tStudentAdmission
	    SET
			  PreviousSchool = @rPreviousSchool,
			  PreviousSchoolTypeId = @rPreviousSchoolTypeId, 
			  PreviousStudentId = @rPreviousStudentId, 
			  AdmissionFormId = @rAdmissionFormId,
			  AdmissionFormNumber = @rAdmissionFormNumber, 
			  AdmissionStandardId = @rAdmissionStandardId, 
			  AdmissionDate = @rAdmissionDate, 
			  AdmissionYear = @rAdmissionYear,
			  LeftStandardId = @rLeftStandardId,
			  LeftDate = @rLeftDate, 
			  LeftYear = @rLeftYear,
			  InactiveDate = @rInactiveDate, 
			  InActiveReason = @rInActiveReason,
			  LeftReason = @rLeftReason, 
			  LCProgress = @rLCProgress,
			  LCConduct = @rLCConduct, 
			  LCBook = @rLCBook, 
			  LCNumber = @rLCNumber,
			  LCDate = @rLCDate, 
			  LCRemark = @rLCRemark, 
			  LCCopy = @rLCCopy, 
			  LcId = @rLcId, 
			  UpdatedUserId = @rUpdatedUserId, 
			  UpdatedDateTime =sCommon.fGetDate(),
			  
			  AdmissionNumber=@rAdmissionNumber,
			  IsTransfer=@rIsTransfer,
		  	  TransferFrom=@rTransferFrom,
			  PassingYear=@rPassingYear,
			  IsTFWS=@rIsTFWS,
			  IsCertificateHolder=@rIsCertificateHolder,
			  CertificateName=@rCertificateName,
			  AdmissionQuotaId=@rAdmissionQuotaId,
			  PreviousStandard=@rPreviousStandard
	      
	      WHERE StudentId = @rStudentId 	 
	      
	END  
	 
		SELECT 11 AS Result
		
	END

		UPDATE A
		SET ClassStatusId = 3
		FROM sStudent.tAcademic A
		INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
		INNER JOIN sStudent.tStudentAdmission SA ON A.StudentId = SA.StudentId AND A.ClassId = SA.LeftStandardId
		WHERE SM.StatusId = 3 AND SM.Id = @rStudentId

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


GO

ALTER PROCEDURE [sStudent].[pStudentCustomFieldAdd]
		 
	@rId int,
	@rOrgId int,
	@rFieldTitle nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	@rFieldOrder smallint,
	@rCreatedUserId bigint,	
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rIsObsolete int =0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
BEGIN TRANSACTION	
 
IF(@rId = 0)	
BEGIN
    --IF NOT EXISTS(SELECT 2 FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle=@rFieldTitle OR FieldGroup=@rFieldGroup)
    IF NOT EXISTS(SELECT 2 FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle=@rFieldTitle)
	BEGIN
	      DECLARE @lNextNumber int
	      EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
Print @lNextNumber
	      INSERT INTO sStudent.tStudentCustomFieldMaster
	      (
		    Id
		   ,FieldTitle
		   ,FieldTypeId
		   ,FieldList
		   ,IsFieldMandatory
		   ,FieldGroup
		   ,FieldOrder
		   ,CreatedUserId
		   ,CreatedDateTime
		   ,OrgGroupId
		   ,IsObsolete
	      )
	     VALUES
	     (
		   @lNextNumber
		  ,@rFieldTitle
		  ,@rFieldTypeId
		  ,@rFieldList
		  ,@rIsFieldMandatory
		  ,@rFieldGroup
		  ,@rFieldOrder
		  ,@rCreatedUserId
		  ,@rCreatedDateTime
		  ,@rOrgId
		  ,@rIsObsolete
		
	     )
     END
	 ELSE
	 SELECT -101 As RESULT
END
	 	 
ELSE
BEGIN
	SET @lNextNumber = @rId
	
	UPDATE sStudent.tStudentCustomFieldMaster
	SET 
		FieldTitle = @rFieldTitle
		,FieldTypeId = @rFieldTypeId
		,FieldList=@rFieldList
		,IsFieldMandatory=@rIsFieldMandatory
		,IsObsolete=@rIsObsolete
		,FieldGroup=@rFieldGroup
		,FieldOrder=@rFieldOrder
		,UpdatedUserId=@rUpdatedUserId
		,UpdatedDateTime=@rUpdatedDateTime
	WHERE Id = @rId 	   
END  
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sStudent].[pStudentCustomFieldDataModify]...';


GO
ALTER PROCEDURE [sStudent].[pStudentCustomFieldDataModify]	 
	--@rCategoryId int,
	@rXML nvarchar(max),
	--@rSubCategoryField nvarchar(100),
	@rOrgId int = 0,
	@rCustomFieldId nvarchar(100)
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
Declare @Sql nvarchar(max) 
DECLARE @loDoc INT


EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),CustomFieldId int,UpdatedUserId bigint,IsExist bit);
	
	insert into ListofData(Id,StudentId,SubCategory,CustomFieldId,UpdatedUserId,IsExist)
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),@rCustomFieldId,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,CustomFieldId,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (						
						StudentId BIGINT,
						--AutoId int,
						SubCategory nvarchar(150),
                        CustomFieldId int,
						UpdatedUserId bigint
						)	
						)E 	
		--UPDATE ListofData SET IsExist=1 WHERE (StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCustomFieldData) AND CustomFieldId NOT IN (SELECT StudentCustomFieldId FROM sStudent.tStudentCustomFieldData))
		UPDATE LD SET IsExist=1 
		   FROM sStudent.tStudentCustomFieldData SC
		      LEFT JOIN ListofData LD ON SC.StudentId=LD.StudentId 
		      AND  EXISTS (SELECT StudentCustomFieldId FROM sStudent.tStudentCustomFieldData WHERE StudentId=LD.StudentId AND StudentCustomFieldId = LD.CustomFieldId) 
		
		
		--SELECT *From ListofData --where StudentId=1101000003521
		
		set @sql='INSERT INTO sStudent.tStudentCustomFieldData
					(StudentId,StudentCustomFieldId,FieldData,CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,ISNULL('+@rCustomFieldId+',0),LD.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=0'
					
		--print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentCustomFieldData set FieldData = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentCustomFieldData SC 
					INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND SC.StudentCustomFieldId=LD.CustomFieldId AND IsExist=1'
		print @sql
		Exec sp_executesql @sql
	
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	   
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
GO
PRINT N'Altering [sStudent].[pStudentCustomFieldDelete]...';


GO

ALTER PROCEDURE [sStudent].[pStudentCustomFieldDelete]

@rId int,
@rOrgId smallint=0,
@rOrgGroupId int=0
AS
BEGIN
 	 
	 IF NOT EXISTS(Select 1 from sStudent.tStudentCustomFieldData SCF 
	          INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SCF.StudentId
	          INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SM.OrgId 
	        WHERE SCF.StudentCustomFieldId=@rId AND StatusId=1 AND OM.OrgGroupId=@rOrgGroupId
	           AND (SCF.FieldData <> '0' AND SCF.FieldData<>'' AND SCF.FieldData IS NOT NULL))
	 BEGIN
        
        DELETE SCF FROM sStudent.tStudentCustomFieldData SCF 
           INNER JOIN sStudent.tStudentMaster SM ON SM.Id=SCF.StudentId
	       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SM.OrgId 
        WHERE SCF.StudentCustomFieldId=@rId AND StatusId=1 AND OM.OrgGroupId=@rOrgGroupId
         
		DELETE	FROM sStudent.tStudentCustomFieldMaster WHERE Id=@rId 
		SELECT 1 AS RESULT
	  END 

	  ELSE

	    SELECT -101 As RESULT

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


GO

ALTER PROCEDURE [sStudent].[pStudentCustomFieldsUpdateGet]
	 		
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rBatchId int,	
	 @rStatusId int,	 
	 @rSubCategoryId int
	 
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=FieldTypeId FROM sStudent.tStudentCustomFieldMaster WHERE Id=@rSubCategoryId
		
		 Declare @Sql nvarchar(max)
		 Declare @Sql1 nvarchar(max)
		 
		 --IF(@lDataTypeId=3)   --For Free Text and Numeric
		 --BEGIN
		 
		     SET @Sql = 'select *from (Select Row_Number() OVER (PARTITION BY SA.StudentID ORDER BY CASE WHEN SCF.FieldTypeId IS NOT NULL THEN SCF.FieldTypeId END Desc) as RowNumber, SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
		            CASE WHEN SCF.FieldTypeId=3 OR SCF.FieldTypeId=4 THEN
					ISNULL(SC.FieldData,'''') 
					WHEN SCF.FieldTypeId=2 THEN
					ISNULL(SC.FieldData,''0'')
					WHEN SCF.FieldTypeId=1 THEN
					ISNULL(SC.FieldData,''False'') 				
					END AS SubCategory
			FROM 
		       sStudent.vStudentAcademic SA
		         LEFT JOIN sStudent.tStudentCustomFieldData SC ON SC.StudentId=SA.StudentId
		         LEFT JOIN sStudent.tStudentCustomFieldMaster SCF ON SCF.Id=SC.StudentCustomFieldId AND SCF.FieldTypeId='''+@lDataTypeId+'''  AND SCF.Id= '''+CAST(@rSubCategoryId AS nvarchar(15))+''' AND SCF.IsObsolete=0 
		         
		    Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
			+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
			AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
			AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
			AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')) AS a where RowNumber =1'     
		 		
		  print @Sql		
		   		
			EXECUTE  sp_executesql @Sql		
	   
END
GO
PRINT N'Altering [sStudent].[pStudentGenerateReport]...';


GO
ALTER PROCEDURE [sStudent].[pStudentGenerateReport]
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9999-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9999-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@rIsCommon bit,
	@rIsCommonForOrg bit,
	@rCreatedUserId bigint,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rSpecificCode nvarchar(max),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount smallint=0,
	@rStudentStatusId smallint=0,
	@rHostelId nvarchar(max) = '',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption nvarchar(max)=''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
 
				
		IF(@rHostelId IS NULL)
			SET @rHostelId = ''
		IF(@rStudentGroupId IS NULL)
			SET @rStudentGroupId = ''
		IF(@rStudentOtherGroupId IS NULL)
			SET @rStudentOtherGroupId = ''	
		IF(@rOrgGroupBatchId IS NULL)
			SET @rOrgGroupBatchId = 0
		IF(@rGenderId IS NULL)
			SET @rGenderId = ''
		IF(@rBusRouteId IS NULL)
			SET @rBusRouteId = ''	
		IF(@rDOBFromDate IS NULL)
			SET @rDOBFromDate='0001-01-01'
		IF(@rDOBToDate IS NULL)
			SET @rDOBToDate='9999-12-31'
		IF(@rDOAFromDate IS NULL)
			SET @rDOAFromDate='0001-01-01'
		IF(@rDOAToDate IS NULL)
			SET @rDOAToDate='9999-12-31'
		IF(@rDOLFromDate IS NULL)
			SET @rDOLFromDate='0001-01-01'
		IF(@rDOLToDate IS NULL)
			SET @rDOLToDate='9999-12-31'
		
		IF(@rTitle != '' AND @rId = 0)
		BEGIN
			DECLARE @lNextNumber BIGINT
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sStudent.tStudentCustomSearch
			(
				Id,Title,ColumnName,OrderBy,OrgId,Code,FirstName,LastName,Country,State,City,Area,DivisionId,
				StatusId,TransportModeId,BusRouteDestinationId,BloodGroupId,GenderId,ReligionId,CastCategoryId,
				HouseId,MotherTongueId,NationalityId,Hobby,FatherQualification,MotherQualification,FatherOccupation,
				MotherOccupation,PreviousSchool,AdmissionCategoryId,DOBFromDate,DOBToDate,DOAFromDate,DOAToDate,
				DOLFromDate,DOLToDate,IsPysicalDeformity,IsMajorIllness,IsCommon,IsCommonForOrg, CreatedUserId,CreatedDateTime,
				IsBlackList,FromCode,ToCode,CustomTag,CustomGroup,Club,RepeatCount,StudentStatusId,Hostel,StudentGroup,
				StudentOtherGroup,FeeExemption
			)
			VALUES
			(
				@lNextNumber,@rTitle,@rColumnName,@rOrderBy,@rOrgId,@rSpecificCode,@rFirstName,@rLastName,@rCountry,@rState,
				@rCity,@rArea,@rDivisionId,@rStatusId,@rTransportModeId,@rBusRouteDestinationId,@rBloodGroupId,@rGenderId,
				@rReligionId,@rCastCategoryId,@rHouseId,@rMotherTongueId,@rNationalityId,@rHobby,@rFatherQualification,
				@rMotherQualification,@rFatherOccupation,@rMotherOccupation,@rPreviousSchool,@rAdmissionCategoryId,
				@rDOBFromDate,@rDOBToDate,@rDOAFromDate,@rDOAToDate,@rDOLFromDate,@rDOLToDate,@rIsPysicalDeformity,
				@rIsMajorIllness,@rIsCommon,@rIsCommonForOrg,@rCreatedUserId,sCommon.fGetDate(),@rIsBlackList,@rFromCode,@rToCode,
				@rCustomTagId,@rCustomGroupId,@rClubId,@rRepeatCount,@rStudentStatusId,@rHostelId,@rStudentGroupId,
				@rStudentOtherGroupId,@rFeeExemption
			)
		END
		
		
		IF(@rId > 0)
		BEGIN
			Select @rColumnName=ColumnName,@rOrderBy=OrderBy,@rOrgId=OrgId,@rSpecificCode=Code,@rFirstName=FirstName,
			@rLastName=LastName,@rCountry=Country,@rState=State,@rCity=City,@rArea=Area,@rDivisionId=DivisionId,
			@rStatusId=StatusId,@rTransportModeId=TransportModeId,@rBusRouteDestinationId=BusRouteDestinationId,
			@rBloodGroupId=BloodGroupId,@rGenderId=GenderId,@rReligionId=ReligionId,@rCastCategoryId=CastCategoryId,
			@rHouseId=HouseId,@rMotherTongueId=MotherTongueId,@rNationalityId=NationalityId,@rHobby=Hobby,
			@rFatherQualification=FatherQualification,@rMotherQualification=MotherQualification,
			@rFatherOccupation=FatherOccupation,@rMotherOccupation=MotherOccupation,
			@rPreviousSchool=PreviousSchool,@rAdmissionCategoryId=AdmissionCategoryId,
			@rDOBFromDate=DOBFromDate,@rDOBToDate=DOBToDate,@rDOAFromDate=DOAFromDate,
			@rDOAToDate=DOAToDate,@rDOLFromDate=DOLFromDate,@rDOLToDate=DOLToDate,
			@rIsPysicalDeformity=IsPysicalDeformity,@rIsMajorIllness=IsMajorIllness,
			@rIsBlackList=IsBlackList,@rFromCode=FromCode,@rToCode=ToCode,
			@rCustomTagId=CustomTag,@rCustomGroupId = CustomGroup,@rClubId = Club,
			@rRepeatCount = RepeatCount,@rStudentStatusId =StudentStatusId,
			@rHostelId = Hostel,@rStudentGroupId = StudentGroup,
			@rStudentOtherGroupId = StudentOtherGroup,@rFeeExemption =FeeExemption
			FROM sStudent.tStudentCustomSearch WHERE Id=@rId
		END
		
		DECLARE @ListofCodes TABLE(Code nvarchar(25), ID INT IDENTITY(1,1));
			INSERT INTO @ListofCodes
	
		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
		
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		SET @rColumnName=Replace(@rColumnName,'PhysicalDeformityRemark','PysicalDeformityRemark')
		SET @rColumnName=Replace(@rColumnName,'IsPhysicalDeformity','IsPysicalDeformity')
		SET @rOrderBy=Replace(@rOrderBy,'PhysicalDeformityRemark','PysicalDeformityRemark')
		SET @rOrderBy=Replace(@rOrderBy,'IsPhysicalDeformity','IsPysicalDeformity')
		
		DECLARE @Sql nvarchar(MAX)= ''
		
		SET @rSpecificCode = sCommon.fSearchStringGet(@rSpecificCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rCountry = sCommon.fSearchStringGet(@rCountry)
		SET @rState = sCommon.fSearchStringGet(@rState)
		
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent1')
		 BEGIN
			DROP Table sStudent.tTempStudent1
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent2')
		 BEGIN		
			DROP Table sStudent.tTempStudent2
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent3')
		 BEGIN
			DROP Table sStudent.tTempStudent3
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent4')
		 BEGIN
			DROP Table sStudent.tTempStudent4
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent5')
		 BEGIN
			DROP Table sStudent.tTempStudent5  
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent6')
		 BEGIN
			DROP Table sStudent.tTempStudent6
		 END
		 
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent7')
		 BEGIN
			DROP Table sStudent.tTempStudent7
		 END
		 
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent8')
		 BEGIN
			DROP Table sStudent.tTempStudent8
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent9')
		 BEGIN
			DROP Table sStudent.tTempStudent9
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent10')
		 BEGIN
			DROP Table sStudent.tTempStudent10
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent11')
		 BEGIN
			DROP Table sStudent.tTempStudent11
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent12')
		 BEGIN
			DROP Table sStudent.tTempStudent12
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent13')
		 BEGIN
			DROP Table sStudent.tTempStudent13
		 END
		
		SELECT  DISTINCT SM.Id AS StudentId6,
		CASE WHEN SF.IsFatherExStudent = 0 THEN 'No' WHEN SF.IsFatherExStudent = 1 THEN 'Yes' ELSE '' END AS IsFatherExStudent,
		CASE WHEN SF.IsMotherExStudent = 0 THEN 'No' WHEN SF.IsMotherExStudent = 1 THEN 'Yes' ELSE '' END AS IsMotherExStudent,
		SF.FatherOrganization, SF.FatherDesignation, SF.MotherOrganization, SF.MotherDesignation, SF.RelativeOrganization, SF.RelativeDesignation
		INTO sStudent.tTempStudent11
		FROM sStudent.tStudentMaster SM
			 INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND SM.OrgId = @rOrgId AND A.BatchId=@BatchId
			 INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
	
		-- For Left Detail
		SELECT DISTINCT  SA.StudentId AS StudentId12,InactiveDate,InActiveReason,LCBook,--LeftStandardId,
		CM.Title AS LeftStandard,
		CONVERT(VARCHAR(10),LCDate,111) AS LCDate,LCCopy,LeftReason,LCProgress,
		LCConduct,LCRemark 
		INTO sStudent.tTempStudent12
		FROM sStudent.tStudentAdmission SA
		     INNER JOIN sStudent.tAcademic A ON A.StudentId = SA.StudentId AND A.OrgId = @rOrgId AND A.BatchId=@BatchId
		     LEFT JOIN sSetup.tClassMaster CM ON CM.Id = SA.LeftStandardId
		
		-- For Custom Tag
		IF (@rCustomTagId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId1
			INTO sStudent.tTempStudent5
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId
			AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId1
			INTO sStudent.tTempStudent5
		END
		
		-- For Custom Group
		IF (@rCustomGroupId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId2
			INTO sStudent.tTempStudent6
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId
			AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId2
			INTO sStudent.tTempStudent6
		END
		
		-- For Club Group
		IF (@rClubId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId3
			INTO sStudent.tTempStudent7
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId
			AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId3
			INTO sStudent.tTempStudent7
		END
		
		-- For Hostel
		IF (@rHostelId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId4
			INTO sStudent.tTempStudent9
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
			AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
			WHERE SM.OrgId = @rOrgId
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId4
			INTO sStudent.tTempStudent9
		END
		
		--Transport
		IF (@rBusRouteId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId5
			INTO sStudent.tTempStudent10
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
			AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE SM.OrgId = @rOrgId 
			AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId5
			INTO sStudent.tTempStudent10
			
			
		END
		
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		--if @rColumnName <> ''
		--begin
		--	select @rColumnName = left(@rColumnName,len(@rColumnName)-1)
		--end
		--print 'asdasda'
		    DECLARE @lAvailableStudentColumns nvarchar(max)=''
			DECLARE @lAvailableStudentCustomRes nvarchar(max)=''
			Declare @Title as nvarchar(max)
			DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
		
          --BEGIN  
		   
		   --drop table sStudent.tTempStudent13

             
			--print @BatchId
			--print @rOrgId
            --DECLARE @rOrgGroupId smallint
            -- SET @rOrgGroupId = (Select orggroupid from sSetup.tOrganizationMaster where Id=@rOrgId)           
             
			SET @lAvailableStudentColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
								from sStudent.tStudentCustomFieldMaster PP      
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
	        IF(@lAvailableStudentColumns IS NOT NULL)
	        BEGIN
				set @query = 'SELECT  StudentId AS StudentId13 ,' + @lAvailableStudentColumns + ' into sStudent.tTempStudent13 from 
					 (
						select PPE.FieldTitle,PP.StudentId,FieldData 
						FROM
						sStudent.tStudentCustomFieldData PP 
							INNER JOIN sStudent.tStudentCustomFieldMaster PPE ON PPE.Id = PP.StudentCustomFieldId AND PPE.IsObsolete=0
							INNER JOIN sStudent.tStudentMaster SM ON SM.Id = PP.StudentId						
							INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND A.BatchId='+convert(varchar(20),@BatchId)+' 
							WHERE SM.OrgId='''+convert(varchar(20),@rOrgId)+''' 					              
					) x 
					pivot 
					(
						Max(FieldData)
						for FieldTitle in (' +@lAvailableStudentColumns  + ')
					) p'

				 -- print @query
                execute(@query)
		   
		  
		
		Select * into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
		LEFT JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6
		LEFT JOIN  sStudent.tTempStudent12 T12 ON SCS.StudentId= T12.StudentId12 
		LEFT JOIN  sStudent.tTempStudent13 T13 ON SCS.StudentId= T13.StudentId13 
		WHERE SCS.OrgId = @rOrgId 
		AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0)) 
		--AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
		AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
		AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%') OR(@rCountry = ''))
		AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
		AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
		AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
		AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
		AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
		AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR (@rGenderId=''))
		AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
		AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
		AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
		AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
		AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
		AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		AND ((SCS.Code >= @rFromCode) OR (@rFromCode=0))
		AND ((SCS.Code <= @rToCode) OR (@rToCode=0))
		AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
		AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		
		--AND (ISNULL(SCS.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--Select * from sStudent.tTempStudent return	
		
				
				
		set @sql = 'SELECT '+ @rColumnName+' FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		
		
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		
		exec(@Sql)
			
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
		DROP Table sStudent.tTempStudent12
		DROP Table sStudent.tTempStudent13
 
	END 
	 
	ELSE
	BEGIN
	    Select * into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
		LEFT JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6
		LEFT JOIN  sStudent.tTempStudent12 T12 ON SCS.StudentId= T12.StudentId12 
		
		WHERE SCS.OrgId = @rOrgId 
		AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0)) 
		--AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
		AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
		AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%') OR(@rCountry = ''))
		AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
		AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
		AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
		AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
		AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
		AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR (@rGenderId=''))
		AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
		AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
		AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
		AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
		AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
		AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		AND ((SCS.Code >= @rFromCode) OR (@rFromCode=0))
		AND ((SCS.Code <= @rToCode) OR (@rToCode=0))
		AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
		AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		
		--AND (ISNULL(SCS.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--Select * from sStudent.tTempStudent return	
		
				
				
		set @sql = 'SELECT '+ @rColumnName+' FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		
		
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		
		exec(@Sql)
			
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
		DROP Table sStudent.tTempStudent12
		
	    
	    
	END 
	 
	 
END
GO
PRINT N'Altering [sStudent].[pStudentMasterAdd]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentMasterAdd]
	 
	@rId bigint,
	@rCode nvarchar(20),
	@rRegistrationNumber nvarchar(20),
	@rNumber bigint,
	@rFirstName nvarchar(100),
	@rMiddleName nvarchar(100),
	@rLastName nvarchar(100),
	@rOrgId int,
	--@rDepartmentId int,
	@rAdmissionCategoryId int,
	@rStatusId smallint,
	@rRecordStatusId smallint,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupBatchId int =0,
	@OutStudentId BIGINT = NULL OUTPUT,
	@rSUId nvarchar(20) = '',
	@rOrgGroupId int = 0,
	@rMobileNo nvarchar(50)='',
	@rStudentGroupId int=0,
	@rStudentOtherGroupId int=0,
	@rDateOfBirth Date=NULL,
    @rGenderId int=0,
    @rAcademicId bigint = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--UPDATE sStudent.tAcademic SET ClassStatusId = 1 WHERE ClassStatusId is null WHERE Id = 
	
	--if(@rStatusId=3)
	--UPDATE A
	--	SET ClassStatusId = 3
	--	FROM sStudent.tAcademic A
	--	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
	--	--INNER JOIN sStudent.tStudentAdmission SA ON A.StudentId = SA.StudentId AND A.ClassId = SA.LeftStandardId
	--	WHERE SM.StatusId = 3 AND A.Id = @rAcademicId
	--else if(@rStatusId=1)
	--UPDATE A
	--SET ClassStatusId = 1
	--	FROM sStudent.tAcademic A
	--	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
	--	--INNER JOIN sStudent.tStudentAdmission SA ON A.StudentId = SA.StudentId AND A.ClassId = SA.LeftStandardId
	--	WHERE SM.StatusId = 3 AND A.Id = @rAcademicId
	
	
	
	
	Declare @lStudCap int,@lOrgStudentCap int
	--IF(@rNumber=0)
	--SET @rNumber=NULL
	IF(@rId=0)
	BEGIN		 
	 
		--IF((@rCode = Null) OR (@rCode = ''))	
		--BEGIN

		--	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2001,@rStoreLocationId = 0, @rNextNumber = @rCode OUTPUT

		--	SET @rCode = ISNULL(@rCode, '-300')

		--	IF @rCode = '-300'
		--	BEGIN
		--		 SELECT -300 AS Result, '' AS Code, 0 AS Id 
		--		 RETURN
		--	END
		--END
		--ELSE
		--BEGIN
			Select @lStudCap=ISNULL(NoOfStudent,0)+ISNULL(StudentExtraCap,0) from
			sSetup.tOrgGroupSetting Where OrgGroupId= @rOrgGroupId
			
			Select @lOrgStudentCap=[sSetup].[fStudentCapGet](@rOrgGroupBatchId)
			 
			IF(@lOrgStudentCap >= @lStudCap )
			BEGIN
				Select -111 AS RESULT, '' AS Code, @lStudCap AS Id 
				Return
			END
		
			IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
					   WHERE SM.SUId=@rSUId AND OM.OrgGroupId=@rOrgGroupId)
			BEGIN
				SELECT -101 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
			ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId)
			BEGIN
				SELECT -100 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
			ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE ISNULL(@rRegistrationNumber,'')!='' AND RegistrationNumber=@rRegistrationNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -200 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
		--END
	END
	ELSE
	BEGIN
	
		Select @lStudCap=ISNULL(NoOfStudent,0)+ISNULL(StudentExtraCap,0) from
		sSetup.tOrgGroupSetting Where OrgGroupId= @rOrgGroupId
		
		Select @lOrgStudentCap=[sSetup].[fStudentCapGet](@rOrgGroupBatchId)
		 
		IF(@lOrgStudentCap >= @lStudCap AND (@rStatusId = 1 OR @rStatusId = 2))
		BEGIN
			Select -111 AS RESULT, '' AS Code, @lStudCap AS Id 
			Return
		END
	
		DECLARE @lReferenceSourceId bigint=0
		SELECT @lReferenceSourceId = ISNULL(ReferenceSourceId,0)  FROM sStudent.tStudentMaster WHERE Id = @rId
		
		IF(@lReferenceSourceId=0)
			SELECT @lReferenceSourceId = Id FROM sStudent.tStudentMaster WHERE ReferenceSourceId = @rId
		IF(@lReferenceSourceId = 0)
		BEGIN 
			IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
						   WHERE SM.SUId=@rSUId AND OM.OrgGroupId=@rOrgGroupId AND SM.Id!=@rId)
			BEGIN
				SELECT -101 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
		END
		 
		IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId AND Id!=@rId)
		BEGIN
			SELECT -100 AS RESULT, '' AS Code, 0 AS Id 
			RETURN
		END 
		ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE RegistrationNumber=@rRegistrationNumber AND OrgId=@rOrgId AND Id!=@rId)
		BEGIN
			SELECT -200 AS RESULT, '' AS Code, 0 AS Id 
			RETURN
		END 
	END

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

	IF(@rNumber=0)
	BEGIN
	SET @rNumber=@lNextNumber
	END
	INSERT INTO sStudent.tStudentMaster
		(
			Id,
			Code,
			Number,
			RegistrationNumber,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			--DepartmentId,
			AdmissionCategoryId,
			StatusId,
			RecordStatusId,
			CreatedUserId,
			CreatedDateTime,
		    SUId,
		    StudentGroupId,
		    StudentOtherGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rNumber,
			@rRegistrationNumber,
			@rFirstName,
			@rMiddleName,
			@rLastName,
			@rOrgId,
			--@rDepartmentId,
			@rAdmissionCategoryId,
			@rStatusId,
			@rRecordStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSUId,
			@rStudentGroupId ,
			@rStudentOtherGroupId 
		)
		
		INSERT INTO sStudent.tStudentOther
		(
			StudentId,
			DateOfBirth,
			GenderId,
			CreatedUserId,
			CreatedDateTime
		)
		VALUES
		(
			@lNextNumber,
			@rDateOfBirth,
			@rGenderId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		----IF(@rMobileNo!='')
		--BEGIN
			INSERT INTO sStudent.tStudentCommunication
			(
				StudentId,
				ParentContactNo,
				CreatedUserId,
				CreatedDateTime
			)
			VALUES
			(
				@lNextNumber,
				@rMobileNo,
				@rCreatedUserId,
				sCommon.fGetDate()
			)
		--END
		      
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
			IF(@rNumber=0)
			BEGIN
			SET  @rNumber=(SELECT ISnull(Number,0) FROM sStudent.tStudentMaster WHERE  Id=@rId)
			IF(@rNumber=0)
			SET @rNumber=@lNextNumber
			END
	    UPDATE  sStudent.tStudentMaster
	    SET
			Code=@rCode,
			Number=@rNumber,
			RegistrationNumber=@rRegistrationNumber,
			FirstName=@rFirstName,
			MiddleName=@rMiddleName,
			LastName=@rLastName,
			--OrgId=@rOrgId,
			--DepartmentId=@rDepartmentId,
			AdmissionCategoryId=@rAdmissionCategoryId,
			StatusId=@rStatusId,
			RecordStatusId=@rRecordStatusId,
	        UpdatedUserId=@rUpdatedUserId,
	        UpdatedDateTime=sCommon.fGetDate(),
			SUId=@rSUId,
			StudentGroupId=@rStudentGroupId ,
		    StudentOtherGroupId=@rStudentOtherGroupId
	      
	      WHERE Id = @rId 
	      
	    UPDATE  sStudent.tStudentOther
		SET
			DateOfBirth=@rDateOfBirth,
			GenderId=@rGenderId,
	        UpdatedUserId=@rUpdatedUserId,
	        UpdatedDateTime=sCommon.fGetDate()
	      WHERE StudentId = @rId 
	     
	     
	     IF(@rStatusId=3)
		BEGIN
		    UPDATE sSecurity.tUser
			   SET IsObsolete=1 
			WHERE SourceTypeId=2003 AND SourceId=@rId
		END
	 END  
	 
		SET @OutStudentId = @lNextNumber
	  SELECT 1 AS Result, @rCode AS Code, @lNextNumber AS Id 
		--SELECT @lNextNumber AS Result
	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pStudentSearchGet]...';


GO

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

BEGIN 	 
	BEGIN
		SET @rCode= sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rMiddleName = sCommon.fSearchStringGet(@rMiddleName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	END
 IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.MiddleName,
			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,
			ISNULL(SA.SUId,'') AS SUId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.ClassStatusId,
			SA.ClassStatusName
  FROM 
            sStudent.vStudentAcademic SA
            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.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = '')) 
			AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
			AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
			AND (OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			AND(SA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
			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.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.MiddleName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			ISNULL(SA.SUId,'') AS SUId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.ClassStatusId,
			SA.ClassStatusName
  FROM 
          sStudent.vStudentAcademic SA             
          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.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND ( OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		AND(SA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
		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.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		--AND(SA.BatchId=@rBatchId)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

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


GO

 
ALTER PROCEDURE [sTimetable].[pStudentTimeTableGet]
	
	 @rStudentId bigint,
	 @rTimeTableSchemaId int,
	 @rDivisionId int
	 

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(Title) 
                    from sCommon.tDayMaster
                    group by Title,Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
     
 
set @query = 'SELECT LectureNumber , ' + @cols + ' from 
             (
            Select LectureNumber, ISNULL(EM.ShortName + '+ ''' - ''' +' +SM.Code ,'''') + [sTimetable].[fTimeTableDetailGet](T.Id,1) AS EmployeeName ,DM.Title AS DayNames 
            from
            sTimetable.tTimeTable T 
            INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId AND TTS.IsPublish = 1
            INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=T.EmployeeId
	        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
	        INNER JOIN sStudent.tAcademic A ON A.DivisionId=T.DivisionId
	         WHERE    
	        ((A.StudentId=' + CAST(@rStudentId AS NVARCHAR(30))+') OR('+ CAST(@rStudentId AS NVARCHAR(30))+'=0))
			AND  ((T.DivisionId=' + CAST(@rDivisionId AS NVARCHAR(30))+') OR ('+CAST(@rDivisionId AS NVARCHAR(30))+'= 0) )
	         AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') OR ('+CAST(@rTimeTableSchemaId AS NVARCHAR(30))+'= 0))
	       
            ) x
            pivot 
            (
                max(EmployeeName)
                for DayNames in (' + @cols + ')
            ) p '
            
print @query
execute(@query)
     
        
	
		
END
GO
PRINT N'Altering [sTool].[pDeleteStaticData]...';


GO
 
ALTER PROCEDURE [sTool].[pDeleteStaticData]
 
	 
AS
SET NOCOUNT ON
BEGIN 
 

DELETE FROM sAlert.tEventMaster
DELETE FROM sCommon.tAutoCompleteMaster
DELETE FROM sCommon.tCommonMaster
DELETE FROM sCommon.tDepends
DELETE FROM sCommon.tModuleMaster
DELETE FROM sCommon.tPrefixFunctionality
DELETE FROM sCommon.tRefferedTableForObsoleteCheck
DELETE FROM sCommon.tRefferedTableWithoutForeignKey
DELETE FROM sCommon.tReport
DELETE FROM sCommon.tReportFormatGroupMaster
DELETE FROM sCommon.tReportGroupMaster
DELETE FROM sCommon.tSourceScreenMaster
DELETE FROM sCommon.tSourceTypeMaster
DELETE FROM sCommon.tStatusMaster
DELETE FROM sCommon.tStatusTypeMaster
DELETE FROM sCommon.tTableRowIdMaster
DELETE FROM sCommon.tUpdateFieldMaster
DELETE FROM sCommon.tValidationType
DELETE FROM sConfig.tColorLegendMaster
DELETE FROM sConfig.tConfigurationMaster
DELETE FROM sConfig.tConfigurationValue
DELETE FROM sSecurity.tMenu
DELETE FROM sSecurity.tResourceTypeMaster
DELETE FROM sSecurity.tScreen
DELETE FROM sSecurity.tScreenGroupMaster
DELETE FROM sSecurity.tScreenTypeMaster
DELETE FROM sSecurity.tTask
DELETE FROM sSystem.tTable
DELETE FROM sTool.tObjects
DELETE FROM sCommon.tReportTypeMaster


DELETE FROM sSetup.tAffiliationClassGroup
DELETE FROM sSetup.tAffiliationTypeMaster
DELETE FROM sSetup.tAffiliationMaster	
DELETE FROM sSetup.tStreamMaster

-- temp insert
DELETE FROM sAttendance.tAttendanceForMaster
DELETE FROM sEExam.tEntryModeMaster
DELETE FROM sSetup.tTermScopeMaster	 
 
DELETE FROM sConfig.tConfigurationLevelMaster

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

DELETE FROM sSecurity.tScreenGroupMapping
DELETE FROM sAssessment.tCCEExamMaster
DELETE FROM sSetup.tTermPatternMaster


DELETE FROM sAdmission.tAdmissionStatusMaster
DELETE FROM sAssessment.tCCERptGroup
DELETE FROM sHrm.tEmployeeICardTemplate
DELETE FROM sSecurity.tDashletMaster
DELETE FROM sStudent.tICardTemplate
DELETE FROM sSystem.tCustomQuery

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

DELETE FROM sOp.tPayTypeMaster
DELETE FROM sOp.tTransactionStatusMaster
--DELETE FROM sPayroll.tForm16B
DELETE FROM sStudent.tBatchStatusMaster
DELETE FROM [sFinanceCommon].[tPayTypeMaster]

DELETE FROM sAttendance.tAttendanceTagMaster
DELETE FROM sCommon.tLiveWithMaster
DELETE FROM sConfig.tDisplayFieldMaster

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

DELETE FROM sCommon.tCalculationTypeMaster
DELETE FROM sFee.tApplayAsMaster
DELETE FROM sSecurity.tScreenDependency
DELETE FROM sStudent.tSUIdFieldMaster

DELETE FROM [sAlert].[tAlertModeMaster]
DELETE FROM sCommon.tReportRemarkGroupMaster
DELETE FROM sStudent.tEnrollmentStatusMaster
DELETE FROM [sSetup].[tClassGroupMaster]

DELETE FROM sCommon.tTemplateSourceMaster
DELETE FROM sErp.tCustomerStatusMaster
DELETE FROM sErp.tInstallationTypeMaster
DELETE FROM sRecruitment.tRecruitmentStatusMaster

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

DELETE FROM sCommon.tImportFieldMaster
DELETE FROM sCRM.tHostingTypeMaster
DELETE FROM sHrm.tMainLeaveTypeMaster

DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sHrm.tTravelPeriodMaster
DELETE FROM sLoan.tInsterestTypeMaster

DELETE FROM sAppraisal.tBHRatingStatus
DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sAppraisal.tKPAMeasureMaster
DELETE FROM sAppraisal.tKPATypeMaster
DELETE FROM sAppraisal.tRatingStatus
DELETE FROM sCommon.tHeaderDisplayMaster
DELETE FROM sCommon.tModuleGroupMaster
DELETE FROM sHrm.tLeaveTransactionMaster
DELETE FROM sCommon.tCheckFrequencyMaster

DELETE FROM sErp.tLeadAffiliationMaster
DELETE FROM sErp.tLeadSourceMaster
DELETE FROM sErp.tLeadStatusMaster

DELETE FROM sSystem.tStaticVersion

DELETE FROM sCommunication.tFeedBackAnswerGroupMaster

DELETE FROM sCommon.tSubmitDocumentFunctionalityMaster
DELETE FROM sSetup.tMandatoryFeild
DELETE FROM sSetup.tMandatoryFeildFunctionalityMaster

DELETE FROM sSystem.tTimeZone
DELETE FROM sTool.tTestCaseTypeMaster

DELETE FROM sAlumni.tEmployeementType

DELETE FROM sErp.tCampusTypeMaster

DELETE FROM sAlert.tMailTypeMaster
DELETE FROM sAlert.tSMSVendorMaster
DELETE FROM sCommon.tWeekOffRules

DELETE FROM sSecurity.tScreenHelp
DELETE FROM sSystem.tSettingInfo

DELETE FROM sProcurement.tOtherLocationSourceTypeMaster

DELETE FROM sCommon.tFieldTypeMaster
DELETE FROM sErp.tLeadInfrastructureMaster

DELETE FROM sHostel.tHostelEventMainTypeMaster

DELETE FROM sCertificate.tCertificateTypeMaster	
DELETE FROM sWorkflow.tActionStatusMaster
DELETE FROM sWorkflow.tApprovingDepartmentMaster
DELETE FROM sWorkflow.tWorkflowFunctionalityMaster

DELETE FROM sAcademic.tHomeworkCheckStatusMaster
DELETE FROM sAssessment.tExamTypeMaster

DELETE FROM sErp.tMarketingActivityMaster
DELETE FROM sErp.tMarketingSubActivityMaster
DELETE FROM sSetup.tCommonOrgGroupBatchMaster
DELETE FROM sWorkflow.tWorkflowFunctionalityMaster

DELETE FROM sAudit.tOperationMaster

DELETE FROM sAdmission.tInquiryMainStatusMaster
DELETE FROM sCertificate.tPrintTemplateFunctionalityMaster
DELETE FROM sErp.tTripLogStatusMaster

DELETE FROM sErp.tFollowupTypeMaster
DELETE FROM sErp.tSupportCategoryMaster
DELETE FROM sErp.tSupportPriorityMaster
DELETE FROM sErp.tSupportTicketStatusMaster


DELETE FROM sErp.tPlugInMaster
DELETE FROM sErp.tTagMaster

END
GO
PRINT N'Creating [sAcademic].[pLessonPlanMobileGet]...';


GO
CREATE PROCEDURE [sAcademic].[pLessonPlanMobileGet]

	 @rId bigint=0,
	 @rClassId int=0,
	 @rSubjectId int=0,
	 @rDivisionId int=0,
	 @rIsCompleted bit=0,
	 @rBatchId int=0,
	 @rEmployeeId bigint=0,
	 @rDepartmentid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rIsCompletedAPI tinyint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
DECLARE @lIsCompleted bit = 0
	
	If(@rIsCompletedAPI=1)
		SET @lIsCompleted = 1
	else If(@rIsCompletedAPI=2)
		SET @lIsCompleted = 0
	
	SELECT 
			LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId   
	WHERE 
		((LP.BatchId = @rBatchId) OR (LP.BatchId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND((LP.IsCompleted=@lIsCompleted) OR (@rIsCompletedAPI=0))
		AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
	ORDER BY
		LP.id 
END
GO
PRINT N'Creating [sAssessment].[pRptResultSheetStandardGetwithResultDetailOther]...';


GO
CREATE PROCEDURE [sAssessment].[pRptResultSheetStandardGetwithResultDetailOther]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @GradeString nvarchar(1000),  @GradeStringRemark nvarchar(500),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId
 
	SELECT 
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		ESGM.Title AS Exam,
		StuM.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		R.AcademicId,			
		R.ResultStatus,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,
		R.Percentile,			
		RD.Id AS ResultDetailId,		
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		RD.Obtain AS SubjectObtain,
		ED.Minimum AS SubjectMinimum,
		ED.Maximum AS SubjectMaximum,
		RD.SubjectGrade,
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		R.Id AS ResultId,
		CS.Id AS SubjectId,			 	
		EM.IsMarksInDecimal,
		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsMarksInDecimal,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		--ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END) AS StudentPhoto,
		RD.IsPresent,
		CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,			
		OM.SmallAddress1,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
		
		EM.IsDisplayTeacherSign,
		Em.IsDisplayPrincipalSign,
		(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
		ELSE NULL END)AS EmployeeSign,
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			OI.CertificateHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		
		SR.StudentHeight,
		SR.StudentWeight,		
		SR.PresentDays,			
		SR.TotalDays,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.Resultremark3,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		BM.Title AS BatchName,
		Em.DecimalFormat,
		RD.GraceMark,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(BGM.Title,'') AS BloodGroup,
		GS.GradeTitle,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		RD.KrupaMark,
		RDO.TotalCount,
		RDO.PresentCount,
		RDO.Remark As Remark4
		

	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
		LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
		LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId  and RD.SubjectGrade = GS.GradeCode
		LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id				
		LEFT JOIN sAssessment.tResultDetailOther RDO ON  RDO.ExamId = EM.Id AND R.Academicid =RDO.AcademicId AND ED.ClassSubjectId = RDO.ClassSubjectId
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		order by A.RollNo,ED.DisplayOrder
END
GO
PRINT N'Creating [sCommunication].[pPhotoCategoryMasterDelete]...';


GO

CREATE PROCEDURE [sCommunication].[pPhotoCategoryMasterDelete]
	 
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN TRY
		
		BEGIN TRANSACTION		

		BEGIN
			DELETE FROM [sCommunication].[tPhotoCategoryMaster] WHERE Id=@rId 
			SELECT 1 AS Result
		END		
	
	COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END
GO
PRINT N'Creating [sErp].[pPluginLogAdd]...';


GO
 

CREATE PROCEDURE [sErp].[pPluginLogAdd]    
	@rOrgGroupID int, 
	@rPlugin int,
	@rStatusRemark nvarchar(200) = 'Active',
	@rCreatedUserId bigint,
	@rPlugInStatusId tinyint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
   
	BEGIN TRY
 	BEGIN TRANSACTION
	 
		BEGIN			
		INSERT INTO sErp.tCustomerPlugInLog
			(
			
			OrgGroupId,
			PlugInId,
			LogDate,
			StatusRemark,
			CreatedUserId,
			CreatedDateTime,
			PlugInStatusId
			)
			VALUES
			(
			
			@rOrgGroupID ,
			@rPlugin ,
			sCommon.fGetDate(),
			@rStatusRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rPluginStatusId
			)
		
		
		SELECT 1 AS RESULT
		END

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


GO
CREATE PROCEDURE [sLibrary].[pRptBookListCirculationLowFrequencyGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	--@rReaderSourceTypeId smallint,
	 --@rReaderSourceId bigint,
	 --@rOrgId smallint,
	 --@rBatchId int,
	 --@rClassId int,
	 --@rDivisionId int,
	 @rFromLogDate date,
	 @rToLogDate date,
	 @rLibraryId int,
	 @rTopFrequency  smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		SELECT Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2 FROM sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		WHERE (BL.LibraryId=@rLibraryId)
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			GROUP  by BM.Id,BM.Code,BM.Title
			ORDER BY COUNT(BL.Id) 

END
GO
PRINT N'Creating [sProcurement].[pStockInwardReturnGet]...';


GO
-- exec [sProcurement].[pStockIssReturnGet]
-- drop proc [sProcurement].[pStockIssReturnGet]
CREATE Procedure [sProcurement].[pStockInwardReturnGet]
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0,
	@rItemCode nvarchar(100)='',
	@rItemName nvarchar(200)='',
	@rSearchType nvarchar(5)= '1'
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	  
SET @rNumber = sCommon.fSearchStringGet(@rNumber)
	if(@rSearchType='1')
		begin
				SELECT		
				SIR.Id,SIR.Number,isnull(SIR.StockInwardId,0) as StockInwardId,
				SIR.ReturnByName as ReturnByName,
				case when SIR.TransactionDate is not null  then SIR.TransactionDate else  SIR.CreatedDateTime End AS IssuedDate,
				 SIR.CreatedDateTime as TranjactionDate,
				 '' StockItemCode,
				 '' StockItemName
				FROM sProcurement.tStockInwardReturn SIR 
				WHERE ((SIR.Number like @rNumber) OR (@rNumber = ''))
				AND  SIR.OrgGroupId = @rOrgGroupId
				AND (( Convert(Date,SIR.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SIR.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SIR.FromStoreLocationId=@rStoreLocationId 
				Order by SIR.CreatedDateTime desc
				
		end
	else
		begin
				SELECT		
				SIR.Id,SIR.Number,isnull(SIR.StockInwardId,0) as StockInwardId,
				SIR.ReturnByName as ReturnByName,
				case when SIR.TransactionDate is not null  then SIR.TransactionDate else  SIR.CreatedDateTime End AS IssuedDate,
				 SIR.CreatedDateTime as TranjactionDate,
				 SIM.Code as StockItemCode,
				 SIM.TItle as StockItemName
				FROM sProcurement.tStockInwardReturn SIR 
				INNER JOIN sProcurement.tStockInwardReturnBatch SIRB ON SIRB.StockInwardReturnId=SIR.Id
				INNER JOIN sProcurement.tStockInwardBatch SIB ON SIB.Id=SIRB.StockInwardBatchId
				left join sProcurement.tStockBatch Sb on sb.id = SIB.StockBatchId and sb.Number is not null
				INNER JOIN sProcurement.tStockInwardDetail SIND ON SIND.Id=SIB.StockInwardDetailId
				INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
				--INNER JOIN sProcurement.tStockInward SI ON SI.Id=SIR.StockInwardId
				
				WHERE ((SIR.Number like @rNumber) OR (@rNumber = ''))
				AND  SIR.OrgGroupId = @rOrgGroupId
				AND (( Convert(Date,SIR.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SIR.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SIR.FromStoreLocationId=@rStoreLocationId 
				AND (SIM.Id = @rItemCode or @rItemCode='')
				AND (SIM.Id = @rItemName or @rItemName='')
				Order by SIR.CreatedDateTime desc	
		end
END
GO
PRINT N'Creating [sProcurement].[pStockIssReturnGet]...';


GO
-- exec [sProcurement].[pStockIssReturnGet]
-- drop proc [sProcurement].[pStockIssReturnGet]
CREATE Procedure [sProcurement].[pStockIssReturnGet]
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0,
	@rItemCode nvarchar(100)='',
	@rItemName nvarchar(200)='',
	@rSearchType nvarchar(5)= '1'
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	  
SET @rNumber = sCommon.fSearchStringGet(@rNumber)
	if(@rSearchType='1')
		begin
				SELECT		
				SIR.Id,SIR.Number,isnull(SIR.StockIssueId,0) as StockIssueId,
				SIR.ReturnedByName as ReturnByName,
				case when SIR.TransactionDate is not null  then SIR.TransactionDate else  SIR.CreatedDateTime End AS IssuedDate,
				 SIR.CreatedDateTime as TranjactionDate,
				 '' StockItemCode,
				 '' StockItemName
				FROM sProcurement.tStockIssueReturn SIR 
				WHERE ((SIR.Number like @rNumber) OR (@rNumber = ''))
				AND  SIR.OrgGroupId = @rOrgGroupId
				AND (( Convert(Date,SIR.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SIR.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SIR.ToStoreLocationId=@rStoreLocationId 
				Order by SIR.CreatedDateTime desc
		end
	else
		begin
				SELECT		
				SIR.Id,SIR.Number,isnull(SIR.StockIssueId,0) as StockIssueId,
				SIR.ReturnedByName as ReturnByName,
				case when SIR.TransactionDate is not null  then SIR.TransactionDate else  SIR.CreatedDateTime End AS IssuedDate,
				 SIR.CreatedDateTime as TranjactionDate,
				 SIM.Code as StockItemCode,
				 SIM.TItle as StockItemName
				FROM sProcurement.tStockIssueReturn SIR 
				INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SIR.Id
				INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id=SIRB.StockIssueBatchId
				left join sProcurement.tStockBatch Sb on sb.id = SIB.StockBatchId and sb.Number is not null
				INNER JOIN sProcurement.tStockIssueDetail SIND ON SIND.Id=SIB.StockIssueDetailId
				INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
				WHERE ((SIR.Number like @rNumber) OR (@rNumber = ''))
				AND  SIR.OrgGroupId = @rOrgGroupId
				AND (( Convert(Date,SIR.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SIR.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SIR.ToStoreLocationId=@rStoreLocationId 
				AND (SIM.Id = @rItemCode or @rItemCode='')
				AND (SIM.Id = @rItemName or @rItemName='')
				Order by SIR.CreatedDateTime desc	
		end
END
GO
PRINT N'Creating [sSecurity].[pOrgGroupMappingGet]...';


GO

CREATE PROCEDURE [sSecurity].[pOrgGroupMappingGet]

	 @rOrgGroupId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		SELECT * FROM sSetup.tOrgGroupEIS WHERE OrgGroupId  = @rOrgGroupId
END
GO

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