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

 
GO
PRINT N'Dropping [sTimetable].[tTimeTableTime].[UK_tTimeTableTime]...';


GO
DROP INDEX [UK_tTimeTableTime]
    ON [sTimetable].[tTimeTableTime];


GO
PRINT N'Dropping [sStudent].[tTempStudent11]...';


GO
DROP TABLE [sStudent].[tTempStudent11];


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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [AdhaarNumber] NVARCHAR (100) NULL,
        [UIdNumber]    NVARCHAR (100) NULL;


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


GO
ALTER TABLE [sCommunication].[tAssignment]
    ADD [StatusId]             SMALLINT NULL,
        [ApprovedByEmployeeId] BIGINT   NULL;


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


GO
ALTER TABLE [sErp].[tLeadFollowup]
    ADD [Displacement] DECIMAL (10, 2) NULL;


GO
PRINT N'Altering [sFee].[tFeeAllocation]...';


GO
ALTER TABLE [sFee].[tFeeAllocation]
    ADD [DiscountRemark]      NVARCHAR (200) NULL,
        [AdditionalRemark]    NVARCHAR (200) NULL,
        [NotApplicableRemark] NVARCHAR (200) NULL;


GO
PRINT N'Altering [sTimetable].[tTimeTableTime]...';


GO
ALTER TABLE [sTimetable].[tTimeTableTime]
    ADD [IsBreak] BIT NULL;


GO
PRINT N'Creating [sTimetable].[tTimeTableTime].[UK_tTimeTableTime]...';


GO
CREATE UNIQUE NONCLUSTERED INDEX [UK_tTimeTableTime]
    ON [sTimetable].[tTimeTableTime]([DayId] ASC, [LectureNumber] ASC, [DivisionId] ASC, [TimeTableSchemaId] ASC, [IsBreak] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


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


GO
CREATE TABLE [sAdmission].[tAdmissionInquiryField] (
    [AdmissionInquiryId]            BIGINT          NOT NULL,
    [AdmissionInquiryFormId]        INT             NOT NULL,
    [AdmissionInquiryFieldResponse] NVARCHAR (1000) NULL
);


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


GO
CREATE TABLE [sAdmission].[tAdmissionInquiryForm] (
    [Id]               INT            NOT NULL,
    [ClassId]          INT            NOT NULL,
    [BatchId]          INT            NOT NULL,
    [FieldRemark]      NVARCHAR (500) NOT NULL,
    [FieldTypeId]      TINYINT        NOT NULL,
    [FieldList]        NVARCHAR (500) NULL,
    [IsFieldMandatory] BIT            NOT NULL,
    [FieldGroup]       NVARCHAR (200) NULL,
    [FieldOrder]       SMALLINT       NULL
);


GO
PRINT N'Creating PK_tAdmissionInquiryForm...';


GO
ALTER TABLE [sAdmission].[tAdmissionInquiryForm]
    ADD CONSTRAINT [PK_tAdmissionInquiryForm] 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 [sFee].[tStudentFee]...';


GO
CREATE TABLE [sFee].[tStudentFee] (
    [AcademicId]           BIGINT          NOT NULL,
    [FeeSetupId]           INT             NOT NULL,
    [IsOptionalApplicable] BIT             NOT NULL,
    [IsVariableApplicable] BIT             NOT NULL,
    [FeeAmount]            DECIMAL (12, 2) NOT NULL,
    [VariableAmount]       DECIMAL (12, 2) NOT NULL,
    [DiscountAmount]       DECIMAL (12, 2) NOT NULL,
    [AdditionalAmount]     DECIMAL (12, 2) NOT NULL,
    [NotApplicableAmount]  DECIMAL (12, 2) NOT NULL,
    [PaidAmount]           DECIMAL (12, 2) NOT NULL,
    [PendingAmount]        DECIMAL (12, 2) NOT NULL
);


GO
PRINT N'Creating [sFee].[tStudentFee].[IX_tStudentFee]...';


GO
CREATE UNIQUE NONCLUSTERED INDEX [IX_tStudentFee]
    ON [sFee].[tStudentFee]([AcademicId] ASC, [FeeSetupId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


GO


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


GO

CREATE FUNCTION [sFee].[fFeeAllocationRemarkGet](@rAcademicId bigint,@rRemarkId int)
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rFeeAllocationRemark  nvarchar(2000)

IF(@rRemarkId =1)
BEGIN
(SELECT 
			@rFeeAllocationRemark=COALESCE(@rFeeAllocationRemark+',','') +   F.DiscountRemark
			 FROM
			 sFee.tFeeAllocation F			  
			 WHERE F.SourceId = @rAcademicId 
			  )
	END
	ELSE IF(@rRemarkId=2)
	BEGIN
	(SELECT 
			@rFeeAllocationRemark=COALESCE(@rFeeAllocationRemark+',','') +   F.Remark
			 FROM
			 sFee.tFeeAllocation F			  
			 WHERE F.SourceId = @rAcademicId 
			  )
	END
	ELSE IF(@rRemarkId=3)
	BEGIN
	(SELECT 
			@rFeeAllocationRemark=COALESCE(@rFeeAllocationRemark+',','') +   F.AdditionalRemark
			 FROM
			 sFee.tFeeAllocation F			  
			 WHERE F.SourceId = @rAcademicId 
			  )
	END
	ELSE IF(@rRemarkId=4)
	BEGIN
	 (SELECT 
			@rFeeAllocationRemark=COALESCE(@rFeeAllocationRemark+',','') +   F.NotApplicableRemark
			 FROM
			 sFee.tFeeAllocation F			  
			 WHERE F.SourceId = @rAcademicId 
			  )
	END
  RETURN ISNULL(@rFeeAllocationRemark,'') 
END
GO
PRINT N'Creating [sFee].[fPendingFeeAmountForAlertGet]...';


GO
CREATE FUNCTION [sFee].[fPendingFeeAmountForAlertGet] (@rAcademicId bigint)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rReceiptAmount decimal(12,0),@lClassId int, @lDivisionId int, @lAdmissionCategoryId int, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int
    SELECT @rOrgGroupBatchId=OrgGroupBatchId,@rOrgId=OrgId,@rBatchId=BatchId,@lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
    
    (
    SELECT 
		@rReceiptAmount = 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))
    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			 
			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=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				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 
				
			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=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId
		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				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.AcademicId = @rAcademicId
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=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)
			)
			
	RETURN @rReceiptAmount
END
GO
PRINT N'Creating [sHrm].[fAttendanceJoiningDateGet]...';


GO
CREATE FUNCTION [sHrm].[fAttendanceJoiningDateGet](@rDateOfJoining date,@rAttendanceDate nvarchar(20),@rDateOfLeaving date,@rStatus nvarchar(10))
RETURNS [nvarchar](50) WITH EXECUTE AS CALLER
AS 
BEGIN
	DECLARE @lDate nvarchar(20)
	
	
if isnull(@rStatus,'') = ''
BEGIN
	Set @ldate = @rDateOfJoining	
	if ISDATE(@ldate)=1
	BEGIN
		if(@rDateOfJoining > @rAttendanceDate)
		BEGIN
			SET @rStatus = 'NA'
			RETURN @rStatus
		END
		if(@rDateOfJoining <= @rAttendanceDate)
		BEGIN
			SET @rStatus='L'
			RETURN @rStatus
		END
		 
	 END	
	END	    
	RETURN @rStatus
END
GO
PRINT N'Altering [sCertificate].[vPrintTemplateStudentBasicDetails]...';


GO
ALTER VIEW [sCertificate].[vPrintTemplateStudentBasicDetails]
AS
	SELECT 
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS StudentName,
	  SM.Code,	
	  DM.Code AS ClassDivision,
	  A.RollNo,
	  BM.Title AS BatchName,
	  SO.DateOfBirth AS DateOfBirth,  	 
	  '[BatchName],[ClassDivision],[Code],[DateOfBirth],[RollNo],[FirstName],[MiddleName],[LastName],[PreviousSchool],[Caste],[SubCaste],[BirthPlace],[DOBInWords]' As ColumnList
  FROM 
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId
	INNER JOIN sSetup.tDepartmentMaster DeptM
		ON DeptM.Id=CM.DepartmentId
	INNER JOIN sSetup.tOrganizationMaster OM 
	    ON A.OrgId = OM.Id
	INNER JOIN [sStudent].[tStudentOther] SO
	    ON SO.StudentId=SM.Id
GO
PRINT N'Altering [sCertificate].[vPrintTemplateStudentDetail]...';


GO
ALTER VIEW [sCertificate].[vPrintTemplateStudentDetail]
 
AS  
  
SELECT 
			A.Id AS AcademicId,
		    DivM.Id AS DivisionId,
		    DivM.DisplayTitle AS DivisionName,
		    CM.Id AS ClassId,
		    CM.DisplayTitle AS ClassName,
		    CM.DisplayTitle+'-'+DivM.DisplayTitle AS ClassDivision,
		    DM.Id AS DepartmentId,
		    DM.DisplayTitle AS DepartmentName,
		    SM.FirstName AS FirstName,
		    SM.MiddleName AS MiddleName,
		    SM.LastName AS LastName,
		    SM.Code,
		    A.RollNo,
		    A.BatchId,
		    BM.Title AS BatchName,
		    CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
		    SA.PreviousSchool,
			SO.FamilyCast AS Caste,  
			SO.FamilySubCast AS SubCaste,
			SO.BirthPlace,
			SO.BirthDateInWord AS DOBInWords
	FROM 
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DivM ON DivM.Id=A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
GO

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


GO
 
ALTER PROCEDURE [sAcademic].[pClassv4Get]

	 @rEmployeeId bigint,
	 @rOrgGroupBatchId int,
	 @rClassworkDate Date,
	 @rOrgId smallint,
	 @rBatchId int	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsClassworkHomeworkBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 323 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsClassworkHomeworkBasedOnApproval = 0
	ELSE
	SET @lIsClassworkHomeworkBasedOnApproval = 1	

	SELECT 
			TSD.SubjectId ,
		    SM.Title AS SubjectName,
			ISNULL(AC.Id,0) AS ClassworkId,
		    ISNULL(AC.Classwork,CC.ClassworkTemplate) AS Classwork,
		    ISNULL(AC.Homework,CC.HomeworkTemplate) AS Homework,
		    ISNULL(CONVERT(VARCHAR(10), AC.HomeWorkEndDate, 103),'') AS HomeWorkEndDate,
		    DM.Id AS DivisionId,
		    DM.ClassId,
		    CM.Title +'-'+DM.Title AS ClassDivisionName,
		    OM.Id As OrgId,
		    OM.DisplayTitle AS OrgTitle,
		    DM.OrderIndex,
		    ISNULL(AC.ClassworkStatusId,1) AS ClassworkStatusId,
		    ISNULL(AC.HomeWorkStatusId,1) AS HomeWorkStatusId
	FROM
			sAcademic.tTeacherSubjectDivision TSD			
			INNER JOIN sSetup.tSubjectMaster SM ON TSD.SubjectId = SM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON TSD.DivisionId = DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sSetup.tClassMaster CM On CM.Id = DM.ClassId
			LEFT JOIN sAcademic.tClasswork AC ON TSD.SubjectId = AC.SubjectId AND TSD.DivisionId = AC.DivisionId AND TSD.EmployeeId = AC.EmployeeId AND AC.ClassWorkDate = @rClassworkDate --AND AC.BatchId = @rBatchId
			LEFT JOIN sAcademic.tClassworkConfig CC ON CC.OrgId = DM.OrgId
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id  AND BM.OrgId = @rOrgId
	WHERE 
			TSD.EmployeeId= @rEmployeeId AND OGBM.Id = @rOrgGroupBatchId 
			--AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
			--AND AC.StatusId=550
	ORDER BY 
			OM.Id,DM.OrderIndex
		
END
GO
PRINT N'Altering [sAcademic].[pClassworkHomeworkQueueGet]...';


GO
ALTER PROCEDURE [sAcademic].[pClassworkHomeworkQueueGet]

	 @rId bigint=0,	 
	 @rSubjectId int=0,
	 @rClassId int=0,
	 @rEmployeeId bigint=0,
	 @rDivisionid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rOrgId int=0,
     --@rBatchId int
     @rOrgGroupBatchId int=0,
    @rUserId bigint =0,
	@rStatusId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	if(@rId = 0)
		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,
			ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
			CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status
	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))
			AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
	order by 
			AC.HomeWorkEndDate DESC
		END 
	ELSE
		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))
			GROUP BY AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ClassworkStatusId,
			HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			AC.HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title,
		  vTSD.SubjectName,
		    EM.FirstName,  EM.LastName,
		    vTSD.ClassTitle,
		   vTSD.DivisionTitle,
		    BM.OrgId,
		    OM.DisplayTitle,
		     AC.ClassWorkDate, AC.DivisionId,AC.SubjectId
	order by 
			AC.HomeWorkEndDate DESC
		END
	
END
GO
PRINT N'Altering [sAcademic].[pClassworkStudentGet]...';


GO
ALTER PROCEDURE [sAcademic].[pClassworkStudentGet]

	 @rStudentId bigint,
	 @rBatchId int,	 
	 @rFromDate date='',
     @rToDate date='',
     @rHomeWorkEndDate	date=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	DECLARE @lOrgGroupBatchId int=0
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rBatchId

	DECLARE @lDivisionId int
	SELECT @lDivisionId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId

	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsClassworkHomeworkBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 323 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsClassworkHomeworkBasedOnApproval = 0
	ELSE
	SET @lIsClassworkHomeworkBasedOnApproval = 1	
	
	SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    AC.Classwork,
		    AC.Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    --ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    OM.OrgGroupId AS OrgId
	FROM 
			sAcademic.tClasswork AC			 
			INNER Join sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER Join sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER Join sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER Join sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			
	WHERE 
	    AC.DivisionId = @lDivisionId		 
		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
		AND (AC.HomeWorkEndDate>=@rHomeWorkEndDate OR ISNULL(@rHomeWorkEndDate,'')='')
		AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
		order by  AC.CreatedDateTime desc
END
GO
PRINT N'Altering [sAcademic].[pClassworkStudentWithStatusGet]...';


GO
ALTER PROCEDURE [sAcademic].[pClassworkStudentWithStatusGet]

	 @rStudentId bigint,
	 @rBatchId int,	 
	 @rFromDate date='',
     @rToDate date='',
     @rHomeWorkEndDate	date='' 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	DECLARE @lDivisionId int
	DECLARE @lAcademicId bigint
	SELECT @lDivisionId = DivisionId,@lAcademicId = Id FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId

	DECLARE @lOrgGroupBatchId int=0
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rBatchId

	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsClassworkHomeworkBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 323 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsClassworkHomeworkBasedOnApproval = 0
	ELSE
	SET @lIsClassworkHomeworkBasedOnApproval = 1
	
	SELECT 
			DISTINCT(AC.Id),
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    CASE WHEN AC.ClassworkStatusId != 2 THEN AC.Classwork ELSE 'NA' END AS Classwork,
		    CASE WHEN AC.HomeWorkStatusId != 2 THEN AC.Homework ELSE 'NA' END AS Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    OM.OrgGroupId AS OrgId,
		    ISNULL(HCSM.Title,'Assigned') AS HomeworkStatus
	FROM 
			sAcademic.tClasswork AC			 
			INNER JOIN sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER JOIN sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER JOIN sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER JOIN sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sStudent.tAcademic SA ON SA.ClassId = AC.ClassId AND SA.DivisionId = AC.DivisionId AND SA.BatchId = AC.BatchId
			LEFT JOIN sAcademic.tHomeworkCheck HWC ON HWC.AcademicId = SA.Id AND HWC.ClassworkId = AC.Id
			LEFT JOIN sAcademic.tHomeworkCheckStatusMaster HCSM ON HCSM.Id = HWC.HomeWorkCheckStatusId
	WHERE 
			AC.DivisionId = @lDivisionId		 
			AND (AC.ClassWorkDate=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (AC.HomeWorkEndDate>=@rHomeWorkEndDate OR ISNULL(@rHomeWorkEndDate,'')='')
			AND AC.BatchId = @rBatchId
			AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
			--AND AC.StatusId=550
			--AND SA.Id = @lAcademicId
	ORDER BY  AC.ID DESC
END
GO
PRINT N'Altering [sAcademic].[pMonthlyStatusGet]...';


GO
ALTER PROCEDURE [sAcademic].[pMonthlyStatusGet]

    
	 
     @rOrgId smallint,
     @rBatchId Bigint,     
     @rYear smallint,
     @rMonth smallint,
	 @rDayOfMonth smallint,
	 @rAttendanceTypeId int,
	 @rClassId Bigint,
	 @rDivisionId Bigint
     --@rDate smallint,
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 	
	



 SELECT 	A.ClassId ,A.DivisionId,vCD.ClassDivisionName,ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
		  

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,01,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,01,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-01')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-01'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P1	,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,02,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,02,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-02')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-02'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P2,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,03,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,03,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-03')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-03'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P3,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,04,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,04,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-04')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-04'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P4,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,05,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,05,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-05')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-05'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P5,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,06,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,06,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-06')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-06'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P6,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,07,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,07,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-07')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-07'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P7,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,08,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,08,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-08')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-08'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P8,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,09,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,09,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-09')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-09'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P9,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,10,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,10,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-10')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-10'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P10,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,11,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,11,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-11')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-11'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P11,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,12,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,12,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-12')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-12'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P12,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,13,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,13,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-13')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-13'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P13,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,14,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,14,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-14')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-14'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P14,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,15,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,15,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-15')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-15'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P15,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,16,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,16,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-16')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-16'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P16,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,17,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,17,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-17')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-17'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P17,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,18,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,18,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-18')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-18'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P18,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,19,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,19,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-19')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-19'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P19,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,20,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,20,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-20')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-20'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P20,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,21,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,21,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-21')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-21'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P21,

				(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,22,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,22,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-22')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-22'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P22,


			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,23,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,23,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-23')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-23'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P23,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,24,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,24,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-24')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-24'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P24,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,25,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,25,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-25')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-25'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P25,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,26,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,26,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-26')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-26'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P26,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,27,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,27,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-27')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-27'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P27,

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,28,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,28,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-28')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-28'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) AS P28,

			CASE WHEN @rDayOfMonth >=29 THEN

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,29,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,29,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-29')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-29'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) ELSE '' END AS P29,

			CASE WHEN @rDayOfMonth >=30 THEN

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,30,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,30,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-30')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-30'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) ELSE '' END AS P30,


			CASE WHEN @rDayOfMonth =31 THEN

			(SELECT CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,31,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,31,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-31')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  
			   
			FROM 	sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-31'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId	AND SR.IsPresent=1		
			WHERE A.ClassId=@rClassId		AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId	) ELSE '' END AS P31

			
		
			   
    FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId        
			WHERE A.ClassId=@rClassId	AND A.DivisionId=@rDivisionId
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId


END
GO
PRINT N'Altering [sAdmission].[pAdmissionDocumentGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionDocumentGet]
	 
	@rClassId int,
	@rBatchId int,
	@rDocumentId int,
	@rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		ACD.BatchId,ACD.ClassId,ACD.SubmitDocumentMasterId AS DocumentId,SDM.DocumentName,ISNULL(ACD.Remark,'') AS Remark
	FROM 
		sAdmission.tAdmissionCriteriaDocument ACD
		LEFT JOIN sCommon.tSubmitDocumentMaster SDM ON SDM.Id = ACD.SubmitDocumentMasterId and SDM.OrgId=@rOrgId
	WHERE 
		(ACD.ClassId = @rClassId OR ISNULL(@rClassId,0)=0)
		AND (ACD.BatchId = @rBatchId OR ISNULL(@rBatchId,0)=0)
		AND (ACD.SubmitDocumentMasterId = @rDocumentId OR ISNULL(@rDocumentId,0)=0)

		UNION
		SELECT 
		0 BatchId,0 ClassId,Id AS DocumentId,DocumentName,'' AS Remark
	FROM 
		sCommon.tSubmitDocumentMaster SDM		
		WHERE  SubmitDocumentFunctionalityId=3 AND ID NOT IN(SELECT SubmitDocumentMasterId FROM sAdmission.tAdmissionCriteriaDocument WHERE ClassId = @rClassId AND  BatchId = @rBatchId )
		AND OrgId=@rOrgId
END
GO
PRINT N'Altering [sAdmission].[pAdmissionInquiryGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionInquiryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rId bigint = 0,
	 
	 @rForClassId int = 0,
	 @rClassId int = 0,
	 @rBatchId int = 0,
	 @rStatusId int =0,
	-- @rStatusId smallint,
	 @rInquiryStatusMasterId int = 0,
	 @rOrgId int,
	 @rFirstName nvarchar(100) = '',
	 @rLastName nvarchar(100) = '',
	 @rFromDate datetime='',
	 @rToDate datetime='',
	 @rForBatchId int = 0,
	 @rDepartmentId int,
	 @rFromMeritMarks decimal(10,2) = 0,
	 @rToMeritMarks decimal(10,2)=0,
	 @rInquiryModeId smallint=0,
	 @rInquiryReferenceId int=0,
	 @rNumber bigint=0,
	 @rOrgGroupBatchId int = 0,
	 @rFollowUpdate datetime='',
	 @rIsTransportRequired int=0,
	 @rIsHostelRequired int=0,
	 @rOrderBy int =0,
	 @rIsGivenAdmissionForm int =0,
	 @rContactNo nvarchar(100)=''
	  --@rIsGivenAdmissionFormNew int =0
	 --@rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	
	 
	 
	 SET @rToDate = DATEADD(d,1,@rToDate)
	 --IF @rIsSearch = 1
		BEGIN
			SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName= sCommon.fSearchStringGet(@rLastName)
			--SET @rContactNo= sCommon.fSearchStringGet(@rContactNo)
		END
	
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 AI.Id
			,AI.ForBatchId
			,AI.ForClassId
			,AI.StatusId
			,ISNULL(SM.Id,0) AS InquiryStatusMasterId
			,ISNULL(AI.GenderId,0) AS GenderId
			,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
			,ISNULL(IMM.Title,'') AS InquiryMode
			,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		    ,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		    ,AI.OrgId
		    ,ISNULL(AI.Number,0) AS InquiryNumber
		    ,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		    ,OM.DisplayTitle AS OrgName
		    ,BM.Title AS ForBatch
			,ISNULL(CM.Title,'') AS ClassName	
			,AI.FirstName
			,AI.MiddleName
			,AI.LastName
			,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
			,ISNULL(AI.DateOfBirth,'') As DateOfBirth
			,ISNULL(GM.Title,'') As Gender			
			,AI.ContactNo
			,AI.ContactEmail			
			,AI.StreetOne
			,AI.StreetTwo
			,AI.StreetThree
			,AI.Country
			,AI.State
			,AI.City
			,AI.ZipCode
			,ISNULL(AI.Remark,'') AS Remark						
		    ,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
			,ISNULL(AI.MeritMarks,0) AS MeritMarks
			,ISNULL(AI.MeritGrade,'') AS MeritGrade
			,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
			,SM.Title as StatusName	
			--,cast(replace(FollowupDate,'/','-') as date) As FollowupDate
			,ISNULL(AI.FollowupDate,'') As FollowupDate
			,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
			,ISNULL(IRM.Title ,'') AS InquiryReference	
			,ISNULL(SCM.Title,'') AS AdmissionCategory		
			,ISNULL(AI.HandledBy,'') AS HandledBy
			,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
			,ISNULL(AI.StudentId,0) AS StudentId,
			ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
			ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
			ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
			ISNULL(AI.IsGivenAdmissionForm,0) AS IsGivenAdmissionForm,
			ISNULL(SM.HighlightColor,'') AS HighlightColor,
			ISNULL(SA.PreviousStandard,'') As PreviousStandard,
			AI.AlternateContactNo,
			AI.AlternateContactEmail
			,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString
  FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
           --INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AI.StatusId AND StatusTypeId=104
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  --AND ((AI.StatusId=@rStatusId) OR (@rStatusId=0))
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (@rNumber=0))
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
	  AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN ISNULL(AI.IsTransportRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	  
	  AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN ISNULL(AI.IsHostelRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
      AND (AI.IsGivenAdmissionForm = CASE @rIsGivenAdmissionForm
                              WHEN 0 THEN ISNULL(AI.IsGivenAdmissionForm,0)
                              WHEN 2 THEN 1
                              WHEN 1 THEN 0
                         END)
	 AND ((AI.ContactNo = @rContactNo) OR (@rContactNo=''))
	  --AND ((AI.IsTransportRequired=@rIsTransportRequired) OR (@rIsTransportRequired=0))	   
	    --AND ((AI.IsHostelRequired =@rIsHostelRequired) OR (@rIsHostelRequired=0))
	  Order by Case @rOrderBy When 1 then AI.MeritMarks END desc ,
			    Case @rOrderBy when 0 then AI.Number Else 
			    AI.Number  END  
			    
END
GO
PRINT N'Altering [sAdmission].[pAdmissionStudentDocumentAdd]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionStudentDocumentAdd]
	 
        @rAdmissionFormId bigint,
		@rSubmitDocumentMasterId int,
		@rDocumenet NVARCHAR(MAX)
		--@rDocumenetXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	
 
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
		
	BEGIN		
	
	declare @rCount int

	Set @rCount = (SELECT ISNULL(COUNT (*),0)  FROM sAdmission.tAdmissionStudentDocument WHERE AdmissionFormId = @rAdmissionFormId AND SubmitDocumentMasterId= @rSubmitDocumentMasterId )

	if(@rCount =0)
	begin
	
	INSERT INTO sAdmission.tAdmissionStudentDocument
		([AdmissionFormId],[SubmitDocumentMasterId],[DocumentName])
	VALUES
		(@rAdmissionFormId,@rSubmitDocumentMasterId,@rDocumenet)
		     SELECT 1 AS Result	
			 end
			 else
			 begin
			 UPDATE  sAdmission.tAdmissionStudentDocument  SET  SubmitDocumentMasterId= @rSubmitDocumentMasterId ,DocumentName=@rDocumenet   WHERE AdmissionFormId = @rAdmissionFormId AND SubmitDocumentMasterId= @rSubmitDocumentMasterId 
			 end
	
	
	
	SELECT 1 AS Result 
	
	COMMIT TRANSACTION
	END
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
		
END
GO
PRINT N'Altering [sAdmission].[pAdmissionStudentDocumentSubmitGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionStudentDocumentSubmitGet]
	 
        @rAdmissionFormId bigint,
		@rOrgId bigint,
		@rClassId bigint,
	@rBatchId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN

	IF(@rAdmissionFormId =0)
	BEGIN
			SELECT  Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName, ISNULL(S.DocumentName,'') as DocumentFileName,
			CASE WHEN  S.SubmitDocumentMasterId Is null THEN 'False' ELSE 'False'END AS IsCheck
			 --'False' AS IsCheck
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT Join sAdmission.tAdmissionStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND (S.AdmissionFormId= @rAdmissionFormId  OR @rAdmissionFormId=0)
			WHERE  SubmitDocumentFunctionalityId='3' AND D.OrgId=@rOrgId AND D.Id IN (select SubmitDocumentMasterId from sAdmission.tAdmissionCriteriaDocument WHERE ClassId=@rClassId AND BatchId = @rBatchId  )
			END

			ELSE
			SELECT Isnull(D.Id,0) AS DocumentId,ISNULL(D.DocumentName,'') AS DocumentName,ISNULL(S.DocumentName,'') as DocumentFileName,
			CASE WHEN  S.SubmitDocumentMasterId Is null THEN 'False' ELSE 'True'END AS IsCheck
			-- 'False'  AS IsCheck
		 	FROM sCommon.tSubmitDocumentMaster D
			LEFT Join sAdmission.tAdmissionStudentDocument  S ON S.SubmitDocumentMasterId=D.id AND (S.AdmissionFormId= @rAdmissionFormId  OR @rAdmissionFormId=0)
			WHERE  SubmitDocumentFunctionalityId='3' AND  D.OrgId=@rOrgId AND D.Id IN (select SubmitDocumentMasterId from sAdmission.tAdmissionCriteriaDocument WHERE ClassId=@rClassId AND BatchId = @rBatchId  )
			
END
GO
PRINT N'Altering [sAdmission].[pExportAllAdmissionFormDetail]...';


GO
 
ALTER PROCEDURE [sAdmission].[pExportAllAdmissionFormDetail]
	 @rAdmissionFormId bigint = 0,
	 @rFormNo int=0,
	 @rForClassId int=0,
	 @rBatchId int=0,
	 @rStatusId smallint='',
	 @rOrgId int,
	 @rFirstName nvarchar(200)='',
	 @rLastName nvarchar(200)='',
 
	 @rFromDate datetime= '1900-01-01',
	 @rToDate datetime = '9990-12-31',
	 @rDepartmentId int=0,
	 @rDataEntryStatusId smallint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	SET @rToDate = DATEADD(d,1,@rToDate)		 

BEGIN 
		--IF @rIsSearch = 1
		--BEGIN
		--SET @rFirstName = ISNULL(@rFirstName,'')
		--SET @rLastName = ISNULL(@rLastName,'')
		--	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		--	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		--END
	CREATE Table #tempAdmissionForm
	(
		AdmissionFormId bigint,
		FormNo int,
		FirstName nvarchar(500),
		MiddleName nvarchar(500),
		LastName nvarchar(500),
		Name nvarchar(500),
		ClassId int,
		ClassName nvarchar(500),
		ForBatch nvarchar(500),
		DateOfBirth date,
		--StatusName nvarchar(200),
		ProcessStatus nvarchar(100),
		FormStatus nvarchar(500),
		StreetOne nvarchar(500),
		StreetTwo nvarchar(500),
		StreetThree nvarchar(500),
		Country nvarchar(500),
		State nvarchar(500),
		City nvarchar(500),
		ZipCode nvarchar(500),
		ContactNo nvarchar(500),
		ContactEmail nvarchar(500),
		Religion nvarchar(500),
		Nationality nvarchar(500),
		MotherTongue nvarchar(500),
		OtherInformation nvarchar(500),
		IsPysicalDeformity	bit	,
		PysicalDeformityRemark	nvarchar(500)	,
		IsMajorIllness	bit	,
		MajorIllnessRemark	nvarchar(500)	,
		IsAllergy	bit	,
		AllergyRemark	nvarchar(500)	,
		BirthPlace	nvarchar(500)	,
		BirthTaluka	nvarchar(500)	,
		BirthDistrict	nvarchar(500),
		BloodGroupName	nvarchar(500)	,
		AdhaarNumber	nvarchar(500)	,
		IsHostelRequired	nvarchar(500)	,
		IsTransportRequired	nvarchar(500)	,
		Remark nvarchar(500),
		PreviousSchool nvarchar(500),
		MeritMarks decimal(6,2),
		MeritGrade nvarchar(500),
		Gender nvarchar(500),
		
		FamilyCast nvarchar(500),
		FamilySubCast nvarchar(500),
		 
		AdmissionFormDate date,
		FatherName nvarchar(500),
		--FatherDateOfBirth date,
		FatherOccupation nvarchar(500),
		FatherQualification nvarchar(500),
		FatherDesignation  nvarchar(500),
		FatherOrganization nvarchar(500),
		FatherOfficePhone nvarchar(500),
		FatherContactNo nvarchar(500),
		FatherMail nvarchar(500),
		FatherOfficeAddress nvarchar(500),
		FatherIncome int	,
		MotherName nvarchar(500),
		--MotherDateOfBirth date ,
		MotherOccupation nvarchar(500),
		MotherQualification nvarchar(500),
		MotherDesignation nvarchar(500),
		MotherOrganization nvarchar(500),
		MotherOfficePhone nvarchar(500),
		MotherContactNo nvarchar(500),
		MotherMail nvarchar(500),
		MotherOfficeAddress nvarchar(500), 
		MotherIncome int,
		RelationshipName nvarchar(500),
		GuardianName nvarchar(500),
		--GuardianDateOfBirth date,
		GuardianOccupation nvarchar(500),
		GuardianQualification nvarchar(500),
		GuardianOrganization nvarchar(500),
		GuardianDesignation nvarchar(500),
		GuardianOfficePhone nvarchar(500),
		GuardianContactNo nvarchar(500),
		GuardianMail nvarchar(500),
		GuardianOfficeAddress nvarchar(500),
		GuardianIncome int,
		FatherPassOutYear nvarchar(500),
		MotherPassOutYear nvarchar(500),
		RelativePassOutYear nvarchar(500),
		CustomField1Answer  nvarchar(500),
		CustomField2Answer  nvarchar(500),
		CustomField3Answer  nvarchar(500),
		CastCategory nvarchar(50)
		
	)
	Insert into #tempAdmissionForm
	(
		AdmissionFormId,
		FormNo ,
		FirstName ,
		MiddleName ,
		LastName ,
		Name ,
		ClassId,
		ClassName ,
		ForBatch ,
		DateOfBirth ,
		--StatusName ,
		ProcessStatus ,
		FormStatus ,
		StreetOne ,
		StreetTwo ,
		StreetThree,
		Country,
		State ,
		City ,
		ZipCode ,
		ContactNo ,
		ContactEmail,
		Religion,
		Nationality,
		MotherTongue,
		OtherInformation,
		IsPysicalDeformity,
		PysicalDeformityRemark,
		IsMajorIllness,
		MajorIllnessRemark,
		IsAllergy,
		AllergyRemark,
		BirthPlace,
		BirthTaluka,
		BirthDistrict,
		BloodGroupName,
		AdhaarNumber,
		IsHostelRequired,
		IsTransportRequired,
		Remark ,
		PreviousSchool,
		MeritMarks ,
		MeritGrade,
		Gender,
		
		FamilyCast ,
		FamilySubCast,
		 
		AdmissionFormDate,
		FatherName ,
		--FatherDateOfBirth ,
		FatherOccupation,
		FatherQualification ,
		FatherDesignation,
		FatherOrganization,
		FatherOfficePhone,
		FatherContactNo  ,
		FatherMail  ,
		FatherOfficeAddress   ,
		FatherIncome  	,
		MotherName  ,
		--MotherDateOfBirth   ,
		MotherOccupation  ,
		MotherQualification  ,
		MotherDesignation,
		MotherOrganization,
		MotherOfficePhone,
		MotherContactNo  ,
		MotherMail  ,
		MotherOfficeAddress  , 
		MotherIncome  ,
		RelationshipName  ,
		GuardianName  ,
		--GuardianDateOfBirth  ,
		GuardianOccupation  ,
		GuardianQualification  ,
		GuardianDesignation,
		GuardianOrganization,
		GuardianOfficePhone,
		GuardianContactNo  ,
		GuardianMail  ,
		GuardianOfficeAddress   ,
		GuardianIncome  ,
		FatherPassOutYear,
		MotherPassOutYear,
		RelativePassOutYear,
		CustomField1Answer,
		CustomField2Answer,
		CustomField3Answer,
		CastCategory
	)
	SELECT 
			  AF.Id
			,AF.FormNo
			,AF.FirstName
			,AF.MiddleName
			,AF.LastName
			,AF.FirstName+' '+AF.LastName as Name
			--,AF.ForClassId
			--,AF.BatchId
			,CM.Id AS ClassId
			,CM.Title AS ClassName
			,AF.ForBatch
			,ISNULL(AF.DateOfBirth,'') AS DateOfBirth
			--,AF.DateOfBirthInWord
			--,AF.StatusId
			--,SM.Title as StatusName
			,SM1.Title AS DataEntryStatus
			,ISNULL(ASM.Title,'') AS FormStatus
			,AF.StreetOne
			,AF.StreetTwo
			,AF.StreetThree
			,AF.Country
			,AF.State
			,AF.City
			,AF.ZipCode
			,AF.ContactNo
			,AF.ContactEmail,
			RM.Title AS Religion,
			AF.Nationality,
			AF.MotherTongue,
			AF.OtherInformation,
			AF.IsPysicalDeformity,
			AF.PysicalDeformityRemark,
			AF.IsMajorIllness,
			AF.MajorIllnessRemark,
			AF.IsAllergy,
			AF.AllergyRemark,
			AF.BirthPlace,
			AF.BirthTaluka,
			AF.BirthDistrict,
			BGm.Title,
			AF.AdhaarNumber,
			CAse WHEn ISnull(AF.IsHostelRequired,0)=0 THEN 'No' Else 'Yes' END AS IsHostelRequired,
			CAse WHEn ISnull(AF.IsTransportRequired,0)=0 THEN 'No' Else 'Yes' END AS IsTransportRequired
			
			,AF.Remark
			,AF.PreviousSchool
			,AF.MeritMarks
			,AF.MeritGrade
			--,AF.GenderId
			,ISNULL(GM.Title,'') AS Gender
			--,ISNULL(AF.ReligionId,0) AS ReligionId
			,AF.FamilyCast
			,AF.FamilySubCast
			--,ISNULL(AF.CastCategoryId,0) AS CastCategoryId
			,AF.CreatedDateTime AS AdmissionFormDate,
			--,ISNULL(AF.StudentId,0) AS StudentId
			--,AF.StudentPhoto,
			ISNULL(AFFD.FatherName,'') AS FatherName,
			--Isnull(AFFD.FatherDateOfBirth,'') AS FatherDateOfBirth,
			Isnull(AFFD.FatherOccupation,'') AS FatherOccupation,
			Isnull(AFFD.FatherQualification,'') AS FatherQualification,
			Isnull(AFFD.FatherDesignation,'') AS FatherDesignation,
			Isnull(AFFD.FatherOrganization,'') AS FatherOrganization,
			Isnull(AFFD.FatherOfficePhone,'') AS FatherOfficePhone,
			Isnull(AFFD.FatherContactNo,'') AS FatherContactNo,
			Isnull(AFFD.FatherMail,'') AS FatherMail,
			Isnull(AFFD.FatherOfficeAddress,'') As FatherOfficeAddress,
			Isnull(AFFD.FatherIncome,'') as FatherIncome,
			Isnull(AFFD.MotherName,'') AS MotherName,
			--iSNULL(AFFD.MotherDateOfBirth,'')AS MotherDateOfBirth,
			isnull(AFFD.MotherOccupation,'') AS MotherOccupation,
			isnull(AFFD.MotherQualification,'') AS MotherQualification,
			
			Isnull(AFFD.MotherDesignation,'') AS MotherDesignation,
			Isnull(AFFD.MotherOrganization,'') AS MotherOrganization,
			Isnull(AFFD.MotherOfficePhone,'') AS MotherOfficePhone,
			
			isnull(AFFD.MotherContactNo,'') as MotherContactNo,
			isnull(AFFD.MotherMail,'') As MotherMail,
			isnull(AFFD.MotherOfficeAddress,'') as MotherOfficeAddress,
			isnull(AFFD.MotherIncome,'') as MotherIncome,
		 
			isnull(AFFD.RelationshipName,'') as RelationshipName,
			isnull(AFFD.RelativeName,'')  AS GuardianName ,
			--isnull(AFFD.RelativeDateOfBirth ,'')AS GuardianDateOfBirth,
			isnull(AFFD.RelativeOccupation,'') AS GuardianOccupation,
			isnull(AFFD.RelativeQualification,'') AS GuardianQualification,
			
			Isnull(AFFD.RelativeDesignation,'') AS GuardianDesignation,
			Isnull(AFFD.RelativeOrganization,'') AS GuardianOrganization,
			Isnull(AFFD.RelativeOfficePhone,'') AS GuardianOfficePhone,
			
			isnull(AFFD.RelativeContactNo,'') AS GuardianContactNo,
			isnull(AFFD.RelativeMail,'')  AS GuardianMail,
			isnull(AFFD.RelativeOfficeAddress,'') AS GuardianOfficeAddress,
			isnull(AFFD.RelativeIncome,'') AS GuardianIncome  ,
			isnull(AFFD.FatherPassOutYear,'') AS FatherPassOutYear,
			isnull(AFFD.MotherPassOutYear,'')As MotherPassOutYear,
			isnull(AFFD.RelativePassOutYear,'') As RelativePassOutYear,
			isnull(AF.CustomField1Answer,'') AS CustomField1Answer,
			isnull(AF.CustomField2Answer,'')As CustomField2Answer,
			isnull(AF.CustomField3Answer,'') As CustomField3Answer,
   			ISNULL(CCM.Title,'') AS CastCategory
  FROM 
            sAdmission.tAdmissionForm AF
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sCommon.tStatusMaster SM1 ON SM1.Id=AF.DataEntryStatusId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFFD ON AFFD.AdmissionFormId = AF.Id
			LEFT JOIN sCommon.tReligionMaster RM on RM.Id= AF.religionId
			LEFT JOIN sCommon.tBloodGroupMaster BGM on BGM.Id= AF.BloodGroupId
			--LEFT JOIN sAdmission.tAdmissionFormSibling ASB ON ASB.AdmissionFormId = AF.Id
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=AF.CastCategoryId
			 
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
		AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))
		AND ((AF.FirstName like @rFirstName) OR (@rFirstName=''))
		AND ((AF.LastName like @rLastName) OR (@rLastName=''))
		AND ((AF.CreatedDateTime>= @rFromDate) OR (@rFromDate=''))
		AND ((AF.CreatedDateTime < @rToDate) OR (@rToDate=''))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0)) 
		AND ((AF.BatchId=@rBatchId) OR (@rBatchId=0)) 
		--AND ((AF.MeritMarks=@rMeritMarks) OR (@rMeritMarks=0))
		
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId = ''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND AF.OrgId=@rOrgId
		AND ((AF.DataEntryStatusId=@rDataEntryStatusId) OR (@rDataEntryStatusId = 0))
 
 create table #tempStudentAcademic
(
	AdmissionFormId bigint,
	 
	
	StudentAcademicYear1 nvarchar(500),	StudentAdmissionClass1 nvarchar(500),	StudentInstituteName1 nvarchar(500),	StudentInstituteCity1 nvarchar(500),	StudentInstituteAffiliaton1 nvarchar(500),	StudentLanguage1 nvarchar(500),	StudentResult1 Nvarchar(500),
	StudentAcademicYear2 nvarchar(500),	StudentAdmissionClass2 nvarchar(500),	StudentInstituteName2 nvarchar(500),	StudentInstituteCity2 nvarchar(500),	StudentInstituteAffiliaton2 nvarchar(500),	StudentLanguage2 nvarchar(500),	StudentResult2 Nvarchar(500),
	StudentAcademicYear3 nvarchar(500),	StudentAdmissionClass3 nvarchar(500),	StudentInstituteName3 nvarchar(500),	StudentInstituteCity3 nvarchar(500),	StudentInstituteAffiliaton3 nvarchar(500),	StudentLanguage3 nvarchar(500),	StudentResult3 Nvarchar(500),
	StudentAcademicYear4 nvarchar(500),	StudentAdmissionClass4 nvarchar(500),	StudentInstituteName4 nvarchar(500),	StudentInstituteCity4 nvarchar(500),	StudentInstituteAffiliaton4 nvarchar(500),	StudentLanguage4 nvarchar(500),	StudentResult4 Nvarchar(500),
	StudentAcademicYear5 nvarchar(500),	StudentAdmissionClass5 nvarchar(500),	StudentInstituteName5 nvarchar(500),	StudentInstituteCity5 nvarchar(500),	StudentInstituteAffiliaton5 nvarchar(500),	StudentLanguage5 nvarchar(500),	StudentResult5 Nvarchar(500),
	StudentAcademicYear6 nvarchar(500),	StudentAdmissionClass6 nvarchar(500),	StudentInstituteName6 nvarchar(500),	StudentInstituteCity6 nvarchar(500),	StudentInstituteAffiliaton6 nvarchar(500),	StudentLanguage6 nvarchar(500),	StudentResult6 Nvarchar(500),
	StudentAcademicYear7 nvarchar(500),	StudentAdmissionClass7 nvarchar(500),	StudentInstituteName7 nvarchar(500),	StudentInstituteCity7 nvarchar(500),	StudentInstituteAffiliaton7 nvarchar(500),	StudentLanguage7 nvarchar(500),	StudentResult7 Nvarchar(500),
	StudentAcademicYear8 nvarchar(500),	StudentAdmissionClass8 nvarchar(500),	StudentInstituteName8 nvarchar(500),	StudentInstituteCity8 nvarchar(500),	StudentInstituteAffiliaton8 nvarchar(500),	StudentLanguage8 nvarchar(500),	StudentResult8 Nvarchar(500),
	StudentAcademicYear9 nvarchar(500),	StudentAdmissionClass9 nvarchar(500),	StudentInstituteName9 nvarchar(500),	StudentInstituteCity9 nvarchar(500),	StudentInstituteAffiliaton9 nvarchar(500),	StudentLanguage9 nvarchar(500),	StudentResult9 Nvarchar(500),
	StudentAcademicYear10 nvarchar(500),	StudentAdmissionClass10 nvarchar(500),	StudentInstituteName10 nvarchar(500),	StudentInstituteCity10 nvarchar(500),	StudentInstituteAffiliaton10 nvarchar(500),	StudentLanguage10 nvarchar(500),	StudentResult10 Nvarchar(500) 


	 
	

)
INsert into #tempStudentAcademic
(AdmissionFormId, 
StudentAcademicYear1  ,	StudentAdmissionClass1  ,	StudentInstituteName1  ,	StudentInstituteCity1  ,	StudentInstituteAffiliaton1   ,	StudentLanguage1  ,	StudentResult1  ,
	StudentAcademicYear2  ,	StudentAdmissionClass2  ,	StudentInstituteName2  ,	StudentInstituteCity2  ,	StudentInstituteAffiliaton2  ,	StudentLanguage2  ,	StudentResult2   ,
	StudentAcademicYear3   ,	StudentAdmissionClass3  ,	StudentInstituteName3  ,	StudentInstituteCity3  ,	StudentInstituteAffiliaton3  ,	StudentLanguage3  ,	StudentResult3  ,
	StudentAcademicYear4  ,	StudentAdmissionClass4  ,	StudentInstituteName4  ,	StudentInstituteCity4  ,	StudentInstituteAffiliaton4  ,	StudentLanguage4   ,	StudentResult4  ,
	StudentAcademicYear5  ,	StudentAdmissionClass5  ,	StudentInstituteName5  ,	StudentInstituteCity5  ,	StudentInstituteAffiliaton5  ,	StudentLanguage5  ,	StudentResult5  ,
	StudentAcademicYear6  ,	StudentAdmissionClass6  ,	StudentInstituteName6  ,	StudentInstituteCity6  ,	StudentInstituteAffiliaton6  ,	StudentLanguage6  ,	StudentResult6  ,
	StudentAcademicYear7  ,	StudentAdmissionClass7  ,	StudentInstituteName7  ,	StudentInstituteCity7  ,	StudentInstituteAffiliaton7  ,	StudentLanguage7   ,	StudentResult7  ,
	StudentAcademicYear8  ,	StudentAdmissionClass8  ,	StudentInstituteName8  ,	StudentInstituteCity8  ,	StudentInstituteAffiliaton8  ,	StudentLanguage8  ,	StudentResult8  ,
	StudentAcademicYear9  ,	StudentAdmissionClass9  ,	StudentInstituteName9  ,	StudentInstituteCity9  ,	StudentInstituteAffiliaton9  ,	StudentLanguage9  ,	StudentResult9  ,
	StudentAcademicYear10  ,	StudentAdmissionClass10  ,	StudentInstituteName10  ,	StudentInstituteCity10  ,	StudentInstituteAffiliaton10  ,	StudentLanguage10  ,	StudentResult10  
	
)

SELECT AdmissionFormId,
  ISNULL(max(case when    rn = 1  then  AcademicYear  end),'') StudentAcademicYear1,
  ISNULL(max(case when    rn = 1  then  AdmissionClass  end),'') StudentAdmissionClass1,
   ISNULL(max(case when    rn = 1  then  InstituteName  end),'') StudentInstituteName1,
  ISNULL(max(case when    rn = 1  then  InstituteCity  end),'') StudentInstituteCity1,
  ISNULL(max(case when    rn = 1  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton1,
  ISNULL(max(case when    rn = 1  then  Language  end),'') StudentLanguage1,
    ISNULL(max(case when    rn = 1  then  Result  end),'') StudentResult1,
     
  ISNULL(max(case when    rn = 2 then  AcademicYear  end),'') StudentAcademicYear2,
  ISNULL(max(case when    rn = 2  then  AdmissionClass  end),'') StudentAdmissionClass2,
   ISNULL(max(case when    rn = 2  then  InstituteName  end),'') StudentInstituteName2,
  ISNULL(max(case when    rn = 2  then  InstituteCity  end),'') StudentInstituteCity2,
  ISNULL(max(case when    rn = 2  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton2,
  ISNULL(max(case when    rn = 2  then  Language  end),'') StudentLanguage2,
    ISNULL(max(case when    rn = 2  then  Result  end),'') StudentResult2,

     
  ISNULL(max(case when    rn = 3  then  AcademicYear  end),'') StudentAcademicYear3,
  ISNULL(max(case when    rn = 3  then  AdmissionClass  end),'') StudentAdmissionClass3,
   ISNULL(max(case when    rn = 3  then  InstituteName  end),'') StudentInstituteName3,
  ISNULL(max(case when    rn = 3  then  InstituteCity  end),'') StudentInstituteCity3,
  ISNULL(max(case when    rn = 3  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton3,
  ISNULL(max(case when    rn = 3  then  Language  end),'') StudentLanguage3,
  ISNULL(max(case when    rn = 3  then  Result  end),'') StudentResult3,
     
  ISNULL(max(case when    rn = 4  then  AcademicYear  end),'') StudentAcademicYear4,
  ISNULL(max(case when    rn = 4  then  AdmissionClass  end),'') StudentAdmissionClass4,
   ISNULL(max(case when    rn = 4  then  InstituteName  end),'') StudentInstituteName4,
  ISNULL(max(case when    rn = 4  then  InstituteCity  end),'') StudentInstituteCity4,
  ISNULL(max(case when    rn = 4  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton4,
  ISNULL(max(case when    rn = 4  then  Language  end),'') StudentLanguage4,
  ISNULL(max(case when    rn = 4  then  Result  end),'') StudentResult4,
           
  ISNULL(max(case when    rn = 5  then  AcademicYear  end),'') StudentAcademicYear5,
  ISNULL(max(case when    rn = 5  then  AdmissionClass  end),'') StudentAdmissionClass5,
   ISNULL(max(case when    rn = 5  then  InstituteName  end),'') StudentInstituteName5,
  ISNULL(max(case when    rn = 5  then  InstituteCity  end),'') StudentInstituteCity5,
  ISNULL(max(case when    rn = 5  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton5,
  ISNULL(max(case when    rn = 5  then  Language  end),'') StudentLanguage5,
    ISNULL(max(case when    rn = 5  then  Result  end),'') StudentResult5,
   
  ISNULL(max(case when    rn = 6  then  AcademicYear  end),'') StudentAcademicYear6,
  ISNULL(max(case when    rn = 6  then  AdmissionClass  end),'') StudentAdmissionClass6,
   ISNULL(max(case when    rn = 6  then  InstituteName  end),'') StudentInstituteName6,
  ISNULL(max(case when    rn = 6  then  InstituteCity  end),'') StudentInstituteCity6,
  ISNULL(max(case when    rn = 6  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton6,
  ISNULL(max(case when    rn = 6  then  Language  end),'') StudentLanguage6,
  ISNULL(max(case when    rn = 6  then  Result  end),'') StudentResult6,
     
  ISNULL(max(case when    rn = 7  then  AcademicYear  end),'') StudentAcademicYear7,
  ISNULL(max(case when    rn = 7  then  AdmissionClass  end),'') StudentAdmissionClass7,
  ISNULL(max(case when    rn = 7  then  InstituteName  end),'') StudentInstituteName7,
  ISNULL(max(case when    rn = 7  then  InstituteCity  end),'') StudentInstituteCity7,
  ISNULL(max(case when    rn = 7  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton7,
  ISNULL(max(case when    rn = 7  then  Language  end),'') StudentLanguage7,
   ISNULL(max(case when    rn = 7  then  Result  end),'') StudentResult7,
  
  ISNULL(max(case when    rn = 8  then  AcademicYear  end),'') StudentAcademicYear8,
  ISNULL(max(case when    rn = 8  then  AdmissionClass  end),'') StudentAdmissionClass8,
   ISNULL(max(case when    rn = 8  then  InstituteName  end),'') StudentInstituteName8,
  ISNULL(max(case when    rn = 8  then  InstituteCity  end),'') StudentInstituteCity8,
  ISNULL(max(case when    rn = 8  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton8,
  ISNULL(max(case when    rn = 8  then  Language  end),'') StudentLanguage8,
  ISNULL(max(case when    rn = 8  then  Result  end),'') StudentResult8,
     
  ISNULL(max(case when    rn = 9  then  AcademicYear  end),'') StudentAcademicYear9,
  ISNULL(max(case when    rn = 9  then  AdmissionClass  end),'') StudentAdmissionClass9,
   ISNULL(max(case when    rn = 9  then  InstituteName  end),'') StudentInstituteName9,
  ISNULL(max(case when    rn = 9  then  InstituteCity  end),'') StudentInstituteCity9,
  ISNULL(max(case when    rn = 9  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton9,
  ISNULL(max(case when    rn = 9  then  Language  end),'') StudentLanguage9,
   ISNULL(max(case when    rn = 9  then  Result  end),'') StudentResult9,
     
  ISNULL(max(case when    rn = 10  then  AcademicYear  end),'') StudentAcademicYear10,
  ISNULL(max(case when    rn = 10 then  AdmissionClass  end),'') StudentAdmissionClass10,
   ISNULL(max(case when    rn = 10 then  InstituteName  end),'') StudentInstituteName10,
  ISNULL(max(case when    rn = 10  then  InstituteCity  end),'') StudentInstituteCity10,
  ISNULL(max(case when    rn = 10  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton10,
  ISNULL(max(case when    rn = 10  then  Language  end),'') StudentLanguage10,
    ISNULL(max(case when    rn = 10  then  Result  end),'') StudentResult10
                     
from
(
  select AP.AdmissionFormId,  AcademicYear, AdmissionClass, InstituteName, InstituteCity,InstituteAffiliaton,Language,Result
      , row_number() over(partition by AP.AdmissionFormId 
                          Order by AP.AdmissionFormId) rn
  from sAdmission.tAdmissionFormStudentAcademic AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
  
) d
group by AdmissionFormId order by AdmissionFormId 

Create Table #tempFatherAcademic
(
	AdmissionFormId bigint,
	FatherAcademicYear1 nvarchar(500),
	FatherInstituteName1 nvarchar(500),
	FatherInstituteCity1 nvarchar(500),
	FatherInstituteAffilation1 nvarchar(500),
	FatherAdmissionClass1 nvarchar(500),
	FatherMediumStudy1 nvarchar(500),
	
	FatherAcademicYear2 nvarchar(500),
	FatherInstituteName2 nvarchar(500),
	FatherInstituteCity2 nvarchar(500),
	FatherInstituteAffilation2 nvarchar(500),
	FatherAdmissionClass2 nvarchar(500),
	FatherMediumStudy2 nvarchar(500),
	
	
	FatherAcademicYear3 nvarchar(500),
	FatherInstituteName3 nvarchar(500),
	FatherInstituteCity3 nvarchar(500),
	FatherInstituteAffilation3 nvarchar(500),
	FatherAdmissionClass3 nvarchar(500),
	FatherMediumStudy3 nvarchar(500),
	
	
	
	FatherAcademicYear4 nvarchar(500),
	FatherInstituteName4 nvarchar(500),
	FatherInstituteCity4 nvarchar(500),
	FatherInstituteAffilation4 nvarchar(500),
	FatherAdmissionClass4 nvarchar(500),
	FatherMediumStudy4 nvarchar(500),
	
	FatherAcademicYear5 nvarchar(500), 
	FatherInstituteName5 nvarchar(500), 
	FatherInstituteCity5 nvarchar(500),
    FatherInstituteAffilation5 nvarchar(500),
    FatherAdmissionClass5 nvarchar(500),
    FatherMediumStudy5 nvarchar(500),
	
	MotherAcademicYear1 nvarchar(500),
	MotherInstituteName1 nvarchar(500),
	MotherInstituteCity1 nvarchar(500),
	MotherInstituteAffilation1 nvarchar(500),
	MotherMediumStudy1 nvarchar(500),
	MotherAdmissionClass1 nvarchar(500),
	
	MotherAcademicYear2 nvarchar(500),
	MotherInstituteName2 nvarchar(500),
	MotherInstituteCity2 nvarchar(500),
	MotherInstituteAffilation2 nvarchar(500),
	MotherMediumStudy2 nvarchar(500),
	MotherAdmissionClass2 nvarchar(500),
	
	MotherAcademicYear3 nvarchar(500),
	MotherInstituteName3 nvarchar(500),
	MotherInstituteCity3 nvarchar(500),
	MotherInstituteAffilation3 nvarchar(500),
	MotherMediumStudy3 nvarchar(500),
	MotherAdmissionClass3 nvarchar(500),
	
	
	MotherAcademicYear4 nvarchar(500),
	MotherInstituteName4 nvarchar(500),
	MotherInstituteCity4 nvarchar(500),
	MotherInstituteAffilation4 nvarchar(500),
	MotherMediumStudy4 nvarchar(500),
	MotherAdmissionClass4 nvarchar(500),
	
	MotherAcademicYear5 nvarchar(500), 
	MotherInstituteName5 nvarchar(500), 
	MotherInstituteCity5 nvarchar(500), 
	MotherInstituteAffilation5 nvarchar(500), 
	MotherMediumStudy5 nvarchar(500), 
	MotherAdmissionClass5 nvarchar(500) ,
	
	GuardianAcademicYear1 nvarchar(500),
	GuardianInstituteName1 nvarchar(500),
	GuardianInstituteCity1 nvarchar(500),
	GuardianInstituteAffilation1 nvarchar(500),
	GuardianAdmissionClass1 nvarchar(500),
	GuardianMediumStudy1 nvarchar(500),
	
	
	GuardianAcademicYear2 nvarchar(500),
	GuardianInstituteName2 nvarchar(500),
	GuardianInstituteCity2 nvarchar(500),
	GuardianInstituteAffilation2 nvarchar(500),
	GuardianAdmissionClass2 nvarchar(500),
	GuardianMediumStudy2 nvarchar(500),
	
	
	GuardianAcademicYear3 nvarchar(500),
	GuardianInstituteName3 nvarchar(500),
	GuardianInstituteCity3 nvarchar(500),
	GuardianInstituteAffilation3 nvarchar(500),
	GuardianAdmissionClass3 nvarchar(500),
	GuardianMediumStudy3 nvarchar(500),
	
	
	GuardianAcademicYear4 nvarchar(500),
	GuardianInstituteName4 nvarchar(500),
	GuardianInstituteCity4 nvarchar(500),
	GuardianInstituteAffilation4 nvarchar(500),
	GuardianAdmissionClass4 nvarchar(500),
	GuardianMediumStudy4 nvarchar(500),
	
	GuardianAcademicYear5 nvarchar(500),
	GuardianInstituteName5 nvarchar(500),
	GuardianInstituteCity5 nvarchar(500),
	GuardianInstituteAffilation5 nvarchar(500),
	 GuardianAdmissionClass5 nvarchar(500),
	 GuardianMediumStudy5 nvarchar(500)
	
)	
Insert into #tempFatherAcademic
(
	AdmissionFormId, 
	FatherAcademicYear1,FatherInstituteName1,FatherInstituteCity1,FatherInstituteAffilation1,FatherMediumStudy1,FatherAdmissionClass1,
	FatherAcademicYear2,FatherInstituteName2,FatherInstituteCity2,FatherInstituteAffilation2,FatherMediumStudy2,FatherAdmissionClass2,
	FatherAcademicYear3,FatherInstituteName3,FatherInstituteCity3,FatherInstituteAffilation3,FatherMediumStudy3,FatherAdmissionClass3,
	FatherAcademicYear4,FatherInstituteName4,FatherInstituteCity4,FatherInstituteAffilation4,FatherMediumStudy4,FatherAdmissionClass4,
	FatherAcademicYear5,FatherInstituteName5,FatherInstituteCity5,FatherInstituteAffilation5,FatherMediumStudy5,FatherAdmissionClass5,
	
	 
	MotherAcademicYear1,MotherInstituteName1,MotherInstituteCity1,MotherInstituteAffilation1,MotherMediumStudy1,MotherAdmissionClass1,
	MotherAcademicYear2,MotherInstituteName2,MotherInstituteCity2,MotherInstituteAffilation2,MotherMediumStudy2,MotherAdmissionClass2,
	MotherAcademicYear3,MotherInstituteName3,MotherInstituteCity3,MotherInstituteAffilation3,MotherMediumStudy3,MotherAdmissionClass3,
	MotherAcademicYear4,MotherInstituteName4,MotherInstituteCity4,MotherInstituteAffilation4,MotherMediumStudy4,MotherAdmissionClass4,
	MotherAcademicYear5,MotherInstituteName5,MotherInstituteCity5,MotherInstituteAffilation5,MotherMediumStudy5,MotherAdmissionClass5,
	    
	GuardianAcademicYear1,GuardianInstituteName1, GuardianInstituteCity1,GuardianInstituteAffilation1,GuardianMediumStudy1,GuardianAdmissionClass1,
	GuardianAcademicYear2,GuardianInstituteName2,GuardianInstituteCity2,GuardianInstituteAffilation2,GuardianMediumStudy2,GuardianAdmissionClass2,
	GuardianAcademicYear3,GuardianInstituteName3,GuardianInstituteCity3,GuardianInstituteAffilation3,GuardianMediumStudy3,GuardianAdmissionClass3,
	GuardianAcademicYear4,GuardianInstituteName4,GuardianInstituteCity4,GuardianInstituteAffilation4,GuardianMediumStudy4,GuardianAdmissionClass4,
	GuardianAcademicYear5,GuardianInstituteName5,GuardianInstituteCity5,GuardianInstituteAffilation5,GuardianMediumStudy5,GuardianAdmissionClass5
	
	 
)
SELECT AdmissionFormId,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  AcademicYear  end),'') FatherAcademicYear1,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteName  end),'') FatherInstituteName1, 
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteCity  end),'') FatherInstituteCity1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteAffiliaton  end),'') FatherInstituteAffilation1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  Language  end),'') FatherMediumStudy1,
     ISNULL(max(case when  relationshipId =2 and rn = 1  then  AdmissionClass  end),'') FatherAdmissionClass1,
     
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AcademicYear  end),'') FatherAcademicYear2,
    ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteName  end),'') FatherInstituteName2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteCity  end),'') FatherInstituteCity2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteAffiliaton  end),'') FatherInstituteAffilation2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  Language  end),'') FatherMediumStudy2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  AdmissionClass  end),'') FatherAdmissionClass2,


  ISNULL(max(case when  relationshipId =2 and rn = 3  then  AcademicYear  end),'') FatherAcademicYear3,
 ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteName  end),'') FatherInstituteName3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteCity  end),'') FatherInstituteCity3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteAffiliaton  end),'') FatherInstituteAffilation3,
    ISNULL(max(case when  relationshipId =2 and rn = 3  then  Language  end),'') FatherMediumStudy3,
    ISNULL(max(case when  relationshipId =2 and rn = 3  then  AdmissionClass  end),'') FatherAdmissionClass3,

  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AcademicYear  end),'') FatherAcademicYear4,
      ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteName  end),'') FatherInstituteName4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteCity  end),'') FatherInstituteCity4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteAffiliaton  end),'') FatherInstituteAffilation4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  Language  end),'') FatherMediumStudy4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  AdmissionClass  end),'') FatherAdmissionClass4,

  ISNULL(max(case when  relationshipId =2 and rn = 5  then  AcademicYear  end),'') FatherAcademicYear5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteName  end),'') FatherInstituteName5,
    ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteCity  end),'') FatherInstituteCity5,
    ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteAffiliaton  end),'') FatherInstituteAffilation5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  Language  end),'') FatherMediumStudy5,
    ISNULL(max(case when  relationshipId =2 and rn = 5  then  AdmissionClass  end),'') FatherAdmissionClass5,
   
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  AcademicYear  end),'') MotherAcademicYear1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteName  end),'') MotherInstituteName1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteCity  end),'') MotherInstituteCity1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteAffiliaton  end),'') MotherInstituteAffilation1,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  Language  end),'') MotherMediumStudy1,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  AdmissionClass  end),'') MotherAdmissionClass1,

  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AcademicYear  end),'') MotherAcademicYear2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteName  end),'') MotherInstituteName2,
    ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteCity  end),'') MotherInstituteCity2,
     ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteAffiliaton  end),'') MotherInstituteAffilation2,
       ISNULL(max(case when  relationshipId =2 and rn = 2  then  Language  end),'') MotherMediumStudy2,
       ISNULL(max(case when  relationshipId =2 and rn = 2  then  AdmissionClass  end),'') MotherAdmissionClass2,
    
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  AcademicYear  end),'') MotherAcademicYear3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteName  end),'') MotherInstituteName3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteCity  end),'') MotherInstituteCity3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteAffiliaton  end),'') MotherInstituteAffilation3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  Language  end),'') MotherMediumStudy3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  AdmissionClass  end),'') MotherAdmissionClass3,
  
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AcademicYear  end),'') MotherAcademicYear4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteName  end),'') MotherInstituteName4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteCity  end),'') MotherInstituteCity4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteAffiliaton  end),'') MotherInstituteAffilation4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  Language  end),'') MotherMediumStudy4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AdmissionClass  end),'') MotherAdmissionClass4,
  
  ISNULL(max(case when  relationshipId =2 and rn = 5  then  AcademicYear  end),'') MotherAcademicYear5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteName  end),'') MotherInstituteName5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteCity  end),'') MotherInstituteCity5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteAffiliaton  end),'') MotherInstituteAffilation5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  Language  end),'') MotherMediumStudy5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  AdmissionClass  end),'') MotherAdmissionClass5,
   
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  AcademicYear  end),'') GuardianAcademicYear1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteName  end),'') GuardianInstituteName1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteCity  end),'') GuardianInstituteCity1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  Language  end),'') GuardianMediumStudy1, 
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  AdmissionClass  end),'') GuardianAdmissionClass1,
    
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AcademicYear  end),'') GuardianAcademicYear2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteName  end),'') GuardianInstituteName2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteCity  end),'') GuardianInstituteCity2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  Language  end),'') GuardianMediumStudy2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AdmissionClass  end),'') GuardianAdmissionClass2,
  
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  AcademicYear  end),'') GuardianAcademicYear3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteName  end),'') GuardianInstituteName3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteCity  end),'') GuardianInstituteCity3,
   ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation3,
   ISNULL(max(case when  relationshipId =2 and rn = 3  then  Language  end),'') GuardianMediumStudy3,
   ISNULL(max(case when  relationshipId =2 and rn = 3  then  AdmissionClass  end),'') GuardianAdmissionClass3,
   
   
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AcademicYear  end),'') GuardianAcademicYear4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteName  end),'') GuardianInstituteName4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteCity  end),'') GuardianInstituteCity4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  Language  end),'') GuardianMediumStudy4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AdmissionClass  end),'') GuardianAdmissionClass4,
  
  ISNULL(max(case when  relationshipId =2 and rn = 5  then  AcademicYear  end),'') GuardianAcademicYear5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteName  end),'') GuardianInstituteName5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteCity  end),'') GuardianInstituteCity5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  Language  end),'') GuardianMediumStudy5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  AdmissionClass  end),'') GuardianAdmissionClass5  
   
from
(
  select AP.AdmissionFormId, RelationshipId, AcademicYear, AdmissionClass, InstituteName, InstituteCity,InstituteAffiliaton,Language
      , row_number() over(partition by AP.AdmissionFormId, RelationshipId
                          order by RelationshipId) rn
  from sAdmission.tAdmissionFormParentAcademic AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
) d
group by AdmissionFormId order by AdmissionFormId 


 

create table #tempReference
(
	AdmissionFormId bigint ,
	ReferenceDetail1 nvarchar(500),
	ReferenceName1 nvarchar(500),
	ReferenceRelation1 nvarchar(500),
	ReferenceContactNo1 nvarchar(500),
	ReferenceDetail2 nvarchar(500),
	ReferenceName2 nvarchar(500),
	ReferenceRelation2 nvarchar(500),
	ReferenceContactNo2 nvarchar(500)
)
INsert Into  #tempReference
 (
	AdmissionFormId,
	ReferenceDetail1,
	ReferenceName1,
	ReferenceRelation1,
	ReferenceContactNo1,
	ReferenceDetail2,
	ReferenceName2,
	ReferenceRelation2,
	ReferenceContactNo2
 )
SELECT AdmissionFormId,
  ISNULL(max(case when    rn = 1  then  ReferenceDetail  end),'') ReferenceDetail1,
  ISNULL(max(case when   rn = 1  then  ReferenceName  end),'') ReferenceName1,
  ISNULL(max(case when    rn = 1  then  ReferenceRelation  end),'') ReferenceRelation1,
  ISNULL(max(case when    rn = 1  then  ReferenceContactNo  end),'') ReferenceContactNo1,
  
  ISNULL(max(case when  rn = 2  then  ReferenceDetail  end),'') ReferenceDetail2,
  ISNULL(max(case when   rn = 2  then  ReferenceName  end),'') ReferenceName2,
  ISNULL(max(case when   rn = 2  then  ReferenceRelation  end),'') ReferenceRelation2,
  ISNULL(max(case when  rn = 2 then  ReferenceContactNo  end),'') ReferenceContactNo2
   
from
(
  select AP.AdmissionFormId,ReferenceDetail, ReferenceName, ReferenceRelation, ReferenceContactNo 
      , row_number() over(partition by AP.AdmissionFormId 
                           order by AP.AdmissionFormId ) rn
  from sAdmission.tAdmissionFormReference AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
) d
group by AdmissionFormId order by AdmissionFormId 

Create table #TempSibling
(
	AdmissionFormId bigint,
	Code1 nvarchar(500),
	SiblingName1 nvarchar(500),
	SiblingRelation1 nvarchar(500),
	SiblingStandard1 nvarchar(500),
	SiblingSchool1 nvarchar(500),
	Code2 nvarchar(500),
	SiblingName2 nvarchar(500),
	SiblingRelation2 nvarchar(500),
	SiblingStandard2 nvarchar(500),
	SiblingSchool2 nvarchar(500),
	Code3 nvarchar(500),
	SiblingName3 nvarchar(500),
	SiblingRelation3 nvarchar(500),
	SiblingStandard3 nvarchar(500),
	SiblingSchool3 nvarchar(500),
	Code4 nvarchar(500),
	SiblingName4 nvarchar(500),
	SiblingRelation4 nvarchar(500),
	SiblingStandard4 nvarchar(500),
	SiblingSchool4 nvarchar(500)
)
Insert Into #TempSibling
(AdmissionFormId,
Code1,	
SiblingName1,
	SiblingRelation1,
	SiblingStandard1,
	SiblingSchool1,
	Code2,	
	SiblingName2,
	SiblingRelation2,
	SiblingStandard2,
	SiblingSchool2,
	Code3,	
	SiblingName3,
	SiblingRelation3,
	SiblingStandard3,
	SiblingSchool3,
	Code4,	
	SiblingName4,
	SiblingRelation4,
	SiblingStandard4,
	SiblingSchool4
)
SELECT AdmissionFormId,
  ISNULL(max(case when    rn = 1  then  Code  end),'') Code1,
  ISNULL(max(case when    rn = 1  then  SiblingName  end),'') SiblingName1,
  ISNULL(max(case when    rn = 1  then  SiblingRelation  end),'') SiblingRelation1,
   ISNULL(max(case when    rn = 1  then  SiblingStandard  end),'') SiblingStandard1,
    ISNULL(max(case when    rn = 1  then  SiblingSchool  end),'') SiblingSchool1,
  
  ISNULL(max(case when    rn = 2  then  Code  end),'') Code2,
  ISNULL(max(case when    rn = 2  then  SiblingName  end),'') SiblingName2,
  ISNULL(max(case when    rn = 2  then  SiblingRelation  end),'') SiblingRelation2,
  ISNULL(max(case when    rn = 2  then  SiblingStandard  end),'') SiblingStandard2,
  ISNULL(max(case when    rn = 2 then  SiblingSchool  end),'') SiblingSchool2,
  
  ISNULL(max(case when    rn = 2  then  Code  end),'') Code3,
   ISNULL(max(case when    rn = 2  then  SiblingName  end),'') SiblingName3,
  ISNULL(max(case when    rn = 2  then  SiblingRelation  end),'') SiblingRelation3,
  ISNULL(max(case when    rn = 2  then  SiblingStandard  end),'') SiblingStandard3,
  ISNULL(max(case when    rn = 2 then  SiblingSchool  end),'') SiblingSchool3,
  
  ISNULL(max(case when    rn = 2  then  Code  end),'') Code4,
   ISNULL(max(case when    rn = 2  then  SiblingName  end),'') SiblingName4,
  ISNULL(max(case when    rn = 2  then  SiblingRelation  end),'') SiblingRelation4,
  ISNULL(max(case when    rn = 2  then  SiblingStandard  end),'') SiblingStandard4,
  ISNULL(max(case when    rn = 2 then  SiblingSchool  end),'') SiblingSchool4
   
from
(
  select AP.AdmissionFormId,    SiblingName, SiblingRelation, SiblingStandard,SiblingSchool,Code  
      , row_number() over(partition by AP.AdmissionFormId 
                          order by AP.AdmissionFormId) rn
  from sAdmission.tAdmissionFormSibling AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
) d
group by AdmissionFormId order by AdmissionFormId 

 
DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

-- CTE for Admission Form Field
;WITH AdmissionCriteriaFormCTE AS (SELECT  DISTINCT FieldRemark FROM sAdmission.tAdmissionCriteriaForm ACF
INNER JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
WHERE ACF.BatchId = @rBatchId
GROUP BY Id,FieldRemark,ClassId,BatchId
)

SELECT @cols = STUFF((SELECT  ',' + QUOTENAME(FieldRemark) FROM AdmissionCriteriaFormCTE
GROUP BY FieldRemark
ORDER BY FieldRemark FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')

IF object_id('tempdb..##tempAdmissionCriteriaForm') IS NOT NULL 
BEGIN
   DROP TABLE ##tempAdmissionCriteriaForm 
END

IF(@cols IS NOT NULL)
BEGIN 
	SET @query = N'SELECT DISTINCT AdmissionFormId,' + @cols + N' INTO ##tempAdmissionCriteriaForm FROM 
				 (
					SELECT DISTINCT  AFF.AdmissionFormId,AdmissionFormFieldResponse, FieldRemark
					FROM 
					sAdmission.tAdmissionCriteriaForm ACF
					INNER JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
					WHERE ACF.BatchId = '+CONVERT(nvarchar(10),@rBatchId)+'
				) x
				PIVOT
				(
					MAX(AdmissionFormFieldResponse)
					FOR FieldRemark IN (' + @cols + N')
				) p '
			
	exec sp_executesql @query

	SELECT * from #tempAdmissionForm tempAF
	LEFT JOIN #tempStudentAcademic tempSA ON tempSA.AdmissionFormId = tempAF.AdmissionFormId
	LEFT JOIN #tempFatherAcademic tempFA ON tempFA.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #tempReference tempRF on tempRF.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #TempSibling tempSB ON tempSB.AdmissionFormId = tempAF.AdmissionFormId
	LEFT JOIN ##tempAdmissionCriteriaForm tempACF ON tempACF.AdmissionFormId = tempAF.AdmissionFormId
	Order by tempAF.Formno

END
ELSE 
BEGIN 
	SELECT * from #tempAdmissionForm tempAF
	LEFT JOIN #tempStudentAcademic tempSA ON tempSA.AdmissionFormId = tempAF.AdmissionFormId
	LEFT JOIN #tempFatherAcademic tempFA ON tempFA.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #tempReference tempRF on tempRF.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #TempSibling tempSB ON tempSB.AdmissionFormId = tempAF.AdmissionFormId
	Order by tempAF.Formno
END
END
GO
PRINT N'Altering [sAlert].[pBusRouteGet]...';


GO

 
ALTER PROCEDURE [sAlert].[pBusRouteGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rBusRouteId int,
	 	 @rOrgGroupBatchId int,
		 @rTransportId int=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,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',isnull(SC.Name,'')),
			'[Class]',isnull(SC.ClassName,'')),
			'[Division]',isnull(SC.DivisionName,'')),
			'[BusRoute]',isnull(BRM.Title,'')),
			'[PickupPoint]',isnull(BRDM.Title,'')),
			'[PickupTime]',isnull(BRDM.PickupTime,'')),
			'[DropTime]',isnull(BRDM.DropTime,''))
			 AS Template
		
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SC.StudentId AND AR.SourceTypeId=2003
	INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId 
			AND ((BRDM.BusRouteId=@rBusRouteId) OR (@rBusRouteId=0))
	INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND BRM.OrgGroupBatchId = SC.OrgGroupBatchId 
	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 (BRM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (SC.StatusId=1)
		AND ((BRM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
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

	IF CHARINDEX('[PendingAmount]',@rTemplate) > 0   
	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 (
				replace(@rTemplate,'[Name]',SC.Name),
				'[Class]',SC.ClassName),
				'[Division]',SC.DivisionName),
				'[ReceiptNumber]',R.ReceiptNumber),
				'[ReceiptDate]',convert(varchar,R.ReceiptDate,103)),
				'[PaidAmount]',convert(int,R.ReceiptAmount)),
				'[PendingAmount]',[sFee].[fPendingFeeAmountForAlertGet](SC.AcademicId))
				 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
	ELSE
	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]',convert(varchar,R.ReceiptDate,103)),
				'[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
	
	
	
	
END
GO
PRINT N'Altering [sAlert].[pStudentAdmissionGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pStudentAdmissionGet]
	 	 
		 @rStudentId bigint,	 	 
	 	 @rBatchId int,	 	 	 	
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),	 	
	 	 @rMailSubject nvarchar(500)=''
	 	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,			
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[Code]',SC.Code),			
			'[AdmissionDate]',SA.AdmissionDate),
			'[AdmissionClass]',SC.ClassName)
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject
		
		
	From 
		sStudent.vStudentCommunication SC	
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SC.StudentId
	WHERE
	(SC.StudentId= @rStudentId)
	AND (SC.OrgId=@rOrgId)
	AND (SC.BatchId=@rBatchId)
	AND (SC.StatusId=1) AND (SC.IsBlockAllAlert=0)	
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,HeaderAdjustment,IsPublishExamSchedule,LinkExamId,OverallPercentageForGrace,MinimumGracePercetage,GraceMaxMark,KrupaMaxMark,IsApplySiddhiKrupa,IsDisplayGraph,IsGenerateRankNo
	)
	 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,HeaderAdjustment,IsPublishExamSchedule,LinkExamId,OverallPercentageForGrace,MinimumGracePercetage,GraceMaxMark,KrupaMaxMark,IsApplySiddhiKrupa,IsDisplayGraph,IsGenerateRankNo
	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].[pExamFullDetailGet]...';


GO
 
ALTER PROCEDURE [sAssessment].[pExamFullDetailGet]
	 @rId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
					 
	SELECT 
	EM.Id,
	EM.BatchId,
	ESGM.Code,
	ESGM.Title AS Name,
	ESGM.Id AS ExamGRoupId,
	EM.ClassId,
	EM.IsRankNo,
	EM.IsGrade,
	EM.IsPercentile,
	EM.IsPercentage,
	EM.IsSubjectPercentile,
	ISNULL(EM.GradeSetId,0) AS GradeSetId,
	ISNULL(EM.RankSetId,0) AS RankSetId,
	ISNULL(EM.LevelSetId,0) AS LevelSetId ,
	CASE WHEN ISNULL(IsProcessResult,0) = 0 THEN 'false' ELSE 'true' END AS IsProcessResult,
	CASE WHEN IsNull(IsMarksInDecimal,0) = 0 THEN 'false' ELSE 'true' END AS IsMarksInDecimal,
	CASE WHEN ISNULL(ISNegativeMarks,0)=0 THEN 'false' ELSE 'true' END AS ISNegativeMarks,
	Isnull(ED.Id,0) as ExamDetailId,
	ISNULL(ED.GradeSetId,0) as GradeSetDetailId,
	ISNULL(ED.ExamId,0) as ExamId,
	ISNULL(CS.Id,0) as ClassSubjectId,
	ISNULL(ED.Maximum,0) as Maximum,
	ISNULL(ED.Minimum,0) as Minimum,
	ISNULL(ED.IsIncludeInTotal,0) as IsIncludeInTotal,
	ISNULL(ED.IsDisplayInMarksheet,0) as IsDisplayInMarksheet,
	ISNULL(ED.IsShowSubjectGrade,0) as IsShowSubjectGrade,
	ISNULL(ED.IsShowSubjectMark,1) as IsShowSubjectMark,
	
	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	ISNULL(ED.ExamDate,sCommon.fGetDate()) as ExamDate,
	ISNULL(ED.ExamTime,'') as ExamTime,
	ISNULL(ED.ExamTopic,'') as ExamTopic,
	GSM.Title as GradeSET,
	EGM.Title as ExamGroup,
	ESGM.Title as ExamName,
	SM.Title as SubjectName,
	CM.DisplayTitle as ClassName,
	
	CASE WHEN ISNULL(IsOnPrePrinted,0) = 0 THEN 'false' ELSE 'true' END AS IsOnPrePrinted,
	CASE WHEN ISNULL(IsDisplayBirthDate,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayBirthDate,
	CASE WHEN ISNULL(IsDisplayPhoto,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayPhoto,
	CASE WHEN ISNULL(IsDisplaySchoolName,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplaySchoolName,
	CASE WHEN ISNULL(IsLockForEdit,0) = 0 THEN 'false' ELSE 'true' END AS IsLockForEdit,
	CASE WHEN ISNULL(IsIncludeCoScholastic,0) = 0 THEN 'false' ELSE 'true' END AS IsIncludeCoScholastic,
	CASE WHEN ISNULL(IsCoScholasticGrade,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGrade,
	CASE WHEN ISNULL(IsCoScholasticGradeIndicator,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGradeIndicator,
	CASE WHEN ISNULL(IsCoScholasticGradeDesIndicator,0) = 0 THEN 'false' ELSE 'true' END AS IsCoScholasticGradeDesIndicator,
	
	CASE WHEN ISNULL(IsDisplayAttendance,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayAttendance,
	CASE WHEN ISNULL(IsDisplayHeightWeight,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayHeightWeight,
	CASE WHEN ISNULL(IsResultStatus,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayResultStatus,
	CASE WHEN ISNULL(IsIncludeSubExam,0) = 0 then 'false' ELSE 'true' END AS IsIncludeSubExam,
	
	CASE WHEN ISNULL(IsPublished,0) = 0 then 'false' ELSE 'true' END AS IsPublished,
	CASE WHEN ISNULL(IsDisplayHighestDivisionMark,0) = 0 then 'false' ELSE 'true' END AS IsDisplayHighestDivisionMark,
	CASE WHEN ISNULL(IsDisplayHighestDivisionGrade,0) = 0 then 'false' ELSE 'true' END AS IsDisplayHighestDivisionGrade,
	CASE WHEN ISNULL(IsDisplayGradeString,0) = 0 then 'false' ELSE 'true' END AS IsDisplayGradeString,
	
	CASE WHEN ISNULL(IsExcludeAbsentTotal,0) = 0 then 'false' ELSE 'true' END AS IsExcludeAbsentTotal,
	
	EM.Remark1,
	EM.Remark2,
	EM.Remark3,
	EM.DisplayTitle,
	ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
	ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
	ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
	ISNULL(EM.TermScopeId,0) AS TermScopeId,	
	ISNULL(EM.ReportId,0) as ReportId,
	CASE WHEN ED.ClassSubjectId=CS.Id THEN 'true' ELSE 'false' END AS Selected,
	
	ISNULL(EM.CoScholasticScopeId,0) AS CoScholasticScopeId,
	ISNULL(EM.SubjectGroupPerPage,0) AS SubjectGroupPerPage,
	CASE WHEN ISNULL(IsDisplayParentName,0) = 0 THEN 'false' ELSE 'true' END AS IsDisplayParentName,
	CASE WHEN ISNULL(IsDisplayTeacherSign,0)=0 THEN 'false' ELSE 'true' END AS IsDisplayTeacherSign,
	CASE WHEN ISNULL(IsDisplayPrincipalSign,0)=0 THEn 'false' ELSE 'true' END AS IsDisplayPrincipalSign,
	ISNULL(EM.PercentileScopeId,0) AS PercentileScopeId,
	ISNULL(EM.CoScholasticGradeSetId,0) AS CoScholasticGradeSetId ,
	ISNULL(EM.IsRemovePercentageForFail,0) AS IsFailPercentageZero,
	--CASE WHEN ISNULL(IsGenerateRankNo,0) = 0 THEN 'No' ELSE 'Yes' END AS IsGenerateRankNo
	EM.IsGenerateRankNo
	
	
	
  FROM 
			[sAssessment].[tExamMaster] EM
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId
			INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId				
			INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id					
			INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			LEFT Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
						
WHERE       
            EM.Id=@rId
			order by Selected Desc,DisplayOrder Asc,ESGM.Title Desc
		
END
GO
PRINT N'Altering [sAssessment].[pExamMasterAdd]...';


GO
ALTER PROCEDURE [sAssessment].[pExamMasterAdd]
	 
	        @rId int
	       ,@rBatchId int
           ,@rExamSubGroupId int           
           ,@rClassId int
           ,@rIsRankNo bit
           ,@rIsGrade bit
           ,@rIsPercentile bit
           ,@rIsPercentage bit
           ,@rIsSubjectPercentile bit
           ,@rGradeSetId int
           ,@rRankSetId int
           ,@rLevelSetId int
           ,@rIsProcessResult bit
           ,@rIsMarkInDecimal bit
           ,@rIsNegativeMarks bit
           ,@rIsPrePrinted bit
           ,@rIsDisplayBirthDate bit
           ,@rIsDisplayPhoto bit
           ,@rIsDisplayschoolName bit
           ,@rIsIncludeCoScholastic bit
           ,@rIsCoScholasticGrade bit
           ,@rIsCoScholasticGradeIndicator bit
           ,@rIsCoScholasticGradeDesIndicator bit
           ,@rIsLockForEdit bit
           ,@rRemark1 nvarchar(1000)
           ,@rRemark2 nvarchar(150)
           ,@rDisplayTitle nvarchar(150)
           ,@rFooterAdjustment smallint
           ,@rReportId smallint
           ,@rRemark3 nvarchar(150)
           ,@rIsDisplayHeightWeight bit
           ,@rIsDisplayAttendance bit
           ,@rIsDisplayResultStatus bit
           ,@rDetailAdjustment smallint
           ,@rTermScopeId smallint
           ,@rMaximumMark Decimal
           ,@rIsIncludeSubExam bit
           ,@rCreatedUserId bigint
           ,@rOrgId int
           ,@rIsPublished bit
           ,@rIsDisplayHighestDivisionMark bit
           ,@rIsDisplayHighestDivisionGrade bit
           ,@rIsDisplayGradeString bit,
            @rCoScholasticScopeId tinyint,
            @rIsDisplayParentsName bit=0,
			@rSubjectGroupPerPage tinyint,
			@rIsDisplayTeacherSign bit,
			@rIsDisplayPrincipalSign bit,
			@rPercentileScope tinyint=0,
			@rCoScholasticGradeSetId int =0,
			@rIsExcludeAbsentTotal bit =0,
			@rDecimalUpto nvarchar(10),
			@rIsShowAddress bit=0,
			@rIsShowTotalMarks  bit =0,
			@rIsShowResultIndicator  bit =0,
			@rIsFailPercentageZero bit=0,
			@rRemark1Caption nvarchar(100),
			@rRemark2Caption nvarchar(100),
			@rRemark3Caption nvarchar(100),
			@rTeacherSignCaption nvarchar(100),
			@rPrincipalSignCaption nvarchar(100),
			@rParentSignCaption nvarchar(100),
			@rIsSubjectWeightage bit=0,
			@rIsDisplayActivityGrade bit=0,
			@rIsAllExamPassRequired bit=0,
			@rIsPublishExamSchedule bit=0,
			@rLinkedExamId int=0,
			@rOverallPercentageForGrace smallint = 0,
			@rMinimumGracePercetage smallint = 0,
			@rGraceMaxMark smallint = 0,
			@rKrupaMaxMark smallint = 0,
			@rIsSiddhiKrupaApplicable bit = 0,
			@rIsGenerateRankNo bit=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId AND ClassId=@rClassId AND BatchId=@rBatchId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		--If Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId and ClassId=@rClassId AND BatchId=@rBatchId)
		--	BEGIN
		--	select -103 as Result
		--	RETURN
		--END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId AND ClassId=@rClassId AND BatchId=@rBatchId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		--If  Exists(select Id from sAssessment.tExamMaster where ExamSubGroupId=@rExamSubGroupId and ClassId=@rClassId AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -103 as Result
		--	RETURN
		--End

	END
	
	
	
	 	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAssessment].[tExamMaster]
			   (
			     Id 
				,BatchId 
				--,Code 
				--,Name 
				,ExamSubGroupId 
				,ClassId 
				,IsRankNo 
				,IsGrade 
				,IsPercentile
				,IsSubjectPercentile
				,IsPercentage
				,GradeSetId 
				,RankSetId 
				,LevelSetId
				,IsProcessResult
				,IsMarksInDecimal
				,IsNegativeMarks
				,IsOnPrePrinted
				,IsDisplayBirthDate
				,IsDisplayPhoto
				,IsDisplaySchoolName
				,IsLockForEdit
				,IsIncludeCoScholastic
				,IsCoScholasticGrade
				,IsCoScholasticGradeIndicator
				,IsCoScholasticGradeDesIndicator
				,IsDisplayAttendance
				,IsDisplayHeightWeight
				,IsResultStatus
				,Remark1
				,Remark2
				,Remark3
				,DisplayTitle
				,FooterAdjustment
				,DetailAdjustment
				,ReportId
				,TermScopeId
				,ExamMaximum
				,IsIncludeSubExam
				,UpdatedUserId
				,UpdatedDateTime
				,IsPublished
				,IsDisplayHighestDivisionMark
				,IsDisplayHighestDivisionGrade
				,IsDisplayGradeString,
				CoScholasticScopeId,
				IsDisplayParentName,
				 SubjectGroupPerPage,
				 IsdisplayTeacherSign,
				 IsDisplayPrincipalSign,
				 PercentileScopeId,
				 CoScholasticGradeSetId,
				 IsExcludeAbsentTotal,
				 DecimalFormat,
				 IsDisplayTotalMark,
				 IsDisplayResultIndicator,
				 IsRemovePercentageForFail,
				 Remark1Caption ,
				 Remark2Caption ,
				 Remark3Caption,
				 TeacherSignCaption,
				 PrincipalSignCaption,
				 ParentSignCaption,
				 IsSubjectWeightage,
				 IsDisplayActivityGrade,
				 IsAllExamPassRequired,
				 IsPublishExamSchedule,
				 LinkExamId,
			     OverallPercentageForGrace,
			     MinimumGracePercetage,
			     GraceMaxMark,
			     KrupaMaxMark,
			     IsApplySiddhiKrupa,
				 IsGenerateRankNo
			   )
		 VALUES
			   (
				@lNextNumber 
			   ,@rBatchId 
			   --,@rCode 
			   --,@rExamName 
			   ,@rExamSubGroupId 
			   ,@rClassId 
			   ,@rIsRankNo 
			   ,@rIsGrade 
			   ,@rIsPercentile 
			   ,@rIsSubjectPercentile
			   ,@rIsPercentage 
			   ,@rGradeSetId 
			   ,@rRankSetId 
			   ,@rLevelSetId 
			   ,@rIsProcessResult
			   ,@rIsMarkInDecimal
			   ,@rIsNegativeMarks
			   ,@rIsPrePrinted
			   ,@rIsDisplayBirthDate
			   ,@rIsDisplayPhoto
			   ,@rIsDisplayschoolName
			   ,@rIsLockForEdit
			   ,@rIsIncludeCoScholastic
			   ,@rIsCoScholasticGrade
               ,@rIsCoScholasticGradeIndicator
               ,@rIsCoScholasticGradeDesIndicator
			   ,@rIsDisplayAttendance
			   ,@rIsDisplayHeightWeight
			   ,@rIsDisplayResultStatus
			   ,@rRemark1
			   ,@rRemark2
			   ,@rRemark3
			   ,@rDisplayTitle
			   ,@rFooterAdjustment
			   ,@rDetailAdjustment
			   ,@rReportId
			   ,@rTermScopeId
			   ,@rMaximumMark
			   ,@rIsIncludeSubExam
			   ,0
			   ,sCommon.fGetDate()
			   ,@rIsPublished
			   ,@rIsDisplayHighestDivisionMark
			   ,@rIsDisplayHighestDivisionGrade
			   ,@rIsDisplayGradeString,
			   @rCoScholasticScopeId,
			   @rIsDisplayParentsName,
			   
			   
			  @rSubjectGroupPerPage ,
			  @rIsDisplayTeacherSign,
			  @rIsDisplayPrincipalSign,
			  @rPercentileScope,
			  @rCoScholasticGradeSetId,
			  @rIsExcludeAbsentTotal,
			  @rDecimalUpto,
			  @rIsShowTotalMarks,
			  @rIsShowResultIndicator,
			  @rIsFailPercentageZero,
			  @rRemark1Caption ,
			  @rRemark2Caption ,
			  @rRemark3Caption,
			  @rTeacherSignCaption,
			  @rPrincipalSignCaption,
			  @rParentSignCaption,
			  @rIsSubjectWeightage,
			  @rIsDisplayActivityGrade,
			  @rIsAllExamPassRequired,
			  @rIsPublishExamSchedule	,
			  @rLinkedExamId,
			  @rOverallPercentageForGrace,
			  @rMinimumGracePercetage,
			  @rGraceMaxMark,
			  @rKrupaMaxMark,
			  @rIsSiddhiKrupaApplicable,
			  @rIsGenerateRankNo
			   )
				SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAssessment].[tExamMaster]
	    SET
			   -- Code =@rCode 
			   --,Name = @rExamName 
			    ExamSubGroupId =@rExamSubGroupId 
			   ,ClassId =@rClassId 
			   ,IsRankNo=@rIsRankNo 
			   ,IsGrade=@rIsGrade 
			   ,IsPercentile =@rIsPercentile 
			   ,IsSubjectPercentile = @rIsSubjectPercentile
			   ,IsPercentage=@rIsPercentage 
			   ,GradeSetId =@rGradeSetId 
			   ,RankSetId=@rRankSetId 
			   ,LevelSetId=@rLevelSetId 
			   ,IsProcessResult = @rIsProcessResult
			   ,IsMarksInDecimal = @rIsMarkInDecimal			   
			   ,IsNegativeMarks = @rIsNegativeMarks
			   
			   ,IsOnPrePrinted = @rIsPrePrinted
			   ,IsDisplayBirthDate=@rIsDisplayBirthDate
			   ,IsDisplayPhoto=@rIsDisplayPhoto
			   ,IsDisplaySchoolName=@rIsDisplayschoolName
			   ,IsIncludeCoScholastic=@rIsIncludeCoScholastic
			   ,IsCoScholasticGrade=@rIsCoScholasticGrade
			   ,IsCoScholasticGradeIndicator=@rIsCoScholasticGradeIndicator
			   ,IsCoScholasticGradeDesIndicator=@rIsCoScholasticGradeDesIndicator
			   ,IsLockForEdit=@rIsLockForEdit
			   ,IsDisplayAttendance=@rIsDisplayAttendance
			   ,IsDisplayHeightWeight=@rIsDisplayHeightWeight
			   ,IsResultStatus=@rIsDisplayResultStatus
			   ,Remark1=@rRemark1
			   ,Remark2=@rRemark2
			   ,Remark3=@rRemark3
			   ,DisplayTitle=@rDisplayTitle
			   ,FooterAdjustment=@rFooterAdjustment
			   ,DetailAdjustment=@rDetailAdjustment
			   ,ReportId = @rReportId
			   ,TermScopeId=@rTermScopeId
			   ,ExamMaximum=@rMaximumMark
			   ,IsIncludeSubExam = @rIsIncludeSubExam
			   ,UpdatedUserId=@rCreatedUserId
			   ,UpdatedDateTime=sCommon.fGetDate()          
			   ,IsPublished=@rIsPublished
			   ,IsDisplayHighestDivisionMark=@rIsDisplayHighestDivisionMark
			   ,IsDisplayHighestDivisionGrade=@rIsDisplayHighestDivisionGrade
			   ,IsDisplayGradeString=@rIsDisplayGradeString,
			   CoScholasticScopeId=@rCoScholasticScopeId,
			   IsDisplayParentName=@rIsDisplayParentsName,
			   SubjectGroupPerPage = @rSubjectGroupPerPage,
			   IsDisplayTeacherSign = @rIsDisplayTeacherSign,
			   IsDisplayPrincipalSign = @rIsDisplayPrincipalSign,
			   PercentileScopeId = @rPercentileScope,
			   CoScholasticGradeSetId=@rCoScholasticGradeSetId,
			   IsExcludeAbsentTotal = @rIsExcludeAbsentTotal,
			   DecimalFormat = @rDecimalUpto,
			   IsDisplayTotalMark = @rIsShowTotalMarks,
			   IsDisplayResultIndicator = @rIsShowResultIndicator,
			   IsRemovePercentageForFail=@rIsFailPercentageZero,
			   Remark1Caption= @rRemark1Caption ,
			   Remark2Caption= @rRemark2Caption ,
			   Remark3Caption= @rRemark3Caption,
			   TeacherSignCaption=@rTeacherSignCaption,
			   PrincipalSignCaption=@rPrincipalSignCaption,
			   ParentSignCaption=@rParentSignCaption,
			   IsSubjectWeightage=@rIsSubjectWeightage,
			   IsDisplayActivityGrade =@rIsDisplayActivityGrade,
			   IsAllExamPassRequired =@rIsAllExamPassRequired,
               IsPublishExamSchedule = @rIsPublishExamSchedule,
               LinkExamId= @rLinkedExamId,
               OverallPercentageForGrace=@rOverallPercentageForGrace,
			   MinimumGracePercetage=@rMinimumGracePercetage,
			   GraceMaxMark=@rGraceMaxMark,
			   KrupaMaxMark=@rKrupaMaxMark,
			   IsApplySiddhiKrupa=@rIsSiddhiKrupaApplicable,
			   IsGenerateRankNo=@rIsGenerateRankNo
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		 
	 END  	

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


GO
 
ALTER PROCEDURE [sAssessment].[pMarkEntryDetailAdd]
	 
	        @rId bigint
           ,@rResultId bigint
		   ,@rExamDetailId int
		   ,@rObtain Decimal(6,2)=0
		   ,@rIsPresent bit
		   ,@rExamId int
		   ,@rAcademicId bigint
		   ,@rOrgId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lMarkInDecimal bit
	 DECLARE @lClassId int
	 DECLARE @lDecimalPlace nvarchar(10)

Select @lMarkInDecimal=IsMarksInDecimal,@lClassId = ClassId,@lDecimalPlace=DecimalFormat from sAssessment.tExamMaster Where Id = @rExamId
	 
--Select @lMarkInDecimal=IsMarksInDecimal from sAssessment.tExamMaster Where Id = @rExamId And ClassId IN (SELECT ClassId FROM sStudent.tAcademic WHERE ID=@rAcademicId)
--Select @lClassId = ClassId From sAssessment.tExamMaster Where Id=@rExamId

IF @lMarkInDecimal = 1 AND @lDecimalPlace='0.0'
	BEGIN
		SET @rObtain = ROUND(@rObtain,1)
		
	END
ELSE if @lMarkInDecimal = 1 AND @lDecimalPlace='0.00'
	BEGIN	 
			SET @rObtain =round(round(@rObtain,2),2)
		END	
ELSE
	BEGIN
		SET @rObtain =round(ROUND(@rObtain,2),0)
		END		
	

IF(@rObtain < 0)
	SET @rObtain = 0
		
If NOT EXISTS (SELECT 1 FROM sAssessment.tExamDetail Where Id= @rExamDetailId And   ClassSubjectId in 
				(Select cs.Id from sSetup.tClassSubject CS 
					Left join sAssessment.tOptionalSubject O ON o.ClassSubjectId=cs.Id 
					AND O.AcademicId=@rAcademicId
					WHERE (CS.ClassId =@lClassId AND IsOptional = 0) OR (IsOptional = 1 AND AcademicId IS NOt Null))
					)
BEGIN
	SELECT 1 as Result
END

ELSE IF NOT EXISTS(SELECT Id From sAssessment.tResultDetail Where ResultId IN (SELECT ID from sAssessment.tResult Where AcademicId=@rAcademicId AND ExamId=@rExamId) AND ExamDetailId=@rExamDetailId)	
BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
	 
	INSERT INTO [sAssessment].[tResultDetail]
			   (
			    [Id]
			   ,[ResultId] 
			   ,[ExamDetailId]
			   ,[Obtain]
			   ,[IsPresent]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rResultId
			   ,@rExamDetailId
			   ,@rObtain
			   ,@rIsPresent
			   )
			  
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 
ELSE
	 BEGIN
	 
	 Select @rId = Id From sAssessment.tResultDetail Where ResultId IN (SELECT ID from sAssessment.tResult Where AcademicId=@rAcademicId AND ExamId=@rExamId) AND ExamDetailId=@rExamDetailId
	
	    UPDATE  [sAssessment].[tResultDetail]
	    SET
	         -- ResultId=@rResultId
	         --,ExamDetailId=@rExamDetailId,
			 Obtain=@rObtain
			 ,IsPresent=@rIsPresent
			 ,SubjectGrade = ''
			 ,SubjectGradePoint=0
			 ,Percentile=0
	      WHERE Id = @rId 	   
	      SELECT @rId AS Result
	
		--COMMIT TRANSACTION
	 END  
		
	--END
--END	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pRptExamFullGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptExamFullGet]
	 @rId int=0,
	 @rExamIds nvarchar(200)='',
	 @rBuilder1 nvarchar(200)='' 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	

					 
	SELECT 
	EM.Id,
	@rBuilder1 AS Builder1,
	Convert (nvarchar(20),EM.Id) AS ExamIdText,
	EM.BatchId,
	ESGM.Code,
	ESGM.Title AS Name,
	ESGM.Id AS ExamGRoupId,
	EM.ClassId,
	--EC.Id,
	--EM.IsRankNo,
	CASE WHEN ISNULL(IsRankNo,0) = 0 THEN 'No' ELSE 'Yes' END AS IsIsRankNo,
	--EM.IsGrade,
	CASE WHEN ISNULL(IsGrade,0) = 0 THEN 'No' ELSE 'Yes' END AS IsGrade,
	--EM.IsPercentile,
	CASE WHEN ISNULL(IsPercentile,0) = 0 THEN 'No' ELSE 'Yes' END AS IsPercentile,
	--EM.IsPercentage,
	CASE WHEN ISNULL(IsPercentage,0) = 0 THEN 'No' ELSE 'Yes' END AS IsPercentage,
	--EM.IsSubjectPercentile,
	CASE WHEN ISNULL(IsSubjectPercentile,0) = 0 THEN 'No' ELSE 'Yes' END AS IsSubjectPercentile,
	ISNULL(EM.GradeSetId,0) AS GradeSetId,
	ISNULL(EM.RankSetId,0) AS RankSetId,
	ISNULL(EM.LevelSetId,0) AS LevelSetId ,
	CASE WHEN ISNULL(IsProcessResult,0) = 0 THEN 'No' ELSE 'Yes' END AS IsProcessResult,
	CASE WHEN IsNull(IsMarksInDecimal,0) = 0 THEN 'No' ELSE 'Yes' END AS IsMarksInDecimal,
	CASE WHEN ISNULL(ISNegativeMarks,0)=0 THEN 'No' ELSE 'Yes' END AS ISNegativeMarks,
	Isnull(ED.Id,0) as ExamDetailId,
	ISNULL(ED.GradeSetId,0) as GradeSetDetailId,
	ISNULL(ED.ExamId,0) as ExamId,
	ISNULL(CS.Id,0) as ClassSubjectId,
	ISNULL(ED.Maximum,0) as Maximum,
	ISNULL(ED.Minimum,0) as Minimum,
	--ISNULL(ED.IsIncludeInTotal,0) as IsIncludeInTotal,
	CASE WHEN ISNULL(IsIncludeInTotal,0)=0 THEN 'No' ELSE 'Yes' END AS IsIncludeInTotal,
	--ISNULL(ED.IsDisplayInMarksheet,0) as IsDisplayInMarksheet,
	CASE WHEN ISNULL(IsDisplayInMarksheet,0)=0 THEN 'No' ELSE 'Yes' END AS IsDisplayInMarksheet,
	--ISNULL(ED.IsShowSubjectGrade,0) as IsShowSubjectGrade,
	CASE WHEN ISNULL(IsShowSubjectGrade,0)=0 THEN 'No' ELSE 'Yes' END AS IsShowSubjectGrade,
	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	ISNULL(ED.ExamDate,sCommon.fGetDate()) as ExamDate,
	ISNULL(ED.ExamTime,'') as ExamTime,
	ISNULL(ED.ExamTopic,'') as ExamTopic,
	GSM.Title as GradeSET,
	EGM.Title as ExamGroup,
	ESGM.Title as ExamName,
	SM.Title as SubjectName,
	CM.DisplayTitle as ClassName,
	
	CASE WHEN ISNULL(IsOnPrePrinted,0) = 0 THEN 'No' ELSE 'Yes' END AS IsOnPrePrinted,
	CASE WHEN ISNULL(IsDisplayBirthDate,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayBirthDate,
	CASE WHEN ISNULL(IsDisplayPhoto,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayPhoto,
	CASE WHEN ISNULL(IsDisplaySchoolName,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplaySchoolName,
	CASE WHEN ISNULL(IsLockForEdit,0) = 0 THEN 'No' ELSE 'Yes' END AS IsLockForEdit,
	CASE WHEN ISNULL(IsIncludeCoScholastic,0) = 0 THEN 'No' ELSE 'Yes' END AS IsIncludeCoScholastic,
	
	CASE WHEN ISNULL(IsDisplayAttendance,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayAttendance,
	CASE WHEN ISNULL(IsDisplayHeightWeight,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayHeightWeight,
	CASE WHEN ISNULL(IsResultStatus,0) = 0 THEN 'No' ELSE 'Yes' END AS IsDisplayResultStatus,
	EM.Remark1,
	EM.Remark2,
	EM.Remark3,
	EM.DisplayTitle,
	ISNULL(EM.ExamMaximum,0) AS ExamMaximum,
	ISNULL(EM.FooterAdjustment,0) AS FooterAdjustment,
	ISNULL(EM.DetailAdjustment,0) AS DetailAdjustment,
	--ISNULL(EM.TermScopeId,0) AS TermScopeId,	
	TSM.Title AS TermScopeTitle,
	ISNULL(EM.ReportId,0) as ReportId,
	CASE WHEN ED.ClassSubjectId=CS.Id THEN 'Yes' ELSE 'false' END AS Selected,
	CASE WHEN ISNULL(IsShowSubjectMark,0)=0 THEN 'No' ELSE 'Yes' END AS IsShowSubjectMark,
	CASE WHEN ISNULL(EM.IsDisplayParentName,0)=0 THEN 'No' ELSE 'Yes' ENd AS IsDisplayParentName,
	ISNULL(EM.SubjectGroupPerPage,0)AS SubjectGroupPerPage,
	CASE WHEN ISNULL(EM.IsDisplayTeacherSign,0)=0 THEN 'No' ELSe 'Yes' END AS IsDisplayTeacherSign,
	CASE WHEN ISNULL(EM.IsDisplayPrincipalSign,0)=0 THEN 'No' ELSe 'Yes' ENd  AS IsDisplayPrincipalSign,
	CASE WHEN ISNULL(EM.PercentileScopeId,0)=0 THEN 'No' ELSE 'Yes' END AS PercentileScopeId ,
 	CASE WHEN 	ISNULL(EM.CoScholasticScopeId,0)=1 THEn 'Single' ELSE 'Combine' END AS CoScholasticScope,
 	CASE WHEN ISNULL(EM.IsExcludeAbsentTotal,0) = 0 THEN 'No' ELSE 'Yes' END AS IsExcludeAbsentTotal,
	ISNULL(EM.IsDisplayTotalMark,0) AS IsDisplayTotalMarks,
	CASE WHEN ISNULL(IsAllExamPassRequired,0)=0 THEN 'No' ELSE 'Yes' END AS IsAllExamPassRequired,
	CASE WHEN ISNULL(IsGenerateRankNo,0) = 0 THEN 'No' ELSE 'Yes' END AS IsGenerateRankNo
	 
	 
	
  FROM 
			--		sAssessment.tExamCombine EC
			--INNER JOIN 
			sAssessment.tExamMaster EM  
			INNER JOIN sAssessment.tExamSubGroupMaster	ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
			INNER JOIN sSetup.tClassMaster CM on CM.Id=EM.ClassId			
			INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId 
			INNER JOIN sSetup.tSubjectMaster SM on   CS.SubjectId=SM.Id
			LEFT JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id
			Left Join sAssessment.tGradeSetMaster GSM ON GSM.Id = ED.GradeSetId
			LEFT JOIN sSetup.tTermScopeMaster TSM ON TSM.Id = EM.TermScopeId
			
												
						
WHERE       
           
            (EM.Id=@rId OR @rId = 0)			 
            AND (ISNULL(EM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamIds,','))OR @rExamIds='')
			 
          	
			order by  DisplayOrder
		
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardGet]
	 
	 @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,
		RD.Remark AS OtherDetailRemark,
		ISNULL(SO.AdhaarNumber,'') AS AdharNumber,
		ISNULL(SO.UIDNumber,'') AS UIDNumber
	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
	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'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
 IF(@rOrgGroupBatchId=0)
	SELECT @rOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id=@rBatchId  
  
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,
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100)
	)	
	 --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,
	HouseName,
	HouseId,
	AdhaarNumber,
	UIdNumber
	
	)
	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,
	    HM.Title As HouseName,HM.Id as HouseId,
	    ISNULL(SO.AdhaarNumber,'') As AdhaarNumber,
	    ISNULL(SO.UIdNumber,'') As UIdNumber
	   		
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 sActivity.tHouseMaster HM ON SO.HouseId = HM.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
	--print ('tempcombine')
	--SELECT * FROM #tempcombineExam
	--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)  
						
print(@query)
	 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
	--SELECT * FROM #TempAllExam	
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

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


GO


ALTER PROCEDURE [sAssessment].[pRptResultWithSubjectAnalysisBatchwise]
	 
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 --@rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 --@rExamId int,
     --@rExamSubGroupId1 int=0,
     --@rExamSubGroupId2 int=0,
	 @rCode nvarchar(20),
	 @rFromRollNo int =0,
	 @rToRollNo int =0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rStatusId int = 0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rResultStatus nvarchar(20)='',
	 @rDepartmentId int=0,
	 @rExamId1 int ,
	 @rExamId2 int ,
	 @rBatchId1 int,
	 @rBatchId2 int 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
 
	BEGIN
	
	CREATE TABLE #Temp_StudentId (StudentId bigint);
	INSERT INTO #Temp_StudentId
	SELECT A1.StudentId From sStudent.tAcademic A1 
	INNER JOIN
	sStudent.tAcademic A2 ON A1.StudentId = A2.StudentId 
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A1.StudentId
	WHERE A1.BatchId =  @rBatchId1 AND A2.BatchId = @rBatchId2
	AND (A1.ClassId=@rClassId OR @rClassId=0) 
	AND (A1.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND ((A1.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((A1.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SM.Code=@rCode) OR (@rCode=''))
	
	
CREATE TABLE #Temp_Academic (tempAcademicId bigint);
INSERT INTO #Temp_Academic 
SELECT  A.Id As tempAcademicId FROM sAssessment.tResult R 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
		WHERE BM.Id = @rBatchId2 AND R.ExamId =@rExamId2
	--SELECT * FROM #temp
	--RETURN 	
		
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			SR.PresentDays,
			SR.TotalDays
			--RD.SubjectGrade AS TermSubjectGrade,
			--RD.SubjectGrade AS SubjectGrade
			--1 As ExamNo
	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 sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN #Temp_StudentId TEMP2 ON TEMP2.StudentId = A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
			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
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			
	WHERE 
			
		EM.BatchId = @rBatchId1
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@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 ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId1 = 0))		
		AND ((EM.Id=@rExamId1 )	OR (@rExamId1 = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	A.BatchId = @rBatchId1
		--AND BM.Id = @rBatchId1
		AND R.ExamId = @rExamId1

UNION 
	
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			--temp.tempAcademicId,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			SR.PresentDays,
			SR.TotalDays

			--2 As ExamNo
	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 sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN #Temp_Academic temp ON temp.tempAcademicId= A.Id  
			INNER JOIN #Temp_StudentId TEMP2 ON TEMP2.StudentId = A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
			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
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			
	WHERE 
			
		EM.BatchId = @rBatchId2
		--AND (A.ClassId=@rClassId OR @rClassId=0)  
		--AND (A.ClassId=temp.tempClassId )
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0))
		--AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		--AND (A.DivisionId=temp.tempDivisionId )
		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 ((ESGM.Id = @rExamSubGroupId2) OR (@rExamSubGroupId2 = 0))		
		AND ((EM.Id=@rExamId2 )	OR (@rExamId2 = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	((A.BatchId = @rBatchId2 ))
		--AND ((BM.Id = @rBatchId2))
		AND R.ExamId = @rExamId2
		order by A.RollNo,ClassOrderIndex
	--	SELECT * FROM #temp
	--RETURN 
		END
		DROP Table #Temp_Academic
		DROP Table #Temp_StudentId
		
		----For Report Dataset
		--SELECT 
		--	@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2,
		--	EM.DisplayTitle AS Exam,
		--	EM.Id AS ExamId,
		--	StuM.Code,
		--	[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		--	A.RollNo,
		--	--temp.tempAcademicId,
		--	R.AcademicId,
		--	RD.Obtain,
		--	R.ResultStatus,
		--	CM.DisplayTitle AS Class,
		--	Cm.Id AS ClassId,
		--	DM.DisplayTitle AS Division,
		--	DM.Id AS DivisionId,
		--	DM.OrderIndex AS DivisinOrderIndex,
		--	R.TotalMarks,
		--	R.TotalObtain,
		--	R.Percentage,
		--	R.RankNumber,
		--	R.ResultGrade,
		--	SM.Title AS ClassSubject,
		--	RD.Id AS ResultDetailId,
		--	R.Id AS ResultId,
		--	CS.Id AS SubjectId,
		--	ED.Maximum,
		--	RD.SubjectGrade, 
			
		--	EM.IsMarksInDecimal,
		--	--SM.OrderIndex AS SubjectCode,
		--	SM.Code AS SubjectCode,
		--	ED.DisplayOrder AS SubjectOrderIndex,
		--	CM.OrderIndex AS ClassOrderIndex,
		--	RD.IsPresent,
		--	EM.IsGrade,
		--	EM.IsPercentage,
		--	EM.IsResultStatus,
		--	EM.IsRankNo ,
		--	ED.Minimum,
		--	RD.GraceMark,
		--	EM.DecimalFormat,
		--	CS.IsOptional,
		--	SR.PresentDays,
		--	SR.TotalDays,
		--	BM.Id As BatchId,
		--	BM.Title As BatchName
		--	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 sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		--	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		--	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
		--	INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
		--	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
		--	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
		--	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			
END
GO
PRINT N'Altering [sAssessment].[pRptStudentPercentageAnalysis]...';


GO
ALTER PROCEDURE [sAssessment].[pRptStudentPercentageAnalysis]
	 
	 @rOrgId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rDepartmentId int = 0,
	 @rGroupId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

--DECLARE  @TempFields TABLE

--(
--	MarkRange nvarchar(20),
--	StudentCount int,
--	GroupId int,
--	GroupName nvarchar(75),
--	GroupTitle nvarchar(75),
--	OrderIndex int
--)

DECLARE @lCount int
DECLARE @lMarkRange nvarchar(50)
DECLARE @lPercentage decimal(5,2)
DECLARE @lAnalysisGradeSetId int
DECLARE @lMinimumScore decimal(5,2)

SELECT @lAnalysisGradeSetId = ISNULL(AnalysisGradeSetId,0) From sAssessment.tConfiguration Where OrgId = @rOrgId

	CREATE TABLE #tempGradeSetDetail
	(
		Id INT IDENTITY (1, 1),
		MinimumScore decimal(5,2),
		MarkRange nvarchar(50),				 
	) 
	INSERT INTO #tempGradeSetDetail
	SELECT MinimumScore,MarkRange		
	FROM   sAssessment.tGradeSetDetail 
	WHERE  GradesetId=@lAnalysisGradeSetId
	ORDER BY MinimumScore DESC
	
	CREATE TABLE #tempPercentageUpdate
	(
		Id INT IDENTITY (1, 1),
		ResultId bigint,
		AcademicId bigint,
		Percentage decimal(5,2),
		MarkRange nvarchar(50)				 
	) 
	
	INSERT INTO #tempPercentageUpdate (ResultId,AcademicId,Percentage)
	SELECT R.Id,R.AcademicId,R.Percentage	
	FROM  sAssessment.tResult R 
		  INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
		  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
	WHERE A.BatchId = @rBatchId AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId
	
	 
    SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
	WHILE (@lCount > 0)
	
	BEGIN
		SELECT
			  @lMarkRange = MarkRange,
			  @lMinimumScore = MinimumScore
		FROM 
			  #tempGradeSetDetail WHERE Id = @lCount
			
			
		UPDATE T SET T.MarkRange=@lMarkRange 
	    FROM   #tempPercentageUpdate T
			   INNER JOIN sAssessment.tResult R ON R.Id = T.ResultId
			   INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			   INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = T.AcademicId
			   INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		WHERE  ROUND(R.Percentage,0) >= @lMinimumScore 
		       AND EM.ExamSubGroupId = @rExamSubGroupId
		       AND A.BatchId = @rBatchId
		       AND EM.BatchId = @rBatchId
		       AND ((A.ClassId = @rClassId) OR (@rClassId = 0))
		       AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		       AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId =0))

		SET @lCount = @lCount - 1
    END	
	
	SELECT	 
		  MarkRange, Count(T.AcademicId) AS StudentCount,
		  
		  CASE WHEN @rGroupId=1 THEN DM.Id 
			   WHEN @rGroupId=2 THEN CM.ClassId 
			   WHEN @rGroupId=3 THEN Dept.Id 
			   WHEN @rGroupId=4 THEN OM.Id 
		  END AS GroupId,
			
		  CASE WHEN @rGroupId=1 THEN DM.Code
			   WHEN @rGroupId=2 THEN CM.ClassName
			   WHEN @rGroupId=3 THEN Dept.Title 
			   WHEN @rGroupId=4 THEN OM.Title 
		  END AS GroupName,
			
		  CASE WHEN @rGroupId=1 THEN DM.OrderIndex
			   WHEN @rGroupId=2 THEN CM.OrderIndex
			   WHEN @rGroupId=3 THEN Dept.Id
			   WHEN @rGroupId=4 THen OM.OrderIndex  
		  END AS OrderIndex,
			
		  CASE WHEN @rGroupId=1 THEN 'Class/Division'
			   WHEN @rGroupId=2 THEN 'Class'
			   WHEN @rGroupId=3 THEN 'Department'
			   WHEN @rGroupId=4 THEN 'Organization'  
		  END AS GroupTitle
					
   FROM     
         #tempPercentageUpdate T
		 INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = T.AcademicId
		 INNER JOIN ssetup.tDivisionMaster DM ON DM.Id = A.DivisionId
		 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
		 INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
		 INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
   WHERE	 
         ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		 AND ((DM.ClassId=@rClassId ) or (@rClassId=0))
		 AND CM.BatchId=@rBatchId
		 AND EM.BatchId = @rBatchId
		 AND EM.ExamSubGroupId = @rExamSubGroupId
	     AND (ISNULL(DM.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	     AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId =0))
   GROUP BY 
		 MarkRange
		 ,
		 
		 CASE WHEN @rGroupId=1 THEN DM.Id WHEN @rGroupId=2 THEN CM.ClassId  
		 WHEN @rGroupId=3 THEN Dept.Id WHEN @rGroupId=4 THEN OM.Id END
		 , 
		 
		 CASE WHEN @rGroupId=1 THEN DM.Code WHEN @rGroupId=2 THEN CM.ClassName  
		 WHEN @rGroupId=3 THEN Dept.Title WHEN @rGroupId=4 THEN OM.Title END
		 ,
		 
		 CASE WHEN @rGroupId=1 THEN DM.OrderIndex WHEN @rGroupId=2 THEN CM.OrderIndex  
		 WHEN @rGroupId=3 THEN Dept.Id WHEN @rGroupId=4 THEN OM.OrderIndex END
		 
   ORDER BY OrderIndex ASC, MarkRange DESC ,GroupName ASC 
	
   DROP Table #tempPercentageUpdate
   DROP Table #tempGradeSetDetail
	
	
   --SELECT * from @TempFields
   
   --DROP Table @TempFields
	--MarkRange,OM.Id,OM.Title,OM.OrderIndex,Dept.Id,Dept.Title,CM.ClassId,CM.ClassName,CM.OrderIndex,DM.Id,
	--DM.DisplayTitle,DM.OrderIndex
END
GO
PRINT N'Altering [sAssessment].[pTypeWiseAssessmentConsolidatedDashboardGet]...';


GO
 
ALTER PROCEDURE [sAssessment].[pTypeWiseAssessmentConsolidatedDashboardGet]
	 
	@rOrgId int=0,
	@rTypeId int=0,
	@rCommonOrgGroupBatchId int=0,
	@rExamSubGroupId nvarchar(max)='',
	@rRangeId int=0,
	@rClassId int =0,
	@rDivisionId int =0,
	@rSubjectId int=0,
	@rEmployeeId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
/******
	TypeId = 1 Class wise Count
	TypeId = 2 DiVision Wise Count
	TypeId = 3 Subject Wise Count
	TypeId = 4 Teacher Wise Count
	
	TypeId = 11 Class wise Detail's
	TypeId = 21 DiVision Wise Detail's
	TypeId = 31 Subject Wise Detail's
	TypeId = 41 Teacher Wise Detail's
******/

	CREATE TABLE #TblFinalRecord
			(
				Id int identity,
				FromPercentage int,
				ToPercentage int
			) 
				INSERT INTO #TblFinalRecord(FromPercentage,ToPercentage) VALUES (90,100),(80,90),(70,80),(60,70),(50,60),(40,50),(0,40)	
			DECLARE @lFromPercentage int,@lToPercentage int

	IF(@rTypeId = 1)--TypeId = 1  is For Class Wise Count
		BEGIN
			SELECT CM.Id AS ClassId,CM.Title AS ClassName,COUNT(R90.R90) AS '91-100',COUNT(R80.R80) AS '81-90',COUNT(R70.R70) AS '71-80',COUNT(R60.R60) AS '61-70'
			,COUNT(R50.R50) AS '51-60',COUNT(R40.R40) AS '41-50',COUNT(R30.R30) AS 'Below-40'
			FROM  sSetup.tClassMaster CM
					INNER JOIN sAssessment.tExamMaster EM ON CM.Id = EM.ClassId
					INNER JOIN sAssessment.tResult R ON  EM.Id = R.ExamId
					INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
					--LEFT JOIN sSetup.tClassMaster CM ON CM.Id = A.classId AND 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
					  (SELECT R1.Id AS R90  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100			
					  )R90 ON R90.R90 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R80  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 80.49 AND R1.Percentage <= 90.49			
					  )R80 ON R80.R80 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R70  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 70.49 AND R1.Percentage <= 80.49			
					  )R70 ON R70.R70 = R.Id	
				   LEFT JOIN 
					  (SELECT R1.Id AS R60  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 60.49 AND R1.Percentage <= 70.49			
					  )R60 ON R60.R60 = R.Id
				  LEFT JOIN 
					  (SELECT R1.Id AS R50  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49		
					  )R50 ON R50.R50 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R40  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49
					  )R40 ON R40.R40 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R30  FROM sAssessment.tResult R1
	WHERE R1.Percentage <= 40.49
					  )R30 ON R30.R30 = R.Id
				   
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId='') 
				--AND CM.Id = 110100003
				AND CM.OrgId = @rOrgId
				GROUP BY CM.Id,CM.Title
		END
	ELSE IF (@rTypeId = 2)--TypeId = 2 is For Division Wise Count
		BEGIN
			SELECT DM.Id AS DivisionId,DM.Code AS ClassDivisionName,COUNT(R90.R90) AS '91-100',COUNT(R80.R80) AS '81-90',COUNT(R70.R70) AS '71-80',COUNT(R60.R60) AS '61-70'
			,COUNT(R50.R50) AS '51-60',COUNT(R40.R40) AS '41-50',COUNT(R30.R30) AS 'Below-40'
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			LEFT JOIN 
				  (SELECT R1.Id AS R90,A1.DivisionId AS DivisionId   FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100
				  )R90 ON R90.R90 = R.Id AND DM.Id = R90.DivisionId	
		    LEFT JOIN 
				  (SELECT R1.Id AS R80,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > 80.49 AND R1.Percentage <= 90.49
				  )R80 ON R80.R80 = R.Id AND DM.Id = R80.DivisionId	
		    LEFT JOIN 
				  (SELECT R1.Id AS R70,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > 70.49 AND R1.Percentage <= 80.49
				  )R70 ON R70.R70 = R.Id AND DM.Id = R70.DivisionId		
			LEFT JOIN 
				  (SELECT R1.Id AS R60,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > 60.49 AND R1.Percentage <= 70.49
				  )R60 ON R60.R60 = R.Id AND DM.Id = R60.DivisionId	
		    LEFT JOIN 
				  (SELECT R1.Id AS R50,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49
				  )R50 ON R50.R50 = R.Id AND DM.Id = R50.DivisionId	
			LEFT JOIN 
				  (SELECT R1.Id AS R40,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49
				  )R40 ON R40.R40 = R.Id AND DM.Id = R40.DivisionId	
			LEFT JOIN 
				  (SELECT R1.Id AS R30,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage <= 40.49
				  )R30 ON R30.R30 = R.Id AND DM.Id = R30.DivisionId	
			   
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId='')
				AND DM.OrgId = @rOrgId AND DM.IsObsolete = 0
				GROUP BY DM.Id,DM.Code,DM.OrderIndex
				ORDER BY DM.OrderIndex
		END
	ELSE IF (@rTypeId = 3)--TypeId = 3 is For Subject Wise Count
		BEGIN
			SELECT SM.Id AS SubjectId,SM.Title AS SubjectName,COUNT(R90.R90) AS '91-100',COUNT(R80.R80) AS '81-90',COUNT(R70.R70) AS '71-80',COUNT(R60.R60) AS '61-70'
			,COUNT(R50.R50) AS '51-60',COUNT(R40.R40) AS '41-50',COUNT(R30.R30) AS 'Below-40'
			FROM  sAssessment.tResult R 
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
			INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId AND CS.ClassId = A.classId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
			LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		    LEFT JOIN 
			  (SELECT R1.Id AS R90,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
			  -- INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
			   INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
			   INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100
			  )R90 ON R90.R90 = R.Id AND SM.Id = R90.SubjectId	AND DM.Id = R90.DivisionId
		  LEFT JOIN 
			  (SELECT R1.Id AS R80,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
			   --INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
			   INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
			   INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 80.49 AND R1.Percentage <= 90.49 
			  )R80 ON R80.R80 = R.Id AND SM.Id = R80.SubjectId AND DM.Id = R80.DivisionId	
		 LEFT JOIN 
			  (SELECT R1.Id AS R70,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
			   --INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
			   INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
			   INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 70.49 AND R1.Percentage <= 80.49 
			  )R70 ON R70.R70 = R.Id AND SM.Id = R70.SubjectId	AND DM.Id = R70.DivisionId	
		  LEFT JOIN 
			  (SELECT R1.Id AS R60,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
			   --INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
			   INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
			   INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 60.49 AND R1.Percentage <= 70.49 
			  )R60 ON R60.R60 = R.Id AND SM.Id = R60.SubjectId	AND DM.Id = R60.DivisionId	
		  LEFT JOIN 
			  (SELECT R1.Id AS R50,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
			   --INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
			   INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
			   INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49 
			  )R50 ON R50.R50 = R.Id AND SM.Id = R50.SubjectId	AND DM.Id = R50.DivisionId	
		 LEFT JOIN 
			  (SELECT R1.Id AS R40,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
			   --INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
			   INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
			   INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49 
			  )R40 ON R40.R40 = R.Id AND SM.Id = R40.SubjectId	AND DM.Id = R40.DivisionId		
		 LEFT JOIN 
			  (SELECT R1.Id AS R30,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
			   --INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
			   INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
			   INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage <= 40.49
			  )R30 ON R30.R30 = R.Id AND SM.Id = R30.SubjectId AND DM.Id = R30.DivisionId		
		   
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId='')
			 --AND CM.Id = 110100003
			AND SM.OrgId = @rOrgId AND DM.IsObsolete = 0
			GROUP BY SM.Id,SM.title,SM.OrderIndex 
			ORDER BY SM.OrderIndex 
		END
		
	ELSE IF (@rTypeId = 4)--TypeId = 4 is For Teacher Wise Count
		BEGIN
			SELECT ISNULL(DM.Id,'') AS DivisionId,ISNULL(DM.Code,'') AS ClassDivisionName,ISNULL(SM.Id,'') AS SubjectId,ISNULL(SM.Title,'') AS SubjectName,COUNT(R90.R90) AS '91-100',COUNT(R80.R80) AS '81-90',COUNT(R70.R70) AS '71-80',COUNT(R60.R60) AS '61-70'
			,COUNT(R50.R50) AS '51-60',COUNT(R40.R40) AS '41-50',COUNT(R30.R30) AS 'Below-40',EMP.EmployeeName,EMP.EmployeeId
			FROM  sAssessment.tResult R 
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId			
			INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId --AND CS.ClassId = A.classId
			LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
			LEFT JOIN sSetup.tDivisionMaster DM ON  DM.ClassId = EM.ClassId
			INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId AND TS.DivisionId=DM.ID AND TS.EmployeeId = @rEmployeeId
			--INNER JOIN  sHrm.tEmployeeMaster EM ON EM.ID = TS.EmployeeId
			INNER JOIN sSetup.tBatchMaster BM ON  BM.Id = EM.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			LEFT JOIN (
			SELECT Id AS EmployeeId,FirstName+' '+ LastName AS EmployeeName FROM sHrm.tEmployeeMaster
			)EMP ON EMP.EmployeeId = TS.EmployeeId
			
			LEFT JOIN 
			(SELECT R1.Id AS R90,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				-- INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100
			)R90 ON R90.R90 = R.Id AND SM.Id = R90.SubjectId	AND DM.Id = R90.DivisionId
			LEFT JOIN 
			(SELECT R1.Id AS R80,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 80.49 AND R1.Percentage <= 90.49 
			)R80 ON R80.R80 = R.Id AND SM.Id = R80.SubjectId AND DM.Id = R80.DivisionId	
			LEFT JOIN 
			(SELECT R1.Id AS R70,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 70.49 AND R1.Percentage <= 80.49 
			)R70 ON R70.R70 = R.Id AND SM.Id = R70.SubjectId	AND DM.Id = R70.DivisionId	
			LEFT JOIN 
			(SELECT R1.Id AS R60,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 60.49 AND R1.Percentage <= 70.49 
			)R60 ON R60.R60 = R.Id AND SM.Id = R60.SubjectId	AND DM.Id = R60.DivisionId	
			LEFT JOIN 
			(SELECT R1.Id AS R50,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49 
			)R50 ON R50.R50 = R.Id AND SM.Id = R50.SubjectId	AND DM.Id = R50.DivisionId	
			LEFT JOIN 
			(SELECT R1.Id AS R40,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49 
			)R40 ON R40.R40 = R.Id AND SM.Id = R40.SubjectId	AND DM.Id = R40.DivisionId		
			LEFT JOIN 
			(SELECT R1.Id AS R30,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage <= 40.49
			)R30 ON R30.R30 = R.Id AND SM.Id = R30.SubjectId AND DM.Id = R30.DivisionId		
			WHERE COGBM.Id = @rCommonOrgGroupBatchId
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId='')
			AND SM.OrgId = @rOrgId AND DM.IsObsolete = 0
			GROUP BY SM.Id,SM.title,EMP.EmployeeName,EMP.EmployeeId,DM.Code,DM.Id,SM.OrderIndex 
			ORDER BY SM.OrderIndex 
		END
		
		
	ELSE IF(@rTypeId = 11)--TypeId = 11  is For Class Wise Detail's
		BEGIN
		
				SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId
				SELECT CM.Id AS ClassId,CM.Title AS ClassName,STM.Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo--,COUNT(RAll.RAll) AS 'RAll'
				FROM  sAssessment.tResult R 
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
					INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
					LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
					LEFT JOIN sSetup.tClassMaster CM ON CM.Id = A.classId AND CM.Id = EM.ClassId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN 
					(SELECT R1.Id AS RAll  FROM sAssessment.tResult R1
	WHERE R1.Percentage >= @lFromPercentage AND R1.Percentage <= @lToPercentage			
					)RAll ON RAll.RAll = R.Id
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId='')
				--AND EM.ExamSubGroupId = @rExamSubGroupId
				AND CM.OrgId = @rOrgId AND ((CM.Id = @rClassId)OR(@rClassId=0))
				GROUP BY CM.Id,CM.Title,STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
				HAVING COUNT(RAll.RAll) >0

				DROP TABLE #TblFinalRecord
		END
	ELSE IF(@rTypeId = 21) -- TypeId = 21  is For Division Wise Detail's
		BEGIN
	
		SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId
			SELECT DM.Id AS ClassId,DM.Code AS ClassName,STM.Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo
				FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
				(SELECT R1.Id AS RAll,A1.DivisionId AS DivisionId   FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage >= @lFromPercentage AND R1.Percentage <= @lToPercentage
				--WHERE  R1.Percentage <= 40
				)RAll ON RAll.RAll = R.Id AND DM.Id = RAll.DivisionId	
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId='')
			--AND EM.ExamSubGroupId = @rExamSubGroupId 
			 AND ((DM.Id = @rDivisionId)OR(@rDivisionId=0))
			AND DM.OrgId = @rOrgId
			GROUP BY DM.Id,DM.Code,STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
			HAVING COUNT(RAll.RAll) >0

			DROP TABLE #TblFinalRecord
		END
	ELSE IF(@rTypeId = 31) -- TypeId = 31  is For Subject Wise Detail's
		BEGIN
			SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId
			SELECT SM.Id AS SubjectId,SM.Title AS SubjectName,STM.Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo
				FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
				INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId AND CS.ClassId = A.classId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
					(SELECT R1.Id AS RAll,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
					INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
					INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage >= @lFromPercentage AND R1.Percentage <= @lToPercentage
				)RAll ON RAll.RAll = R.Id AND SM.Id = RAll.SubjectId	AND DM.Id = RAll.DivisionId
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId='')
			--AND EM.ExamSubGroupId = @rExamSubGroupId 
			 AND ((SM.Id = @rSubjectId)OR(@rSubjectId=0))
			AND DM.OrgId = @rOrgId
			GROUP BY SM.Id,SM.title,STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
				HAVING COUNT(RAll.RAll) >0

			DROP TABLE #TblFinalRecord
		END
	ELSE IF(@rTypeId = 41) -- TypeId = 41  is For Teacher Wise Detail's
		BEGIN
				 SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId


			SELECT ISNULL(STM.Code,'')AS Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo
			--,EMP.EmployeeName,EMP.EmployeeId
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id			
				INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId AND CS.ClassId = A.classId
				LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
				INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
				LEFT JOIN sSetup.tDivisionMaster DM ON  DM.ClassId = EM.ClassId
				INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId AND TS.DivisionId=DM.ID
				--INNER JOIN  sHrm.tEmployeeMaster EM ON EM.ID = TS.EmployeeId
				INNER JOIN sSetup.tBatchMaster BM ON  BM.Id = EM.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN (
				SELECT Id AS EmployeeId,FirstName+' '+ LastName AS EmployeeName FROM sHrm.tEmployeeMaster
				)EMP ON EMP.EmployeeId = TS.EmployeeId
				
				LEFT JOIN 
				  (SELECT R1.Id AS RAll,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				  -- INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				   INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
				   INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage >= @lFromPercentage AND R1.Percentage <= @lToPercentage
				  )RAll ON RAll.RAll = R.Id AND SM.Id = RAll.SubjectId	AND DM.Id = RAll.DivisionId
		 	
		   
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId='')
			--AND EM.ExamSubGroupId = @rExamSubGroupId  
			--AND CM.Id = 110100003
				AND SM.OrgId = @rOrgId
				AND DM.Id = @rDivisionId AND SM.Id = @rSubjectId AND EMP.EmployeeId = @rEmployeeId
				GROUP BY STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
			HAVING COUNT(RAll.RAll) >0

			DROP TABLE #TblFinalRecord
			
		END
	
END
GO
PRINT N'Altering [sAttendance].[pAttendanceSummaryDashboard]...';


GO
ALTER  PROCEDURE [sAttendance].[pAttendanceSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rAttendanceDate date ='',
	@rClassId int=0,
	@rDepartmentId int =0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'AttendanceList')
		BEGIN
			SELECT COUNT(SR.AcademicId)
					,ISNULL((SELECT COUNT(SR.AcademicId)
						FROM sStudent.vStudentAcademic SA 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId	 
							 AND SR.AttendanceDate = @rAttendanceDate WHERE SR.IsPresent=1 AND ((SA.OrgId=@rOrgId)OR(@rOrgId=0))
							 AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS PresentCount,
					ISNULL((SELECT COUNT(SR.AcademicId)
					FROM sStudent.vStudentAcademic SA 
						INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId AND SR.AttendanceDate = @rAttendanceDate
						INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId	 
						  WHERE SR.IsPresent=0 AND  ((CM.Id =@rClassId)OR(@rClassId=0)) AND ((SA.OrgId=@rOrgId)OR(@rOrgId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0)) ),0) AS AbsentCount,
				ISNULL((SELECT COUNT(SR.AcademicId)
				FROM sStudent.vStudentAcademic SA 
				INNER JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=SA.AcademicId  AND SLR.LeaveFromDate = @rAttendanceDate AND  SLR.LeaveToDate = @rAttendanceDate
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId	 
				WHERE ((CM.Id =@rClassId)OR(@rClassId=0)) AND ((SA.OrgId=@rOrgId)OR(@rOrgId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS LeaveCount
				FROM sStudent.vStudentAcademic SA 
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId  AND SR.AttendanceDate = @rAttendanceDate
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
			WHERE ((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
		END
	ELSE IF(@rType = 'ClassWiseAttendance')
		BEGIN 
			SELECT CM.Id,CM.Title,ISNULL(T.PresentCount,0) AS PresentCount ,ISNULL(T1.AbsentCount,0) As AbsentCount,CM.OrderIndex
				FROM sSetup.tClassMaster CM
						LEFT JOIN sStudent.vStudentAcademic SA  ON CM.Id = SA.ClassId	
						LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId  AND SR.AttendanceDate = @rAttendanceDate
						LEFT JOIN 
							(SELECT COUNT(SA.AcademicId) AS PresentCount,SA.ClassId FROM sStudent.vStudentAcademic SA 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
							WHERE SR.IsPresent=1 AND  AttendanceDate = @rAttendanceDate
							GROUP BY SA.ClassId 
						)T ON T.ClassId = SA.ClassId
						
						LEFT JOIN 
							(SELECT COUNT(SA.AcademicId) AS AbsentCount,SA.ClassId FROM sStudent.vStudentAcademic SA 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
							WHERE SR.IsPresent=0 AND  AttendanceDate = @rAttendanceDate
							GROUP BY SA.ClassId 
						)T1 ON T1.ClassId = SA.ClassId 
						--AND T.ClassId = T1.ClassId
			WHERE ((CM.OrgId=@rOrgId)OR (@rOrgId=0))
			AND ((CM.Id =@rClassId)OR(@rClassId=0))
			AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
				GROUP BY CM.Title, CM.Id,T.PresentCount,T1.AbsentCount,CM.OrderIndex
				ORDER BY CM.OrderIndex
		END
END
GO
PRINT N'Altering [sAttendance].[pMonthlyRegisterStudentGet]...';


GO
ALTER PROCEDURE [sAttendance].[pMonthlyRegisterStudentGet]
	 	 
	 	 @rBatchId int,
	 	 @rAcademicId bigint,
	 	 @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 EXISTS (SELECT 1 FROM  sSetup.fMonthYearForBatchGET(@rBatchId) WHERE  YearNumber = Year(GETDATE()))
--For Current Batch
BEGIN
IF NOT EXISTS(select 1 From sAttendance.tMonthlyRegister MR  where AcademicId=@rAcademicId and ForMonth=Month(GETDATE()) and ForYear=Year(GETDATE()))
--Current Month Count If Exists
	BEGIN
		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)
		DECLARE @AverageAbsent DECIMAL(10,2)

		SET @YearNumber =Year(GETDATE())

		print @YearNumber

		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()))		
		
		IF(@AttendanceCount<>0.00)		
		    SET @AveragePresence= (@PresentCount/@AttendanceCount)*100		
		ELSE
		 SET @AveragePresence= 0
		 print @AveragePresence
		 IF(@AttendanceCount<>0.00)		
		    SET @AverageAbsent= (@AbsentCount/@AttendanceCount)*100		
		ELSE
		 SET @AverageAbsent= 0

		 print @AverageAbsent
		
		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
)
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,
		ISNULL(100.00-MR.AveragePresence,0) As AverageAbsent
		
		
	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(@AveragePresence,0) AS AveragePresence,
		   ISNULL(@AbsentDays,0) AS AbsentDays,
		   ISNULL(@AverageAbsent,0) AS AverageAbsent) AS TempStudentAttendance	
	ORDER BY ForYear,ForMonth
	END
END
ELSE --For Past Batch
	BEGIN
	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,
		ISNULL(100.00-MR.AveragePresence,0) As AverageAbsent
		
		
	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) 
	END
END
GO
PRINT N'Altering [sAttendance].[pSubjectwiseAttendanceGet]...';


GO
ALTER PROCEDURE [sAttendance].[pSubjectwiseAttendanceGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
		 @rAttendanceDate date,
		 @rSubjectId int,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rAttendanceGroupId int = 0,
	 	 @rPeriodNo int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF(@rAttendanceGroupId=0)
	BEGIN
		SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			ISNULL(SR.PeriodNo,0) AS PeriodNo,
			SA.ClassName+' - '+SA.DivisionName AS Class,
			SA.StudentId
		FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
				AND (SR.AttendanceTypeId=5)
				AND (SR.AttendanceDate=@rAttendanceDate)
				AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
				AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
				AND  ISNULL(SR.AttendanceGroupId,0) = @rAttendanceGroupId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
		WHERE 
			((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (SA.OrgId = @rOrgId)
			AND (SA.BatchId = @rBatchID)
			AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rAttendanceDate)
			
			ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
  END
  ELSE
  BEGIN
		SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			ISNULL(SR.PeriodNo,0) AS PeriodNo,
			SA.ClassName+' - '+SA.DivisionName AS Class,
			SA.StudentId
		FROM 
		sStudent.vStudentAcademic SA 
		INNER JOIN sAttendance.tAttendanceGroupStudent AGS ON AGS.AcademicId = SA.AcademicId 
			AND AGS.AttendanceGroupId=@rAttendanceGroupId
		INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
		LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=5)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
			AND SR.AttendanceGroupId=@rAttendanceGroupId
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
		WHERE 
		(SA.OrgId = @rOrgId)
		AND (SA.BatchId = @rBatchID)
		AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
		AND (AD.AdmissionDate <= @rAttendanceDate)
		ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
  END
END
GO
PRINT N'Altering [sBiometric].[pBiometricReportData]...';


GO
ALTER PROCEDURE [sBiometric].[pBiometricReportData]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int,
	@rDeptId int,
	@rForYear int=0,
	@rForMonth int=0,
	@rIsFirstIn bit=0,
	@rIsLastOut bit=0,
	@rIsOT bit=0,
	@rIsLateBy	bit=0,
	@rIsEarlyBy bit=0,
	@rIsDuration  bit=0,
	@rEmployeeStatusId int=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @lATTN_DATE nvarchar(20)
	DECLARE @lBatchID int
	DECLARE @Days int 
	SELECT @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1

	SET @lATTN_DATE = CONVERT(nvarchar(10),@rForYear) + '-' + Right('000000' + CONVERT(nvarchar, @rForMonth), 2) + '-01'
	
	DECLARE @lDN1 nvarchar(10),@lDN2 nvarchar(10),@lDN3 nvarchar(10),@lDN4 nvarchar(10),@lDN5 nvarchar(10),
	@lDN6 nvarchar(10),@lDN7 nvarchar(10),@lDN8 nvarchar(10),@lDN9 nvarchar(10),@lDN10 nvarchar(10),
	@lDN11 nvarchar(10),@lDN12 nvarchar(10),@lDN13 nvarchar(10),@lDN14 nvarchar(10),@lDN15 nvarchar(10),
	@lDN16 nvarchar(10),@lDN17 nvarchar(10),@lDN18 nvarchar(10),@lDN19 nvarchar(10),@lDN20 nvarchar(10),
	@lDN21 nvarchar(10),@lDN22 nvarchar(10),@lDN23 nvarchar(10),@lDN24 nvarchar(10),@lDN25 nvarchar(10),
	@lDN26 nvarchar(10),@lDN27 nvarchar(10),@lDN28 nvarchar(10),@lDN29 nvarchar(10),@lDN30 nvarchar(10),
	@lDN31 nvarchar(10)
	
	SET @lDN1 = '01 ' + substring(DATENAME( dw, convert( date, ( '01' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN2 = '02 ' + substring(DATENAME( dw, convert( date, ( '02' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN3 = '03 ' + substring(DATENAME( dw, convert( date, ( '03' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN4 = '04 ' + substring(DATENAME( dw, convert( date, ( '04' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN5 = '05 ' + substring(DATENAME( dw, convert( date, ( '05' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN6 = '06 ' + substring(DATENAME( dw, convert( date, ( '06' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN7 = '07 ' + substring(DATENAME( dw, convert( date, ( '07' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN8 = '08 ' + substring(DATENAME( dw, convert( date, ( '08' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN9 = '09 ' + substring(DATENAME( dw, convert( date, ( '09' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN10 = '10 ' + substring(DATENAME( dw, convert( date, ( '10' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN11 = '11 ' + substring(DATENAME( dw, convert( date, ( '11' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN12 = '12 ' + substring(DATENAME( dw, convert( date, ( '12' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN13 = '13 ' + substring(DATENAME( dw, convert( date, ( '13' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN14 = '14 ' + substring(DATENAME( dw, convert( date, ( '14' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN15 = '15 ' + substring(DATENAME( dw, convert( date, ( '15' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN16 = '16 ' + substring(DATENAME( dw, convert( date, ( '16' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN17 = '17 ' + substring(DATENAME( dw, convert( date, ( '17' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN18 = '18 ' + substring(DATENAME( dw, convert( date, ( '18' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN19 = '19 ' + substring(DATENAME( dw, convert( date, ( '19' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN20 = '20 ' + substring(DATENAME( dw, convert( date, ( '20' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN21 = '21 ' + substring(DATENAME( dw, convert( date, ( '21' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN22 = '22 ' + substring(DATENAME( dw, convert( date, ( '22' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN23 = '23 ' + substring(DATENAME( dw, convert( date, ( '23' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN24 = '24 ' + substring(DATENAME( dw, convert( date, ( '24' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN25 = '25 ' + substring(DATENAME( dw, convert( date, ( '25' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN26 = '26 ' + substring(DATENAME( dw, convert( date, ( '26' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN27 = '27 ' + substring(DATENAME( dw, convert( date, ( '27' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN28 = '28 ' + substring(DATENAME( dw, convert( date, ( '28' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN29 = case when @Days >= 29 then '29 ' + substring(DATENAME( dw, convert( date, ( '29' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end
	SET @lDN30 = case when @Days >= 30 then '30 ' + substring(DATENAME( dw, convert( date, ( '30' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end
	SET @lDN31 = case when @Days < 31 Then '' else '31 ' + substring(DATENAME( dw, convert( date, ( '31' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end

	SELECT 
		datediff(day, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE),
		dateadd(month, 1, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE))) AS DayCount,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		
		@lDN1 as DN1,@lDN2 as DN2,@lDN3 as DN3,@lDN4 as DN4,@lDN5 as DN5,@lDN6 as DN6,@lDN7 as DN7,@lDN8 as DN8,@lDN9 as DN9,@lDN10 as DN10,
		@lDN11 as DN11,@lDN12 as DN12,@lDN13 as DN13,@lDN14 as DN14,@lDN15 as DN15,@lDN16 as DN16,@lDN17 as DN17,@lDN18 as DN18,@lDN19 as DN19,
		@lDN20 as DN20,@lDN21 as DN21,@lDN22 as DN22,@lDN23 as DN23,@lDN24 as DN24,@lDN25 as DN25,@lDN26 as DN26,@lDN27 as DN27,@lDN28 as DN28,	@lDN29 as DN29,@lDN30 as DN30,@lDN31 AS DN31,
		
		E.Code,	
		E.ShortName,
		DM.Displaytitle DeptName,
		DM.Code AS DeptCode,
		E.OrgID,
		DM.Id AS DepartmentId,
		EDM.Title AS Designation,
		EDM.Code AS DesignationCode,
		@rIsFirstIn AS IsFirstIn,
		@rIsLastOut AS IsLastOut,
		@rIsOT AS IsOT,
		@rIsLateBy	AS IsLateBy,
		@rIsEarlyBy AS IsEarlyBy,
		@rIsDuration  AS IsDuration,
		E.FirstName +' ' + E.MiddleName +' '+ E.LastName AS Name,
		sBiometric.fEmployeeLeaveTypeGet(Attn_Dt,T.EmployeeId) AS LeaveStatus,
		ISNULL(sBiometric.fEmployeeCLTypeGet(@rForMonth,@rForYear,T.EmployeeId),'') AS CLeaveStatus,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,1,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D01,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,2,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D02,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,3,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D03,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,4,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D04,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,5,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D05,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,6,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D06,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,7,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D07,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,8,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D08,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,9,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D09,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,10,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D10,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,11,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D11,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,12,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D12,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,13,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D13,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,14,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D14,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,15,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D15,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,16,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D16,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,17,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D17,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,18,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D18,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,19,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D19,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,20,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D20,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,21,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D21,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,22,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D22,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,23,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D23,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,24,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D24,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,25,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D25,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,26,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D26,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,27,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D27,
		[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,28,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D28,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,29,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D29,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,30,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D30,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,31,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D31,

		case when @Days >= 29 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,29,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D29,
		case when @Days >= 30 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,30,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D30,
		case when @Days >= 31 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,31,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D31,


		
		E.Code AS  EmpCode, Attn_Dt, D01_IN, D02_IN, D03_IN, D04_IN, D05_IN, D06_IN, D07_IN, D08_IN, D09_IN, D10_IN, D11_IN, D12_IN, D13_IN, D14_IN, D15_IN, D16_IN, 
		D17_IN, D18_IN, D19_IN, D20_IN, D21_IN, D22_IN, D23_IN, D24_IN, D25_IN, D26_IN, D27_IN, D28_IN, D29_IN, D30_IN, D31_IN, D01_OUT, D02_OUT, D03_OUT, 
		D04_OUT, D05_OUT, D06_OUT, D07_OUT, D08_OUT, D09_OUT, D10_OUT, D11_OUT, D12_OUT, D13_OUT, D14_OUT, D15_OUT, D16_OUT, D17_OUT, D18_OUT, 
		D19_OUT, D20_OUT, D21_OUT, D22_OUT, D23_OUT, D24_OUT, D25_OUT, D26_OUT, D27_OUT, D28_OUT, D29_OUT, D30_OUT, D31_OUT, D01_O, D02_O, D03_O, 
		D04_O, D05_O, D06_O, D07_O, D08_O, D09_O, D10_O, D11_O, D12_O, D13_O, D14_O, D15_O, D16_O, D17_O, D18_O, D19_O, D20_O, D21_O, D22_O, D23_O, 
		D24_O, D25_O, D26_O, D27_O, D28_O, D29_O, D30_O, D31_O, D01_L, D02_L, D03_L, D04_L, D05_L, D06_L, D07_L, D08_L, D09_L, D10_L, D11_L, D12_L, D13_L, 
		D14_L, D15_L, D16_L, D17_L, D18_L, D19_L, D20_L, D21_L, D22_L, D23_L, D24_L, D25_L, D26_L, D27_L, D28_L, D29_L, D30_L, D31_L, D01_T, D02_T, D03_T, 
		D04_T, D05_T, D06_T, D07_T, D08_T, D09_T, D10_T, D11_T, D12_T, D13_T, D14_T, D15_T, D16_T, D17_T, D18_T, D19_T, D20_T, D21_T, D22_T, D23_T, D24_T, 
		D25_T, D26_T, D27_T, D28_T, D29_T, D30_T, D31_T, D01_E, D02_E, D03_E, D04_E, D05_E, D06_E, D07_E, D08_E, D09_E, D10_E, D11_E, D12_E, D13_E, D14_E, 
		D15_E, D16_E, D17_E, D18_E, D19_E, D20_E, D21_E, D22_E, D23_E, D24_E, D25_E, D26_E, D27_E, D28_E, D29_E, D30_E, D31_E, D01_S, D02_S, D03_S, D04_S, 
		D05_S, D06_S, D07_S, D08_S, D09_S, D10_S, D11_S, D12_S, D13_S, D14_S, D15_S, D16_S, D17_S, D18_S, D19_S, D20_S, D21_S, D22_S, D23_S, D24_S, D25_S, 
		D26_S, D27_S, D28_S, D29_S, D30_S, D31_S, Tot_Attn, Tot_Abs, Tot_WeekOFF, Tot_Holiday, TotalHour, Tot_HD, Tot_Early, Tot_Late, Tot_OT, Tot_OD, Tot_Leave, 
		Count_Late, Count_Early, Count_OT, Tot_CL, Tot_SL, Tot_EL, Tot_SP, Tot_C, Tot_PL, Tot_ML, T.EmployeeId
	FROM 
		sBiometric.tMonthTrans T
		LEFT JOIN sHRM.tEmployeeMaster E on E.Id = T.EmployeeId
		LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = E.Id
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
		LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId
	WHERE 
		(E.OrgId=@rOrgId) 
		AND (DM.Id = @rDeptId OR @rDeptId = 0)		 
		AND(T.Attn_dt = @lATTN_DATE) --AND E.StatusID = 7
		AND (MONTH(ED.DateofLeaving) >= @rForMonth AND YEAR(ED.DateofLeaving) >= @rForYear OR ED.DateofLeaving Is null )
		AND (E.STatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
	ORDER BY 
	E.Code,T.Attn_dt
END
GO
PRINT N'Altering [sCommunication].[pAssignmentListGet]...';


GO
 
ALTER PROCEDURE [sCommunication].[pAssignmentListGet]
	 @rBatchId int,
	 @rUserId bigint,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int,
	 @rSyncedAssignmentId bigint = 0,
	 @rName nvarchar(100)='',
	 @rFromDate date='',
	 @rToDate date=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 


DECLARE @lOrgGroupBatchId int=0
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rBatchId

	--DECLARE @lDivisionId int
	--SELECT @lDivisionId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId

	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsAssignmentBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 329 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsAssignmentBasedOnApproval = 0
	ELSE
	SET @lIsAssignmentBasedOnApproval = 1	
	
	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END
	
	if @rUserSourceTypeId   = 2003 -- For Student Login
	
	BEGIN
	
	
 	SELECT 	
			A1.Id as AssignmentId,
			A1.SubjectId,
			SM.Title as SubjectName,
			A1.Title,
			A1.Remark,
			A1.StartDate,
			A1.EndDate,
			ISNULL(AV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			SM.OrgId
			
	 FROM 
            sCommunication.tAssignment A1       
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A1.SubjectId 
            LEFT JOIN sCommunication.tAssignmentView AV ON AV.AssignmentId=A1.Id AND UserId=@rUserId     
            INNER JOIN sCommunication.tAssignmentScope AS1 ON AS1.AssignmentId=A1.Id 
            INNER JOIN ( SELECT A.DivisionId FROM sStudent.tAcademic A 
            WHERE A.StudentId = @rUserSourceId  AND A.BatchId = @rBatchId) D
            ON D.DivisionId =  AS1.SourceId AND AS1.SourceTypeId = 2005
            INNER JOIN sSecurity.tUser U ON U.Id=A1.CreatedUserId   
             WHERE 	 A1.BatchId=@rBatchId 
             AND ( A1.Id > @rSyncedAssignmentId OR @rSyncedAssignmentId = 0)
            AND (Convert(date,A1.CreatedDateTime)>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
			AND (Convert(date,A1.CreatedDateTime)<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
			AND (A1.Title like @rName OR ISNULL(@rName,'')='')
			AND ((@lIsAssignmentBasedOnApproval=0) OR (@lIsAssignmentBasedOnApproval=1 AND A1.StatusId=550))
             Order by A1.CreatedDateTime DESC 
					

	
 END
 ELSE 
 BEGIN
 --IF @rUserSourceTypeId   = 2003 -- For Student Login
 	SELECT 	
			A1.Id as AssignmentId,
			A1.SubjectId,
			SM.Title as SubjectName,
			A1.Title,
			A1.Remark,
			A1.StartDate,
			A1.EndDate,
			ISNULL(AV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			SM.OrgId
			
	 FROM 
            sCommunication.tAssignment A1 
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A1.SubjectId 
            LEFT JOIN sCommunication.tAssignmentView AV ON AV.AssignmentId=A1.Id AND UserId=@rUserId           
            INNER JOIN sCommunication.tAssignmentScope AS1 ON AS1.AssignmentId=A1.Id 
            INNER JOIN ( SELECT EJD.OrganizationDepartmentId FROM sHrm.tEmployeeMaster EM
            INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
             WHERE EM.Id = @rUserSourceId) D
            ON D.OrganizationDepartmentId =  AS1.SourceId AND AS1.SourceTypeId = 2017
             INNER JOIN sSecurity.tUser U ON U.Id=A1.CreatedUserId   
             WHERE 	 A1.BatchId=@rBatchId 
               AND ( A1.Id > @rSyncedAssignmentId OR @rSyncedAssignmentId = 0)
                AND (Convert(date,A1.CreatedDateTime)>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
			AND (Convert(date,A1.CreatedDateTime)<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
			AND (A1.Title like @rName OR ISNULL(@rName,'')='')
					Order by A1.CreatedDateTime DESC
             
 END
 END
GO
PRINT N'Altering [sCommunication].[pCircularQueueGet]...';


GO
ALTER PROCEDURE [sCommunication].[pCircularQueueGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100)='',
	 @rFromDate date,
	 @rToDate date,
	 @rOrgGroupBatchId int,
	 @rIsSearch bit = 1,
	 @rAssigneeId tinyint,
	 @rCircularTypeId int,
	 @rCreatedUserId bigint=0,
	 @rStatusId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

 --   DECLARE @lConfigValue nvarchar(50)
	--DECLARE @lIsCircularBasedOnApproval bit=0
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 302 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsCircularBasedOnApproval = 0
	--ELSE
	--SET @lIsCircularBasedOnApproval = 1	




	 --IF (@rIsSearch = 1)
		--BEGIN
		--	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END
	   
	SELECT 
	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			U.DisplayTitle as CreatedUserName,
			C.AssigneeId,
			AM.Title AS Assignee,
			CTM.Title AS CircularTypeTitle,
			CTM.HighlightColor,
			C.CircularTypeId,
			C.CreatedUserId,
			C.CreatedDateTime,
			ISNULL(C.StatusId,549) AS StatusId,
			CASE WHEN ISNULL(C.StatusId,549) =549 then 'Pending' WHEN C.StatusId=550 then 'Approve' ELSE 'Reject' END AS Status
  FROM 
            sCommunication.tCircular C
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=C.AssigneeId
            INNER JOIN sCommunication.tCircularTypeMaster CTM ON CTM.Id = C.CircularTypeId
  WHERE 
  
		((C.Id = @rId) OR (@rId = 0))
	AND ((C.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((C.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((C.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((C.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((C.AssigneeId IN (1,2,3) AND @rAssigneeId=1)  OR
		 (C.AssigneeId = @rAssigneeId AND @rAssigneeId IN (2,3)) OR
		  @rIsSearch = 0)
     --AND (C.CircularTypeId=@rCircularTypeId OR @rIsSearch = 0)
	  AND (C.CircularTypeId=@rCircularTypeId OR @rCircularTypeId = 0)
    AND (C.CreatedUserId = @rCreatedUserId OR @rCreatedUserId = 0)
     AND (C.StatusId = @rStatusId OR (@rStatusId = 0))
     --AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
    
	ORDER BY C.StartDate DESC
END
GO
PRINT N'Altering [sCommunication].[pDailyFeedGet]...';


GO
ALTER PROCEDURE [sCommunication].[pDailyFeedGet]
	 
@rUserId bigint=0,
@rOrgGroupId int=0,
@rOrgGroupBatchId int=0,
@rOrgId int=0,	 
@rBatchId int=0,
@rFeedDate date=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	DECLARE @lSourceId bigint=0,@lSourceTypeId smallint=0,@lAcademicId bigint,@lClassId int,@lDivisionId int,@lDepartmentId int
    SELECT @lSourceId=SourceId,@lSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE Id = @rUserId

	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsClassworkHomeworkBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 323 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsClassworkHomeworkBasedOnApproval = 0
	ELSE
	SET @lIsClassworkHomeworkBasedOnApproval = 1	
    
    -- Student
	IF(@lSourceTypeId = 2003)	
	BEGIN
		SELECT @lAcademicId = A.Id,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lDepartmentId=CM.DepartmentId 
		FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		WHERE  StudentId = @lSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
	END
	-- Employee
	ELSE
	BEGIN
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId 
		FROM sHrm.tEmployeeMaster EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		WHERE EM.Id=@lSourceId
	END
	
	
	-- Student
	IF(@lSourceTypeId = 2003)	
	BEGIN
		-- Circular
		--print @rOrgId
		--print @lDepartmentId
		--print @lClassId
		--print @lDivisionId
		--print @lSourceId
		--print @lAcademicId
		--print @rFeedDate
		
		--print @lSourceTypeId
		SELECT C.Id,C.Title,C.Remark,20085 AS ScreenId,C.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tCircular C INNER JOIN 
		(SELECT CS.CircularId FROM sCommunication.tCircularScope CS WHERE
		(
			(CS.SourceTypeId = 2021 AND CS.SourceId =@rOrgId) 
			OR (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId)
			OR (CS.SourceTypeId = 2016 AND CS.SourceId =@lClassId)
			OR (CS.SourceTypeId = 2005 AND CS.SourceId =@lDivisionId)
			OR (CS.SourceTypeId = 2003 AND CS.SourceId =@lSourceId)
			OR (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId)
		)
		) D ON D.CircularId= C.Id
		INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
		WHERE CONVERT(DATE,C.StartDate) = @rFeedDate AND C.AssigneeId IN (1,2) AND C.OrgGroupBatchId=@rOrgGroupBatchId AND StatusId=550
		
		UNION ALL
		
		-- Assignment
		SELECT A.Id,A.Title,A.Remark,20093 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tAssignment A INNER JOIN 
		(SELECT ASO.AssignmentId FROM sCommunication.tAssignmentScope ASO WHERE
		(
		(ASO.SourceTypeId = 2005 AND ASO.SourceId =@lDivisionId)
		)
		) D ON D.AssignmentId= A.Id
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
		WHERE CONVERT(DATE,A.StartDate) = @rFeedDate AND  A.BatchId=@rBatchId
		
		UNION ALL
		
		-- Poll
		SELECT P.Id,P.Title,P.Remark,20204 AS ScreenId,P.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tPoll P INNER JOIN 
		(SELECT PM.PollId FROM sCommunication.tPollMember PM  WHERE
		(
		(PM.SourceTypeId = 2005 AND PM.SourceId =@lDivisionId)
		)
		) D ON D.PollId= P.Id
		INNER JOIN sSecurity.tUser U ON U.Id=P.CreatedUserId
		WHERE CONVERT(DATE,P.CreatedDateTime) = @rFeedDate AND  P.OrgGroupBatchId=@rOrgGroupBatchId
		
		UNION ALL
		
		-- Blog
		SELECT B.Id,B.Title,B.Remark,20099 AS ScreenId,B.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tBlog B INNER JOIN 
		(SELECT BS.BlogId FROM sCommunication.tBlogScope BS  WHERE
		(
		(BS.SourceTypeId = 2021 AND BS.SourceId =@rOrgId)
		)
		) D ON D.BlogId= B.Id
		INNER JOIN sSecurity.tUser U ON U.Id=B.CreatedUserId
		WHERE CONVERT(DATE,B.CreatedDateTime) = @rFeedDate AND  B.OrgGroupBatchId=@rOrgGroupBatchId 
		
		UNION ALL
		
		-- News
		SELECT N.Id,N.Title,N.Remark,20104 AS ScreenId,N.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tNews N INNER JOIN 
		(SELECT NS.NewsId FROM sCommunication.tNewsScope NS  WHERE
		(
		(NS.SourceTypeId = 2021 AND NS.SourceId =@rOrgId)
		)
		) D ON D.NewsId= N.Id
		INNER JOIN sSecurity.tUser U ON U.Id=N.CreatedUserId
		WHERE CONVERT(DATE,N.CreatedDateTime) = @rFeedDate AND  N.OrgGroupBatchId=@rOrgGroupBatchId 
		
		UNION ALL
		
		-- Gallery
		SELECT PCM.Id,PCM.Title,PCM.Remark,20183 AS ScreenId,PCM.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tPhotoCategoryMaster PCM INNER JOIN 
		(SELECT PCS.PhotoCategoryId FROM sCommunication.tPhotoCategoryMaster PCM
		INNER JOIN sCommunication.tPhotoCategoryScope PCS ON PCM.Id = PCS.PhotoCategoryId
		WHERE
		((PCM.ScopeSourceTypeId = 2021 AND PCS.ScopeSourceId =@rOrgId))
		OR ((PCM.ScopeSourceTypeId = 2017 AND PCS.ScopeSourceId =@lDepartmentId))
		OR ((PCM.ScopeSourceTypeId = 2016 AND PCS.ScopeSourceId =@lClassId))
		OR ((PCM.ScopeSourceTypeId = 2005 AND PCS.ScopeSourceId =@lDivisionId))
		) D ON D.PhotoCategoryId= PCM.Id
		INNER JOIN sSecurity.tUser U ON U.Id=PCM.CreatedUserId
		WHERE CONVERT(DATE,PCM.CreatedDateTime) = @rFeedDate AND  PCM.OrgGroupId=@rOrgGroupId 
		
		UNION ALL
		
		-- Classwork | Homework
		SELECT C.Id,'Classwork' AS Title,Classwork AS Remark,20563 AS ScreenId,C.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sAcademic.tClasswork C
		INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
		WHERE CONVERT(DATE,C.CreatedDateTime) = @rFeedDate AND  BatchId=@rBatchId AND DivisionId = @lDivisionId AND ClassId = @lClassId 
		AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND C.StatusId=550))
		
		UNION ALL
		
		-- Behaviour
		SELECT B.Id,Title,Remark,20130 AS ScreenId,B.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle FROM sCommunication.tBehaviour B
		INNER JOIN sSecurity.tUser U ON U.Id=B.CreatedUserId
		WHERE CONVERT(DATE,B.CreatedDateTime) = @rFeedDate AND  AcademicId=@lAcademicId
		
		UNION ALL
		
		-- Activity
		SELECT A.Id,A.Title,A.Remark,20209 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sActivity.tActivity A INNER JOIN 
		(SELECT AP.ActivityId FROM sActivity.tActivityParticipant AP  WHERE
		(
		(AP.SourceTypeId = 2003 AND AP.SourceId =@lSourceId)
		)
		) D ON D.ActivityId= A.Id
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
		WHERE CONVERT(DATE,A.CreatedDateTime) = @rFeedDate AND  A.BatchId=@rBatchId
		
		UNION ALL
		
		-- Task
		SELECT T.Id,'Task' AS Title,Remark,20172 AS ScreenId,T.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tAssignTask T
		INNER JOIN sSecurity.tUser U ON U.Id=T.CreatedUserId
		WHERE CONVERT(DATE,T.CreatedDateTime) = @rFeedDate AND  T.OrgId=@rOrgId AND AssignedToSourceTypeId = 2003 AND AssignedToSourceId=@lSourceId
		
		UNION ALL
		
		-- Birthday
		SELECT SM.Id,'Birthday' AS Title,FirstName+' '+LastName AS Remark,20577 AS ScreenId,SO.DateOfBirth AS CreatedDateTime,0 AS CreatedUserId,'' AS CreatedUser FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tStudentOther SO ON SM.Id = SO.StudentId 
		WHERE CONVERT(DATE,SO.DateOfBirth) = @rFeedDate AND  SM.OrgId=@rOrgId AND SM.Id=@lSourceId
		
	END 
	-- Employee
	ELSE
	BEGIN
		-- Circular
		SELECT C.Id,C.Title,C.Remark,20085 AS ScreenId,C.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
		WHERE (
			  (CS.SourceTypeId = 2021 AND CS.SourceId =@rOrgId) 
 			  OR (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId)
 			  OR (CS.SourceTypeId = 95 AND CS.SourceId =@lSourceId)
			  )) D ON D.CircularId= C.Id
		INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId	  
		WHERE CONVERT(DATE,C.StartDate) = @rFeedDate AND C.AssigneeId IN (1,3) AND C.OrgGroupBatchId=@rOrgGroupBatchId AND StatusId=550
		
		UNION ALL
		
		-- Assignment
		SELECT A.Id,A.Title,A.Remark,20093 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tAssignment A INNER JOIN (SELECT ASO.AssignmentId FROM sCommunication.tAssignmentScope ASO
		WHERE (
			  (ASO.SourceTypeId = 2017 AND ASO.SourceId =@lDepartmentId)
			  )) D ON D.AssignmentId= A.Id
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId		  
		WHERE CONVERT(DATE,A.StartDate) = @rFeedDate AND  A.BatchId=@rBatchId
		
		UNION ALL
		
		-- Poll
		SELECT P.Id,P.Title,P.Remark,20204 AS ScreenId,P.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tPoll P INNER JOIN 
		(SELECT PM.PollId FROM sCommunication.tPollMember PM  WHERE
		(
		(PM.SourceTypeId = 2017 AND PM.SourceId =@lDepartmentId)
		)
		) D ON D.PollId= P.Id
		INNER JOIN sSecurity.tUser U ON U.Id=P.CreatedUserId		  
		WHERE CONVERT(DATE,P.CreatedDateTime) = @rFeedDate AND  P.OrgGroupBatchId=@rOrgGroupBatchId
		
		UNION ALL
		
		-- Blog
		SELECT B.Id,B.Title,B.Remark,20099 AS ScreenId,B.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tBlog B INNER JOIN 
		(SELECT BS.BlogId FROM sCommunication.tBlogScope BS  WHERE
		(
		(BS.SourceTypeId = 2021 AND BS.SourceId =@rOrgId)
		)
		) D ON D.BlogId= B.Id
		INNER JOIN sSecurity.tUser U ON U.Id=B.CreatedUserId
		WHERE CONVERT(DATE,B.CreatedDateTime) = @rFeedDate AND  B.OrgGroupBatchId=@rOrgGroupBatchId 
		
		UNION ALL
		
		-- News
		SELECT N.Id,N.Title,N.Remark,20104 AS ScreenId,N.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tNews N INNER JOIN 
		(SELECT NS.NewsId FROM sCommunication.tNewsScope NS  WHERE
		(
		(NS.SourceTypeId = 2021 AND NS.SourceId =@rOrgId)
		)
		) D ON D.NewsId= N.Id
		INNER JOIN sSecurity.tUser U ON U.Id=N.CreatedUserId
		WHERE CONVERT(DATE,N.CreatedDateTime) = @rFeedDate AND  N.OrgGroupBatchId=@rOrgGroupBatchId 
		
		UNION ALL
		
		-- Gallery
		SELECT PCM.Id,PCM.Title,PCM.Remark,20183 AS ScreenId,PCM.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tPhotoCategoryMaster PCM INNER JOIN 
		(SELECT PCS.PhotoCategoryId FROM sCommunication.tPhotoCategoryMaster PCM
		INNER JOIN sCommunication.tPhotoCategoryScope PCS ON PCM.Id = PCS.PhotoCategoryId
		WHERE
		((PCM.ScopeSourceTypeId = 2021 AND PCS.ScopeSourceId =@rOrgId))
		OR ((PCM.ScopeSourceTypeId = 2017 AND PCS.ScopeSourceId =@lDepartmentId))
		) D ON D.PhotoCategoryId= PCM.Id
		INNER JOIN sSecurity.tUser U ON U.Id=PCM.CreatedUserId
		WHERE CONVERT(DATE,PCM.CreatedDateTime) = @rFeedDate AND  PCM.OrgGroupId=@rOrgGroupId 
		
		UNION ALL
		
		-- Activity
		SELECT A.Id,A.Title,A.Remark,20209 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sActivity.tActivity A INNER JOIN 
		(SELECT AP.ActivityId FROM sActivity.tActivityParticipant AP  WHERE
		(
		(AP.SourceTypeId = 95 AND AP.SourceId =@lSourceId)
		)
		) D ON D.ActivityId= A.Id
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
		WHERE CONVERT(DATE,A.CreatedDateTime) = @rFeedDate AND  A.BatchId=@rBatchId
		
		UNION ALL
		
		-- Task
		SELECT A.Id,'Task' AS Title,Remark,20172 AS ScreenId,A.CreatedDateTime,U.Id AS CreatedUserId,U.DisplayTitle AS CreatedUser FROM sCommunication.tAssignTask A
		INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
		WHERE CONVERT(DATE,A.CreatedDateTime) = @rFeedDate AND  A.OrgId=@rOrgId AND AssignedToSourceTypeId = 95 AND AssignedToSourceId=@lSourceId
		
		UNION ALL
		
		-- Birthday
		SELECT EM.Id,'Birthday' AS Title,FirstName+' '+LastName AS Remark,20577 AS ScreenId,EPD.DateOfBirth AS CreatedDateTime,0 AS CreatedUserId,'' AS CreatedUser FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId 
		WHERE CONVERT(DATE,EPD.DateOfBirth) = @rFeedDate AND  EM.OrgId=@rOrgId AND EM.Id=@lSourceId
	END
END
GO
PRINT N'Altering [sErp].[pLeadFollowupAdd]...';


GO


ALTER PROCEDURE [sErp].[pLeadFollowupAdd]
		@rId	bigint,	
		@rLeadId int,
		@rFollowupDate	date,
		@rFollowupRemark	nvarchar(max),
		@rFollowupEmployeeId bigint,							
		@rCreatedUserId	bigint,
		@rOrgId smallint,
		@statusId int,
		@rNextFollowupDate date='',
		@rIsPhysical bit=0,
		@rLatitudeAxis nvarchar(20)='',
		@rLongitudeAxis nvarchar(20)='',
		@rFollowupType smallint=0,
		@rFollowupLocation nvarchar(200)='',
		@rNonEffective tinyint = 0,
		@rWithManagerEmployeeId bigint = 0,
		@rDisplacement decimal(10,2) =0.00
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN



	DECLARE @lFollowId BIGINT 
	IF Exists(select Id from sErp.tLeadFollowup where LeadId = @rLeadId AND FollowupTypeId=@rFollowupType  AND CONVERT(date,FollowupDate) =  CONVERT(date,getdate(),102))
				BEGIN
				SELECT @lFollowId = Id from sErp.tLeadFollowup where LeadId = @rLeadId  AND FollowupTypeId=@rFollowupType  AND CONVERT(date,FollowupDate) =  CONVERT(date,getdate(),102)
				IF Exists(select 1  from sErp.tLeadFollowup where LeadId = @rLeadId  AND FollowupTypeId=@rFollowupType  AND CONVERT(date,FollowupDate) =  CONVERT(date,getdate(),102) AND (LatitudeAxis IS NOT NULL OR LongitudeAxis IS NOT NULL ))
					BEGIN
						UPDATE  sErp.tLeadFollowup
						SET
						LeadId=@rLeadId,
						FollowupDate=@rFollowupDate,
						FollowupRemark=@rFollowupRemark,
						FollowupEmployeeId=@rFollowupEmployeeId,
						IsPhysical = @rIsPhysical,
						LatitudeAxis = @rLatitudeAxis,
						LongitudeAxis = @rLongitudeAxis,
						FollowupNextDate=@rNextFollowupDate,
						LeadStatusId = @statusId,
						FollowupTypeId=@rFollowupType,
						--FollowupLocation=@rFollowupLocation,
						NonEffective=@rNonEffective, 
						WithManagerEmployeeId = @rWithManagerEmployeeId
						WHERE Id = @lFollowId 	   	
						
							UPDATE  sErp.tLeadMaster
							SET LeadStatusId = @statusId,
							NextFollowupDate=@rNextFollowupDate
							WHERE Id = @rLeadId 

						SELECT @lFollowId AS Result    
						SELECT 11 AS Operation  
						return
					END 
				ELSE 
					BEGIN
						UPDATE  sErp.tLeadFollowup
						SET
						LeadId=@rLeadId,
						FollowupDate=@rFollowupDate,
						FollowupRemark=@rFollowupRemark,
						FollowupEmployeeId=@rFollowupEmployeeId,
						IsPhysical = @rIsPhysical,
						--LatitudeAxis = @rLatitudeAxis,
						--LongitudeAxis = @rLongitudeAxis,
						FollowupNextDate=@rNextFollowupDate,
						LeadStatusId = @statusId,
						FollowupTypeId=@rFollowupType,
						NonEffective=@rNonEffective,
						WithManagerEmployeeId = @rWithManagerEmployeeId
						WHERE Id = @lFollowId 	   	



							UPDATE  sErp.tLeadMaster
							SET LeadStatusId = @statusId,
							NextFollowupDate=@rNextFollowupDate
							WHERE Id = @rLeadId 

						SELECT @lFollowId AS Result    
						SELECT 11 AS Operation  
						return
					END
					
				END
			ELSE
			BEGIN
				IF(@rId = 0)	
					BEGIN
						DECLARE @lNextNumber BIGINT 
						EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tLeadFollowup', 0, 1, 1,@outNextNumber = @lNextNumber output
						INSERT INTO sErp.tLeadFollowup
						(Id,LeadId,FollowupDate,FollowupRemark,FollowupEmployeeId,CreatedUserId,CreatedDateTime,IsPhysical,LatitudeAxis,LongitudeAxis,FollowupNextDate,LeadStatusId,FollowupTypeId,FollowupLocation,NonEffective,WithManagerEmployeeId, Displacement)
						VALUES
						(@lNextNumber,@rLeadId,@rFollowupDate,@rFollowupRemark,@rFollowupEmployeeId,@rCreatedUserId,sCommon.fGetDate(),@rIsPhysical,@rLatitudeAxis,@rLongitudeAxis,@rNextFollowupDate,@statusId,@rFollowupType,	@rFollowupLocation,@rNonEffective, @rWithManagerEmployeeId, @rDisplacement)
						UPDATE sErp.tLeadMaster
						SET LeadStatusId = @statusId,
						NextFollowupDate = @rNextFollowupDate
						WHERE ID =@rLeadId
						SELECT @lNextNumber AS Result    
						SELECT 1 AS Operation     
					END	 
					ELSE
						BEGIN
							SET @lNextNumber = @rId
							UPDATE  sErp.tLeadFollowup
							SET
								LeadId=@rLeadId,
								FollowupDate=@rFollowupDate,
								FollowupRemark=@rFollowupRemark,
								FollowupEmployeeId=@rFollowupEmployeeId,
								IsPhysical = @rIsPhysical,
								LatitudeAxis = @rLatitudeAxis,
								LongitudeAxis = @rLongitudeAxis,
								FollowupNextDate=@rNextFollowupDate,
								LeadStatusId = @statusId,
								FollowupTypeId=@rFollowupType,
								--FollowupLocation=@rFollowupLocation,
								NonEffective=@rNonEffective,
								WithManagerEmployeeId=@rWithManagerEmployeeId
							WHERE Id = @rId 	   

							UPDATE  sErp.tLeadMaster
							SET LeadStatusId = @statusId,
							NextFollowupDate=@rNextFollowupDate
							WHERE Id = @rLeadId 	  

							SELECT @rId AS Result 
							SELECT 11 AS Operation
						END  
					END
	
END
GO
PRINT N'Altering [sFee].[pChangeClassFeeReceiptDetailUpdate]...';


GO
 
ALTER PROCEDURE [sFee].[pChangeClassFeeReceiptDetailUpdate]
	
	@rAcademicId bigint,
	@rOldClassId int,
	@rOldDivisionId int,
	@rNewClassId int,
	@rNewDivisionId int,	 
	@rBatchId int,
	@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @rAdmissionCategoryId int
DECLARE @rOldFeeSetupCount int
DECLARE @rNewFeeSetupCount int
DECLARE @rFinalFeeSetupCount int
	


	
		--IF Exists (SELECT R.SourceId FROM sFee.tReceipt R WHERE R.SourceId = @rAcademicId)
		--BEGIN
		--SELECT -111 AS Result
		--RETURN		
		--END
		--IF Exists (SELECT R.SourceId FROM sFee.tFeeOptional R WHERE R.SourceId = @rAcademicId)
		--BEGIN
		--SELECT -112 AS Result
		--RETURN		
		--END
		--IF Exists (SELECT R.SourceId FROM sFee.tFeeAllocation R WHERE R.SourceId = @rAcademicId)
		--BEGIN
		--SELECT -113 AS Result
		--RETURN		
		--END

		IF Exists (SELECT 1 FROM sAssessment.tOptionalSubject R WHERE R.AcademicId = @rAcademicId)
		BEGIN
		SELECT -114 AS Result
		RETURN		
		END


		IF Exists (SELECT 1 FROM sAssessment.tResult R WHERE R.AcademicId = @rAcademicId)
		BEGIN
		SELECT -115 AS Result
		RETURN		
		END
		
		IF Exists (SELECT 1 FROM sAssessment.tCCECSExamScore R WHERE R.AcademicId = @rAcademicId)
		BEGIN
		SELECT -116 AS Result
		RETURN		
		END
		
		IF Exists (SELECT 1 FROM sAssessment.tGradeSujbectExamScore R WHERE R.AcademicId = @rAcademicId)
		BEGIN
		SELECT -117 AS Result
		RETURN		
		END

		BEGIN

			SELECT DISTINCT FS.AdmissionCategoryId,FS.FeeId,FS.Amount,RD.ReceiptId,RD.FeeSetupId INTO #OldFeeSteupTempTable 
			FROM sFee.tFeeSetup FS INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = FS.ID INNER JOIN sFee.tReceipt FR ON FR.ID = RD.RECEIPTID 
			INNER JOIN sStudent.tAcademic A ON  A.Id = FR.SourceId 
			where A.Id=@rAcademicId and FS.ClassId=@rOldClassId AND A.BatchId=@rBatchId order by FS.FeeId

			SET @rOldFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #OldFeeSteupTempTable)

		IF(@rOldFeeSetupCount > 0)
			BEGIN			 
			 SET @rAdmissionCategoryId = (SELECT TOP 1 AdmissionCategoryId  FROM #OldFeeSteupTempTable)

				SELECT Id AS NewFeeSetupId,FeeId,Amount INTO #NewFeeSteupTempTable  FROM sFee.tFeeSetup 
				WHERE ClassId=@rNewClassId and BatchId=@rBatchId and AdmissionCategoryId=@rAdmissionCategoryId 
				And FeeId IN (SELECT FeeId from #OldFeeSteupTempTable)
				order by FeeId

				SET @rNewFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #NewFeeSteupTempTable)

					IF(@rOldFeeSetupCount > @rNewFeeSetupCount)
				BEGIN
				SELECT -103 AS Result
				RETURN
				END

				IF(@rNewFeeSetupCount > 0)
					BEGIN

					SELECT OldFee.ReceiptId,OldFee.FeeSetupId AS OldFeeSetupId,NewFee.NewFeeSetupId INTO #FinalFeeSteupTempTable  FROM #OldFeeSteupTempTable OldFee
					INNER JOIN #NewFeeSteupTempTable NewFee on NewFee.FeeId = OldFee.FeeId
					WHERE OldFee.Amount <= NewFee.Amount order by OldFee.FeeId

					SET @rFinalFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #FinalFeeSteupTempTable)

						IF(@rFinalFeeSetupCount > 0)
							BEGIN
								BEGIN TRY
								BEGIN TRANSACTION							 
									BEGIN
										BEGIN										
											UPDATE RD SET FeeSetupId =FS.NewFeeSetupId from sFee.tReceiptDetail RD 
											INNER JOIN #FinalFeeSteupTempTable FS ON FS.ReceiptId = RD.ReceiptId AND FS.OldFeeSetupId=RD.FeeSetupId

											UPDATE sStudent.tAcademic set ClassId=@rNewClassId,DivisionId=@rNewDivisionId WHERE Id=@rAcademicId AND ClassId=@rOldClassId AND DivisionId=@rOldDivisionId AND BatchId=@rBatchId AND OrgId=@rOrgId  
										END		
										SELECT 1 AS RESULT
									END 
									COMMIT TRANSACTION
								END TRY
								BEGIN CATCH 
									ROLLBACK TRANSACTION
									SELECT -104 AS Result
								END CATCH	
							END
						ELSE
							BEGIN
								SELECT -103 AS Result
							END
					END
				ELSE
					BEGIN
					SELECT -102 AS Result
					END
			END
		ELSE
			BEGIN
			SELECT -101 AS Result
			END
			END
END
GO
PRINT N'Altering [sFee].[pFeeAllocationAdd]...';


GO
ALTER PROCEDURE [sFee].[pFeeAllocationAdd]
	
	@rXmlDoc nvarchar(MAX),
	@rClassId int,
	@rDivisionId int,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rFeeSetupId int,
	@rCreatedUserId bigint,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lInterrorCode INT,
			@intDoc INT
	--BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	IF(@rFeeSetupId=0 AND @rClassId=0 AND @rSourceTypeId!=0 AND @rSourceId!=0)
	BEGIN
		DELETE FROM sFee.tFeeAllocation WHERE SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId
	END
	ELSE IF(@rFeeSetupId!=0 AND @rClassId!=0 AND @rSourceTypeId=0 AND @rSourceId=0)
	BEGIN
		DELETE sFee.tFeeAllocation FROM sFee.tFeeAllocation FA
		INNER JOIN (
			SELECT
			SourceTypeId,
			SourceId,
			FeeSetupId
			 
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId'
		 
	) )TEMP ON Temp.SourceId=FA.SourceId AND Temp.SourceTypeId=FA.SourceTypeId AND FA.FeeSetupId = Temp.FeeSetupId AND FA.FeeSetupId=@rFeeSetupId
		--)
		--INNER JOIN 
		--(
		--	SELECT
		--			2001 AS SourceTypeId,
		--			AcademicId 
		--	FROM 
		--			sStudent.vStudentAcademic WHERE ClassId=@rClassId AND DivisionId=@rDivisionId
		--) Temp ON Temp.AcademicId=FA.SourceId AND Temp.SourceTypeId=FA.SourceTypeId AND FeeSetupId=@rFeeSetupId
	END
	
	INSERT INTO sFee.tFeeAllocation
		(
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			NotApplicableAmount,
			AdditionalAmount,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark
		)
	SELECT
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			NotApplicableAmount,
			AdditionalAmount,
			Remark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark	
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId',
		VariableAmount decimal(12,2) '@VariableAmount',
		DiscountAmount decimal(12,2) '@DiscountAmount',
		NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
		AdditionalAmount decimal(12,2) '@AdditionalAmount',
		Remark nvarchar(200) '@Remark',
		DiscountRemark nvarchar(200) '@DiscountRemark',
		AdditionalRemark nvarchar(200) '@AdditionalRemark',
		NotApplicableRemark nvarchar(200) '@NotApplicableRemark'
	) 
		  
   DELETE FROM  sFee.tFeeAllocation WHERE ISNULL(VariableAmount,0) = 0 AND ISNULL(DiscountAmount,0) = 0 AND ISNULL(AdditionalAmount,0) = 0 AND ISNULL(NotApplicableAmount,0) = 0 
   
   SELECT 1 AS Result 
	
 --   UPDATE sFee.tFeeAllocation
 --   SET
	--	VariableAmount=Temp.VariableAmount,
	--	DiscountAmount=Temp.DiscountAmount,
	--	NotApplicableAmount=Temp.NotApplicableAmount,
	--	AdditionalAmount=Temp.AdditionalAmount,
	--	Remark=Temp.Remark,
	--	UpdatedUserId=@rCreatedUserId,
	--	UpdatedDateTime=sCommon.fGetDate() 
	--FROM sFee.tFeeAllocation FA 
	--INNER JOIN 
	--(SELECT
	--		SourceTypeId,
	--		SourceId,
	--		FeeSetupId,
	--		VariableAmount,
	--		DiscountAmount,
	--		NotApplicableAmount,
	--		AdditionalAmount,
	--		Remark
		
	--FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	--WITH
	--(
	--	SourceTypeId smallint '@SourceTypeId',
	--	SourceId bigint '@SourceId',
	--	FeeSetupId int '@FeeSetupId',
	--	VariableAmount decimal(12,2) '@VariableAmount',
	--	DiscountAmount decimal(12,2) '@DiscountAmount',
	--	NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
	--	AdditionalAmount decimal(12,2) '@AdditionalAmount',
	--	Remark nvarchar(200) '@Remark',
	--	IsRecordExist bit '@IsRecordExist'
	--) 
	--WHERE IsRecordExist=1) Temp ON Temp.SourceTypeId=FA.SourceTypeId 
	--	AND Temp.SourceId=FA.SourceId
	--	AND Temp.FeeSetupId=FA.FeeSetupId
 	 
	--	SELECT 11 AS Result    
		
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeeAllocationGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeAllocationGet]
	 
		
		@rSourceId bigint ,
		@rSourceTypeId int,
		@rBatchId int,
		@rStudentId bigint =0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	if (@rStudentId <> 0)
	SELECT @rSourceId = Id, @rSourceTypeId = 2001 FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
		DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId

SELECT 
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			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.NotApplicableAmount,0.00) AS NotApplicableAmount,
			ISNULL(FA.Remark,'') AS Remark,
			ISNULL(FA.NotApplicableRemark,'') AS NotApplicableRemark,
			ISNULL(FA.AdditionalRemark,'') AS AdditionalRemark,
			ISNULL(FA.DiscountRemark,'') AS ExemptionRemark,
			FM.OrderIndex,
			0 AS ReceiptNumber,
			'1900-01-01'AS ReceiptDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			FS.CollectionGroupId,
			FM.FeeHeadId,
			FS.FeeDuration
			
  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,
				ISNULL(FS1.FeeDuration,'')  AS FeeDuration
			FROM sFee.tFeeSetup FS1
			   
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = @rBatchId
				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 ,
				ISNULL(FS1.FeeDuration,'') AS FeeDuration
				 
			FROM sFee.tFeeSetup FS1
			 
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND(FO.SourceTypeId=@rSourceTypeId)
			WHERE
			 FS1.BatchId = @rBatchId
			AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
		) FS ON FS.FeeId=FM.Id
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
		    FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
			WHERE						
			 R.SourceId= @rSourceId
			AND ((R.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))
			AND R.IsObsolete = 0 
			AND R.BatchId = @rBatchId
			 GROUP BY FeeSetupId
		) R ON R.FeeSetupId = FS.Id	
WHERE 
	FS.BatchId=@rBatchId
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC
END
GO
PRINT N'Altering [sFee].[pHTMLFeeReceiptDetailsGet]...';


GO
ALTER PROCEDURE [sFee].[pHTMLFeeReceiptDetailsGet]
			
			
			
			@rReceiptId bigint = 0
			  

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

	SELECT 
			FR.Id AS ReceiptId,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,			
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.BatchName AS BatchTitle,
			
			
			--FRD.Amount AS PaidAmount,
			FR.ReceiptAmount 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,	
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE '' END 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,	
			sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,0) AS ReceiptAmountInWord,
			FR.Remark,
			RBM.ReportId,
			--OM.Title AS OrganizationName,
			--DM.Title AS DepartmentName,			
			FR.IsObsolete AS IsCancelReceipt,			
			ISNULL(CONVERT(NVARCHAR(20), FR.ChequeDate),'') AS ChequeDate
			
	       
	FROM 
	
			sFee.tReceipt FR				
			
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId			
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))			
   
   -- ORDER BY             FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC

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,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,
			ISNULL(SC.PresentStreetOne +','+ SC.PresentStreetTwo +','+ SC.PresentStreetThree +','+ SC.PresentCity +','+ SC.PresentState +'-'+ SC.PresentZipCode ,'') AS PresentAdress,
			SC.ParentContactNo
	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
	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

--For Dataset

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


GO
 
ALTER PROCEDURE [sFee].[pRptFeeSummaryGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0  
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	
	IF(@rReportId=20624 OR @rReportId=20842 OR @rReportId=10150)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			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(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			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,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			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.FeeHeadId
				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.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 ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.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,
					SA1.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.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			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 ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) 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 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 sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						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 sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 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)) 
			 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 = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		Order by SA.RollNo 
	END
	ELSE IF(@rReportId=30655)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			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(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			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,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			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.FeeHeadId
				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.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 ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.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,
					SA1.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.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			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 ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) 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 RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
						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 sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 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)) 
			 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 = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  ISNULL(FA.NotApplicableAmount,0) > 0) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		
		Order by SA.RollNo
	END
	ELSE
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			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(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			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,
			CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

			CASE WHEN ISNULL(DiscountRemark,'') ='' THEN ''
			ELSE
			(STUFF((SELECT ISNULL(DiscountRemark,'') +','	FROM sFee.tFeeAllocation WHERE SourceId = FA.SourceId	
			ORDER BY DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) END as ExampltedRemark,

			CASE WHEN ISNULL(FA.AdditionalRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,3) END as AdditionalRemark,
			CASE WHEN ISNULL(FA.NotApplicableRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,4) END as NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			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.FeeHeadId
				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.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 ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.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,
					SA1.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.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			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 ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) 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 RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
						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 sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 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)) 
			 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 = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		
		Order by SA.RollNo
	END
	
	
	
END
GO
PRINT N'Altering [sFrontOffice].[pRptOutwardRegisterGet]...';


GO
ALTER PROCEDURE [sFrontOffice].[pRptOutwardRegisterGet]

	
	--@rId int = 0,
	 @rOrgId smallint=0,
	 @rFromDate date='',
	 @rToDate date='',
	 @rLetterTo nvarchar(300)='',
	 @rLetterSubject nvarchar(300)='',
	 @rIsReplyRequired bit=0,
	 @rReplied int=0,
	 @rOutwardNumber int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			--SET @rLetterFrom = sCommon.fSearchStringGet(@rLetterFrom) 
			
BEGIN 
	 
	SELECT 
	
			OWR.OutwardNumber,
			OWR.LetterNumber AS OutwardLetterNumber,
			OWR.LetterDate AS OutwardLetterDate ,
			OWR.OutwardDate,
			OWR.LetterTo,
			OWR.LetterSubject,
			OWR.ReplyDetail,
			OWR.Remark,
			IR.LetterDate As InwardLetterDate,
			IR.LetterNumber As InwardLetterNumber,
			IRO.LetterDate ,
			IRO.LetterNumber,
			OWR.LetterRemark,
			OM.Title AS OrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			OM.OrgLogo
			
		
      
  FROM 
           sFrontOffice.tOutwardRegister OWR
           LEFT JOIN  sFrontOffice.tInwardRegister IR ON OWR.Id=IR.OutwardRegisterId
           LEFT JOIN  sFrontOffice.tInwardRegister IRO ON IRO.Id = OWR.InwardRegisterId
           INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=OWR.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
            
            
  WHERE 
  
     -- ((Id = @rId) OR (@rId = 0))
     ((OWR.LetterTo LIKE @rLetterTo) OR (ISNULL(@rLetterTo,'') = ''))
	AND ((OWR. OutwardDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND (( OWR.OutwardDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((OWR.LetterSubject LIKE @rLetterSubject) OR (ISNULL(@rLetterSubject,'') = ''))
	AND  ((OWR.IsReplyRequired=@rIsReplyRequired) OR(ISNULL(@rIsReplyRequired,0)=0))
	AND((OWR.IsReplied=@rReplied)  OR (ISNULL(@rReplied,2)=2))
	AND OWR.OrgId=@rOrgId
	AND ((OWR.OutwardNumber=@rOutwardNumber) OR (@rOutwardNumber=0))
	
	ORDER BY OWR.OutwardNumber ASC
END
GO
PRINT N'Altering [sFrontOffice].[pVisitorLogGet]...';


GO

ALTER PROCEDURE [sFrontOffice].[pVisitorLogGet]
          
           @rVisitorId int,
           --@rOutTimeFrom datetime,
           --@rOutTimeTo datetime,
           @rFromVisitDate datetime,
           @rToVisitDate datetime,
           @rOrgId int,
           @rWhomToMeetName nvarchar(100),
           @rIsPrintView bit=0,
           @rOrgGroupId int =0,
           @rTypeId int=0 
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rWhomToMeetName = sCommon.fSearchStringGet(@rWhomToMeetName)
		--END
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId


BEGIN
SELECT  
	   VL.Id As VisitorId,
       VL.VisitorName,
       VL.NoOfVisitor,
       VL.PurposeOfVisit,
       VL.WhomToMeet AS WhomToMeetId,
       VL.WhomToMeetName,
       VL.InTime,
       VL.OutTime,
       ISNULL(VL.VisitDate,'1900-01-01 00:00:00') AS VisitDate,
       --VL.CreatedDateTime ,
       (CASE  WHEN @rIsPrintView=1 THEN 
				VL.VisitorPhoto		
			ELSE ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
       --ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
       VL.OrgId,
       ISNULL(OM.DisplayTitle,'') AS Organization,
       ISNULL(Remark,'') AS Remark,
       @GatePassConfig AS ConfigValue,
	   ISNUll(VisitorContactNumber,'') AS VisitorContactNumber,
	   ISNULL(StudentId,0) AS StudentId,
	   (CASE WHEN ISNULL(VL.StudentId,0)=0 THEN 'Visitor'
			 ELSE 'Parents' END) AS VisitorType
		
  FROM  sFrontOffice.tVisitorLog VL 
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId
 
  WHERE 
	(VL.OrgId=@rOrgId OR @rOrgId=0) AND OM.OrgGroupId=@rOrgGroupId
	AND (VL.Id=@rVisitorId OR @rVisitorId=0)
	AND ((VL.WhomToMeetName LIKE @rWhomToMeetName) OR (ISNULL(@rWhomToMeetName,'')=''))
	AND (VL.VisitDate>=@rFromVisitDate OR ISNULL(@rFromVisitDate,'')='')
	AND (VL.VisitDate<=@rToVisitDate OR ISNULL(@rToVisitDate,'')='')
	AND ( (ISNULL(VL.StudentId,1) = @rTypeId) OR  (@rTypeId=0) OR (((VL.StudentId > 0 AND @rTypeId=2) OR  @rTypeId=0))) -- Visitor 
	 -- Parents
  ORDER BY VL.VisitDate DESC,VL.InTime DESC
END
GO
PRINT N'Altering [sHrm].[pEmployeeAttendanceGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeAttendanceGet]
	 
	@rForYear  bigint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int,
	@rDepartmentId int=0
 
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 
			WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
			THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 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,
		ISNULL(CONVERT(VARCHAR(50),EM.DateOfJoining,103),'') AS DateOfJoining,
		ISNULL(CONVERT(VARCHAR(50),EM.DateOfLeaving,103),'') AS DateOfLeaving
		
	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'
		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	ORDER BY 
		EM.Code
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeIcardGet]...';


GO
ALTER PROCEDURE [sHrm].[pRptEmployeeIcardGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint,
	@rIsShowBarcode bit=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ECD.EmployeeId,
	        ECD.Code,	      	
			ECD.EmployeeName, 	 								 
			ECD.DepartmentId,  			
			ECD.DepartmentName,
		    ECD.MobileNumber,
		    ECD.EmployeeDesignation,
		    ECD.PhoneNoCompany,
		    ECD.BloodGroup,
		    ECD.DateOfBirth,
			EI.EmployeePhoto,
		    OM.Title AS OrgName,
		    OM.PrincipalSignature,
			ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,
			ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,
			ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,
			ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,	
		    OM.OrgLogo AS ICardLogo,
			ICO.ICardBackground,	
			ICO.ICardBackBackground,						
			ISNULL(ICO.LabelColor,'Black') AS LabelColor,
			ISNULL(ICO.DetailColor,'Black') AS DetailColor,
			ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,
			ISNULL(EC.PresentStreetOne,'') AS PresentStreetOne,
			ISNULL(EC.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(EC.PresentStreetThree,'') AS PresentStreetThree,
			ISNULL(EC.PresentCity,'') AS PresentCity,
			ISNULL(EC.PresentState,'') AS PresentState,
			ISNULL(EC.PresentCountry,'') AS PresentCountry,
			ISNULL(EC.PresentZipCode,'') AS PresentZipCode,
			ECD.DateofJoining,
			EI.EmployeeSign,
			@rIsShowBarcode As IsShowBarcode,
			ISNULL(EC.EmergencyStreetOne,'') AS EmergencyStreetOne,
			ISNULL(EC.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
			ISNULL(EC.EmergencyStreetThree,'') AS EmergencyStreetThree,
			ISNULL(EC.EmergencyCity,'') AS EmergencyCity,
			ISNULL(EC.EmergencyState,'') AS EmergencyState,
			ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(PanNumber,'') AS PanNumber,
			EC.EmergencyContactNo AS EmergencyContactNo,
			EPD.Qualification AS Qualification,
			ISNULL(EFD.Name,'')AS FatherName
		FROM 
			sHrm.vEmployeeCommonDetail ECD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ECD.OrgID
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeeICardOrg ICO ON ECD.OrgId = ICO.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON ECD.EmployeeId = EC.EmployeeId
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther EO ON EO.EmployeeId = ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EO.EmployeeId
			LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on ECD.EmployeeId=EFD.EmployeeId 
			LEFT JOIN sCommon.tRelationshipMaster RM on EFD.RelationshipId=RM.Id AND RM.Id=2
			
		WHERE
		((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
	  
END
GO
PRINT N'Altering [sIp].[pImportStockIem]...';


GO
-- exec [sIp].[pImportStockIem]
-- drop proc [sIp].[pImportStockIem]
ALTER PROCEDURE [sIp].[pImportStockIem]
	@rOrgId int,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rStoreLocationId int,
	@rOrgGroupId smallint,
	@rLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,@intDoc INT,@lCode nvarchar(20),
	@lName nvarchar(100),@lSubGroup nvarchar(100),
	@lStockItemCategory nvarchar(100),@lIssueUOM nvarchar(50),
	@lSubGroupId int,@lStockItemCategoryId int,@lIssuUOMId int,
	@lResult int,@lresultCode nvarchar(100),@lIsBatchWiseTracking bit,
	@lSafetyStock decimal(12,2),@lStandardDose nvarchar(500),@lReminder nvarchar(500)
	Declare @lbinCode nvarchar(20),@lVendorCode nvarchar(50),@lVendorCategory nvarchar(50),
	@lBinId int,@lVendorId int, @lVendorCategoryId int

	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

	CREATE TABLE #tTable1 
	(
		Id int identity,Code nvarchar(50),Name nvarchar(100),SubGroup nvarchar(100),
		StockItemCategory nvarchar(100),IssueUOM nvarchar(50),SafetyStock decimal(12,2),
		BinCode nvarchar(50),VendorCode nvarchar(50), IsBatchWiseTracking bit 
	)
	INSERT INTO #tTable1
	(
		Code,Name,SubGroup,StockItemCategory,IssueUOM,SafetyStock,BinCode,
		VendorCode, IsBatchWiseTracking
	)      
	SELECT Code,Name,SubGroup,StockItemCategory,IssueUOM,SafetyStock,BinCode,
	VendorCode, IsBatchWiseTracking
	FROM OPENXML (@intDoc, '/Table/ImportStockItem', 1)
	With
	(   
		Code nvarchar(20) '@Code',Name nvarchar(100) '@Name',
		SubGroup nvarchar(100) '@SubGroup',
		StockItemCategory nvarchar(100) '@StockItemCategory',
		IssueUOM nvarchar(50) '@IssueUOM',
		SafetyStock decimal(12,2) '@SafetyStock',
		BinCode nvarchar(50) '@BinCode',
		VendorCode nvarchar(50) '@VendorCode',
		--VendorCategory nvarchar(50) '@VendorCategory',
		IsBatchWiseTracking bit '@IsBatchWiseTracking'
	)
	EXEC sp_xml_removedocument @intDoc
	SELECT @lCount = COUNT(Id) FROM #tTable1
	PRINT @lCount
	WHILE @lCount > 0 
	BEGIN
		SELECT @lCode = Code,@lName = Name,@lSubGroup = SubGroup,
		@lStockItemCategory = StockItemCategory,@lIssueUOM = IssueUOM,
		@lSafetyStock=SafetyStock,@lbinCode=BinCode,
		@lVendorCode=VendorCode, @lIsBatchWiseTracking=IsBatchWiseTracking
		FROM #tTable1 WHERE Id = @lCount
		
		IF NOT EXISTS(SELECT 1 FROM sIp.tStockItemMaster where Code = @lCode AND StoreLocationId = @rStoreLocationId)           
		BEGIN
			SELECT @lSubGroupId = Id From sIp.tItemSubGroupMaster where Title = @lSubGroup
			SELECT @lStockItemCategoryId= Id From sIp.tStockItemCategoryMaster 
			where Title = @lStockItemCategory AND Storelocationid=@rStoreLocationId
			
			Select @lBinId = Id from sIp.tBinMaster where StoreLocationId =@rStoreLocationId And Code = @lBinCode
			Select @lVendorId = Id from sProcurement.tVendorMaster where LocationId= @rStoreLocationId And Code=@lVendorCode
			--Select @lVendorCategoryId=Id from sProcurement.tVendorCategoryMaster Where OrgGroupId =@rOrgGroupId And Code=@lVendorCategory
			
			SELECT @lIssuUOMId= Id From sFinanceCommon.tStockUomMaster where Title = @lIssueUOM AND OrgGroupId=@rOrgGroupId
			
			
			if  @lBinId is null	
			BEGIN
				Select -1 As Result
				Return
END
			if @lVendorId is null
			BEGIN
				Select -2 As Result
				Return
			END
			
			if @lIssuUOMId is null
			BEGIN
				Select -11 As Result
				Return
			END
			--Select @lIssuUOMId AS IssuUOMId,@lStockItemCategoryId AS StockItemCategoryId,@lSubGroupId AS SubGroupId
			--SET @lResult = -101
			 print @lIssuUOMId
			IF(@lSubGroupId > 0  AND @lIssuUOMId>0)
			BEGIN
				DECLARE @lNextNumber INT
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sIp.tStockItemMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				  
				INSERT INTO	sIp.tStockItemMaster
				(
					Id,Code,Title,CreatedUserId,CreatedDateTime,UpdatedUserId,
					UpdatedDateTime,StockItemCategoryId,IsBatchWiseTracking,
					IssueStockUomId,ItemSubGroupId,SafetyStock,VendorId,
					IsObsolete,OrgGroupId,TaxGroupId,Remark,IsBlockedForIssue,
					StoreLocationId,LocationId,StandardDose,BinId,Reminder
				)
				VALUES
				(
					@lNextNumber,@lCode,@lName,@rUserId,sCommon.fGetDate(),
					@rUserId,sCommon.fGetDate(),@lStockItemCategoryId,
					@lIsBatchWiseTracking,@lIssuUOMId,@lSubGroupId,
					@lSafetyStock,@lVendorId,0,@rOrgGroupId,null,null,0,
					@rStoreLocationId,@rLocationId,null,@lBinId,@lReminder
				)
				
				
	EXECUTE [sIp].[pStockItemPlanningAdd] 0,@lNextNumber,0,0,0,0,null,null,@rStoreLocationId,@rOrgGroupId
  	  EXECUTE sProcurement.pStockBatchAdd  @rOrgGroupId,@rStoreLocationId,@lNextNumber,null,null,0,@rUserId ,0 
  	
	--EXECUTE	sIp.pStockItemPurchaseUomAdd @rOrgGroupId,@lNextNumber,@rIssueStockUomId,1,0,@rCreatedUserId	
	--EXEC [sIp].[pItemStandardPriceLogAdd] @lNextNumber, @rStandardPrice, @rCreatedUserId,@rOrgGroupId
 
				SET @lResult = 1
				
			Set @lresultCode= @lCode
				 
			END
		END  
		else
		BEGIN
			Set @lResult=-101
			Set @lresultCode= @lCode
		END
		SET @lCount = @lCount - 1
	END
	Select @lResult AS Result,@lresultCode AS Code
END
GO
PRINT N'Altering [sLibrary].[pReturnDueListGet]...';


GO

ALTER PROCEDURE [sLibrary].[pReturnDueListGet]
	 @rReaderSourceTypeId smallint,
	 @rReaderCode nvarchar(20),
	 @rReaderName nvarchar(200),
	 @rResourceCode nvarchar(25),
	 @rResourceName nvarchar(100),
	 @rDueDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rLibraryId int,
	 @rOrgGroupId int=0,
	 @rSUId nvarchar(20)='',
	 @rClassId int=0,
	 @rDepartmentId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
		
		SET @rReaderCode = sCommon.fSearchStringGet(@rReaderCode)
		SET @rReaderName = sCommon.fSearchStringGet(@rReaderName)
		SET @rResourceCode = sCommon.fSearchStringGet(@rResourceCode)
		SET @rResourceName = sCommon.fSearchStringGet(@rResourceName)
		
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'Student' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReaderSourceId,
			SC.Code AS ReaderCode,
			SC.Name AS ReaderName,
			SC.ClassName+'-'+SC.DivisionName AS ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			CASE WHEN BL.StatusId = 521 Then 'Return' ELSE SM.Title END AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1),'[Name]',SC.Name),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS EmailTemplate,
			replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=2),'[Name]',SC.Name),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS SMSTemplate,

			 replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=3),'[Name]',SC.Name),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS MobileTemplate,

			 (SELECT E.MailSubject FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1) AS MailSubject,
			 LM.Id AS LibraryId,
			 LM.Title AS LibraryName,
			 LM.ReportOrgTitle,
	         LM.SmallAddress1,
	         LM.SmallAddress2,
	         VA.SUId
			 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND BL.BatchId = SC.BatchId
			INNER JOIN sStudent.vStudentLastAcademic VA ON VA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND BL.BatchId = SC.BatchId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			(BL.ReaderSourceTypeId=@rReaderSourceTypeId OR @rReaderSourceTypeId=0)
		AND ((SC.Code Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND ((SC.Name Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		--AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		--AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.DueDate<=@rDueDate) AND (BL.IsCurrentStatus=1)
		AND (BL.StatusId = 523) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId
		AND ((VA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
		AND ((VA.ClassId=@rClassId)OR(@rClassId=0))
		AND(VA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
	UNION ALL

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'Employee' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReaderSourceId,
			EC.Code AS ReaderCode,
			EC.FirstName+' '+EC.LastName AS ReaderName,
			EC.DepartmentName as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			CASE WHEN BL.StatusId = 521 Then 'Return' ELSE SM.Title END AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			EC.PhoneNoCompany AS MobileNo,
			EC.CompanyEmail AS EmailId,
			replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1),'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS EmailTemplate,
			 replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=2),'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS SMSTemplate,
			  replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=3),'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS MobileTemplate,
			 (SELECT E.MailSubject FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1) AS MailSubject,
			 LM.Id AS LibraryId,
			 LM.Title AS LibraryName,
			 LM.ReportOrgTitle,
	         LM.SmallAddress1,
	         LM.SmallAddress2,
	         '' AS SUId
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.vEmployeeCommunication EC ON EC.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95 AND BL.OrgId=EC.OrgId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			
	WHERE 
			(BL.ReaderSourceTypeId=@rReaderSourceTypeId OR @rReaderSourceTypeId=0)
		AND ((EC.Code Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND ((EC.FirstName+' '+EC.LastName Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		--AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		--AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.StatusId = 523) 
		AND (BL.DueDate<=@rDueDate) AND  (BL.IsCurrentStatus=1)
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId
		AND(EC.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
		
	UNION ALL

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'' AS ReaderSourceType,
			0 AS ReaderSourceTypeId,
			0 AS ReaderSourceId,
			'' AS ReaderCode,
			'' AS ReaderName,
			'' as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			SM.Title AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			'' AS MobileNo,
			'' AS EmailId,
			'' AS EmailTemplate,
			'' AS SMSTemplate,
			'' AS MailSubject,
			'' AS MobileTemplate,
			LM.Id AS LibraryId,
			LM.Title AS LibraryName,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2,
	        '' AS SUId
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			(ISNULL(BL.ReaderSourceTypeId,0)=@rReaderSourceTypeId AND @rReaderSourceTypeId=0)
		AND (('' Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND (('' Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		--AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		--AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.StatusId = 523) 
		AND (BL.DueDate<=@rDueDate) AND (BL.IsCurrentStatus=1) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Altering [sMis].[pRptClassCapacityGet]...';


GO
ALTER PROCEDURE [sMis].[pRptClassCapacityGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		@rOrgGroupBatchId int,
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0,
		@rIsDisplayOrgGroup bit=0,
		@rBatchGroupId int=0,
		@rStatusId int=0,
		@rStudentStatusId int=0,
		@rUptoDate datetime = ''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			(SELECT COUNT(1) FROM sSetup.tDivisionMaster DM WHERE DM.ClassId=CM.Id) AS DivisionCount,
			ISNULL(CM.Capacity,0) AS Capacity,
			
			(SELECT ISNULL(count(1),0)  FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id = BM.BatchGroupId 
			INNER JOIN sStudent.tStudentAdmission  SA on SA.StudentId = SM.Id 
			WHERE A.ClassId = CM.Id 
			AND SA.AdmissionDate < @rUptoDate
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((BGM.Id = @rBatchGroupId) OR (@rBatchGroupId = 0)) 
			AND ((SM.StatusId = @rStudentStatusId) OR (@rStudentStatusId=0))) 
			AS CurrentStrength,
			
			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sStudent.tStudentAdmission  SA on SA.StudentId = SM.Id AND SA.leftDate <= @rUptoDate
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id  
			AND BM.OrgId=CM.OrgId AND BM.OrgGroupBatchId=@rOrgGroupBatchId
			WHERE  A.ClassId = CM.Id)
			AS AdmissionLeft,
			
			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sStudent.tStudentAdmission  SA on SA.StudentId = SM.Id AND SA.AdmissionDate = @rUptoDate
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id  
			AND BM.OrgId=CM.OrgId AND BM.OrgGroupBatchId=@rOrgGroupBatchId AND SM.StatusId = 1
			WHERE  A.ClassId = CM.Id) 
			AS AdmissionGiven,

			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			AND BM.OrderIndex = (SELECT TOP 1 BM.OrderIndex -1 FROM sSetup.tBatchMaster BM	INNER JOIN  sSetup.tOrgGroupBatchMaster ORGM ON BM.OrgGroupBatchId=ORGM.Id
			WHERE BM.OrgId=CM.OrgId 
			AND BM.OrgGroupBatchId=@rOrgGroupBatchId ORDER BY BM.OrderIndex DESC
			) WHERE A.ClassId = CM.Id AND SM.StatusId = 1) 
			AS PreviousStrength
	FROM 
			sSetup.tClassMaster CM
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
	WHERE 
			((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering [sProcurement].[pRptStockIssueRegisterGet]...';


GO
ALTER PROCEDURE [sProcurement].[pRptStockIssueRegisterGet]
    @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100),
	@rOrgGroupId int,
	@rFromDate date = '',
	@rToDate date = '',
	@rDetail bit =0,
	@rToDepartmentId int=0,
	@rIssuedToName nvarchar(100)
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
		SIM.Code AS ItemCode,
		SIM.Title AS ItemName,		
		SI.IssuedByName,	
		SI.Number AS Billno, 	
		SI.CreatedDateTime AS IssuedDate,
		ID.IssuedQuantity,
		ID.RequestedQuantity,
		 
		--SI.POReference AS POReference,
		--SI.InvoiceReference AS InvoiceReference,
		--VM.Code As SupplierCode,
		--VM.Title As SupplierName,
		SB.ExpiryDate,
		SIP.WeightedAverageCost AS Amount,
		SB.Number As BatchNumber,
		SI.Id AS  StockInwardId,
		@rDetail AS Detail,
		@rBuilder1 As Builder1,
		@rBuilder2 AS Builder2,
		SUOM.Title AS UOM,
		SI.IssueToName,
		SI.TransactionDate 
				
   FROM  sProcurement.tStockIssue SI		
		INNER JOIN sProcurement.tStockIssueDetail ID ON SI.Id = ID.StockIssueId
		INNER JOIN sProcurement.tStockIssueBatch SIB ON ID.Id = SIB.StockIssueDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
	    LEFT JOIN sProcurement.tStockBatch SB ON SB.Id = SIB.StockBatchId
	    --LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id = SI.VendorId
	    INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
		INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
		LEFT JOIN sIp.tStockItemCategoryMaster SICM ON SICM.Id=SIM.StockItemCategoryId	
		INNER JOIN sFinanceCommon.tStockUomMaster SUOM ON SUOM.Id = SIM.IssueStockUomId
		 
   WHERE	     
	     SIM.IsObsolete=0
		AND(SB.StoreLocationId= @rStoreLocationId)
		AND (IMGM.Id = @rMainGroupId OR @rMainGroupId=0)
		AND (ISGM.Id = @rSubGroupId OR @rSubGroupId=0)
		AND (SICM.Id = @rStockItemCategoryId OR @rStockItemCategoryId = 0)
		AND (SIM.Code = @rItemCode OR @rItemCode = '')
		AND (SIM.Title = @rItemName OR @rItemName = '')
		AND ((convert(Date,ISNULL(SI.CreatedDateTime,'')) >= @rFromDate) OR (convert(date,ISNULL(@rFromDate,''))=''))
	    AND ((convert(date,ISNULL(SI.CreatedDateTime,'')) <= @rToDate) OR (convert(date,ISNULL(@rToDate,''))=''))
		AND (SI.OrgGroupId = @rOrgGroupId)
		AND ((SI.ToOrganizationDepartmentId = @rToDepartmentId) OR (@rToDepartmentId=0))
		AND ((SI.IssueToName = @rIssuedToName) OR (@rIssuedToName = ''))
    Order  by SIM.Title	
	
END
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',
	@rIssueToSourceId BIGINT = null
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,
				 isnull(SI.IssueToSourceId,'') as IssueToSourceId,
				 ISNULL(SI.ToOrganizationDepartmentId,'') as ToDeapartment
				FROM sProcurement.tStockIssue SI 
				WHERE
				SI.OrgGroupId = @rOrgGroupId
				AND  ((Number like @rNumber) OR (@rNumber = ''))
				AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SI.FromStoreLocationId=@rStoreLocationId 
				AND ((SI.IssueToSourceId = @rIssueToSourceId) OR (ISNULL(@rIssueToSourceId,'')=''))
				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,
					isnull(SI.IssueToSourceId,'') as IssueToSourceId
				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='')
				AND (SI.IssueToSourceId = @rIssueToSourceId)
				Order by SI.CreatedDateTime desc
		end
END
GO
PRINT N'Altering [sScholarship].[pRptScholarshipEligibleStudentGet]...';


GO


ALTER PROCEDURE [sScholarship].[pRptScholarshipEligibleStudentGet]
          
           @rScholarshipId int,
           @rAcademicId bigint,
		   @rBatchId int =0 
AS
SET NOCOUNT ON
BEGIN
SELECT 
		STM.Title AS ScholarshipTypeName,
        SM.Title AS ScholarshipName,
        vSA.Code,
        vSA.Name AS StudentName,
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(SES.AcademicId,0) AS AcademicId,
        ISNULL(SES.ScholarshipId,0) AS ScholarshipId,
        ISNULL(SES.EligibleAmount,0) AS EligibleAmount
		
  FROM  sScholarship.tScholarshipEligibleStudent SES
	INNER JOIN  sScholarship.tScholarshipMaster SM ON SM.Id=SES.ScholarshipId
	INNER JOIN  sScholarship.tScholarshipTypeMaster STM ON STM.Id=SM.ScholarshipTypeId
    LEFT JOIN sStudent.vStudentAcademic vSA ON SES.AcademicId=vSA.AcademicId
  WHERE 
		(SES.ScholarshipId=@rScholarshipId OR @rScholarshipId=0)
		AND (SES.AcademicId=@rAcademicId OR @rAcademicId=0)
		AND (SM.BatchId=@rBatchId OR @rBatchId=0)

		order by ClassDivisionName
END
GO
PRINT N'Altering [sScholarship].[pRptScholarshipReceiveGet]...';


GO

ALTER PROCEDURE [sScholarship].[pRptScholarshipReceiveGet]
			
           @rId int,
           @rScholarshipId int,
		   @rBatchId int =0 
AS
SET NOCOUNT ON
BEGIN
SELECT  
		SR.Id,
		SR.ScholarshipId,
		SR.Title,
		SR.ReceiveDate,
		SR.TotalAmount,
		SR.ChequeNumber,
		SR.BankName,
		SR.Remark,
		SM.Title AS ScholarshipName,
		STM.Title AS ScholarshipTypeName
		
  FROM  sScholarship.tScholarshipReceive SR
	INNER JOIN  sScholarship.tScholarshipMaster SM ON SM.Id=SR.ScholarshipId
	INNER JOIN  sScholarship.tScholarshipTypeMaster STM ON STM.Id=SM.ScholarshipTypeId
  WHERE 
		(SR.Id=@rId OR @rId=0)
		AND (SR.ScholarshipId=@rScholarshipId OR @rScholarshipId=0) 
		AND (SM.BatchId=@rBatchId OR @rBatchId=0)
END
GO
PRINT N'Altering [sScholarship].[pRptScholarshipStudentPaidGet]...';


GO
ALTER PROCEDURE [sScholarship].[pRptScholarshipStudentPaidGet]
          
           @rScholarshipReceiveId bigint,
           @rScholarshipId int,
		   @rBatchId int =0 
AS
SET NOCOUNT ON
BEGIN
SELECT  
		STM.Title AS ScholarshipTypeName,
        SM.Title AS ScholarshipName,
        ISNULL(SES.AcademicId,0) AS AcademicId,
        ISNULL(SR.Id,0) AS ScholarshipReceiveId,
        ISNULL(SR.Title,'') AS ScholarshipReceiveName,
        ISNULL(SSP.PaidDate,sCommon.fGetDate()) AS PaidDate,
        ISNULL(SSP.PaidAmount,0) AS PaidAmount,
        ISNULL(SSP.ChequeNumber,'') AS ChequeNumber,
        ISNULL(SSP.BankName,'') AS BankName,
        ISNULL(SSP.Remark,'') AS Remark,
        vSA.Code,
        vSA.Name AS StudentName,
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName
		
  FROM 		
	  	sStudent.vStudentAcademic vSA
		INNER JOIN sScholarship.tScholarshipEligibleStudent SES ON SES.AcademicId =vSA.AcademicId
		INNER JOIN sScholarship.tScholarshipMaster SM ON SM.Id= SES.ScholarshipId
		INNER JOIN  sScholarship.tScholarshipTypeMaster STM ON STM.Id=SM.ScholarshipTypeId
		INNER JOIN sScholarship.tScholarshipReceive SR ON SR.ScholarshipId = SM.Id
		LEFT JOIN sScholarship.tScholarshipStudentPaid SSP ON SSP.ScholarshipReceiveId = SR.Id AND SSP.AcademicId = SES.AcademicId
  WHERE 
		(SR.Id=@rScholarshipReceiveId OR @rScholarshipReceiveId=0)
		AND (SM.Id=@rScholarshipId OR @rScholarshipId=0)
		AND SSP.PaidAmount <> 0
		AND (SM.BatchId=@rBatchId OR @rBatchId=0)
		order by ClassDivisionName
END
GO
PRINT N'Altering [sSecurity].[pDashletGet]...';


GO
ALTER PROCEDURE [sSecurity].[pDashletGet]
	@rOrgGroupId int=0,
	@rDate date='',
	@rDashletId int=0,
	@rOrgGroupBatchId int=0,
	@rUserId bigint=0,
	@rUserSourceId bigint=0,
	@rUserSourceTypeId int=0,
	@rOrgId Int=0,
	@rSourceTypeId smallint=0,
	@rSourceId bigint=0,
	@rBatchId int=0,
	@rExamId int=0,
	@rStatusId int =0
	
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
DECLARE @TimeZoneDate datetime
SET  @TimeZoneDate=sCommon.fGetDate()
if(@rDashletId='1')
       BEGIN
        exec sCommunication.pCircularListGet @rUserSourceId=@rUserSourceId,@rOrgGroupBatchId=@rOrgGroupBatchId,@rUserSourceTypeId=@rUserSourceTypeId,@rUserId=@rUserId,@rStartDate=@rDate
        END
 if(@rDashletId='2')
        BEGIN
        SELECT  N.Id,N.Title FROM sCommunication.tNews N WHERE N.OrgGroupBatchId=@rOrgGroupBatchId AND Convert(date,N.CreatedDateTime)=convert(date,@TimeZoneDate)
        END
 if(@rDashletId='3')
          BEGIN
        exec sActivity.pMyEventGet @rSourceTypeId=@rSourceTypeId,@rSourceId=@rSourceId,@rOrgId=@rOrgId,@rBatchId=@rBatchId,@rFromDate=@rDate,@rToDate=@rDate
          END
if(@rDashletId='4')
        BEGIN
        exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=1,@rStatus=0,@rIsSearch=1
        END
 if(@rDashletId='5')
        BEGIN
        exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=0,@rStatus=0,@rIsSearch=1
        END
 if(@rDashletId='6')
        BEGIN
       
        SELECT 	EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName AS Name,	EM.DepartmentName  FROM [sHrm].[vExtEmployeeMaster] EM	
        WHERE  	EM.OrgId = @rOrgId  
         AND (MONTH(EM.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND EM.DateOfBirth!='' AND EM.StatusId=7
	    AND (DAY(EM.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))   
		
        END
 if(@rDashletId='7')
        BEGIN
        SELECT SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name, SC.ClassName+' '+SC.DivisionName AS ClassName FROM sStudent.vStudentAllDetail SC WHERE SC.OrgId=@rOrgId AND SC.BatchId=@rBatchId
         AND (MONTH(SC.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND SC.DateOfBirth!='' AND SC.StatusId=1
	    AND (DAY(SC.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))   
        END
         if(@rDashletId='10')
        BEGIN
       exec sAttendance.pDashletAttendanceStatusGet @rAcademicId=@rSourceId
        END
   
   if(@rDashletId='11')
        BEGIN
       SELECT EM.EmployeeName,L.FromDate,L.ToDate FROM  sHrm.tLeave L 
        INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId	
        INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
         WHERE  
			   BM.OrgGroupBatchId = @rOrgGroupBatchId
			   AND L.OrgId = @rOrgId
			   AND (EJD.EmployeeManagerId = @rUserSourceId OR @rUserSourceId = 0)
			   AND ((L.FromDate >= @rDate) OR (ISNULL(@rDate,'') = ''))
			   AND EM.EmployeeStatusId=7
             
       -- exec [sHrm].[pLeaveListingGet] @rOrgId=@rOrgId,@rEmployeeId=@rUserSourceId,@rLeaveTypeId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromDate=@rDate,@rTodate=''
        END
   if(@rDashletId='12')
        BEGIN
     exec sCommunication.pPollGet @rOrgGroupBatchId=@rOrgGroupBatchId,@rSourceTypeId=@rUserSourceTypeId,@rCreatedUserId=@rUserId,@rCreatedDateTime=@rDate
        END
  if(@rDashletId='14')
       BEGIN
        exec sCommunication.pMyBookGet @rReaderSourceTypeId=@rUserSourceTypeId,@rReaderSourceId=@rUserSourceId,@rBatchId=@rBatchId,@rStatusId=@rStatusId

        END
  if(@rDashletId='16')
        BEGIN
      exec [sFee].[pRptFeeReceiptTotalGet] @rFromDate=@rDate,@rToDate=@rDate,@rOrgGroupBatchId=@rOrgGroupBatchId
        END
      
  if(@rDashletId='17')
        BEGIN
      exec [sFee].[pFeeDueAlertGet] @rSourceId=@rSourceId,@rSourceTypeId=@rSourceTypeId,@rBatchId=@rBatchId

        END
  if(@rDashletId='18')
        BEGIN
     exec sCommunication.pBlogGet @rId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rTitle=NULL,@rCreatedUserId=0,@rOrgId=@rOrgId,@rCreatedDateTime=@rDate
        END
 if(@rDashletId='19')
        BEGIN
     exec sAssessment.pStudentResultGet @rAcademicId=@rSourceId,@rStudentId=@rUserSourceId,@rBatchId=@rBatchId,@rExamId=@rExamId
     END
  if(@rDashletId='21')
       BEGIN
       SELECT vCD.ClassDivisionName,ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,CASE WHEN COUNT(SR.AcademicId)=0 THEN 'Pending' ELSE 'Complete' END AS PresentStatus
        FROM sStudent.tAcademic A INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId 
       AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId  AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
       INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId 
       LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceTypeId = 1 
       AND SR.IsPresent=1 AND SR.AttendanceDate=@rDate GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName ORDER BY vCD.OrderIndex
         END
  if(@rDashletId='22')
       BEGIN
        SELECT VL.Id,VL.VisitorName, VL.NoOfVisitor, VL.WhomToMeetName FROM sFrontOffice.tVisitorLog VL  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId 
        WHERE VL.OrgId=@rOrgId AND VL.VisitDate=@rDate ORDER BY VL.VisitDate DESC,VL.InTime DESC
        END
  if(@rDashletId='23')
       BEGIN
        SELECT DispatchedTo, DispatchedCity  FROM sFrontOffice.tCourierDispatch  WHERE OrgGroupId=@rOrgGroupId AND DispatchDate=@rDate  AND @rDashletId='23' ORDER BY DispatchDate
        END
    if(@rDashletId='24')
       BEGIN
        SELECT ReceiveFrom, ReceiveFor  FROM  sFrontOffice.tCourierReceive  WHERE OrgGroupId=@rOrgGroupId  AND ReceiveDate=@rDate  AND @rDashletId='24' ORDER BY ReceiveDate
    END
     if(@rDashletId='25')
        BEGIN
     SELECT ISNULL(Ps.LectureNumber,'') AS LactureNumber,PS.EmployeeId,ISNULL(SMT.Title,'') AS Subject,ISNULL(EM1.FirstName,'') + ' '+ISNULL(EM1.LastName,'') AS EmployeeName,ISNULL(Em.FirstName,'') + ' '+ISNULL(Em.LastName,'') AS ProxyEmployeeName, ISNULL(DV.Code,'') AS ClassDivisionName,ISNULL(SM.Title,'') AS ProxySubject from sTimetable.tProxySetting PS 
     INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId INNER JOIN sCommon.tDayMaster DM ON DM.Id = PS.DayId INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = PS.DivisionId
     INNER JOIN sTimetable.tTimeTable TT ON TT.Id=PS.TimeTableId 
     INNER JOIN sSetup.tSubjectMaster SMT ON SMT.Id = TT.SubjectId 
     INNER JOIN sHrm.tEmployeeMaster EM1  ON TT.EmployeeId=EM1.Id 
     INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = PS.EmployeeId  WHERE PS.ProxyDate=@rDate AND PS.BatchId=@rBatchId AND ((PS.EmployeeId=@rSourceId) OR (@rSourceId=0))  ORDER BY PS.ProxyDate
        END
        
        if(@rDashletId='27')
        BEGIN
     --Asset Check
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),AM.CheckedLastDate,103) AS CheckedLastDate
        FROM sAssetManagement.tAssetMaster AM INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
        INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
        WHERE ISNULL(AM.IsCheckRequired,0) = 1 AND (AM.CheckFrequencyId=1 AND AM.CheckedLastDate <=  DATEADD(dd,1,@TimeZoneDate) OR AM.CheckFrequencyId=2 AND AM.CheckedLastDate <=  DATEADD(dd,7,@TimeZoneDate) OR AM.CheckFrequencyId=3 AND AM.CheckedLastDate <= DATEADD(dd,30,@TimeZoneDate))
        AND AU.InchargeUserId =   @rUserId AND AM.OrgGroupId = @rOrgGroupId
     
     
     
  --      SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
		--AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate
		--FROM sAssetManagement.tAssetMaster AM 
		--INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
		--INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		-- WHERE AU.InchargeUserId = @rUserId AND AM.OrgGroupId = @rOrgGroupId
		 END
		if(@rDashletId='28')
        BEGIN
     --Asset maintenance
			 SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
			 AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate 
             FROM sAssetManagement.tAssetMaster AM 
             INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
             INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
                                WHERE AU.InchargeUserId =@rUserId  AND AM.OrgGroupId = @rOrgGroupId
		 END
		if(@rDashletId='29')
        BEGIN
     --Asset Renew
        SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),
         AM.RenewLastDate,103) AS RenewLastDate, CONVERT(nvarchar(12), AM.RenewNextDate,103) AS RenewNextDate
           FROM sAssetManagement.tAssetMaster AM INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
           INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
            WHERE ISNULL(AM.IsRenewRequired,0) = 1
            -- AND AM.RenewNextDate >= DATEADD(dd,ISNULL(AM.RenewAlertBeforeDays,0),AM.RenewLastDate) 
             AND convert(Date,@TimeZoneDate) >=  DATEADD(dd,-ISNULL(AM.RenewAlertBeforeDays,0), AM.RenewNextDate)
                           AND AU.InchargeUserId =  @rUserId  AND AM.OrgGroupId = @rOrgGroupId
        END
        --Inward
       IF(@rDashletId='30')
        BEGIN
        DECLARE @InwardRegisterGrid VARCHAR(max)=''
        SELECT  @InwardRegisterGrid = @InwardRegisterGrid + '<tr>
	       <td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterFrom,'') + '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(ReceivedDate,'01/01/0001'),103) + '</td>
	 	</tr>'		
	 	FROM
	 	 sFrontOffice.tInwardRegister
	 	 WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId
	 	 AND ReceivedDate<=convert(Date,@TimeZoneDate)
	   SELECT Isnull(@InwardRegisterGrid,'') As	InwardRegisterGrid
        END
            --Outward
         IF(@rDashletId='31')
        BEGIN
        DECLARE @OutwardRegisterGrid VARCHAR(max)=''
        SELECT  @OutwardRegisterGrid = @OutwardRegisterGrid + '<tr>
	    <td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterTo,'') + '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(OutWardDate,'01/01/0001'),103) + '</td>
	 	</tr>'	
	 	FROM
	 	 sFrontOffice.tOutwardRegister
	 	 WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId
	 	 AND OutwardDate<=convert(Date,@TimeZoneDate)
	   SELECT Isnull(@OutwardRegisterGrid,'') As	OutwardRegisterGrid
	   END
	   
	   IF(@rDashletId='32')
        BEGIN
        DECLARE @ReorderQuantityGrid VARCHAR(max)=''
        SELECT   @ReorderQuantityGrid=@ReorderQuantityGrid+'<tr>
		     <td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
	        <td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
	      <td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(SP.ReOrderQuantity,0)) + '</td>
	 	 </tr>'	
	 	FROM
	 	 sProcurement.tStockBatch SB
	 	  INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
	 	 INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
	 	 INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
	 	 --INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
	 	 WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0 
	 	 group by SE.Title,SM.Title,SP.ReOrderQuantity,SP.ReOrderPoint
	 	 HAVING SUM(SB.AvailableQuantity) < SP.ReOrderPoint
	   
		SELECT Isnull(@ReorderQuantityGrid,'') As	ReorderQuantityGrid
		END
		
		 IF(@rDashletId='33')
        BEGIN
        DECLARE @SafetyStockGrid VARCHAR(max)=''
        SELECT   @SafetyStockGrid=@SafetyStockGrid+'<tr>
		     <td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
	        <td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
	      <td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(SP.SafetyStock,0)) + '</td>
	 	 </tr>'	
	 	FROM
	 	 sProcurement.tStockBatch SB
	 	  INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
	 	 INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
	 	 INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
	 	 --INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
	 	 WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0 
	 	 group by SE.Title,SM.Title,SP.SafetyStock,SP.ReOrderPoint
	 	 HAVING SUM(SB.AvailableQuantity) < SP.SafetyStock
	   
		SELECT Isnull(@SafetyStockGrid,'') As	SafetyStockGrid
        END
		 IF(@rDashletId='34')
		 BEGIN 
		 DECLARE @Increment varchar(max)=''
		 SELECT @Increment=@Increment+'<tr>
		  <td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
	        <td align="left" scope="col">' +convert(varchar,isnull(IncrementDate,'01/01/0001'),103)  + '</td></tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE IncrementDate BETWEEN GETDATE()-1 AND GETDATE()+7
		AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Increment, '') As	IncrementGrid
		END
		
			 IF(@rDashletId='78')
		 BEGIN 
		 DECLARE @Retirement varchar(max)=''
		 SELECT @Retirement=@Retirement+'<tr>
		  <td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
	        <td align="left" scope="col">' +convert(varchar,isnull(RetirementDate,'01/01/0001'),103)  + '</td></tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE RetirementDate BETWEEN GETDATE()-1 AND GETDATE()+7
		AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Retirement, '') As RetirementGrid
		END
  END
GO
PRINT N'Altering [sSecurity].[pPendingLoginStudentdGet]...';


GO
 

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

BEGIN
	SELECT 
	-- TOP 100
			ISNULL(U.Id,0) AS Id,
			SC.StudentId,
			SC.Code,
			SC.Name,
			SC.ClassName + '-' + SC.DivisionName AS ClassName,
			SC.RollNo,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			U.LoginTitle AS UserName,
			U.LoginPassword,
			SC.SUId,
			SM.Title AS Status,
			(CASE WHEN A.UserId IS NULL THEN 'Not Register' ELSE 'Register' END) AS UserRegisterStatus
	FROM 
			sStudent.vStudentCommunication SC
			LEFT JOIN sSecurity.tUser U ON U.SourceId = SC.StudentId AND U.SourceTypeId=2003
			INNER JOIN sStudent.tStatusMaster SM ON SM.Id = SC.StatusId 
			LEFT JOIN 
			(
				SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers
			) AS A ON A.UserId = U.Id
	WHERE 
			((U.LoginPassWord is Null AND @rIsPendingLogin=1) OR (U.LoginPassWord is NOT Null AND @rIsCreatedLogin=1))
			 AND	(SC.OrgId = @rOrgId)
			 AND	(SC.BatchId = @rBatchId) 
			 AND	((SC.ClassId = @rClassId) OR(@rClassId=0))
			 AND	((SC.DivisionId = @rDivisionId) OR(@rDivisionId=0))
			 AND SC.StatusId = 1
	Order By SC.DivisionOrderIndex,SC.RollNo
	
END
GO
PRINT N'Altering [sSetup].[pPortalConfigurationSetupAdd]...';


GO
ALTER PROCEDURE [sSetup].[pPortalConfigurationSetupAdd]
	
	@rStrXml nvarchar(MAX),
    @rOrgId 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 TRANSACTION 
	 BEGIN
	 
	 DECLARE @lOrgGroupId int = 0
	 SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	 
	 -- Org Group Delete
	 DELETE FROM sConfig.tConfigurationSetup 
	 WHERE SourceId = @lOrgGroupId AND SourceTypeId= 2010 
	 
	 -- Organization Delete
	 DELETE SE FROM sConfig.tConfigurationSetup SE 
	 INNER JOIN sSetup.tOrganizationMaster OM ON SE.SourceId = OM.Id 
	 WHERE OM.OrgGroupId = @lOrgGroupId AND SourceTypeId= 1016
	 
	 -- Employee Delete
	 DELETE SE FROM sConfig.tConfigurationSetup SE 
	 INNER JOIN sSecurity.tUser U ON U.SourceId = SE.SourceId
	 INNER JOIN sSetup.tOrganizationMaster OM ON U.OrgID = OM.Id
	 WHERE OM.OrgGroupId = @lOrgGroupId AND SE.SourceTypeId= 95 
	 
	 INSERT INTO sConfig.tConfigurationSetup
		(
			Id,
			ConfigurationId,
			ItemValue,
			SourceTypeId,
			SourceId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
			)
		SELECT		
			A.Id,
			A.ConfigurationId,
			sSetup.fPortalXMLTagsReplaceReverse(A.ItemValue),
			A.SourceTypeId,
			A.SourceId,
			A.CreatedUserId,
			A.CreatedDateTime,
			A.UpdatedUserId,
			A.UpdatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				Id bigint,
				ConfigurationId int,
				ItemValue nvarchar(100),
				SourceTypeId smallint,
				SourceId bigint,
				CreatedUserId bigint,
				CreatedDateTime datetime,
				UpdatedUserId bigint,
				UpdatedDateTime datetime
			  ) 
			   A
		WHERE SourceTypeId != 0 AND SourceId != 0
		
        SELECT 1 AS Result
        
        DECLARE @lMaxId int=0
        SELECT @lMaxId = MAX(Id) FROM sConfig.tConfigurationSetup WHERE LEFT(Id,4)=@rOrgId
        UPDATE sCommon.tTableRowId SET CurrentNumber = @lMaxId WHERE OrgId = @rOrgId AND TableTitle = 'sConfig.tConfigurationSetup'
        
	 END	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSystem].[pExceptionLogGet]...';


GO
ALTER PROCEDURE [sSystem].[pExceptionLogGet]
	@rOrgGroupId int,
	@rFromDate date,
	@rToDate date
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SET @rToDate = DATEADD(day,1,@rToDate)
SELECT 
	EL.Id AS ExceptionId,
	EL.ExceptionType AS ExceptionType,
	EL.ExceptionDetail AS ExceptionDetail,
	EL.CreatedDateTime AS CreateUpdateTime,
	ISNULL(EL.PagePath,'') AS PagePath
FROM sSystem.tExceptionLog EL
	--INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
	--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
	--INNER JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId
WHERE ((EL.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
	AND (EL.CreatedDateTime >= @rFromDate)
	AND (EL.CreatedDateTime <= @rToDate)
	AND (EL.ExceptionType <> 'System.Threading.ThreadAbortException')
ORDER BY EL.CreatedDateTime DESC
END
GO
PRINT N'Altering [sTimetable].[pAssignTimeTableTime]...';


GO
ALTER PROCEDURE [sTimetable].[pAssignTimeTableTime]

		@rTimeTableSchemaId int,
        @rDivisionId int,
		@rDayId int,
		@rLectureNumber int,
		@rFromTime nvarchar(MAX),
		@rToTime nvarchar(MAX)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT 1 FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = @rTimeTableSchemaId AND DivisionId = @rDivisionId AND DayId = @rDayId AND LectureNumber = @rLectureNumber AND IsBreak = 0)
	BEGIN
	 UPDATE  sTimetable.tTimeTableTime
	    SET
			 FromTime = @rFromTime,
			 ToTime = @rToTime
	      
	      WHERE TimeTableSchemaId = @rTimeTableSchemaId 
				AND DivisionId = @rDivisionId 
				AND DayId = @rDayId 
				AND LectureNumber = @rLectureNumber
		SELECT 1 As Result
	END
ELSE
	BEGIN
	Insert Into sTimetable.tTimeTableTime
		(
			TimeTableSchemaId,
			DivisionId,
			DayId,
			LectureNumber,
			FromTime,
			ToTime,
			IsBReak
		)
	VALUES
		(
		@rTimeTableSchemaId,
        @rDivisionId,
		@rDayId,
		@rLectureNumber,
		@rFromTime,
		@rToTime,
		0
		)
		SELECT 11 AS Result
	END
END
GO
PRINT N'Altering [sTimetable].[pDivisionTimeTableGet]...';


GO
 
ALTER PROCEDURE [sTimetable].[pDivisionTimeTableGet]
	
	 @rDivisionId int,
	 @rTimeTableSchemaId 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,'')
        
     
 IF EXISTS(SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId)
 BEGIN
set @query = 'SELECT LectureNumber , ' + @cols + ' from 
             (
            Select T.LectureNumber, ISNULL(EM.ShortName + '+ ''' - ''' +'+ SM.Code + '+ '''|''' +' +ISNULL(TTM.FromTime,0) +'+ '''-''' +'+ ISNULL(TTM.ToTime,0) ,'''') + [sTimetable].[fTimeTableDetailGet](T.Id,1) AS EmployeeName ,DM.Title AS DayNames 
            from
            sTimetable.tTimeTable T 
            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
			LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=T.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = T.DivisionId AND TTM.LectureNumber = T.LectureNumber AND TTM.IsBreak = 0
	         WHERE    
	        ((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 '
   END
   ELSE
   BEGIN
   set @query = 'SELECT LectureNumber , ' + @cols + ' from 
             (
            Select T.LectureNumber, ISNULL(EM.ShortName + '+ ''' - ''' +' + SM.Code,'''') + [sTimetable].[fTimeTableDetailGet](T.Id,1) AS EmployeeName ,DM.Title AS DayNames 
            from
            sTimetable.tTimeTable T 
            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
	         WHERE    
	        ((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 '
   END         
print @query
execute(@query)
END
GO
PRINT N'Altering [sTimetable].[pRptDivisionTimeTableGet]...';


GO
 
ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

	  --@rBuilder1 nvarchar(max)='',
	  --@rBuilder2 nvarchar(max)='', 
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rEmployeeId bigint,
	  @rTimeTableSchemaId int,
	  @rReportId int=0,
	  @rDate Date=''
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN   
  IF(@rReportId=10166) -- Teacherwise
  BEGIN
  SELECT

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	0 As IsPresent,
	'' As WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	'' AS TimeTableDetail,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	--ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber),'') AS TimeTableDetail
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime
	FROM 
	sTimetable.tTimeTable TT	 
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  
	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TTD.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime
	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TTD.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	 
	  
	  --ORDER BY DV.OrderIndex
	  )
	  A
			RIGHT JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			WHERE TimeTableSchemaId=@rTimeTableSchemaId  ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
ELSE IF(@rReportId = 30661) --- Absent Teacher Divisionwise
	BEGIN
	  SELECT

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	ISNULL(A.ClassDivisionName,'')AS ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	A.IsPresent,
	'' As WeekOffs,
	0 As FromTime,
	0 As ToTime
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EAR.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	'' AS TimeTableDetail,
	ISNULL(EAR.IsPresent,0) AS IsPresent
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	--ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber),'') AS TimeTableDetail
	FROM 
	sTimetable.tTimeTable TT	 
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (EAR.AttendanceDate = @rDate OR @rDate = '')
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')

	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TTD.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(EAR.IsPresent,'') As IsPresent
	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TTD.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (EAR.AttendanceDate = @rDate OR @rDate = '')
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
	  
	  --ORDER BY DV.OrderIndex
	  )
	  A
			INNER JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			
			WHERE TimeTableSchemaId=@rTimeTableSchemaId ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
 ELSE
 BEGIN
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,0) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	 AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
		END
END
GO
PRINT N'Altering [sTimetable].[pRptFreeTeacherTimetableGet]...';


GO
 
ALTER PROCEDURE [sTimetable].[pRptFreeTeacherTimetableGet]

	  --@rBuilder1 nvarchar(max)='',
	  --@rBuilder2 nvarchar(max)='', 
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rEmployeeId bigint,
	  @rTimeTableSchemaId int,
	  @rReportId int=0
	
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN   
 
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	 
	CASE WHEN A.TimeTableID is not null THEN ISNULL(A.Subject,'FREE') ELSE '' END AS Subject,
	--CASE WHEN A.EmployeeId=-1 THEN 'FREE' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	--CASE WHEN A.SubjectId=-1 THEN 'FREE' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--ELSE
	 A.EmployeeName AS EmployeeName,
	--CASE WHEN A.EmployeeId=0 THEN 'Free' ELSE '' END AS Subject,
	 
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	'' AS ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code 
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code
	
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	
	WHERE  1=1
	AND (ClassId = @rClassId OR @rClassId=0)
	AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  --ORDER BY DV.OrderIndex
	  )
	  A
			--RIGHT JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			--INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			--WHERE TimeTableSchemaId=@rTimeTableSchemaId ) L
			--ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId
		 
END
GO
PRINT N'Altering [sTransport].[pRptRoutewiseStudentListGet]...';


GO
ALTER PROCEDURE [sTransport].[pRptRoutewiseStudentListGet]
	 
	
	 
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rDepartmentId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rRouteId int=0,
	 @rDestinationId int=0,
	 @rTransportId int =0,
	 @rDropDestinationId int=0,
	 @rDropBusRouteId int=0,
	 @rStatusId int=0,
	 @rStrRouteId nvarchar(500)=null,
	 @rDestinationTitle nvarchar(50)=null,
	 @rIsWithDetail bit
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 


	SELECT 
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			AR.SourceId,
			SM.Code,
			SM.FirstName+' '+SM.LastName AS Name,
			DM.Id AS DivisionId,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			BRDM.Title AS DestinationPoint,
			BRM.Id AS BusRouteId,
			BRM.Title AS BusRoute,
			A.RollNo,
			VM.Title AS Vehicle,
			VM.NoOfSeats,
			BRM.OrderIndex AS RouteOrder,
			BRDM.OrderIndex AS PickupOrder,
			DM.OrderIndex AS DivisionOrderIndex,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrganizationName,
			DMast.Id AS DepartmentId,
			DMast.Title AS DepartmentName,
			SC.ParentContactNo AS ParentContactNo,
			ISNULL(SC.PresentStreetone,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS PresentAddress,
			ISNULL(VM.RegistrationNumber,'') AS RegistrationNumber,
			ISNULL(BRM.DriverName,'') AS DriverName,
			ISNULL(BRM.DriverMobileNo,'') AS DriverMobileNo,
			ISNULL(BRM.ConductorName,'') AS ConductorName,
			ISNULL(BRM.ConductorMobileNo,'') AS ConductorMobileNo,
			BRDM.Amount,
			ISNULL(BRM1.DriverName,'') AS DropRoutDriverName,
			ISNULL(BRM1.DriverMobileNo,'') AS DropRoutDriverMobileNo,
			ISNULL(BRM1.ConductorName,'') AS DropRoutConductorName,
			ISNULL(BRM1.ConductorMobileNo,'') AS DropRoutConductorMobileNo,
			BRM1.Id AS DropRoutBusRouteId,
			BRM1.Title AS DropRoutBusRoute,
			ISNULL(VM1.RegistrationNumber,'') AS DropRoutRegistrationNumber,
			VM1.Title AS DropRoutVehicle,
			VM1.NoOfSeats AS DropRoutVehicleNoOfSeats,
			BRM1.OrderIndex AS DropRoutRouteOrder,
			BRDM1.OrderIndex AS DropRoutOrder,
			BRDM1.Title AS DropDestinationPoint ,
			BRDM1.DropTime,
			BRDM.PickUpTime,
			@rIsWithDetail As WithDetails
			
	FROM 
			sTransport.tAssignRoute AR
			INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 
			LEFT JOIN sStudent.tStudentCommunication SC ON A.StudentId=SC.StudentId AND SM.StatusId=1
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tDepartmentMaster DMast ON DMast.Id=CM.DepartmentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
			LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
			LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR.DropDestinationId 
			LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND (BRM1.OrgGroupBatchId=@rOrgGroupBatchId)
			INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = BRM.OrgGroupBatchId AND BMM.Id = A.BatchId 
			LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
	WHERE 
			--((AR.SourceId=@rAcademicId) OR (@rAcademicId=0))
			(BRM.OrgGroupBatchId=@rOrgGroupBatchId)
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((DMast.Id=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((CM.Id=@rClassId) OR (@rClassId=0))
			AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
			AND ((BRM.Id=@rRouteId) OR (@rRouteId=0))
			AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
			AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
			AND ((BRDM1.BusRouteId=@rDropBusRouteId) OR (@rDropBusRouteId=0))
			AND ((BRDM1.Id=@rDropDestinationId) OR (@rDropDestinationId=0))
			AND ((SM.StatusId = @rStatusId) OR (@rStatusId=0))
			AND BMM.IsInContext = 1
			AND (BRM.Id IN (SELECT item from sCommon.fnSplit(@rStrRouteId,',')) OR ISNULL(@rStrRouteId,'') = '')
			AND (BRDM.Title Like @rDestinationTitle OR ISNULL(@rDestinationTitle,'') = '')
	END
GO
PRINT N'Creating [sActivity].[pRptActivityWiseStudentListGet]...';


GO
CREATE PROCEDURE [sActivity].[pRptActivityWiseStudentListGet]

		   	
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='', 	
           @rClassId int,
           @rDivisionId int,
           @rActivityTypeId int,
           @rActivityId int,
           @rOrgId int,
           @rStatusId int,
           @rOrgGroupId int=0
          
AS
SET NOCOUNT ON

BEGIN

	SELECT  
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		SA.AcademicId,
		SA.RollNo,
		SA.Code,
		SA.Name,
		SA.ClassId,
		SA.DivisionId,
		SA.DivisionOrder,
		SA.ClassName+'-'+SA.DivisionName AS ClassName,	
		A.Id AS ActivityId,	
		A.Title AS ActivityName,
		ATM.Id AS ActivityTypeId,		
		ATM.Title AS ActivityTypeName,
		OM.Id AS OrgId,
		OM.DisplayTitle AS OrgName,
		SA.StudentId 
		
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sActivity.tActivityParticipant AP ON AP.SourceId=SA.AcademicId AND AP.SourceTypeId=2003
		INNER JOIN sActivity.tActivity A ON A.Id=AP.ActivityId
		INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id = A.ActivityTypeId	
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id	
	WHERE 
		(SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND (ATM.Id=@rActivityTypeId OR ISNULL(@rActivityTypeId,0)=0)
		AND (A.Id=@rActivityId OR ISNULL(@rActivityId,0)=0)
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		AND (SA.OrgId=@rOrgId OR @rOrgId=0)
		AND (SA.IsActiveBatch=1)
		AND (OGM.Id = @rOrgGroupId OR @rOrgGroupId = 0)
END
GO
PRINT N'Creating [sAdmission].[pAdmissionInquiryFieldAdd]...';


GO
 
CREATE PROCEDURE [sAdmission].[pAdmissionInquiryFieldAdd]
	  
	@rAdmissionInquiryId bigint=0,
	@rStrXml nvarchar(max) 
		
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
		
		DELETE FROM sAdmission.tAdmissionInquiryField WHERE AdmissionInquiryId=@rAdmissionInquiryId
	
		INSERT INTO sAdmission.tAdmissionInquiryField
		(
			AdmissionInquiryId,
			AdmissionInquiryFormId,
			AdmissionInquiryFieldResponse
		)
		SELECT
			@rAdmissionInquiryId,AdmissionInquiryFormId,AdmissionInquiryFieldResponse
		FROM
			OPENXML (@loDoc, '/Table/AdmissionInquiryFormField', 1)WITH 
			( 
			AdmissionInquiryFormId int,
			AdmissionInquiryFieldResponse nvarchar(1000)
			)
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sAdmission].[pAdmissionInquiryFormAdd]...';


GO
 
Create PROCEDURE [sAdmission].[pAdmissionInquiryFormAdd]
		 
	@rId int,
	@rOrgId int,
	@rClassId int,
	@rBatchId int,
	@rFieldRemark nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	@rFieldOrder smallint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

	INSERT INTO sAdmission.tAdmissionInquiryForm
	(
		Id
		,ClassId
		,BatchId
		,FieldRemark
		,FieldTypeId
		,FieldList
		,IsFieldMandatory
		,FieldGroup
		,FieldOrder
	)
	VALUES
	(
		@lNextNumber
		,@rClassId
		,@rBatchId
		,@rFieldRemark
		,@rFieldTypeId
		,@rFieldList
		,@rIsFieldMandatory
		,@rFieldGroup
		,@rFieldOrder
	)
END	 
ELSE
BEGIN
	SET @lNextNumber = @rId
	
	UPDATE sAdmission.tAdmissionInquiryForm
	SET 
		FieldRemark = @rFieldRemark
		,FieldTypeId = @rFieldTypeId
		,FieldList=@rFieldList
		,IsFieldMandatory=@rIsFieldMandatory
		,FieldGroup=@rFieldGroup
		,FieldOrder=@rFieldOrder
	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'Creating [sAdmission].[pAdmissionInquiryFormGet]...';


GO
 
CREATE PROCEDURE [sAdmission].[pAdmissionInquiryFormGet]
	 
	@rClassId int,
	@rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		Id,
		ClassId,
		BatchId,
		FieldRemark,
		FieldTypeId,
		FieldList,
		IsFieldMandatory,
		FieldGroup,
		FieldOrder
	FROM 
		sAdmission.tAdmissionInquiryForm
	WHERE 
		ClassId = @rClassId
		AND BatchId = @rBatchId
END
GO
PRINT N'Creating [sAlert].[pGetEmployeeMananger]...';


GO
CREATE PROCEDURE [sAlert].[pGetEmployeeMananger]
	 	 @rLeadFollowupId int,
	 	 @rTemplate nvarchar(max),
	 	 @rOrgGroupId smallint,
	 	 @rEmployeeManagerId bigint 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
			replace(
			replace(
			replace(
			replace (
			replace (
			replace(@rTemplate,'[EmployeeName]',(EM.FirstName +' '+ EM.MiddleName +' '+ EM.LastName)),			
			'[LeadName]',LM.Title),
			'[StreetDetail]', LM.StreetDetail),
			'[Area]',LM.AreaName),
			'[city]', LM.CityName),
			'[Displacement]',ISNULL(LF.Displacement,0))
			 AS MsgText,
			'95' AS SourceTypeId,
			@rEmployeeManagerId AS SourceId,
			LM.OrgId,
			@rOrgGroupid As OrgGroupId
	FROM 
		  sErp.tLeadMaster LM
		  INNER JOIN sErp.tLeadFollowup LF ON LF.LeadId = LM.Id 
		  INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LF.FollowupEmployeeId

	WHERE LF.Id = @rLeadFollowupId 

END
GO
PRINT N'Creating [sAssessment].[pRptTeacherEvaluationExamWise]...';


GO
 
 
CREATE PROCEDURE [sAssessment].[pRptTeacherEvaluationExamWise]
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rDepartmentId int=0,
	 @rClassId int,
	 @rDivisionId int,
	 @rCode nvarchar(20),
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int = 0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rOrgGroupId int,
	 @rTop int=0,
	 @rTeacherClass NVARCHAR(MAX)='',
	 @rEmployeeId bigint,
	 @rClassExam NVARCHAR(MAX)='',
	 @rBatchId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @lMarkEntryBasedOn nvarchar(50)
SELECT @lMarkEntryBasedOn=CS.ItemValue FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id=CS.Configurationid AND CS.SourceId=@rOrgGroupId WHERE CM.Id = 188


IF(@lMarkEntryBasedOn='Class Teacher')
BEGIN

SELECT 
			@rTop RowNum,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			SR.PresentDays,
			SR.TotalDays,
			EM.Id AS ExamId
	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 sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
			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
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			--INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId  AND TS.DivisionId=DM.ID
			
	WHERE 
			
		EM.BatchId = @rBatchId 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND (A.ClassId=@rClassId OR @rClassId=0)
		--AND TS.EmployeeId=@rEmployeeId
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rTeacherClass,','))OR @rTeacherClass='')
		AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClassExam,','))OR @rClassExam='')
		AND	A.BatchId = @rBatchId
		order by A.RollNo,CS.OrderIndex 
	
END 
IF(@lMarkEntryBasedOn='Class Teacher Batch')
BEGIN
SELECT 
			@rTop AS RowNum,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			SR.PresentDays,
			SR.TotalDays,
			EM.Id AS ExamId
	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 sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
			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
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId  AND TS.DivisionId=DM.ID
			INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
			
	WHERE 
		EM.BatchId = @rBatchId 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND (A.ClassId=@rClassId OR @rClassId=0)
		AND TS.EmployeeId=@rEmployeeId
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rTeacherClass,','))OR @rTeacherClass='')
		AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClassExam,','))OR @rClassExam='')
		AND	A.BatchId = @rBatchId
		order by A.RollNo,CS.OrderIndex 
END 

IF(@lMarkEntryBasedOn='Academic Setup')
BEGIN
SELECT 
			@rTop AS RowNum,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			SR.PresentDays,
			SR.TotalDays,
			EM.Id AS ExamId
			
	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 sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
			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
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId  AND TS.DivisionId=DM.ID
			
	WHERE 
		EM.BatchId = @rBatchId 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND (A.ClassId=@rClassId OR @rClassId=0)
		AND TS.EmployeeId=@rEmployeeId
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rTeacherClass,','))OR @rTeacherClass='')
		AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClassExam,','))OR @rClassExam='')
		AND	A.BatchId = @rBatchId
		order by A.RollNo,CS.OrderIndex 
END 

IF(@lMarkEntryBasedOn='User Access')
BEGIN
SELECT 
			@rTop AS RowNum,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			SR.PresentDays,
			SR.TotalDays,
			EM.Id AS ExamId
	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 sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
			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
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			--INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId  AND TS.DivisionId=DM.ID
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId= 2005
			
	WHERE 
		EM.BatchId = @rBatchId 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND (A.ClassId=@rClassId OR @rClassId=0)
		--AND TS.EmployeeId=@rEmployeeId
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rTeacherClass,','))OR @rTeacherClass='')
		AND (ISNULL(ESGM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClassExam,','))OR @rClassExam='')
		AND	A.BatchId = @rBatchId
		order by A.RollNo,CS.OrderIndex 
END 

END
GO
PRINT N'Creating [sBiometric].[pMonthlyStatus]...';


GO
CREATE PROCEDURE [sBiometric].[pMonthlyStatus]  
    
 @rOrgId smallint,
     @rBatchId int,     
     @rYear smallint,
     @rMonth smallint,
	 @rDayOfMonth smallint,
	 @rAttendanceTypeId int WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
  
 CREATE Table #temptable  
 ( 
 ClassId bigint , DivisionId bigint,ClassDivisionName nvarchar(50) , ClassTeacherName nvarchar(100) ,
  P1 nvarchar(5),P2 nvarchar(5),P3 nvarchar(5),P4 nvarchar(5),P5 nvarchar(5),P6 nvarchar(5),P7 nvarchar(5),P8 nvarchar(5),P9 nvarchar(5),  
  P10 nvarchar(5),P11 nvarchar(5),P12 nvarchar(5),P13 nvarchar(5),P14 nvarchar(5),P15 nvarchar(5),P16 nvarchar(5),P17 nvarchar(5),  
  P18 nvarchar(5),P19 nvarchar(5),P20 nvarchar(5),P21 nvarchar(5),P22 nvarchar(5),P23 nvarchar(5),P24 nvarchar(5),P25 nvarchar(5),  
  P26 nvarchar(5),P27 nvarchar(5),P28 nvarchar(5),P29 nvarchar(5),P30 nvarchar(5),P31 nvarchar(5)  
 )  

 Insert into #temptable  
 (  
  ClassId,DivisionId,ClassDivisionName,  ClassTeacherName,P1
 ) 
 
( SELECT 	A.ClassId ,A.DivisionId,	
			vCD.ClassDivisionName,
			ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
		    CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,01,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,01,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-01')))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END  AS P1
			   
    FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-01'))		
            AND SR.AttendanceTypeId = @rAttendanceTypeId
			AND SR.IsPresent=1			
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId )
          
 DECLARE @intFlag INT
 DECLARE @DAY INT
SET @intFlag = 2
 DECLARE @COLFlag NVARCHAR(5)

WHILE (@intFlag <=@rDayOfMonth)
BEGIN
--    PRINT @intFlag; 
	
--	--SET @DAY=CASE WHEN LEN(@intFlag)=1 THEN CONCAT('0',@intFlag)  ELSE @intFlag END

	SET @COLFlag=   'P' + CAST(@intFlag AS varchar(12)); 

--	--update #temptable set @COLFlag= 
	
--UPDATE #temptable set P2= 

 --Insert into #temptable  
 --(  
 -- ClassDivisionName,  ClassTeacherName,P2
 --) 
UPDATE  T1 set @COLFlag= ( 
SELECT 				
			
		    CASE WHEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,@intFlag,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) !='' THEN ([sAttendance].[fWeekHOffGet](@rYear,@rMonth,@intFlag,@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId)) ELSE CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-'+CONVERT(NVARCHAR(2),@intFlag))))) =0 THEN 'P' ELSE 'C' END ELSE 'C' END END 
			   
    FROM 


			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId AND vCD.OrgId=@rOrgId
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId  AND  DM.OrgId=@rOrgId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId 		
			AND SR.AttendanceDate=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rYear)+'-'+CONVERT(NVARCHAR(2),@rMonth)+'-'+CONVERT(NVARCHAR(2),@intFlag)))		
            AND SR.AttendanceTypeId =@rAttendanceTypeId
			AND SR.IsPresent=1			
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId ) FROM #temptable T1
			INNER JOIN #temptable T2  ON T2.ClassId =T1.ClassId AND T2.DivisionId=T1.DivisionId 
   

    SET @intFlag = @intFlag + 1;
END 
 
 SELECT * FROM #temptable
 
END
GO
PRINT N'Creating [sCommunication].[pAssignmentQueueGet]...';


GO
CREATE PROCEDURE [sCommunication].[pAssignmentQueueGet]
	 @rId bigint = 0,
	 @rSubjectId int,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rCreatedUserId bigint=0,
	 @rStatusId int=0,
	 @rUserId bigint = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	DISTINCT
			A.Id as AssignmentId,
			A.SubjectId,
			SM.Title as SubjectName,
			A.Title,
			A.Remark,
			A.StartDate,
			A.EndDate,
			U.DisplayTitle as CreatedUserName,
			ISNULL(A.StatusId,549) as StatusId,
			CASE WHEN ISNULL(A.StatusId,549)=549 THEN 'Pending' WHEN A.StatusId=550 THEN 'Approve' ELSE 'Reject' END AS Status
		    
  FROM 
            sCommunication.tAssignment A
            INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = SM.Id
			
  WHERE 
  
      ((A.Id = @rId) OR (@rId = 0))
    AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
	AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((A.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((A.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND A.BatchId=@rBatchId
	AND ((ISNULL(A.StatusId,549) = @rStatusId) OR (@rStatusId = 0))	 
	AND((ISNULL(vTSD.SubjectCordinatorEmployeeId,0) = @rUserId)OR(@rUserId=0))
	 
END
GO
PRINT N'Creating [sCommunication].[pAssignmentQueueUpdate]...';


GO
CREATE PROCEDURE sCommunication.pAssignmentQueueUpdate
	 
	 	
        @rId bigint,        
		@rStatusId int,
		@rLoginUserId bigint
		
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	 BEGIN TRY
		
	    UPDATE  sCommunication.tAssignment
	    SET
			StatusId=@rStatusId,ApprovedByEmployeeId=@rLoginUserId WHERE Id = @rId

	      SELECT 11 AS Result

	END TRY	
	
	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
		
		END
GO
PRINT N'Creating [sFee].[pChangeFeeCategoryFeeReceiptUpdate]...';


GO
CREATE PROCEDURE [sFee].[pChangeFeeCategoryFeeReceiptUpdate]
	
	@rAcademicId bigint,
	@rClassId int,
	@rDivisionId int,	
	@rOldCategoryId int,	
	@rNewCategoryId int,	 
	@rBatchId int,
	@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


DECLARE @rOldFeeSetupCount int
DECLARE @rNewFeeSetupCount int
DECLARE @rOldFeeSetupOptionalCount int
DECLARE @rNewFeeSetupOptionalCount int
DECLARE @rFinalFeeSetupCount int
		

		--IF Exists (SELECT 1 FROM sAssessment.tOptionalSubject R WHERE R.AcademicId = @rAcademicId)
		--BEGIN
		--SELECT -114 AS Result
		--RETURN		
		--END


		--IF Exists (SELECT 1 FROM sAssessment.tResult R WHERE R.AcademicId = @rAcademicId)
		--BEGIN
		--SELECT -115 AS Result
		--RETURN		
		--END
		
		--IF Exists (SELECT 1 FROM sAssessment.tCCECSExamScore R WHERE R.AcademicId = @rAcademicId)
		--BEGIN
		--SELECT -116 AS Result
		--RETURN		
		--END
		
		--IF Exists (SELECT 1 FROM sAssessment.tGradeSujbectExamScore R WHERE R.AcademicId = @rAcademicId)
		--BEGIN
		--SELECT -117 AS Result
		--RETURN		
		--END

		BEGIN

		IF OBJECT_ID('tempdb..#OldFeeSteupTempTable') IS NOT NULL
    DROP TABLE #OldFeeSteupTempTable

		IF OBJECT_ID('tempdb..#NewFeeSteupTempTable') IS NOT NULL
   DROP TABLE #NewFeeSteupTempTable

			SELECT DISTINCT FS.AdmissionCategoryId,A.BatchId,FS.ClassId,FS.FeeId,FS.Amount,RD.ReceiptId,RD.FeeSetupId,FS.IsOptional,FS.IsVariable INTO #OldFeeSteupTempTable 
			FROM sFee.tFeeSetup FS 
			INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = FS.ID 
			INNER JOIN sFee.tReceipt FR ON FR.ID = RD.RECEIPTID 
			INNER JOIN sStudent.tAcademic A ON  A.Id = FR.SourceId 
			where A.Id=@rAcademicId and FS.ClassId=@rClassId AND A.BatchId=@rBatchId AND FS.AdmissionCategoryId=@rOldCategoryId order by FS.FeeId

			SET @rOldFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #OldFeeSteupTempTable)


		IF(@rOldFeeSetupCount > 0)
			BEGIN	

				SELECT Id AS NewFeeSetupId,FeeId,Amount INTO #NewFeeSteupTempTable  FROM sFee.tFeeSetup 
				WHERE ClassId=@rClassId and BatchId=@rBatchId and AdmissionCategoryId=@rNewCategoryId 
				And FeeId IN (SELECT FeeId from #OldFeeSteupTempTable WHERE ClassId=@rClassId AND BatchId=@rBatchId AND AdmissionCategoryId=@rOldCategoryId)
				order by FeeId

				SET @rNewFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #NewFeeSteupTempTable)


				IF((  @rNewFeeSetupCount < @rOldFeeSetupCount))
				BEGIN
				SELECT -103 AS Result
				DROP TABLE #OldFeeSteupTempTable
				DROP TABLE #NewFeeSteupTempTable
				RETURN
				END

				SELECT Id AS NewFeeSetupId,FeeId,Amount INTO #NewFeeSteupOptionalTempTable  FROM sFee.tFeeSetup 
				WHERE ClassId=@rClassId and BatchId=@rBatchId and AdmissionCategoryId=@rNewCategoryId 
				And FeeId IN (SELECT FeeId from #OldFeeSteupTempTable WHERE ClassId=@rClassId AND BatchId=@rBatchId AND AdmissionCategoryId=@rOldCategoryId AND IsOptional=1 and IsVariable=1 ) AND IsOptional=1 and IsVariable=1
				order by FeeId


				SET @rOldFeeSetupOptionalCount = (SELECT ISNULL(COUNT(1),0) from #OldFeeSteupTempTable WHERE IsOptional=1 and IsVariable=1)

				SET @rNewFeeSetupOptionalCount = (SELECT ISNULL(COUNT(1),0) FROM #NewFeeSteupOptionalTempTable)
				

				--IF((@rOldFeeSetupOptionalCount > @rNewFeeSetupOptionalCount) AND (@rOldFeeSetupOptionalCount > 0))
				IF((  @rNewFeeSetupOptionalCount < @rOldFeeSetupOptionalCount))
				BEGIN
				SELECT -105 AS Result
				--DROP TABLE #OldFeeSteupTempTable
				--DROP TABLE #NewFeeSteupTempTable
				--DROP TABLE #NewFeeSteupOptionalTempTable
				RETURN
				END


				IF((@rNewFeeSetupOptionalCount > 0) OR (@rOldFeeSetupOptionalCount=0))
				BEGIN

					IF(@rNewFeeSetupCount > 0)
						BEGIN

							SELECT OldFee.ReceiptId,OldFee.FeeSetupId AS OldFeeSetupId,NewFee.NewFeeSetupId INTO #FinalFeeSteupTempTable 
							FROM #OldFeeSteupTempTable OldFee
							INNER JOIN #NewFeeSteupTempTable NewFee on NewFee.FeeId = OldFee.FeeId
							WHERE OldFee.Amount <= NewFee.Amount 
							order by OldFee.FeeId

							SET @rFinalFeeSetupCount = (SELECT ISNULL(COUNT(1),0) FROM #FinalFeeSteupTempTable)

							IF(@rFinalFeeSetupCount > 0)
								BEGIN
									BEGIN TRY
										BEGIN TRANSACTION							 
											BEGIN
												BEGIN										
													UPDATE RD SET FeeSetupId =FS.NewFeeSetupId from sFee.tReceiptDetail RD 
													INNER JOIN #FinalFeeSteupTempTable FS ON FS.ReceiptId = RD.ReceiptId AND FS.OldFeeSetupId=RD.FeeSetupId

													UPDATE sStudent.tAcademic set AdmissionCategoryId=@rNewCategoryId 
													WHERE Id=@rAcademicId AND ClassId=@rClassId AND DivisionId=@rDivisionId AND BatchId=@rBatchId AND OrgId=@rOrgId  
												END		
												SELECT 1 AS RESULT
												--DROP TABLE #FinalFeeSteupTempTable
												--DROP TABLE #NewFeeSteupTempTable
												--DROP TABLE #NewFeeSteupOptionalTempTable
												--DROP TABLE #OldFeeSteupTempTable
												--DROP TABLE #OldFeeSteupTempTable
											END 
										COMMIT TRANSACTION
									END TRY
									BEGIN CATCH 
										ROLLBACK TRANSACTION
										SELECT -104 AS Result
									END CATCH	
								END
							ELSE
								BEGIN
									SELECT -103 AS Result
									--DROP TABLE #OldFeeSteupTempTable
									--DROP TABLE #NewFeeSteupTempTable
									--DROP TABLE #NewFeeSteupOptionalTempTable
									--DROP TABLE #FinalFeeSteupTempTable
								END
						END
					ELSE
						BEGIN
							SELECT -102 AS Result
							--DROP TABLE #OldFeeSteupTempTable
							--DROP TABLE #NewFeeSteupTempTable
							--DROP TABLE #NewFeeSteupOptionalTempTable
						END
				END
				ELSE
					SELECT -105 AS Result
					--DROP TABLE #OldFeeSteupTempTable
					--DROP TABLE #NewFeeSteupTempTable
					--DROP TABLE #NewFeeSteupOptionalTempTable
				END
			--END
		ELSE
			BEGIN
					UPDATE sStudent.tAcademic set AdmissionCategoryId=@rNewCategoryId 
													WHERE Id=@rAcademicId AND ClassId=@rClassId AND DivisionId=@rDivisionId AND BatchId=@rBatchId AND OrgId=@rOrgId  
				SELECT 1 AS Result
				--DROP TABLE #FinalFeeSteupTempTable
				--								DROP TABLE #NewFeeSteupTempTable
				--								DROP TABLE #NewFeeSteupOptionalTempTable
				--								DROP TABLE #OldFeeSteupTempTable
				--							DROP TABLE #OldFeeSteupTempTable
			END
		END
END
GO
PRINT N'Creating [sFee].[pRptFeePendingDetailListGet_Temp]...';


GO
 
CREATE PROCEDURE [sFee].[pRptFeePendingDetailListGet_Temp]  

	@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) = '',  
	@rIsDetail bit=0,  
	@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) = '',  
	@rIsReceiptBookGroup bit=0,  
	@rFeeHeadId nvarchar(max) = '',  
	@rIsDisplayOrgGroup bit=0,  
	@rFeeId nvarchar(max) = '',  
	@rFilterId int=0,  
	@rOrgIds  nvarchar(max) = '',  
	@rPayDate date='',  
	@rCollectionGroupId int =0,  
	@rCastCategoryId int = 0  

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN
	
	 
	SELECT 
		 AcademicId,
		 FeeSetupId,
		 FeeAmount,
		 DiscountAmount,
		 AdditionalAmount,
		 NotApplicableAmount,
		 FeePaid,
		(T.FeeAmount - T.DiscountAmount - T.FeePaid + T.AdditionalAmount ) AS PendingAmount
	FROM
		(
			SELECT 
			
			A.Id AS AcademicId,
			FS.Id AS FeeSetupId, 
			
			(CASE
				WHEN FS.IsVariable = 1 AND ISNULL(FA.VariableAmount,0) > 0 THEN FA.VariableAmount
				WHEN FS.IsOptional = 0 THEN FS.Amount
				WHEN FS.IsOptional = 1 AND FS.IsVariable = 0 AND FO.FeeSetupId IS NOT NULL THEN FS.Amount
				WHEN FS.IsOptional = 1 AND FO.FeeSetupId IS NULL THEN 0
			 END) AS FeeAmount,	
			
			ISNULL(FA.DiscountAmount,0) AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0) AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0) AS NotApplicableAmount, 
	
			(SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id WHERE R.SourceId = A.Id AND RD.FeeSetupId = FS.Id ) AS FeePaid
	 FROM 
			sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
			INNER JOIN sFee.tFeeSetup FS ON A.ClassId=FS.ClassId AND FS.BatchId = A.BatchId AND A.AdmissionCategoryId = FS.AdmissionCategoryId
			LEFT JOIN sFee.tFeeOptional FO ON FS.Id = FO.FeeSetupId AND FO.BatchId = FS.BatchId AND A.Id = FO.SourceId AND FO.SourceTypeId = 2001
			LEFT JOIN sFee.tFeeAllocation FA ON   FS.Id = FA.FeeSetupId AND A.Id = FA.SourceId AND FO.SourceTypeId = 2001
		
		WHERE 1=1	
		
		)T 
		
		
	
		
 
END
GO
PRINT N'Creating [sFee].[pRptFeePendingDetailListGet_TestPerformance]...';


GO
CREATE PROCEDURE [sFee].[pRptFeePendingDetailListGet_TestPerformance]  

	@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) = '',  
	@rIsDetail bit=0,  
	@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) = '',  
	@rIsReceiptBookGroup bit=0,  
	@rFeeHeadId nvarchar(max) = '',  
	@rIsDisplayOrgGroup bit=0,  
	@rFeeId nvarchar(max) = '',  
	@rFilterId int=0,  
	@rOrgIds  nvarchar(max) = '',  
	@rPayDate date='',  
	@rCollectionGroupId int =0,  
	@rCastCategoryId int = 0  

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 
		
	SELECT T.*,
	(T.FeeAmount - T.DiscountAmount - T.FeePaid + T.AdditionalAmount ) AS PendingAmount
	 FROM
	(
	SELECT A.Id AS AcademicId,
	FS.Id AS FeeSetupId, 
	(
	CASE
	WHEN FS.IsVariable = 1 AND ISNULL(FA.VariableAmount,0) > 0 THEN FA.VariableAmount
	WHEN FS.IsOptional = 0 THEN FS.Amount
	WHEN FS.IsOptional = 1 AND FS.IsVariable = 0 AND FO.FeeSetupId IS NOT NULL THEN FS.Amount
	WHEN FS.IsOptional = 1 AND FO.FeeSetupId IS NULL THEN 0
	END) AS FeeAmount,	
	ISNULL(FA.DiscountAmount,0) AS DiscountAmount,
	ISNULL(FA.AdditionalAmount,0) AS AdditionalAmount,
	ISNULL(FA.NotApplicableAmount,0) AS NotApplicableAmount, 
	(SELECT 
	ISNULL(SUM(RD.Amount),0) AS PaidAmount 
	FROM
	sFee.tReceipt R 
	INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id				 
	WHERE R.SourceId = A.Id AND RD.FeeSetupId = FS.Id
	) AS FeePaid
	from sStudent.tAcademic A 
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	INNER JOIN sFee.tFeeSetup FS ON A.ClassId=FS.ClassId AND FS.BatchId = A.BatchId 
	AND A.AdmissionCategoryId = FS.AdmissionCategoryId
	LEFT JOIN sFee.tFeeOptional FO ON FS.Id = FO.FeeSetupId 
	AND FO.BatchId = FS.BatchId AND A.Id = FO.SourceId AND FO.SourceTypeId = 2001
	LEFT JOIN sFee.tFeeAllocation FA ON   FS.Id = FA.FeeSetupId 
	AND A.Id = FA.SourceId AND FO.SourceTypeId = 2001
	WHERE  
	A.OrgId = 9931 AND A.BatchId = 993100104
	AND SM.StatusId = 1
	)
	T  
	
	CREATE TABLE #TempIsOptional
	(
		FeeId int,  
		Id int,  
		IsOptional bit,  
		IsVariable bit,  
		Amount decimal(12,2),  
		StartDate date,  
		EndDate date,  
		BatchId int,  
		ReceiptBookId int,  
		AcademicId bigint,  
		FeeName nvarchar(100),  
		FeeHeadId int     
	)
	
	INSERT INTO #TempIsOptional
		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   
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id      
			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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
		WHERE   
			BM.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.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=0)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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(SA1.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,  
			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 SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId  
			
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
		WHERE  
			BM.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.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=1)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	
	CREATE TABLE #TempReceipt
	(
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint  
	)
	
	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 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     
		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 ((BM.OrgGroupBatchId = @rOrgGroupBatchId))  
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)  
		AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016  
		-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))  
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		AND ((BM.Title = @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='')  
		AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	GROUP BY FeeSetupId,R.SourceId  
	
	CREATE TABLE #TempAssignRoute
	(
		SourceId bigint  
	)
	
	INSERT INTO #TempAssignRoute
	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))
	
	SELECT   
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,  
		@rIsDetail AS IsDetail,  
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		SA.AcademicId,  
		SA.RollNo,  
		SA.Name,  
		SA.Code,  
		SA.ClassId,  
		SA.DivisionId,  
		SA.ClassName,  
		SA.DivisionName,  
		SA.DivisionOrder,  
		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.FeeName,  
		FHM.Id AS FeeHeadId,  
		FHM.Title AS FeeHeadName,  
		FHM.OrderIndex AS FeeHeadOrderIndex,  
		SA.OrgId,  
		O.Title AS OrgName,  
		O.OrderIndex AS OrgOrderIndex,  
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0  
		WHEN @rIsReceiptBookGroup = 1 THEN FS.ReceiptBookId  
		END) AS ReceiptBookId,   
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'  
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.Title,'')  
		END) AS ReceiptBookTitle,  
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0  
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.OrderIndex,0)  
		END) AS ReceiptOrderIndex,    
		--FS.ReceiptBookId,  
		ISNULL(RBM.FullTitle,'') AS ReceiptBookFullTitle,
		ISNULL(RBM.Address1,'') AS RecieptBookAddress1,
		IsNULL(RBM.Address2,'') As RecieptBookAddress2,
		IsNULL(RBM.Remark1,'') As Remark1,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
		SA.OrgGroupBatchId,  
		SA.DepartmentId,  
		SA.DepartmentName,  
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,  
		ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark,  
		@rPayDate AS PayDate ,  
		ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId,  
		ISNULL(CCM.Title,'') AS CastCategoryName,  
		ISNULL(CCM.OrderIndex,'') AS CastCategoryOrderIndex  
	FROM   
		sStudent.vStudentAcademic SA  
		INNER JOIN #TempIsOptional 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.tStudentCommunication SC   
		ON SC.StudentId = SA.StudentId  
		LEFT JOIN sStudent.tStudentOther SO   
		ON SO.StudentId = SA.StudentId  
		LEFT JOIN sCommon.tCastCategoryMaster CCM   
		ON CCM.Id = SO.CastCategoryId    
		INNER JOIN sFee.tFeeHeadMaster FHM  
		ON FHM.Id = FS.FeeHeadId   
		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))   
		LEFT JOIN #TempAssignRoute RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
	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 (  
				(@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 (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')       
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0))   
	Order by SA.AcademicId ,FS.Id
	
	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
	DROP TABLE #TempAssignRoute
	
END
GO
PRINT N'Creating [sHrm].[pEmployeeRegisterAttendanceGet]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeRegisterAttendanceGet]
	@rForYear  smallint,
	@rForMonth smallint,
	@rBatchId int,
	@rOrgId int,
	@rDepartmentId int=0
AS
SET NOCOUNT ON
	DECLARE @lFirstDate Date,@lLastDate date
	
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	SET @lLastDate = sCommon.fGetLastDateofMonth(@lFirstDate)
	Declare @Days int 
	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	--DECLARE @lAdmissionDate date 
	-- select @lAdmissionDate=Stud.DateOfJoining from    sStudent.tStudentAdmission Stud  inner join sStudent.vStudentAcademic A ON A.StudentId = Stud.StudentId
	--						Where AdmissionStandardId=@rClassId AND Stud.BatchId =@rBatchId  
	 
BEGIN 
 
CREATE Table #EmployeeAttendanceRegistertempTable
(
	 
	EmployeeCode nvarchar(50),
	EmployeeId bigint,
	EmployeeName nvarchar(100),
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	DepartmentId int,
	DepartmentName nvarchar(50),
	IsPresent bit,
	DayPart int,
	AttendanceDate date,
	DateOfJoining date,
	DateOfLeaving  date,
	EmployeeGrade nvarchar(100),
	TotalDays tinyint,
	PresentDays tinyint ,
	PayrollDays tinyint,
	LWP decimal(12,2),
	PaidLeave decimal(12,2),
	UnPaidLeave decimal(12,2),
	LateCount tinyint,
	LateDeductionDays decimal(12,2),
	SandwichDeductionDays decimal(12,2),
	WorkingDays int
 
)
Insert INTO #EmployeeAttendanceRegistertempTable
(	
	EmployeeCode ,
	EmployeeId ,
	EmployeeName,
	ForYear ,
	ForMonth,
	ForMonthInWord,
	DepartmentId ,
	DepartmentName ,
	IsPresent ,
	DayPart ,
	AttendanceDate ,
	DateOfJoining ,
	DateOfLeaving ,
	EmployeeGrade,
	TotalDays ,
	PresentDays  ,
	PayrollDays ,
	LWP,
	PaidLeave ,
	UnPaidLeave ,
	LateCount ,
	LateDeductionDays ,
	SandwichDeductionDays ,
	WorkingDays
  
)
SELECT  
		EM.Code AS EmployeeCode,
		EM.EmployeeId,
		EM.EmployeeName,
		YEAR(EAR.AttendanceDate) AS ForYear,
		MONTH(EAR.AttendanceDate) AS ForMonth,
		DATENAME(month, EAR.AttendanceDate) AS ForMonthInWord,
		EM.DepartmentId,
		EM.DepartmentName,
		EAR.IsPresent,
		day(EAR.AttendanceDate) AS DayPart,
		EAR.AttendanceDate,
		--ISNULL(CONVERT(VARCHAR(50),EM.DateOfJoining,103),'') AS DateOfJoining,
		EM.DateOfJoining,
		EM.DateOfLeaving,
		--ISNULL(CONVERT(VARCHAR(50),EM.DateOfLeaving,103),'') AS DateOfLeaving,
		ISNULL(EM.EmployeeGrade,'') AS EmployeeGrade,
		ISNULL(WD.TotalDays,0) AS TotalDays,
		(ISNULL(AT.TotalWorkingDays,0) - ((ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)))) AS PresentDays,
		(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) 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,
		CASE 
			WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
			THEN DATEDIFF(day, EJD.DateOfJoining , @lLastDate)  + 1 
			WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
			THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 1
			ELSE ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) 
			END AS WorkingDays

	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
		INNER JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = EM.EmployeeId
	WHERE 
		EM.OrgID = @rOrgId 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
		AND ((EM.DateOfJoining <= @lLastDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	
	--SELECT * FROM 	#EmployeeAttendanceRegistertempTable
CREATE TABLE #TempDaysTempTable
(
 DayPart int
 )
WHILE @li<=@Days

BEGIN

INSERT INTO #TempDaysTempTable
(
	DayPart 
)

SELECT 
@li AS DayPart
SET @li = @li + 1

END
 
SELECT  
			@lFirstDate AS LastDate,
			DateOfleaving,
			PivotTable.EmployeeId,
			DepartmentName,isnull(EmployeeCode,'') as EmployeeCode,
			isnull(EmployeeName,'') as EmployeeName,isnull(ForYear,'') AS ForYear,
			isnull(ForMonth,'') AS ForMonth,DepartmentId,DepartmentName,
			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,				 
				0 AS TotalPresent ,
	 		 sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),DateOfLeaving,[1]) AS P1,
			 sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),DateOfLeaving,[2]) AS P2,
			 sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),DateOfLeaving,[3]) AS P3,
			 sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),DateOfLeaving,[4]) AS P4,
			 sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),DateOfLeaving,[5]) AS P5,
			 sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),DateOfLeaving,[6]) AS P6,
			 sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),DateOfLeaving,[7]) AS P7,
			 sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),DateOfLeaving,[8]) AS P8,
			 sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),DateOfLeaving,[9]) AS P9,
			 sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),DateOfLeaving,[10]) AS P10,
			sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),DateOfLeaving,[11]) AS P11,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),DateOfLeaving,[12]) AS P12,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),DateOfLeaving,[13]) AS P13,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),DateOfLeaving,[14]) AS P14,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),DateOfLeaving,[15]) AS P15,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),DateOfLeaving,[16]) AS P16,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),DateOfLeaving,[17]) AS P17,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),DateOfLeaving,[18]) AS P18,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),DateOfLeaving,[19]) AS P19,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),DateOfLeaving,[20]) AS P20,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),DateOfLeaving,[21]) AS P21,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),DateOfLeaving,[22]) AS P22,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),DateOfLeaving,[23]) AS P23,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),DateOfLeaving,[24]) AS P24,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),DateOfLeaving,[25]) AS P25,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),DateOfLeaving,[26]) AS P26,
			  sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),DateOfLeaving,[27]) AS P27,
				sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),DateOfLeaving,[28]) AS P28,
				CASE WHEN @Days>=29 THEN sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),DateOfLeaving,[29]) end AS P29,
				CASE WHEN @Days>=30 THEN sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),DateOfLeaving,[30])end AS P30,
				CASE WHEN @Days>=31 THEN sHrm.fAttendanceJoiningDateGet(DateOfJoining,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),DateOfLeaving,[31])end AS P31,
		 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth
,0 Ispresent,
DateOfJoining   
FROM
(
	Select  
		EmployeeCode,
		EmployeeId,
		EmployeeName,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		DepartmentId,
		DepartmentName,
		(
			CASE 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		DateOfLeaving,		 
		DateOfJoining		
	 FROM 
		#EmployeeAttendanceRegistertempTable ST 
		LEFT JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((DateOfLeaving >= @lFirstDate) OR ISNULL(DateOfLeaving,'') = '')
		AND ForYear=@rForYear AND ForMonth=@rForMonth
		
) 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  EmployeeId AS EmployeeId, COUNT(1) AS TCount 
		   FROM  
				#EmployeeAttendanceRegistertempTable
		     GROUP BY  EmployeeId  
    ) TC ON TC.EmployeeId = PivotTable.EmployeeId 
	LEFT JOIN
	(
		Select EmployeeId AS EmployeeId, COUNT(1) AS ACount 
		   FROM  #EmployeeAttendanceRegistertempTable
		    WHERE   IsPresent = 0	 	 
			GROUP BY  EmployeeId
    ) AC ON AC.EmployeeId = PivotTable.EmployeeId
	LEFT JOIN
	(
		SELECT EM.Id AS EmployeeId, COUNT(1) AS PCount  FROM sHrm.vEmployeeCommonDetail ECD
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = ECD.EmployeeId
		LEFT JOIN  sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = EM.Id 
			WHERE   
			 EAR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
		
	        AND  ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((EAR.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((ECD.DepartmentId = @rDepartmentId)OR (@rDepartmentId=0))
	 GROUP BY EM.Id
    ) PC ON PC.EmployeeId = PivotTable.EmployeeId
   
    
--select * from #TempDaysTempTable 
--SELECT * FROM #EmployeeAttendanceRegistertempTable
drop table #EmployeeAttendanceRegistertempTable	  
drop table #TempDaysTempTable
END
GO
PRINT N'Creating [sHrm].[pGetEmployeeMananger]...';


GO
 
CREATE PROCEDURE [sHrm].[pGetEmployeeMananger]

	  --@rLeadId int 
	  @rLeadFollowupId bigint
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
			 
BEGIN
				 
		 CREATE TABLE #TempEmployeeId
			(
		EmployeeId bigint
			)
		 
BEGIN
		WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeManagerId
			 FROM sHrm.tEmployeeJobDetail EJD
			 --INNER JOIN sErp.tLeadMaster LM ON LM.LeadOwnerEmployeeId = EJD.EmployeeId
			 INNER JOIN sErp.tLeadFollowup LF ON LF.FollowUpEmployeeId = EJD.EmployeeId
			 WHERE LF.Id = @rLeadFollowupId

			 UNION ALL

			 SELECT
			  E.EmployeeManagerId 
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeManagerId = E.EmployeeId
			)
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.EmployeeManagerId FROM EmployeeCTE E
END
    SELECT 
    EM.Id As EmployeeManagerId
     FROM
		sHrm.tEmployeeMaster EM 
		  INNER JOIN #TempEmployeeId EID ON EID.EmployeeId = EM.Id
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			 		  
DROP TABLE #TempEmployeeId
END
END
GO
PRINT N'Creating [sHrm].[pRptEmployeeEmploymentDetail]...';


GO
CREATE PROCEDURE [sHrm].[pRptEmployeeEmploymentDetail]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	--@rIsDetail bit = 0,
	--@rBloodGroupId [int] = 0,
	--@rMaritalStatusId [int] = 0,
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint
	
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
	        ECD.Code,	      	
			ECD.EmployeeName,
			EPE.CompanyName,
			EPE.Duration,
			EPE.Designation,
			EPE.LastSalary,
			EPE.ReasonForLeaving,
			EPE.JobDescription,
			EPE.Remark 	 								 
		
		    
	FROM 
			[sHrm].[vEmployeeCommonDetail] ECD 
			inner join [sHrm].[tEmployeePreviousEmployment] EPE on ECD.EmployeeId=EPE.EmployeeId
	WHERE
			((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,sCommon.fGetDate()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
END
GO
PRINT N'Creating [sHrm].[pRptEmployeeFamilyDetail]...';


GO
CREATE PROCEDURE [sHrm].[pRptEmployeeFamilyDetail]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	--@rIsDetail bit = 0,
	--@rBloodGroupId [int] = 0,
	--@rMaritalStatusId [int] = 0,
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint
	
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ECD.Code,
			ECD.EmployeeName As ShortName,
			RM.Title As Relation,
			EFD.Name,
			BGM.Title As BloodGroup,
			EFD.DateOfBirth,
			EFD.Occupation

	    								 
		
		    
	FROM 
			[sHrm].[tEmployeeFamilyDetails] EFD inner join [sHrm].[vEmployeeCommonDetail] ECD  on EFD.EmployeeId=ECD.EmployeeId
			inner join sCommon.tBloodGroupMaster BGM on EFD.BloodGroupId=BGM.Id
			inner join sCommon.tRelationshipMaster RM on EFD.RelationshipId=RM.Id
	WHERE
			((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,sCommon.fGetDate()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   AND ((DATEDIFF(yy,ECD.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
END
GO
PRINT N'Creating [sPayroll].[pAllElementPaySetupGet]...';


GO
CREATE PROCEDURE [sPayroll].[pAllElementPaySetupGet]
	  
	-- @rId int,
	 @rSourceId bigint=0,
	 @rPayrollId int=0,
	 @rPayrollYearId int=0
	 --@rSourceTypeId smallint,	
	 --@rEmployeeCode nvarchar(100),
	 --@rEmployeeName nvarchar(100),
	 --@rPayElementId int,
	
	 
	 
 WITH EXECUTE AS CALLER
AS
 SET NOCOUNT ON
 
BEGIN 



 SELECT 
		   ISNULL(PS.[ID],0) AS PaySetupId	  		  
		  ,PE.Id AS PayElementId
		  ,PS.SourceId
		  ,PE.Title  AS PayElementName
		  ,[Amount]
		  ,[Percentage]
		  ,ISNULL([ProcessOrder],0) AS ProcessOrder
		  ,ISNULL(PS.DefaultAmount,0) AS DefaultAmount
		  ,ISNULL(PS.[PayrollId],0) AS PayrollId	
		  ,PE.IsEmployeeSpecific      
	      ,PE.IsDepend
	      ,EM.Code
	      ,EM.EmployeeName
	     ,OM.Id AS OrgId
	      ,OM.DisplayTitle AS OrgName
	     
	      
	FROM  sPayroll.tPayElement PE INNER JOIN  [sPayroll].[tPaySetup] PS ON PE.ID = PS.PayElementId  
		   INNER JOIN sHrm.vEmployeeCommonDetail Em ON Em.EmployeeId = PS.SourceId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
		    WHERE (PS.PayrollId = @rPayrollId OR @rPayrollId = 0)   AND (PS.SourceId = @rSourceId OR @rSourceId = 0)    AND (PS.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0)

		   UNION 

		   SELECT 0 PaySetupId, Id as PayElementId,0 SourceId,Title AS PayElementName,
		   0 AS Amount,0 AS Percentage,0 AS ProcessOrder,0 AS DefaultAmount,
		   PayrollId,IsEmployeeSpecific,IsDepend
		   ,'' Code,'' EmployeeName,0 OrgId,'' OrgName 
		   FROM sPayroll.vPayElement WHERE IsObsolete = 0 AND PayrollId=110100001
		   AND Id NOT IN(SELECT PayElementId FROM sPayroll.tPaySetup WHERE  (PayrollId = @rPayrollId OR @rPayrollId = 0)  AND (SourceId = @rSourceId OR @rSourceId = 0) AND (PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) )
		  
		    ORDER BY PayElementName


	

		
	--   SELECT 
	--	   ISNULL(PS.[ID],0) AS PaySetupId	  		  
	--	  ,PE.Id AS PayElementId
	--	  ,PS.SourceId
	--	  ,[Amount]
	--	  ,[Percentage]
	--	  ,ISNULL([ProcessOrder],0) AS ProcessOrder
	--	  ,ISNULL(PS.[PayrollId],0) AS PayrollId
	--      ,PE.Title  AS PayElementName
	--      ,PE.IsDepend
	--      ,EM.Code
	--      ,EM.EmployeeName
	--      ,OM.Id AS OrgId
	--      ,OM.DisplayTitle AS OrgName
	--     ,ISNULL(PS.DefaultAmount,0) AS DefaultAmount
	      
	--FROM  sPayroll.tPayElement PE INNER JOIN  [sPayroll].[tPaySetup] PS ON PE.ID = PS.PayElementId  
	--	   INNER JOIN sHrm.vEmployeeCommonDetail Em ON Em.EmployeeId = PS.SourceId
	--	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
		   
		  
 --  WHERE (PS.SourceId = @rSourceId OR @rSourceId = 0)
 --  AND (PS.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0)
 --  AND (PS.PayrollId = @rPayrollId OR @rPayrollId = 0)
 --        Order By EM.OrgId,EM.Code
		 
END
GO
PRINT N'Creating [sStudent].[pChangeFeeCategoryGet]...';


GO
CREATE PROCEDURE [sStudent].[pChangeFeeCategoryGet]
	 
	 @rClassId int,
	 @rDivisionId int,
	 @rCategoryId bigint,
	 @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
	
	SELECT 
			SN.AcademicId,			
			SM.AdmissionCategoryId as CategoryId,
			SN.ClassId,
			SN.DivisionId,
			SN.RollNo AS RollNo,
			SN.FirstName,
			SN.MiddleName,
			SN.LastName,
			SN.FirstName + ' ' + SN.MiddleName + ' ' + SN.LastName AS Name,			
			SN.Code
      
  FROM 
			[sStudent].[vStudentName] SN
         
           INNER JOIN sStudent.tAcademic SM ON SM.Id=SN.AcademicId 
  WHERE 
				(SN.ClassId=@rClassId OR @rClassId=0)
			AND (SN.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND (SM.AdmissionCategoryId=@rCategoryId OR @rCategoryId=0)
			AND SN.OrgID=@rOrgId 
			AND SN.BatchID=@rBatchId
END
GO
PRINT N'Creating [sTimetable].[pAssignTimeTableBreakTime]...';


GO
 
CREATE PROCEDURE [sTimetable].[pAssignTimeTableBreakTime]
		
		@rTimeTableSchemaId int,
        @rDivisionId int,
		@rDayId int,
		@rAfterLectureNumber int,
		@rFromTime nvarchar(MAX),
		@rToTime nvarchar(MAX),
		@rIsBreak bit = 1,
		@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS(SELECT 1 FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = @rTimeTableSchemaId AND DivisionId = @rDivisionId AND DayId = @rDayId AND LectureNumber = @rAfterLectureNumber AND IsBreak = @rIsBreak)
	BEGIN
	 UPDATE  sTimetable.tTimeTableTime
	    SET
			 FromTime = @rFromTime,
			 ToTime = @rToTime
	      
	      WHERE TimeTableSchemaId = @rTimeTableSchemaId 
				AND DivisionId = @rDivisionId 
				AND DayId = @rDayId 
				AND LectureNumber = @rAfterLectureNumber
				AND IsBreak = @rIsBreak
		SELECT 1 As Result
	END
ELSE
	BEGIN
	Insert Into sTimetable.tTimeTableTime
		(
			TimeTableSchemaId,
			DivisionId,
			DayId,
			LectureNumber,
			FromTime,
			ToTime,
			IsBreak
		)
	VALUES
		(
		@rTimeTableSchemaId,
        @rDivisionId,
		@rDayId,
		@rAfterLectureNumber,
		@rFromTime,
		@rToTime,
		@rIsBreak
		)
		DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tTimeTable', 0, 1, 1,@outNextNumber = @lNextNumber output
	Insert Into sTimetable.tTimeTable
		(
			Id,
			TimeTableSchemaId,
			EmployeeId,
			DivisionId,
			SubjectId,
			DayId,
			LectureNumber,
			LockNo,
			LockColour,
			SchoolRoomId,
			IsBreak
			
		)
	VALUES
		(
		@lNextNumber,
		@rTimeTableSchemaId,
		0,
        @rDivisionId,
		0,
		@rDayId,
		@rAfterLectureNumber,
		0,
		0,
		0,
		@rIsBreak
		)
		SELECT @lNextNumber AS Result
	END
END
GO
PRINT N'Creating [sTimetable].[pRptTimeTableBreakTimeGet]...';


GO
 
CREATE PROCEDURE [sTimetable].[pRptTimeTableBreakTimeGet]
	
	 @rDivisionId int,
	 @rOrgId int,
	 @rTimeTableSchemaId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
IF EXISTS(SELECT 1 FROM sTimeTable.tTimeTableTime WHERE DivisionId = @rDivisionId  AND TimeTableSchemaId = @rTimeTableSchemaId)
	BEGIN
		SELECT 
			 
			TT.DivisionId,
			TT.DayId,
			ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
			TT.LectureNumber,
			TT.FromTime+'-'+TT.ToTime as Time,
			TT.IsBreak

		From 
			sTimeTable.tTimeTableTime TT
			LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
			LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
		WHERE
			TT.DivisionId = @rDivisionId 
			AND TT.TimeTableSchemaId = @rTimeTableSchemaId
		Order By
			DayId
			 
			return 1
	END
ELSE 
	BEGIN
			return 11
	END
END
GO
PRINT N'Creating [sTimetable].[pTimeTableBreakTimeGet]...';


GO
CREATE PROCEDURE [sTimetable].[pTimeTableBreakTimeGet]
	
	 @rDivisionId int,
	 @rOrgId int,
	 @rTimeTableSchemaId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
IF EXISTS(SELECT 1 FROM sTimeTable.tTimeTableTime WHERE DivisionId = @rDivisionId  AND TimeTableSchemaId = @rTimeTableSchemaId)
	BEGIN
		SELECT 
			 
			TT.DivisionId,
			TT.DayId,
			DM.Title,
			TT.LectureNumber,
			TT.FromTime+'-'+TT.ToTime as Time,
			TT.IsBreak

		From 
			sTimeTable.tTimeTableTime TT
			LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
		WHERE
			TT.DivisionId = @rDivisionId 
			AND TT.TimeTableSchemaId = @rTimeTableSchemaId
		Order By
			DayId
			 
			return 1
	END
ELSE 
	BEGIN
			return 11
	END
END
GO
  

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