

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

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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [ExamBlock]         NVARCHAR (100) NULL,
        [AbsentRemarkTerm1] NVARCHAR (100) NULL,
        [AbsentRemarkTerm2] NVARCHAR (100) NULL,
        [AbsentRemarkTerm3] NVARCHAR (100) NULL,
        [IsPresentTerm1]    BIT            NULL,
        [IsPresentTerm2]    BIT            NULL,
        [IsPresentTerm3]    BIT            NULL;


GO
PRINT N'Creating Table [sAssessment].[tReportHistory]...';


GO
CREATE TABLE [sAssessment].[tReportHistory] (
    [Id]              BIGINT         IDENTITY (1, 1) NOT NULL,
    [ScreenId]        INT            NOT NULL,
    [ReportName]      NVARCHAR (MAX) NOT NULL,
    [StatusId]        INT            NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL,
    [Guid]            NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_ReportHistory] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Creating Table [sFee].[tPostDatePayment]...';


GO
CREATE TABLE [sFee].[tPostDatePayment] (
    [Id]                   BIGINT          NOT NULL,
    [OrgId]                INT             NOT NULL,
    [BatchId]              INT             NOT NULL,
    [OrgGroupBatchId]      INT             NOT NULL,
    [SourceTypeId]         SMALLINT        NOT NULL,
    [SourceId]             BIGINT          NOT NULL,
    [ReceiptId]            BIGINT          NULL,
    [ReceiptBookId]        INT             NOT NULL,
    [PayTypeId]            TINYINT         NOT NULL,
    [PaymentClearanceDate] DATE            NOT NULL,
    [ChequeNo]             NVARCHAR (40)   NOT NULL,
    [BankName]             NVARCHAR (200)  NOT NULL,
    [Amount]               DECIMAL (12, 2) NOT NULL,
    [Remark]               NVARCHAR (200)  NULL,
    [CreatedUserId]        BIGINT          NOT NULL,
    [CreatedDateTime]      DATETIME        NOT NULL,
    [UpdatedUserId]        BIGINT          NULL,
    [UpdatedDateTime]      DATETIME        NULL,
    [StatusId]             SMALLINT        NOT NULL,
    CONSTRAINT [PK_tPostDatePayment] PRIMARY KEY CLUSTERED ([Id] ASC)
);


GO
PRINT N'Altering Procedure [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,
	 @rFromObtain decimal(5,2)=0,
	 @rToObtain decimal(5,2)=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)='' 
	
	 --,@rcolumn_visible bit
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  --select * from 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

Declare @lDecimalConfig nvarchar(20)='', @lOrgId int
SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id=@rBatchId
SELECT @lDecimalConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @lOrgId

DECLARE @lAbsentRemarkConfig nvarchar(20) = ''
SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId


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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(100),
		StudCode NVarchar(20),
		StudentName Nvarchar(300),
		RollNo int,
		ResultStatus Nvarchar(50),	
		ClassName NVarchar(100),		
		Division NVarchar(100),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(5,2),
		RankNumber int,
		ResultGrade NVarchar(10),
		
		MaximumMark1 decimal(10,2),		
		SubjectGrade1 NVarchar(10),
		--Obtain1 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain1 decimal(5,2),
		ExamMaximum1 decimal(10,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(10,2),	
		SubjectGrade2 NVarchar(10),
		--Obtain2 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain2 decimal(5,2),
		ExamMaximum2 decimal(10,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(10,2),
		SubjectGrade3 NVarchar(10),
		--Obtain3 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain3 decimal(5,2),
		ExamMaximum3 decimal(10,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(10,2),	
		SubjectGrade4 NVarchar(10),
		--Obtain4 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain4 decimal(5,2),
		ExamMaximum4 decimal(10,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(10,2),		
		SubjectGrade5 NVarchar(10),
		--Obtain5 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain5 decimal(5,2),
		ExamMaximum5 decimal(10,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(10,2),		
		SubjectGrade6 NVarchar(10),
		--Obtain6 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain6 decimal(5,2),
		ExamMaximum6 decimal(10,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(10,2),		
		SubjectGrade7 NVarchar(10),
		--Obtain7 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain7 decimal(5,2),
		ExamMaximum7 decimal(10,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(10,2),	
		SubjectGrade8 NVarchar(10),
		--Obtain8 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain8 decimal(5,2),
		ExamMaximum8 decimal(10,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(10,2),		
		SubjectGrade9 NVarchar(10),
		--Obtain9 decimal(5,2) Default 0,	----remove this line and add below line for mantis: 31081
		Obtain9 decimal(5,2),
		ExamMaximum9 decimal(10,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(10,2),		
		SubjectGrade10 NVarchar(10),
		--Obtain10 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain10 decimal(5,2),
		ExamMaximum10 decimal(10,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(10,2),		
		SubjectGrade11 NVarchar(10),
		--Obtain11 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain11 decimal(5,2),
		ExamMaximum11 decimal(10,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(10,2),		
		SubjectGrade12 NVarchar(10),
		--Obtain12 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain12 decimal(5,2),
		ExamMaximum12 decimal(10,2),
		IsPresent12 bit,
		
		MaximumMark13 decimal(10,2),		
		SubjectGrade13 NVarchar(10),
		--Obtain13 decimal(5,2) Default 0,	--remove this line and add below line for mantis: 31081
		Obtain13 decimal(5,2),
		ExamMaximum13 decimal(10,2),
		IsPresent13 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(10),
		SubjectGradeTerm2 NVarchar(10),
		SubjectGradeTerm3 NVarchar(10),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(300),
		Remark3 nvarchar(300),
		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(5,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(10),
		PercentileTerm1 decimal(5,2),
		ResultStatusTerm1 Nvarchar(50),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(5,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(10),
		PercentileTerm2 decimal(5,2),
		ResultStatusTerm2 Nvarchar(50), 
		TotalMarkTerm3 	decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(5,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(10),
		PercentileTerm3 decimal(5,2),
		ResultStatusTerm3 Nvarchar(50), 
		
		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(10),
		SubjectName NVarchar(100),
		SubjectCode Nvarchar(20),	
		SubjectMinimum decimal(10,2),		
		SubjectMaximum decimal(10,2),
		SubjectObtain  decimal(5,2),
		
		Exam1Name Nvarchar(100),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(5,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(10),
		Percentile1 decimal(5,2),
		ResultStatus1 Nvarchar(50),
		Exam1CombineExamName Nvarchar(100),
				
		Exam2Name nvarchar(100),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(5,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(10),
		Percentile2 decimal(5,2),
		ResultStatus2 Nvarchar(50),
		Exam2CombineExamName Nvarchar(100),
		
		Exam3Name nvarchar(100),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(5,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(10),
		Percentile3 decimal(5,2),		
		ResultStatus3 Nvarchar(50),
		Exam3CombineExamName Nvarchar(100),
		
		Exam4Name nvarchar(100),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(5,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(10),
		Percentile4 decimal(5,2),
		ResultStatus4 Nvarchar(50),
		Exam4CombineExamName Nvarchar(100),
		
		Exam5Name nvarchar(100),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(5,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(10),
		Percentile5 decimal(5,2),
		ResultStatus5 Nvarchar(50),
		Exam5CombineExamName Nvarchar(100),
		
		Exam6Name nvarchar(100),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(5,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(10),
		Percentile6 decimal(5,2),
		ResultStatus6 Nvarchar(50),
		Exam6CombineExamName Nvarchar(100),
		
		Exam7Name nvarchar(100),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(5,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(10),
		Percentile7 decimal(5,2),
		ResultStatus7 Nvarchar(50),
		Exam7CombineExamName Nvarchar(100),
		
		Exam8Name nvarchar(100),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(5,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(10),
		Percentile8 decimal(5,2),
		ResultStatus8 Nvarchar(50),
		Exam8CombineExamName Nvarchar(100),
		
		
		Exam9Name nvarchar(100),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(5,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(10),
		Percentile9 decimal(5,2),
		ResultStatus9 Nvarchar(50),
		Exam9CombineExamName Nvarchar(100),
		
		Exam10Name nvarchar(100),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(5,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(10),
		Percentile10 decimal(5,2),
		ResultStatus10 Nvarchar(50),
		Exam10CombineExamName Nvarchar(100),
		
		Exam11Name nvarchar(100),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(5,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(10),
		Percentile11 decimal(5,2),
		ResultStatus11 Nvarchar(50),
		Exam11CombineExamName Nvarchar(100),
		
		Exam12Name nvarchar(100),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(5,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(10),
		Percentile12 decimal(5,2),
		ResultStatus12 Nvarchar(50),
		Exam12CombineExamName Nvarchar(100),

		Exam13Name nvarchar(100),	
		TotalMarks13 decimal(8,2),
		TotalObtain13 decimal(8,2),
		Percentage13 decimal(5,2),
		RankNumber13 int,
		ResultGrade13 NVarchar(10),
		Percentile13 decimal(5,2),
		ResultStatus13 Nvarchar(50),
		Exam13CombineExamName Nvarchar(100),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		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),
		Exam13Code 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(100),
		LastName nvarchar(100),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(50),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(100),
		SubjectGroupCode nvarchar(20),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(100),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(5,2),	
		SubjectObtainTerm2 decimal(5,2),
		SubjectObtainTerm3  decimal(5,2),
		SubjectMaxTerm1 decimal(10,2),
		SubjectMaxTerm2 decimal(10,2),
		SubjectMaxTerm3 decimal(10,2),
		ContactNo nvarchar(50),
		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(20),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		TotalDays13 decimal(6,2),
		PresentDays13 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(1000),
		GeneralRemarkTerm2 nvarchar(1000),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(6,2),
		SR_WeightTerm1 decimal(6,2),
		SR_HeightTerm2 decimal(6,2),
		SR_WeightTerm2 decimal(6,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(20),
		UIdNumber nvarchar(50),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(50),
		MotherMail nvarchar(50),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(10),
		StreamTitle nvarchar(50),
		AdmissionNo nvarchar(50),
		AdmissionDate Date,
		MiddleName nvarchar(100) ,
		FatherOccupation nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		IsDecimal bit,
		IsAbsentRemark bit,
		FinalAbsentRemark nvarchar(100),
		AbsentRemark1 nvarchar(100),
		AbsentRemark2 nvarchar(100),
		AbsentRemark3 nvarchar(100),
		AbsentRemark4 nvarchar(100),
		AbsentRemark5 nvarchar(100),
		AbsentRemark6 nvarchar(100),
		AbsentRemark7 nvarchar(100),
		AbsentRemark8 nvarchar(100),
		AbsentRemark9 nvarchar(100),
		AbsentRemark10 nvarchar(100),
		AbsentRemark11 nvarchar(100),
		AbsentRemark12 nvarchar(100),
		AbsentRemark13 nvarchar(100),
		ExamMaximumTerm1 decimal(6,2),
		ExamMaximumTerm2 decimal(6,2),
		ExamMaximumTerm3 decimal(6,2),
		--add for 29923 mantis start
		PermanentStreetOne nvarchar(150),
		PermanentStreetTwo nvarchar(150),
		PermanentStreetThree nvarchar(150),
		--add for 29923 mantis end
		CasteCategory nvarchar(50),--Mantis 0030303
		--Mantis Start - 0031091
		FeeCategory nvarchar(100),
		StudentContactNo nvarchar(50),
		--Mantis End - 0031091
		ObtainedMaximum1 decimal(10,2),
		ObtainedMaximum2 decimal(10,2),
		ObtainedMaximum3 decimal(10,2),
		ObtainedMaximum4 decimal(10,2),
		ObtainedMaximum5 decimal(10,2),
		ObtainedMaximum6 decimal(10,2),
		ObtainedMaximum7 decimal(10,2),
		ObtainedMaximum8 decimal(10,2),
		ObtainedMaximum9 decimal(10,2),
		ObtainedMaximum10 decimal(10,2),
		ObtainedMaximum11 decimal(10,2),
		ObtainedMaximum12 decimal(10,2),
		ObtainedMaximum13 decimal(10,2),
		ResultIndicator nvarchar(50),   -- Mantis - 31306
		IsResultIndicator bit,		-- Mantis - 31306
		ExamBlock nvarchar(100), --Mantis - 31848
		AbsentRemarkTerm1 nvarchar(100),    ---Mantis - 32090 - Start
		AbsentRemarkTerm2 nvarchar(100),
		AbsentRemarkTerm3 nvarchar(100),
		IsPresentTerm1 bit,
		IsPresentTerm2 bit,
		IsPresentTerm3 bit         ---Mantis - 32090 - End
		)
	 --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,
	FatherContactNo ,
	MotherContactNo ,
	FatherMail ,
	MotherMail ,
	Gender,
	CoordinatorEmployeeSign,
	StudentAddress,
	SUId,
	HighestDivisionMark,
	HighestDivisionGrade,
	StreamTitle,
	AdmissionNo,
	AdmissionDate,
	MiddleName ,
	FatherOccupation,
	ResultSheetAdditionalTitle,
	IsDecimal,
	IsAbsentRemark,
	FinalAbsentRemark,
	--Mantis Start - 29923 mantis
	PermanentStreetOne,
	PermanentStreetTwo,
	PermanentStreetThree,
	--Mantis End - 29923 mantis
	CasteCategory,--Mantis 0030303
	
	--Mantis Start - 0031091
		FeeCategory,
		StudentContactNo,
	--Mantis End - 0031091
	ResultIndicator,		-- Mantis - 31306
	IsResultIndicator,		-- Mantis - 31306
	ExamBlock             --Mantis - 31848
	)
	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,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS 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,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		OI.MarksheetHeaderA4 
		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,
		ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm1,
	    ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm2,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm1,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm2,
	    HM.Title As HouseName,HM.Id as HouseId,
	    ISNULL(SO.AdhaarNumber,'') As AdhaarNumber,
	    ISNULL(SO.UIdNumber,'') As UIdNumber,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END)AS Gender,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		(SC.PresentStreetOne +' '+ SC.PresentStreetTwo +' '+ SC.PresentStreetThree +' '+ SC.PresentCity +' '+ SC.PermanentState) AS StudentAddress,
		ISNULL(Stum.SUId,'') AS SUId,
		(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,
		ISNULL(StM.Title,'') AS StreamTitle,
		ISNULL(StuA.AdmissionNumber,0) AS AdmissionNo,
		ISNULL(StuA.AdmissionDate,'') AS AdmissionDate,
		Stum.MiddleName ,
		ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
		ISNULL(EM.ResultSheetAdditionalTitle, '') AS ResultSheetAdditionalTitle,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
		ISNULL(RD.AbsentRemark,'') AS FinalAbsentRemark,
		--add for 29923 mantis start
		SC.PermanentStreetOne,
		SC.PermanentStreetTwo,
		SC.PermanentStreetThree,
		--add for 29923 mantis End
		CSM.Title As CasteCategory,      --Mantis 0030303
		--Mantis Start - 0031091
		ACM.Title AS FeeCategory,
		SC.StudentContactNo AS StudentContactNo,
		--Mantis End - 0031091
		R.ResultIndicator as ResultIndicator, 
		EM.IsDisplayResultIndicator as IsResultIndicator, --Mantis - 31306
		SR.ExamBlock as ExamBlock        --Mantis - 31848
				
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
	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.tStreamMaster StM ON CM.StreamId = Stm.Id
	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 AND  ISNULL(EMP.IsOtherUser,0) = 0
	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 sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--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
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId        --Mantis 0030303
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id=StuM.AdmissionCategoryId	--Mantis - 0031091
	 
	 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.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=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)))
    )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	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),	--remove this line and add below line for mantis: 31081
					 Obtain' + convert(nvarchar(15),@lCount)+'= RD.Obtain,
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 AbsentRemark' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.AbsentRemark,' + CHAR(39)+CHAR(39) + '),
					 		
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,

					 ObtainedMaximum' + convert(nvarchar(15),@lCount)+ '= CASE WHEN EM.IsDisplayHighestDivisionMark = 1
									THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
									ELSE 0  END							
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						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)
		
		Declare @lCombineExamId int
			SELECT @lCombineExamId = EC.ExamId  FROM [sAssessment].[tExamMaster] EM 
										INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId  
										INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId in (SELECT SubExamId  FROM sAssessment.tExamCombine WHERE examid=@rExamId) 
										WHERE   (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId AND EM.Id = @lSubExamId
			--SELECT @lSubCombineExamName
		set @query ='update T set 
					 Exam' + convert(nvarchar(15),@lCount)+ 'CombineExamName =  EM.DisplayTitle
					  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), @lCombineExamId) 
				
				--Print @query		
		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,
					 AbsentRemarkTerm1 = RD. AbsentRemark,
					 IsPresentTerm1 = RD.IsPresent
					 							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						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,
					ExamMaximumTerm1 = EM.ExamMaximum
					
					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,
					AbsentRemarkTerm2 = RD. AbsentRemark,
					IsPresentTerm2 = RD.IsPresent
									 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						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,
					ExamMaximumTerm2 = EM.ExamMaximum			
					 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,
					AbsentRemarkTerm3 = RD. AbsentRemark,
					IsPresentTerm3 = RD.IsPresent			 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						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,
					ExamMaximumTerm3 = EM.ExamMaximum			
					 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
	
	--Select
	--	'' As Builder1,
	--	'' As Builder2,
	--    '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
	--	'' As IsDisplayMonthlyAttendanceText,
	--    '' AS ClassIdText,
	--	0 As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	0 As TotalMark ,
	--	0 As TotalObtain,
	--	0 As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
 --       '' As IsMarksInDecimal,
 --             0 As column_visible,

 --             0 As Percentile ,

 --            0 As ResultDetailId, 
 --            0 As ResultId,

	--	'' As Remark1 ,
	--	'' As Remark2 ,
	--	'' As Remark3 ,
	--	'' As DisplayTitle ,		
	--	0 As IsRankNo , 
	--	0 As IsGrade ,
	--	0 As IsPercentile ,
	--	0 As IsPercentage ,
	--	0 As IsSubjectPercentile ,
	--	0 As IsProcessResult ,
	--	0 As IsNegativeMarks ,
	--	0 As IsIncludeCoScholastic ,
	--	0 As IsOnPrePrinted ,
	--	0 As IsDisplayPhoto ,
	--	0 As IsDisplayBirthDate ,
	--	0 As IsLockForEdit ,
	--	0 As IsDisplaySchoolName ,			
	--	0 As IsDisplayAttendance ,
	--	0 As IsDisplayHeightWeight ,
	--	0 As IsResultStatus ,
	--	'' As FooterAdjustmentText ,
	--	'' As DetailAdjustmentText ,
	--	0 As FooterAdjustment ,
	--	0 As DetailAdjustment ,
	--	'' As ResultRemark ,
	--	'' As DateOfBirth ,
	--	0 As HeightTerm1 ,
	--	0 As WeightTerm1 ,
	--	0 As HeightTerm2,
	--	0 As WeightTerm2 ,
	--	0 As HeightAnnual ,
	--	0 As WeightAnnual ,
	--	0 As PresentDaysTerm1,
	--	0 As PresentDaysTerm2 ,
	--	0 As PresentDaysAnnual ,
	--	0 As TotalDaysTerm1 ,
	--	0 As TotalDaysTerm2 ,
	--	0 As TotalDaysAnnual ,
	--	0 As TermScopeId ,		 
	--	0x As StudentPhoto ,
	--	'' As GradeString,
	--	0 As IsDisplayGradeString ,		 
	--	0 As IsDisplayInMarksheet ,
	--	0 As IsShowSubjectGrade ,
	--	0 As IsIncludeInTotal ,
	--	0 As ClassSubjectID ,
	--	0 As SubjectId ,
	--	--Maximum decimal(5,2),
	--	0 As SubjectOrderIndex ,
	--	'' As SubjectGrade ,
	--	'' As SubjectName ,
	--	'' As SubjectCode ,	
	--	0 As SubjectMinimum ,		
	--	0 As SubjectMaximum ,
	--	0 As SubjectObtain ,
	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,

	--	0 As TotalDays ,
	--	0 As PresentDays ,
	--	0 As StudentHeight,
	--	0 As StudentWeight ,
	--	'' As ExamSeatNo ,
	--    0 As ExamId ,

 --       '' AS ExamCode,

	--	0 As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	0 As IsShowSubjectMark , 
	--	0 As IsOptionalSubject ,
	--	0 As CoScholasticScopeId ,
	--	0 As IsDisplayPrincipalSign ,
	--	0 As IsDisplayTeacherSign ,
	--	0x As EmployeeSign,
 --            '' As Batch,
 --            '' As ClassTeacherName,
 --      '' AS FirstName,
 --      '' AS LastName,
 --            0 As IsDisplayMonthlyAttendance,
	--	0x As MarksheetHeaderA4 ,
	--	0 As IsImageHeader ,
 --            '' As    MyGoal,
 --       '' As  AreaOfInterest,
 --       '' As Responsibility,
 --       '' As MyInterestHobby,
 --       '' As MyStrength,
 --       '' As Achievements,

	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
 --             0 As IsDetail,
 --             0 AS   SubjectGroupId,
 --             ''   AS SubjectGroupTitle,
 --        '' AS SubjectGroupCode,
 --        '' AS DecimalFormat,
 --        '' AS SubjectRemark,
 --               0 As GraceMark,
 --               0 As KrupaMark,
 --                '' As GradeStringHtml,
 --          '' As ResultRemark3,
 --         0 As IsDisplayTotalMark,
 --         ''  As ContactNo,
	--	'' As PresentAddress ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
 --       '' As ImprovementArea,
 --       '' As ProgressArea,
 --       '' As GeneralRemark,
 --              '' As MyActivity,
 --        ''  As ClassTeacherRemark,

 --        '' As HouseRemark,
	--	  '' As BloodGroup ,
 --         '' As BatchIdText,
 --                0 As IsShowWithDetail,
 --                0 As IsPresent,
 --                ''  As GradeTitle,

 --         '' As SubjectHighestDivisionGrade,
 --                 0  As SubjectHighestDivisionMark,

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign ,	
 --			'' As FatherOccupation ,
 --			0 AS IsDecimal,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm1,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm2,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm3

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


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanCopy]
	 
        
        @rFromDivisionId int, 
        @rToDivisionId int, 
        @rEmployeeId bigint,
        @rBatchId int,
        @rOrgId int
         
  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 DECLARE @lNextNumber bigint
	 DECLARE @lDataCount int, @lCount int = 1
	 
	 Delete from sAcademic.tLessonPlan where DivisionId = @rToDivisionId AND EmployeeId =@rEmployeeId AND BatchId=@rBatchId	 

	CREATE TABLE #LessonPlanTemp (
    Id INT IDENTITY(1,1), 
    LessonPlanId BIGINT
	);
	INSERT INTO #LessonPlanTemp 
		SELECT Id FROM sAcademic.tLessonPlan where DivisionId =@rFromDivisionId AND EmployeeId =@rEmployeeId;
		Select @lDataCount = Count (Id) from #LessonPlanTemp 

	WHILE @lCount <= @lDataCount
		BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
		Insert into sAcademic.tLessonPlan
		(
		Id,
		DivisionId,
		TopicId,
		NoOfPeriodRequired,
		Objective,
		IndicativeHomework,
		Summary,
		StartDate,
		EndDate,
		IsCompleted,
		EmployeeId,
		BatchId,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		 UpdatedDateTime,
		LearningExperience,
		ToolsAndTechniques,
		EssentialMaterial,
		AssessmentQuestion,
		TeacherExample,
		GuidedPractice,
		IndependentPractice,
		SubTopic ,
		[Session],
		TrainingMethod,
		PeriodCount
		)
		Select 
		@lNextNumber,
		@rToDivisionId,
		TopicId,
		NoOfPeriodRequired,
		Objective,
		IndicativeHomework,
		Summary,
		StartDate,
		EndDate,
		IsCompleted,
		EmployeeId,
		BatchId,
		CreatedUserId,
		sCommon.fGetDate(),
		UpdatedUserId,
		sCommon.fGetDate(),
		LearningExperience,
		ToolsAndTechniques,
		EssentialMaterial,
		AssessmentQuestion,
		TeacherExample,
		GuidedPractice,
		IndependentPractice,
		SubTopic ,
		[Session],
		TrainingMethod,
		PeriodCount
		from sAcademic.tLessonPlan LP
		INNER JOIN #LessonPlanTemp tLP ON tLP.LessonPlanId = LP.Id
		WHERE DivisionId =@rFromDivisionId AND EmployeeId =@rEmployeeId AND tLP.Id = @lCount
		SET @lCount = @lCount + 1
		END	
		Select 1 as result
		
END
GO
PRINT N'Altering Procedure [sAdmission].[pRptAdmissionReceiptGet]...';


GO
ALTER PROCEDURE [sAdmission].[pRptAdmissionReceiptGet]
	 	 
	 	 @rBatchId int,
	 	 @rOrgId int ,
	 	 @rFormNo int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
			ISNULL(AF.FirstName,'') + ' ' + ISNULL(AF.MiddleName, '') + ' ' + ISNULL(AF.LastName,'') AS StudentName,
			AFF.FatherName AS FatherName,
			AFF.MotherName AS MotherName,
			AF.StreetOne+' ' +AF.StreetTwo+' ' +AF.StreetThree+' ' +AF.City +' ' +AF.State+' '+AF.Country AS StudentAddress,
			AF.ContactNo AS MobileNo,
			AF.FormNo as FormNo,
			0 as ReceiptNumber,
			Convert(date,ISNULL(AF.CreatedDateTime,'')) as ReceiptDate,
			CM.DisplayTitle AS ClassName,
			BM.Title AS BatchName,
			AC.FormFeeAmount as FormFeeAmount,
			AC.FormFeeName AS FormFeeName,
			ACF.FeeNumber ,
			ACF.FeeName,
			ACF.FeeOrder,
			AFFE.FeeAmount,
			ISNULL(AF.Remark,'') AS Remark,
			ISNULL(AF.DateOfBirth,'') AS DateOfBirth,
			ISNULL(AF.FirstName,'') AS StudentFirstName,
			ISNULL(AF.MiddleName, '') AS StudentMiddleName,
			ISNULL(AF.LastName,'') AS StudentLastName,
			ISNULL(GM.Title,'') as Gender
			
	FROM 
			sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId 
			INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id AND AC.BatchId = @rBatchId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFF ON AFF.AdmissionFormId= AF.Id 
			LEFT JOIN sAdmission.tAdmissionFormFee  AFFE ON AFFE.AdmissionFormId = AF.Id
			LEFT JOIN sAdmission.tAdmissionCriteriaFee ACF ON ACF.Id = AFFE.AdmissionCriteriaFeeId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			
	WHERE
			AF.BatchId = @rBatchId
			AND AF.OrgId = @rOrgId
			AND AF.FormNo =@rFormNo
END
GO
PRINT N'Altering Procedure [sAlert].[pSMSHistoryGet]...';


GO
ALTER PROCEDURE [sAlert].[pSMSHistoryGet]
	
	@rOrgId smallint,
	@rStatusId int,
	@rContactId nvarchar(50),
	@rEventId int,
	@rSourceEvent nvarchar(50),
	@rUserName nvarchar(100),
	@rAlertModeId tinyint,
	@rFromDate date,
	@rToDate date,
	@rOrgGroupId int,
	@rCode nvarchar(max),
	@rReceiverSourceTypeId int,
	@rIsHistory bit = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rIsHistory = 1)
	BEGIN
		IF(@rCode IS NULL OR @rCode='')
		BEGIN
			IF(@rReceiverSourceTypeId=0)
				BEGIN	
		
				SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				'' AS Code				
				FROM
				sAlert.tAlertLogHistory AL
				INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
				LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
				WHERE
					((AL.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
					AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
					AND ((AL.EventId=@rEventId) OR (@rEventId=0))
					AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
					AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
					AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
					AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
					AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
					AND OM.OrgGroupId = @rOrgGroupId	
					AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId)					
					ORDER BY AL.CreatedDateTime DESC
				END	
	
			ELSE IF(@rReceiverSourceTypeId=2003)
				BEGIN	
				SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code				
				FROM
					sAlert.tAlertLogHistory AL
					INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
					LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
					INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId	
			
				WHERE
					((AL.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
					AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
					AND ((AL.EventId=@rEventId) OR (@rEventId=0))
					AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
					AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
					AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
					AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
					AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
					AND OM.OrgGroupId = @rOrgGroupId	
					AND ((AL.ReceiverSourceTypeId=@rReceiverSourceTypeId) OR AL.ReceiverSourceTypeId = 2001) -- Add Condition for Mantis Id:0031787
					ORDER BY AL.CreatedDateTime DESC
				END
			ELSE IF(@rReceiverSourceTypeId=95)
			BEGIN	
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				tEM.Code AS Code				
		FROM
				sAlert.tAlertLogHistory AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 					
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId)	
			ORDER BY AL.CreatedDateTime DESC
	END
			ELSE 
			BEGIN
		SELECT DISTINCT tmp1.* From(
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code				
		FROM
				sAlert.tAlertLogHistory AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=2003			
			AND OM.OrgGroupId = @rOrgGroupId	
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLogHistory AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId 
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (U.DisplayTitle like 'SysSuperAdmin') OR  (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND AL.ReceiverSourceTypeId=2001
		AND OM.OrgGroupId = @rOrgGroupId		
	
	UNION
	SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				tEM.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=95			
			AND OM.OrgGroupId = @rOrgGroupId	
		
		UNION
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				'' AS Code				
		FROM
				sAlert.tAlertLogHistory AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			
			--AND (AL.ReceiverSourceTypeId NOT IN (95,2001,2003))
			
			AND ((AL.ReceiverSourceTypeId=0 OR @rReceiverSourceTypeId=0))	
			--ORDER BY AL.CreatedDateTime DESC	
	
	)AS tmp1				
			ORDER BY tmp1.CreatedDateTime DESC
	END
		END

	ELSE
	BEGIN
		SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			tEM.Code AS Code
		FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((tEM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
		
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SA.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='')
END		
		
--SELECT DISTINCT OM.Title, D.Code,OM.OrderIndex,D.OrderIndex FROM sSetup.tDivisionMaster D
--INNER JOIN ssetup.tOrganizationMaster OM
--ON D.OrgId = OM.Id
--WHERE D.Id IN
--(
--select DivisionId from sStudent.tAcademic A INNER JOIN
--sStudent.tStudentCommunication SC ON A.StudentId = SC.StudentId
--INNER JOIN SAlert.tAlertLog AL ON SC.ParentContactNo = AL.ContactId
--AND AL.OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = 1141 )
--AND AL.AlertModeId = 2)
--order by  OM.OrderIndex,D.OrderIndex
	END
ELSE 
BEGIN
	IF(@rCode IS NULL OR @rCode='')
	BEGIN
		IF(@rReceiverSourceTypeId=0)
		BEGIN	
		
		SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			'' AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId) 
			
			ORDER BY AL.CreatedDateTime DESC
	END	
	
		ELSE IF(@rReceiverSourceTypeId=2003)
		BEGIN	
		SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SA.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId	
			
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND ((AL.ReceiverSourceTypeId=@rReceiverSourceTypeId) OR AL.ReceiverSourceTypeId=2001) -- Add Condition for Mantis Id:0031787
			ORDER BY AL.CreatedDateTime DESC
	END
		ELSE IF(@rReceiverSourceTypeId=95)
		BEGIN	
		SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			tEM.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 					
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId)	
			ORDER BY AL.CreatedDateTime DESC
		END
	ELSE 
	BEGIN
		SELECT DISTINCT tmp1.* From(		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=2003			
			AND OM.OrgGroupId = @rOrgGroupId	
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId 
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (U.DisplayTitle like 'SysSuperAdmin') OR  (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND AL.ReceiverSourceTypeId=2001
		AND OM.OrgGroupId = @rOrgGroupId		
	
	UNION
	SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				tEM.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=95			
			AND OM.OrgGroupId = @rOrgGroupId	
		
		UNION
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				'' AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			
			AND (AL.ReceiverSourceTypeId NOT IN (95,2001,2003))
			
			--AND ((AL.ReceiverSourceTypeId=0 OR @rReceiverSourceTypeId=0))	
			--ORDER BY AL.CreatedDateTime DESC	
	
	)AS tmp1				
			ORDER BY tmp1.CreatedDateTime DESC
	END
		END

	ELSE
	BEGIN
	SELECT 
		AL.Id AS Id,
		AL.ContactId,
		AL.AlertMessage,
		AL.AlertSubject,
		CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
		--AL.ResultMessage
		CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
		--EM.Title AS EventName,
		AL.SourceEvent,
		U.DisplayTitle AS UserName,
		AL.CreatedDateTime,
		OM.Id AS OrgId,
		OM.DisplayTitle AS Organization,
		tEM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((tEM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
		
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			CASE WHEN AL.EventId=126 THEN 'Employee Birthday' ELSE EM.Title END AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SA.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='')
END		
	END
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetCoScholasticSubCombineGet]...';


GO





ALTER PROCEDURE [sAssessment].[pRptResultSheetCoScholasticSubCombineGet]
	 
	 

	 --@rAcademicIdTextText bigint,
	 --@rExamIdTextText bigint
	  @rAcademicId bigint,
	 @rExamId bigint ,
	 @rCoScholasticScopeId int=0,
	 @rBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--DECLARE
--@rAcademicIdText bigint,
--@rExamIdText int
--SET @rAcademicIdText = convert(bigint, @rAcademicIdTextText)
--SET @rExamIdText = convert(bigint, @rExamIdTextText)
DECLARE
@lIsCoScholasticGrade	bit,
@lIsCoScholasticGradeIndicator bit, 
@lIsCoScholasticGradeDesIndicator bit,
@lIsCoScholasticCombine bit	 	 

--@lCoScholasticScopeId tinyint

SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator,
@lIsCoScholasticCombine = IsCoScholasticCombine 
FROM sAssessment.tExamMaster WHERE Id = @rExamId
 

DECLARE 
@Exam1 int,
@Exam2 int,
@Exam3 int


--@Grade2 nvarchar(50),
--@GradeIndicator1 nvarchar(50),
--@Grade2 nvarchar(50),
--@CategoryID int,
--@BrandID int



 
SELECT @Exam1 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 1
SELECT @Exam2 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 2
SELECT @Exam3 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 3

SELECT
Convert(nvarchar(10),@rExamId) AS ExamIdText,
Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,
  
Convert(nvarchar(20),@rBatchId) AS   BatchIdText,
@rAcademicId AS AcademicId,
--(CASE Term1.AcademicId  WHEN  null THEN Convert(nvarchar(10),Term2.AcademicId)
--ELSE Convert(nvarchar(10),Term1.AcademicId) END) AS   AcademicIdText,
@rExamId AS ExamId, 
Convert(nvarchar(20), @rCoScholasticScopeId ) AS CoScholasticScopeIdText,

--(CASE Term1.AcademicId  WHEN  null THEN Term2.AcademicId
--ELSE Term1.AcademicId END) AS   AcademicId ,
(CASE Term1.CoSubject  WHEN  null THEN Term2.CoSubject
ELSE Term1.CoSubject END) AS   CoSubject ,
(CASE Term1.CoSubjectGroup  WHEN  null THEN Term2.CoSubjectGroup
ELSE Term1.CoSubjectGroup END) AS   CoSubjectGroup ,
(CASE Term1.CoSubjectGroupOrder  WHEN  null THEN Term2.CoSubjectGroupOrder
ELSE Term1.CoSubjectGroupOrder END) AS   CoSubjectGroupOrder ,
(CASE Term1.CoSubjectOrder  WHEN  null THEN Term2.CoSubjectOrder
ELSE Term1.CoSubjectOrder END) AS   CoSubjectOrder , 
ISNULL(Term1.Grade,'') AS Grade1,
ISNULL(Term1.GradeIndicator,'') AS GradeIndicator1,
ISNULL(Term1.DescriptiveIndicator,'') AS DescriptiveIndicator1,
ISNULL(Term2.Grade,'') AS Grade2,
ISNULL(Term2.GradeIndicator,'') AS GradeIndicator2,
ISNULL(Term2.DescriptiveIndicator,'') AS DescriptiveIndicator2,
ISNULL(Term3.Grade,'') AS Grade3,
ISNULL(Term3.GradeIndicator,'') AS GradeIndicator3,
ISNULL(Term3.DescriptiveIndicator,'') AS DescriptiveIndicator3,
@lIsCoScholasticGrade AS IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
ISNULL(Term1.GroupTypeId,0) AS GroupTypeId,
ISNULL(Term1.GroupType,0) AS GroupType ,

ISNULL(Term1.ExamName,'') AS ExamTerm1,
ISNULL(Term2.ExamName,'') AS ExamTerm2,
ISNULL(Term3.ExamName,'') AS ExamTerm3,
Term1.CoScholasticTitle AS CoScholasticTitle


 

FROM 

	(
	SELECT			
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.Id AS CoSubjectId,
			cceCSM.OrderIndex AS CoSubjectOrder,
			cceCSGM.OrderIndex AS CoSubjectGroupOrder,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType ,
			 ESM.Title AS ExamName,
			 EM.CoScholasticTitle 
			
	FROM 
			sAssessment.tCCECSExamScore cceCSS	
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
			INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
			INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = EM.ClassId AND cceCSM.Id = FC.CCECSId AND FC.BatchId = @rBatchId	-- #Start MantisId : 0031752
			LEFT JOIN sAssessment.tOptionalCCECS OCS ON OCS.AcademicId = cceCSS.AcademicId AND OCS.CCECSId = cceCSS.CCECSId				-- #End MantisId : 0031752

	WHERE 
		     cceCSS.ExamId=@Exam1		     
		     AND cceCSS.AcademicId=@rAcademicId
		     AND CCC.BatchID=@rBatchId
			 AND (FC.IsOptional = 0 OR (FC.IsOptional = 1 AND OCS.AcademicId IS NOT NULL))			-- MantisId : 0031752
			 	) Term1
		     
		     FULL OUTER JOIN

		 	(
			SELECT			
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.Id AS CoSubjectId,
			cceCSM.OrderIndex AS CoSubjectOrder,
			cceCSGM.OrderIndex AS CoSubjectGroupOrder,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType,
			ESM.Title AS ExamName 
			 --EM.CoScholasticTitle 
			
			 
			
			
			    
	FROM 
			sAssessment.tCCECSExamScore cceCSS		 
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
			INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
			INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = EM.ClassId AND cceCSM.Id = FC.CCECSId AND FC.BatchId = @rBatchId		-- #Start MantisId : 0031752
			LEFT JOIN sAssessment.tOptionalCCECS OCS ON OCS.AcademicId = cceCSS.AcademicId AND OCS.CCECSId = cceCSS.CCECSId					-- #End MantisId : 0031752
	WHERE 
		     cceCSS.ExamId=@Exam2		     
		     AND cceCSS.AcademicId=@rAcademicId
		     AND CCC.BatchID=@rBatchId	
			 AND (FC.IsOptional = 0 OR (FC.IsOptional = 1 AND OCS.AcademicId IS NOT NULL))					-- MantisId : 0031752
			 ) Term2
		     ON Term1.CoSubjectId = Term2.CoSubjectId    
		     
		     
			FULL OUTER JOIN

		 	(
			SELECT			
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.Id AS CoSubjectId,
			cceCSM.OrderIndex AS CoSubjectOrder,
			cceCSGM.OrderIndex AS CoSubjectGroupOrder,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType,
			ESM.Title AS ExamName 
			 --EM.CoScholasticTitle 	
			    
	FROM 
			sAssessment.tCCECSExamScore cceCSS		 
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
			INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
			INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = EM.ClassId AND cceCSM.Id = FC.CCECSId AND FC.BatchId = @rBatchId				-- #Start MantisId : 0031752
			LEFT JOIN sAssessment.tOptionalCCECS OCS ON OCS.AcademicId = cceCSS.AcademicId AND OCS.CCECSId = cceCSS.CCECSId							-- #End MantisId : 0031752
	WHERE 
		     cceCSS.ExamId=@Exam3		     
		     AND cceCSS.AcademicId=@rAcademicId
		     AND CCC.BatchID=@rBatchId
			 AND (FC.IsOptional = 0 OR (FC.IsOptional = 1 AND OCS.AcademicId IS NOT NULL))				-- MantisId : 0031752
			 	) Term3
		     ON Term1.CoSubjectId = Term3.CoSubjectId    

		     
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClass 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,
	 @rOrgId int=0,
	 @rMultiCode nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 	

 --Select * from   sAssessment.tTempAllExamSubjectActivity
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
SELECT @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

Declare @lDecimalConfig nvarchar(20)=''
SELECT @lDecimalConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		
		ResultStatus Nvarchar(50),	
		
		ClassName NVarchar(100),
				
		Division NVarchar(100),
		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),
		--ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	

		SubjectGrade9 NVarchar(50),
		IsPresent9 bit,

		SubjectGrade10 NVarchar(50),
		IsPresent10 bit,

		SubjectGrade11 NVarchar(50),
		IsPresent11 bit,

		SubjectGrade12 NVarchar(50),
		IsPresent12 bit,

		SubjectGrade13 NVarchar(50),
		IsPresent13 bit,
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		
		Remark2 nvarchar(300),
		Remark3 nvarchar(300),
		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), 
		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),
		
		SubActivityGrade1 nvarchar(50),
		ActivityGrade1 nvarchar(50),
		
		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),
		
		SubActivityGrade2 nvarchar(50),
		ActivityGrade2 nvarchar(50),
		
		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),
		
		SubActivityGrade3 nvarchar(50),
		ActivityGrade3 nvarchar(50),
		
		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),
		
		SubActivityGrade4 nvarchar(50),
		ActivityGrade4 nvarchar(50),
		
		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),
		
		SubActivityGrade5 nvarchar(50),
		ActivityGrade5 nvarchar(50),
		
		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),
		
		SubActivityGrade6 nvarchar(50),
		ActivityGrade6 nvarchar(50),
		
		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),
		
		SubActivityGrade7 nvarchar(50),
		ActivityGrade7 nvarchar(50),
		
		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),

		SubActivityGrade8 nvarchar(50),
		ActivityGrade8 nvarchar(50),

		Exam9Name Nvarchar(150),
		Exam10Name Nvarchar(150),
		Exam11Name Nvarchar(150),
		Exam12Name Nvarchar(150),
		Exam13Name Nvarchar(150),

		SubActivityGrade9 nvarchar(50),
		ActivityGrade9 nvarchar(50),

		SubActivityGrade10 nvarchar(50),
		ActivityGrade10 nvarchar(50),

		SubActivityGrade11 nvarchar(50),
		ActivityGrade11 nvarchar(50),

		SubActivityGrade12 nvarchar(50),
		ActivityGrade12 nvarchar(50),

		SubActivityGrade13 nvarchar(50),
		ActivityGrade13 nvarchar(50),

		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		TotalDays decimal(6, 2),
		PresentDays decimal(6, 2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		IsDisplayParentName bit,
		
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		
		ActivityName nvarchar(200),
		SubActivityName nvarchar(200),
		SubActivityId int,
		ActivityId Int,
		 SubActivityGrade nvarchar(50),
		 ActivityGrade nvarchar(50),
		SubActivityGradeIndicator nvarchar(50),
		SubActivityDescriptiveIndicator nvarchar(200),
		SubjectActivityOrderIndex Smallint,
		SubActivityOrderIndex smallint,
		ColumnSubjectCount SmallInt,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		Height1 decimal(6,2),
		Height2 decimal(6,2),
		Height3 decimal(6,2),
		Height4 decimal(6,2),
		Height5 decimal(6,2),
		Height6 decimal(6,2),
		Height7 decimal(6,2),
		Height8 decimal(6,2),
		Height9 decimal(6,2),
		Height10 decimal(6,2),
		Height11 decimal(6,2),
		Height12 decimal(6,2),
		Height13 decimal(6,2),
		Weight1 decimal(6,2),
		Weight2 decimal(6,2),
		Weight3 decimal(6,2),
		Weight4 decimal(6,2),
		Weight5 decimal(6,2),
		Weight6 decimal(6,2),
		Weight7 decimal(6,2),
		Weight8 decimal(6,2),
		Weight9 decimal(6,2),
		Weight10 decimal(6,2),
		Weight11 decimal(6,2),
		Weight12 decimal(6,2),
		Weight13 decimal(6,2),
		TotalDays1 decimal(6, 2),
		PresentDays1 decimal(6, 2),
		TotalDays2 decimal(6, 2),
		PresentDays2 decimal(6, 2),
		TotalDays3 decimal(6, 2),
		PresentDays3 decimal(6, 2),
		TotalDays4 decimal(6, 2),
		PresentDays4 decimal(6, 2),
		TotalDays5 decimal(6, 2),
		PresentDays5 decimal(6, 2),
		TotalDays6 decimal(6, 2),
		PresentDays6 decimal(6, 2),
		TotalDays7 decimal(6, 2),
		PresentDays7 decimal(6, 2),
		TotalDays8 decimal(6, 2),
		PresentDays8 decimal(6, 2),
		TotalDays9 decimal(6, 2),
		PresentDays9 decimal(6, 2),
		TotalDays10 decimal(6, 2),
		PresentDays10 decimal(6, 2),
		TotalDays11 decimal(6, 2),
		PresentDays11 decimal(6, 2),
		TotalDays12 decimal(6, 2),
		PresentDays12 decimal(6, 2),
		TotalDays13 decimal(6, 2),
		PresentDays13 decimal(6, 2),
		MyActivity1 nvarchar(200),
		MyActivity2 nvarchar(200),
		MyActivity3 nvarchar(200),
		MyActivity4 nvarchar(200),
		MyActivity5 nvarchar(200),
		MyActivity6 nvarchar(200),
		MyActivity7 nvarchar(200),
		MyActivity8 nvarchar(200),
		MyActivity9 nvarchar(200),
		MyActivity10 nvarchar(200),
		MyActivity11 nvarchar(200),
		MyActivity12 nvarchar(200),
		MyActivity13 nvarchar(200),
		GeneralRemark1 nvarchar(1000),
		GeneralRemark2 nvarchar(1000),
		GeneralRemark3 nvarchar(1000),
		GeneralRemark4 nvarchar(1000),
		GeneralRemark5 nvarchar(1000),
		GeneralRemark6 nvarchar(1000),
		GeneralRemark7 nvarchar(1000),
		GeneralRemark8 nvarchar(1000),
		GeneralRemark9 nvarchar(1000),
		GeneralRemark10 nvarchar(1000),
		GeneralRemar11 nvarchar(1000),
		GeneralRemark12 nvarchar(1000),
		GeneralRemark13 nvarchar(1000),
		PresentAddress nvarchar(500) ,
		MobileNo nvarchar(50),
		House nvarchar(100),
		 
		AttendanceTerm1 decimal(6, 2) ,
		AttendanceTerm2 decimal(6, 2),
		WorkingDaysTerm1 decimal(6, 2),
		WorkingDaysTerm2 decimal(6, 2),
		
		BloodGroup nvarchar(20),
		GradeSetIdText nvarchar(50),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ParentEmail nvarchar(500),
		MyGoal nvarchar(200),
		MyStrength nvarchar(200),
		MyInterestHobby nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		Achievements nvarchar(1000),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		ClassTeacherName Nvarchar(100),
		HouseRemark nvarchar(1000),
		GeneralRemark nvarchar(1000),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		IsDecimal bit,
		Name nvarchar(150),
		--mantis 0029914
		PermanentStreetOne nvarchar(150),
		PermanentStreetTwo nvarchar(150),
		PermanentStreetThree nvarchar(150),
		AdmissionNo nvarchar(50),
		StudentContactNo nvarchar(50),
		DescriptiveIndicator nvarchar(200),
		DescriptiveIndicator1 nvarchar(200),
		DescriptiveIndicator2 nvarchar(200),
		DescriptiveIndicator3 nvarchar(200),
		DescriptiveIndicator4 nvarchar(200),
		DescriptiveIndicator5 nvarchar(200),
		DescriptiveIndicator6 nvarchar(200),
		DescriptiveIndicator7 nvarchar(200),
		DescriptiveIndicator8 nvarchar(200),
		DescriptiveIndicator9 nvarchar(200),
		DescriptiveIndicator10 nvarchar(200),
		DescriptiveIndicator11 nvarchar(200),
		DescriptiveIndicator12 nvarchar(200),
		DescriptiveIndicator13 nvarchar(200)

	)	
	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	
	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,
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	SubActivityGrade,
	ActivityGrade,
	ActivityName,
	SubActivityName,
	SubActivityId,
	ActivityId,
	SubActivityGradeIndicator,
	SubActivityDescriptiveIndicator,
	SubjectActivityOrderIndex,
	SubActivityOrderIndex,
	ColumnSubjectCount,
	MarksheetHeaderA4,
	IsImageHeader,
	PresentAddress,
 	MobileNo,
	House,
	AttendanceTerm1   ,
	AttendanceTerm2  ,
	WorkingDaysTerm1  ,
	WorkingDaysTerm2  ,
	BloodGroup,
	GradeSetIdText,
	IsDisplayMonthlyAttendanceText,
	DentalHygiene,
	VisionLeft,
	VisionRight,
	TeacherSignCaption,
	PrincipalSignCaption,ParentSignCaption,
	ParentEmail,
	MyGoal ,
	MyStrength ,
	MyInterestHobby ,
	AreaOfInterest ,
	Responsibility ,
	Achievements ,
	ImprovementArea ,
	ProgressArea ,
	MyActivity ,
	ClassTeacherRemark ,
	ClassTeacherName ,
	HouseRemark ,
	GeneralRemark ,
	FatherContactNo ,
	MotherContactNo ,
	FatherMail,
	MotherMail,
	IsDecimal,
	Name,
	-- mantis-0029914
	PermanentStreetOne,
	PermanentStreetTwo,
	PermanentStreetThree,
	AdmissionNo,
	StudentContactNo,
	DescriptiveIndicator
	)
	
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS StudentName,
		A.RollNo,
		R.ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.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 WHEN EM.IsDisplayPhoto = 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,
	    SAM.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,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		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,
		SSA.Grade AS SubActivityGrade,
		ISNULL(SAS.Grade,'') AS ActivityGrade,
		SAM.Title AS ActivityName,
		SSAM.Title AS SubActivityName,
		SSA.SubjectSubActivityId AS SubActivityId,
		SAM.Id AS ActivityId,
		SSA.GradeIndicator AS SubActivityGradeIndicator,
		SSA.DescriptiveIndicator AS SubActivityDescriptiveIndicator,
		SAM.OrderIndex AS SubjectActivityOrderIndex,
		SSAM.OrderIndex AS SubActivityOrderIndex,
		CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
				ELSE 1 END   AS   ColumnSubjectCount,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.MarksheetHeaderA4
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader	,
		ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		 SC.ParentContactNo,
		ISNULL(HM.Title,'') AS House,
		ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
		ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
		ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
		ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
		ISNULL(BGM.Title,'') AS BloodGroup,
		CONVERT (nvarchar(50),EM.GradeSetId) AS GradeSetIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
		--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(ParentSignCaption,'') AS ParentSignCaption,
		SC.ParentEmail As ParentEmail,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		-- mantis-0029914
		SC.PermanentStreetOne,
		SC.PermanentStreetTwo,
		SC.PermanentStreetThree,
		StuA.AdmissionNumber,
		SC.StudentContactNo,
		SSA.DescriptiveIndicator AS DescriptiveIndicator
		
	FROM 
		sAssessment.tCCESubjectSubActivityExamScore SSA
		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
		INNER JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
		LEFT JOIN sAssessment.tCCESubjectActivityExamScore SAS ON SAS.SubjectActivityId= SAM.Id AND SSA.AcademicId = SAS.AcademicId AND SSA.ExamId = SAS.ExamId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId	
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
		INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = SAM.ClassSubjectId
		--INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
    	INNER JOIN sStudent.tAcademic  A ON   SSA.AcademicId = A.Id
		LEFT JOIN sAssessment.tCCEResult CCER    ON  CCER.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
		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 sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = A.Id AND OS.ClassSubjectId = ED.ClassSubjectId  
		LEFT JOIN sAssessment.tResult R ON R.AcademicId = SSA.AcademicId AND R.ExamId = SSA.ExamId
		LEFT JOIN sAssessment.tResultDetail RD  ON R.Id = RD.ResultId AND ED.ID = RD.ExamDetailId 
		LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = StuM.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =Stum.ID
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		--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
		--0029914
		LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	
	 WHERE
		SSA.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClass) OR (@rClass=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 (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	 
	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.SubExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	 
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int  
	Select @lCount = MAX(Id) from #tempcombineExam	
	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
					
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,					
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
					 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
					 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
					 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark 
					 									
					 From
						 
						 sAssessment.tResult R 
						INNER JOIN  sAssessment.tResultDetail RD ON RD.ResultId = R.Id						
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 							
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
 
	 set @query ='update T SET
					
					 
					 SubActivityGrade' + convert(nvarchar(15),@lCount)+ '=SSA.Grade,
					 DescriptiveIndicator' + convert(nvarchar(15),@lCount)+ '=SSA.DescriptiveIndicator	
					 						
					 From
						sAssessment.tCCESubjectSubActivityExamScore SSA				
						inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	 					
						WHERE SSA.ExamId =' + convert(nvarchar(15), @lSubExamId)  


						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
 
  set @query ='update T SET
					
					  ActivityGrade' + convert(nvarchar(15),@lCount)+ '=SAS.Grade	
					 						
					 From
						sAssessment.tCCESubjectActivityExamScore SAS				
						inner JOIN 	#TempAllExam  T ON T.ActivityId = SAS.SubjectActivityId And T.AcademicId = SAS.AcademicId	 					
						WHERE SAS.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
	-- set @query ='update T SET
					
	--				 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
	--				 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
	--				 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
	--				 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
	--				 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
	--				 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark
	--				 From
	--					sAssessment.tCCESubjectSubActivityExamScore SSA
						
	--					inner JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
	--					inner JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
	--					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
	--					inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.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.Title,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=EM.ExamMaximum
					 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
	SELECT @rBuilder1 , T.*
	FROM #TempAllExam T
	
	
		
	drop table #tempcombineExam
	Drop table #TempAllExam

	--Select 
	-- '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
		
	--	CONVERT(bigint , 0) As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	CONVERT(decimal , 0) As TotalMark ,
	--	CONVERT(decimal , 0) As TotalObtain,
	--	CONVERT(decimal , 0) As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
		
	--	--MaximumMark1 decimal(8,2),		
	--	'' As SubjectGrade1 ,
	--	--Obtain1 decimal(8,2),
	--	--ExamMaximum1 decimal(8,2),
	--	CONVERT(bit , 0) As IsPresent1,
						
	--	CONVERT(decimal , 0) As MaximumMark2 ,	
	--	'' As SubjectGrade2 ,
	--	CONVERT(decimal , 0) As Obtain2 ,
	--	CONVERT(decimal , 0) As ExamMaximum2 ,
	--	CONVERT(bit , 0) As IsPresent2,
				
	--	CONVERT(decimal , 0) As MaximumMark3 ,
	--	'' As SubjectGrade3 ,
	--	CONVERT(decimal , 0) As Obtain3 ,
	--	CONVERT(decimal , 0) As ExamMaximum3 ,
	--	CONVERT(bit , 0) As IsPresent3 ,		
		
	--	CONVERT(decimal , 0) As MaximumMark4 ,	
	--	'' As SubjectGrade4 ,
	--	CONVERT(decimal , 0) As Obtain4 ,
	--	CONVERT(decimal , 0) As ExamMaximum4 ,
	--	CONVERT(bit , 0) As IsPresent4 ,	
				
	--	CONVERT(decimal , 0) As MaximumMark5 ,		
	--	'' As SubjectGrade5 ,
	--	CONVERT(decimal , 0) As Obtain5 ,
	--	CONVERT(decimal , 0) As ExamMaximum5 ,
	--	CONVERT(bit , 0) As IsPresent5 ,	
				
	--	CONVERT(decimal , 0) As MaximumMark6 ,		
	--	'' As SubjectGrade6,
	--	CONVERT(decimal , 0) As Obtain6 ,
	--	CONVERT(decimal , 0) As ExamMaximum6 ,
	--	CONVERT(bit , 0) As IsPresent6 ,	
		
	--	CONVERT(decimal , 0) As MaximumMark7 ,		
	--	'' As SubjectGrade7,
	--	CONVERT(decimal , 0) As Obtain7 ,
	--	CONVERT(decimal , 0) As ExamMaximum7 ,
	--	CONVERT(bit , 0) As IsPresent7 ,	
	
	--	CONVERT(decimal , 0) As MaximumMark8 ,	
	--	'' As SubjectGrade8,
	--	CONVERT(decimal , 0) As Obtain8 ,
	--	CONVERT(decimal , 0) As ExamMaximum8 ,
	--	CONVERT(bit , 0) As IsPresent8 ,	
		
	--	'' As SubjectGrade9,
	--	CONVERT(bit , 0) As IsPresent9 ,

	--	'' As SubjectGrade10,
	--	CONVERT(bit , 0) As IsPresent10 ,

	--	'' As SubjectGrade11,
	--	CONVERT(bit , 0) As IsPresent11 ,

	--	'' As SubjectGrade12,
	--	CONVERT(bit , 0) As IsPresent12 ,

	--	'' As SubjectGrade13,
	--	CONVERT(bit , 0) As IsPresent13 ,

	--	'' As SubjectGradeTerm1,
	--	'' As SubjectGradeTerm2 ,
	--	CONVERT(bit , 0) As IsMarksInDecimal ,
	--	CONVERT(bit , 0) As column_visible ,
	--	--Obtain decimal(5,2),
	--	CONVERT(decimal , 0) As Percentile,
	--	--ClassSubject nvarchar(100),
	--	CONVERT(bigint , 0) As ResultDetailId ,
	--	CONVERT(bigint , 0) As ResultId ,	
	--	'' As Remark1 ,
	--	'' As Remark2 ,
	--	'' As Remark3 ,
	--	'' As DisplayTitle ,		
	--	CONVERT(bit , 0) As IsRankNo , 
	--	CONVERT(bit , 0) As IsGrade ,
	--	CONVERT(bit , 0) As IsPercentile ,
	--	CONVERT(bit , 0) As IsPercentage ,
	--	CONVERT(bit , 0) As IsSubjectPercentile ,
	--	CONVERT(bit , 0) As IsProcessResult ,
	--	CONVERT(bit , 0) As IsNegativeMarks ,
	--	CONVERT(bit , 0) As IsIncludeCoScholastic ,
	--	CONVERT(bit,0) As IsOnPrePrinted ,
	--	CONVERT(bit , 0) As IsDisplayPhoto ,
	--	CONVERT(bit , 0) As IsDisplayBirthDate ,
	--	CONVERT(bit , 0) As IsLockForEdit ,
	--	CONVERT(bit , 0) As IsDisplaySchoolName ,			
	--	CONVERT(bit , 0) As IsDisplayAttendance ,
	--	CONVERT(bit , 0) As IsDisplayHeightWeight ,
	--	CONVERT(bit , 0) As IsResultStatus ,
	--	'' As FooterAdjustmentText ,
	--	'' As DetailAdjustmentText ,
	--	0 As FooterAdjustment ,
	--	0 As DetailAdjustment ,
	--	'' As ResultRemark ,
	--	CONVERT(Date , null) As DateOfBirth ,
	--	CONVERT(decimal , 0) As HeightTerm1 ,
	--	CONVERT(decimal , 0) As WeightTerm1 ,
	--	CONVERT(decimal , 0) As HeightTerm2,
	--	CONVERT(decimal , 0) As WeightTerm2 ,
	--	CONVERT(decimal , 0) As HeightAnnual ,
	--	CONVERT(decimal , 0) As WeightAnnual ,
	--	0 As PresentDaysTerm1,
	--	0 As PresentDaysTerm2 ,
	--	0 As PresentDaysAnnual ,
	--	0 As TotalDaysTerm1 ,
	--	0 As TotalDaysTerm2 ,
	--	0 As TotalDaysAnnual ,
	--	CONVERT(decimal , 0) As TotalMarkTerm1 ,
	--	CONVERT(decimal , 0) As TotalObtainTerm1 ,
	--	CONVERT(decimal , 0) As PercentageTerm1,
	--	0 As RankNumberTerm1 ,
	--	'' As ResultGradeTerm1,
	--	CONVERT(decimal , 0) As PercentileTerm1 ,
	--	'' As ResultStatusTerm1,		   
	--	CONVERT(decimal , 0) As TotalMarkTerm2 ,
	--	CONVERT(decimal , 0) As TotalObtainTerm2 ,
	--	CONVERT(decimal , 0) As PercentageTerm2 ,
	--	0 As RankNumberTerm2 ,
	--	'' As ResultGradeTerm2 ,
	--	CONVERT(decimal , 0) As PercentileTerm2 ,
	--	'' As ResultStatusTerm2 , 
	--	CONVERT(tinyInt , 0) As TermScopeId ,		 
	--	Convert (varbinary(max) , '') As StudentPhoto ,
	--	'' As GradeString,
	--	CONVERT(bit , 0) As IsDisplayGradeString ,		 
	--	CONVERT(bit , 0) As IsDisplayInMarksheet ,
	--	CONVERT(bit , 0) As IsShowSubjectGrade ,
	--	CONVERT(bit , 0) As IsIncludeInTotal ,
	--	0 As ClassSubjectID ,
	--	0 As SubjectId ,
	--	--Maximum decimal(5,2),
	--	0 As SubjectOrderIndex ,
	--	'' As SubjectGrade ,
	--	'' As SubjectName ,
	--	'' As SubjectCode ,	
	--	CONVERT(decimal , 0) As SubjectMinimum ,		
	--	CONVERT(decimal , 0) As SubjectMaximum ,
	--	CONVERT(decimal , 0) As SubjectObtain ,
		
	--	'' As Exam1Name ,		
	--	CONVERT(decimal , 0) As TotalMarks1 ,		
	--	CONVERT(decimal , 0) As TotalObtain1 ,
	--	CONVERT(decimal , 0) As Percentage1 ,
	--	0 As RankNumber1 ,
	--	'' As ResultGrade1,
	--	CONVERT(decimal , 0) As Percentile1 ,
	--	'' As ResultStatus1 ,
		
	--	'' As SubActivityGrade1,
	--	'' As ActivityGrade1,
		
	--	'' As Exam2Name ,	
	--	CONVERT(decimal , 0) As TotalMarks2 ,
	--	CONVERT(decimal , 0) As TotalObtain2 ,
	--	CONVERT(decimal , 0) As Percentage2 ,
	--	0 As RankNumber2 ,
	--	'' As ResultGrade2 ,
	--	CONVERT(decimal , 0) As Percentile2 ,
	--	'' As ResultStatus2 ,
		
	--	'' As SubActivityGrade2,
	--	'' As ActivityGrade2 ,
		
	--	'' As Exam3Name ,	
	--	CONVERT(decimal , 0) As TotalMarks3 ,
	--	CONVERT(decimal , 0) As TotalObtain3 ,
	--	CONVERT(decimal , 0) As Percentage3 ,
	--	0 As RankNumber3 ,
	--	'' As ResultGrade3 ,
	--	CONVERT(decimal , 0) As Percentile3 ,		
	--	'' As ResultStatus3,
		
	--	'' As SubActivityGrade3 ,
	--	'' As ActivityGrade3 ,
		
	--	'' As Exam4Name ,	
	--	CONVERT(decimal , 0) As TotalMarks4 ,
	--	CONVERT(decimal , 0) As TotalObtain4,
	--	CONVERT(decimal , 0) As Percentage4 ,
	--	0 As RankNumber4 ,
	--	'' As ResultGrade4 ,
	--	CONVERT(decimal , 0) As Percentile4 ,
	--	'' As ResultStatus4 ,
		
	--	'' As SubActivityGrade4,
	--	'' As ActivityGrade4 ,
		
	--	'' As Exam5Name ,		
	--	CONVERT(decimal , 0) As TotalMarks5 ,
	--	CONVERT(decimal , 0) As TotalObtain5 ,
	--	CONVERT(decimal , 0) As Percentage5 ,
	--	0 As RankNumber5 ,
	--	'' As ResultGrade5 ,
	--	CONVERT(decimal , 0) As Percentile5 ,
	--	'' As ResultStatus5 ,
		
	--	'' As SubActivityGrade5 ,
	--	'' As ActivityGrade5 ,
		
	--	'' As Exam6Name ,	
	--	CONVERT(decimal , 0) As TotalMarks6 ,
	--	CONVERT(decimal , 0) As TotalObtain6,
	--	CONVERT(decimal , 0) As Percentage6 ,
	--	0 As RankNumber6 ,
	--	'' As ResultGrade6 ,
	--	CONVERT(decimal , 0) As Percentile6 ,
	--	'' As ResultStatus6 ,
		
	--	'' As SubActivityGrade6 ,
	--	'' As ActivityGrade6 ,
		
	--	'' As Exam7Name ,		
	--	CONVERT(decimal , 0) As TotalMarks7 ,
	--	CONVERT(decimal , 0) As TotalObtain7,
	--	CONVERT(decimal , 0) As Percentage7 ,
	--	0 As RankNumber7 ,
	--	'' As ResultGrade7,
	--	CONVERT(decimal , 0) As Percentile7 ,
	--	'' As ResultStatus7 ,
		
	--	--SubActivityGrade7 nvarchar(10),
		
	--	'' As Exam8Name,
	--	CONVERT(decimal , 0) As TotalMarks8 ,
	--	CONVERT(decimal , 0) As TotalObtain8 ,
	--	CONVERT(decimal , 0) As Percentage8,
	--	0 As RankNumber8 ,
	--	'' As ResultGrade8 ,
	--	CONVERT(decimal , 0) As Percentile8,
	--	'' As ResultStatus8,

	--	'' As Exam9Name,
	--	'' As Exam10Name,
	--	'' As Exam11Name,
	--	'' As Exam12Name,
	--	'' As Exam13Name,

	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,
	--	CONVERT(decimal , 0) As TotalDays ,
	--	CONVERT(decimal , 0) As PresentDays ,
	--	CONVERT(decimal , 0) As StudentHeight,
	--	CONVERT(decimal , 0) As StudentWeight ,
	--	'' As ExamSeatNo ,
	--	0 As ExamId ,
	--	CONVERT(bit , 0) As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	CONVERT(bit , 0) As IsShowSubjectMark , 
	--	CONVERT(bit , 0) As IsOptionalSubject ,
	--	CONVERT(tinyInt , 0) As CoScholasticScopeId ,
	--	CONVERT(bit , 0) As IsDisplayPrincipalSign ,
	--	CONVERT(bit , 0) As IsDisplayTeacherSign ,
	--	Convert (varbinary(max) , '') As EmployeeSign,
		
	--	'' As ActivityName ,
	--	'' As SubActivityName ,
	--	0 As SubActivityId ,
	--	0 As ActivityId ,
	--	 '' As SubActivityGrade,
	--	 '' As ActivityGrade ,
	--	'' As SubActivityGradeIndicator ,
	--	'' As SubActivityDescriptiveIndicator,
	--	0 As SubjectActivityOrderIndex ,
	--	0 As SubActivityOrderIndex ,
	--	0 As ColumnSubjectCount ,
	--	Convert (varbinary(max) , '') As MarksheetHeaderA4 ,
	--	CONVERT(bit,0) As IsImageHeader ,
	--	CONVERT(decimal , 0) As Height1 ,
	--	CONVERT(decimal , 0) As Height2 ,
	--	CONVERT(decimal , 0) As Height3,
	--	CONVERT(decimal , 0) As Height4 ,
	--	CONVERT(decimal , 0) As Height5,
	--	CONVERT(decimal , 0) As Height6 ,
	--	CONVERT(decimal , 0) As Height7 ,
	--	CONVERT(decimal , 0) As Height8 ,
	--	CONVERT(decimal , 0) As Height9,
	--	CONVERT(decimal , 0) As Height10 ,
	--	CONVERT(decimal , 0) As Height11,
	--	CONVERT(decimal , 0) As Height12 ,
	--	CONVERT(decimal , 0) As Height13 ,

	--	CONVERT(decimal , 0) As Weight1 ,
	--	CONVERT(decimal , 0) As Weight2 ,
	--	CONVERT(decimal , 0) As Weight3 ,
	--	CONVERT(decimal , 0) As Weight4,
	--	CONVERT(decimal , 0) As Weight5 ,
	--	CONVERT(decimal , 0) As Weight6 ,
	--	CONVERT(decimal , 0) As Weight7 ,
	--	CONVERT(decimal , 0) As Weight8 ,
	--	CONVERT(decimal , 0) As Weight9 ,
	--	CONVERT(decimal , 0) As Weight10,
	--	CONVERT(decimal , 0) As Weight11 ,
	--	CONVERT(decimal , 0) As Weight12 ,
	--	CONVERT(decimal , 0) As Weight13 ,

	--	CONVERT(decimal , 0) As TotalDays1 ,
	--	CONVERT(decimal , 0) As PresentDays1 ,
	--	CONVERT(decimal , 0) As TotalDays2 ,
	--	CONVERT(decimal , 0) As PresentDays2 ,
	--	CONVERT(decimal , 0) As TotalDays3 ,
	--	CONVERT(decimal , 0) As PresentDays3 ,
	--	CONVERT(decimal , 0) As TotalDays4 ,
	--	CONVERT(decimal , 0) As PresentDays4 ,
	--	CONVERT(decimal , 0) As TotalDays5 ,
	--	CONVERT(decimal , 0) As PresentDays5 ,
	--	CONVERT(decimal , 0) As TotalDays6 ,
	--	CONVERT(decimal , 0) As PresentDays6 ,
	--	CONVERT(decimal , 0) As TotalDays7 ,
	--	CONVERT(decimal , 0) As PresentDays7 ,
	--	CONVERT(decimal , 0) As TotalDays8 ,
	--	CONVERT(decimal , 0) As PresentDays8 ,
	--	CONVERT(decimal , 0) As TotalDays9 ,
	--	CONVERT(decimal , 0) As PresentDays9 ,
	--	CONVERT(decimal , 0) As TotalDays10 ,
	--	CONVERT(decimal , 0) As PresentDays10 ,
	--	CONVERT(decimal , 0) As TotalDays11 ,
	--	CONVERT(decimal , 0) As PresentDays11 ,
	--	CONVERT(decimal , 0) As TotalDays12 ,
	--	CONVERT(decimal , 0) As PresentDays12 ,
	--	CONVERT(decimal , 0) As TotalDays13 ,
	--	CONVERT(decimal , 0) As PresentDays13 ,

	--	'' As MyActivity1,
	--	'' As MyActivity2 ,
	--	'' As MyActivity3,
	--	'' As MyActivity4 ,
	--	'' As MyActivity5,
	--	'' As MyActivity6,
	--	'' As MyActivity7,
	--	'' As MyActivity8 ,
	--	'' As MyActivity9,
	--	'' As MyActivity10 ,
	--	'' As MyActivity11,
	--	'' As MyActivity12,
	--	'' As MyActivity13,

	--	'' As GeneralRemark1,
	--	'' As GeneralRemark2 ,
	--	'' As GeneralRemark3 ,
	--	'' As GeneralRemark4,
	--	'' As GeneralRemark5,
	--	'' As GeneralRemark6,
	--	'' As GeneralRemark7,
	--	'' As GeneralRemark8 ,
	--	'' As GeneralRemark9 ,
	--	'' As GeneralRemark10,
	--	'' As GeneralRemark11,
	--	'' As GeneralRemark12,
	--	'' As GeneralRemark13,

	--	'' As PresentAddress ,
	--	'' As  MobileNo,
	--	'' As House ,
		 
	--	CONVERT(decimal , 0) As AttendanceTerm1  ,
	--	CONVERT(decimal , 0) As AttendanceTerm2 ,
	--	CONVERT(decimal , 0) As WorkingDaysTerm1 ,
	--	CONVERT(decimal , 0) As WorkingDaysTerm2 ,
	--	  '' As BloodGroup ,
	--	  '' As GradeSetIdText ,
	--	  '' As IsDisplayMonthlyAttendanceText ,
	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
	--	'' As ParentEmail ,
	--  '' AS MyGoal,
	--	'' AS MyStrength,
	--	'' AS MyInterestHobby,
	--	'' AS AreaOfInterest,
	--	'' AS Responsibility,
	--	'' AS Achievements,
	--	'' As ImprovementArea,
	--	'' AS ProgressArea,
	--	'' AS MyActivity,
	--	'' As ClassTeacherRemark,
	--	'' AS ClassTeacherName,
	--	'' As HouseRemark,
	--	'' As GeneralRemark,
	--	'' AS FatherContactNo,
	--	'' AS MotherContactNo,
	--	'' AS FatherMail,
	--	'' AS MotherMail,
	--  CONVERT(bit , 0) As IsDecimal,
	--  '' As Name,
	--'' AS PermanentStreetOne,
	--'' AS PermanentStreetTwo,
	--'' AS PermanentStreetThree,
	--'' AS AdmissionNo,
	--'' AS StudentContactNo,
	--'' AS DescriptiveIndicator ,
	--'' AS DescriptiveIndicator1,
	--'' AS DescriptiveIndicator2,
	--'' AS DescriptiveIndicator3,
	--'' AS DescriptiveIndicator4,
	--'' AS DescriptiveIndicator5,
	--'' AS DescriptiveIndicator6,
	--'' AS DescriptiveIndicator7,
	--'' AS DescriptiveIndicator8,
	--'' AS DescriptiveIndicator9,
	--'' AS DescriptiveIndicator10,
	--'' AS DescriptiveIndicator11,
	--'' AS DescriptiveIndicator12,
	--'' AS DescriptiveIndicator13

	


end
/*
 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
					
					--sAssessment.tCCESubjectActivityMaster SAM 	
	--		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.SubjectActivityId=SAM.Id  
	--		INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	--		INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
	--		 INNER JOIN sStudent.vStudentAcademic  A ON   A.ClassId = CS.ClassId AND  A.StatusId = 1
	--		 LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SSA ON SSA.AcademicId = A.AcademicId AND SSA.SubjectSubActivityId= SSAM.Id  	
			  */
GO
PRINT N'Altering Procedure [sAssessment].[pRptSubjectActivityExamDetailWithTermGradeGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailWithTermGradeGet]
	 
		@rOrgId int=0,
		@rExamId int=0,
		@rClass int=0,
		@rDivisionId int=0,
		@rBatchId int=0,
		@rBuilder1 nvarchar(max)='',
		@rAcademicId bigint=0,
		@rCode nvarchar(20)='',
		@rFromRollNo int=0,
		@rToRollNo int=0,
		@rMultiCode nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 
Declare @GradeString nvarchar(500),@GradeSetId int
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

Declare @DecimalConfid nvarchar(20)=''
SELECT @DecimalConfid =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId


--Declare @rIsDisplayStudentPhoto bit, @rIsDisplayTeacherSign bit, @rIsDisplayPrincipalSign bit, @rIsDisplayImageHeader bit
--SELECT @rIsDisplayStudentPhoto = ISNULL(IsDisplayPhoto,0), @rIsDisplayTeacherSign = ISNULL(IsDisplayTeacherSign,0),
--	   @rIsDisplayPrincipalSign = ISNULL(IsDisplayPrincipalSign,0),@rIsDisplayImageHeader = ISNULL(IsDisplayImageHeader,0)
--	   From sAssessment.tExamMaster Where Id = @rExamId
	   
		--DECLARE @lAcademicId TABLE (AcademicId bigint, ClassSubjectId int, Term1Grade nvarchar(20), Term2Grade nvarchar(20), AnnualGrade nvarchar(20),
		--Term1PresentDays Int, Term1TotalDays Int, Term2PresentDays Int, Term2TotalDays Int)
		
		--INSERT INTO @lAcademicId (AcademicId, ClassSubjectId)
		--(
		--	SELECT 			 
		--		SA.AcademicId,
		--		CS.ClassSubjectId
		--	FROM 
		--		sStudent.vStudentAcademic SA
		--		INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = SA.ClassId
		--		INNER JOIN sAssessment.tExamDetail ED ON EM.Id = ED.ExamId
		--		INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId = ED.ClassSubjectId 
		--		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		--	WHERE
		--		((SA.AcademicId=@rAcademicId) OR(@rAcademicId=0))
		--		AND ((CS.ClassId=@rClass) OR (@rClass=0))
		--		And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
		--		And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
		--		And ((EM.Id = @rExamId) OR (@rExamId = 0))
		--		and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((SA.Code = @rCode) OR(@rCode=''))
		--		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		--		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--		AND SA.StatusId = 1
		--)
		
		--Declare @FirstTermExamId AS INT,@SecondTermExamId AS INT, @Term1PresentDays AS INT, @Term1TotalDays AS INT,
		--@Term2PresentDays AS INT, @Term2TotalDays AS INT
		
		--Select @FirstTermExamId=SubExamId  from sAssessment.tExamCombine Where ExamId = @rExamId AND ExamOrder = 1
		
		--Select @SecondTermExamId=SubExamId from sAssessment.tExamCombine Where ExamId = @rExamId AND ExamOrder = 2
		
		
	
		--UPDATE @lAcademicId 
		--SET Term1Grade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @FirstTermExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
	    
		--UPDATE @lAcademicId 
		--SET Term2Grade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @SecondTermExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
		
		--UPDATE @lAcademicId 
		--SET AnnualGrade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @rExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
		
		--UPDATE @lAcademicId 
		--SET Term1PresentDays = SR.PresentDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @FirstTermExamId AND SR.AcademicId = A.AcademicId
		
		--UPDATE @lAcademicId 
		--SET Term1TotalDays = SR.TotalDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @FirstTermExamId AND SR.AcademicId = A.AcademicId
		
	 --   UPDATE @lAcademicId 
		--SET Term2PresentDays = SR.PresentDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @SecondTermExamId AND SR.AcademicId = A.AcademicId
		
		--UPDATE @lAcademicId 
		--SET Term2TotalDays = SR.TotalDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @SecondTermExamId AND SR.AcademicId = A.AcademicId
	    
	    --Select * from @lAcademicId
	    
	    SELECT 			 
			Convert(nvarchar(20),SA.Id) AS AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
			@rBuilder1 AS Builder1,
			SA.Id AS AcademicId,
			SA.RollNo,
			StuM.Number,
			AIS.Grade,
			SAM.Title AS SubjectActivityTitle,
			SSA.Title AS SubjectSubActivityTitle,
			SAM.Id AS ActivityId,
			SSA.Id AS SubjectSubActivityId,
			SAM.OrderIndex AS ActivityOrderIndex,
			SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
			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,
			EM.IsDisplayGradeString,
			EM.IsDisplayParentName,
			StuM.FirstName + ' ' +StuM.MiddleName +' ' +StuM.LastName AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			StuM.code,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto, 
			ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
			CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			CS.OrderIndex,
			EM.SubjectGroupPerPage,
			AIS.GradeIndicator,
			EM.IsCoScholasticGradeIndicator,
			(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
			Em.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsCoScholasticGradeDesIndicator,
			EM.IsCoScholasticGrade,
			Em.IsDisplayParentName,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
			--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
			ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		    ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
			ParentSignCaption,
			SR.ResultRemark3,
			ARD.SubjectGrade,
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
			ISNULL(C.ParentContactNo,'') AS ParentContactNo,
			ISNULL(C.StudentContactNo,'') AS StudentContactNo,
			(C.PresentStreetOne+' '+C.PresentStreetTwo+' '+C.PresentStreetThree+' '+C.PresentCountry+' '+C.PresentState+' '+C.PresentCity+' '+C.PresentZipCode) AS Address1,
			CONVERT(bit,@DecimalConfid) AS IsDecimal,
			--added by megha for 0027299
			AR.ResultGrade As OverallGrade,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS StudentName,
			ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
			ISNULL(SR.Achievements,'') AS Achievements,   ---Mantis - 31821
			ISNULL(SR.MyActivity,'') AS MyActivity		---Mantis - 31821
			
			--A.Term1Grade,
			--A.Term2Grade,
			--A.AnnualGrade,
			--A.Term1PresentDays,
			--A.Term1TotalDays,
			--A.Term2PresentDays,
			--A.Term2TotalDays			
			
		FROM 
			sAssessment.tCCESubjectSubActivityExamScore AIS 
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id 
			INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId		
			INNER JOIN sStudent.tAcademic SA ON SA.Id = AIS.AcademicId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = CS.Id 		 			 
			INNER JOIN sAssessment.tResult AR ON AR.ExamId = AIS.ExamId AND AIS.AcademicId = AR.AcademicId
			INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id AND ARD.ExamDetailId = ED.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId	
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=DM.ClassId 
			
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.Id = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.Id AND EM.ID=RD.ExamId AND CS.Id=RD.ClassSubjectID 
			LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId	
			--LEFT JOIN @lAcademicId A ON A.AcademicId = SA.AcademicId AND A.ClassSubjectId = ED.ClassSubjectId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id=DM.InchargeEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 -- Mantis : 28354	
			
		WHERE
			((SA.Id=@rAcademicId) OR(@rAcademicId=0))
			AND ((CS.ClassId=@rClass) OR (@rClass=0))
			And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
			And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
			and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			And AIS.ExamId=@rExamId
			AND ((STum.Code = @rCode) OR(@rCode=''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND StuM.StatusId = 1
			AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--ORDER BY 
		--	SA.RollNo ASC,
		--	SAM.OrderIndex ASC,
		--	SSA.OrderIndex ASC;
			
END
GO
PRINT N'Altering Procedure [sAudit].[pActivityLogGet]...';


GO
ALTER PROCEDURE [sAudit].[pActivityLogGet]
	@rOrgGroupId int,
	@rOrgId int,
	@rUserName nvarchar(100),
	@rScreenName nvarchar(100),
	@rActivity nvarchar(500),
	@rFromDate date,
	@rToDate date,
	@rOSTypeId tinyint=0,
	@rIsHistory bit = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rScreenName = sCommon.fSearchStringGet(@rScreenName)
SET @rActivity = sCommon.fSearchStringGet(@rActivity)
SET @rToDate = DATEADD(day,1,@rToDate)

	IF(@rIsHistory = 1)
	BEGIN
       SELECT 
            AL.OrgGroupId,
            AL.OrgId,
            OM.Title AS OrganizationName,
            AL.UserId,
			U.DisplayTitle AS UserName,
			U.LoginTitle,
			U.SessionId,
			S.Title AS ScreenName,
			AL.AuditDate,
			(CASE WHEN AL.ScreenId=126
				  THEN AL.Activity		
			      WHEN AL.ScreenId=20878
				  THEN AL.Activity		
				  WHEN AL.ScreenId=30179
				  THEN AL.Activity
				  WHEN AL.ScreenId=20196
				  THEN AL.Activity
				  WHEN AL.ScreenId=30788
				  THEN AL.Activity
				  WHEN AL.ScreenId=30780
				  THEN AL.Activity
				  WHEN AL.ScreenId=30790
				  THEN AL.Activity
				  WHEN AL.ScreenId=20745
				  THEN AL.Activity
				  WHEN AL.ScreenId=31257
				  THEN AL.Activity
				  WHEN AL.ScreenId=31341
				  THEN AL.Activity
			 ELSE SUBSTRING(AL.Activity, CHARINDEX(' ', AL.Activity)+1, LEN(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1))  END)AS  Activity,			
			ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
			ISNULL(AL.RecordDetail,'') AS RecordDetail,
			ISNULL(OS.Title,'') AS OSType
			
       FROM 
		   sAudit.tActivityLogHistory AL
		   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
		   LEFT JOIN sAlert.tOSType OS ON OS.Id = AL.OSTypeId
       WHERE
		   AL.OrgGroupId = @rOrgGroupId
		   AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
		   AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
		   AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
		   AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))
		   AND (AL.AuditDate >= @rFromDate)
		   AND (AL.AuditDate <= @rToDate)
		   AND ((AL.OSTypeId = @rOSTypeId) OR (@rOSTypeId=0))
       ORDER BY 
			AL.AuditDate DESC
	END
	ELSE
	BEGIN
		SELECT 
            AL.OrgGroupId,
            AL.OrgId,
            OM.Title AS OrganizationName,
            AL.UserId,
			U.DisplayTitle AS UserName,
			U.LoginTitle,
			U.SessionId,
			S.Title AS ScreenName,
			AL.AuditDate,
			(CASE WHEN AL.ScreenId=126
				  THEN AL.Activity		
			      WHEN AL.ScreenId=20878
				  THEN AL.Activity		
				  WHEN AL.ScreenId=30179
				  THEN AL.Activity
				  WHEN AL.ScreenId=20196
				  THEN AL.Activity
				  WHEN AL.ScreenId=30788
				  THEN AL.Activity
				  WHEN AL.ScreenId=30780
				  THEN AL.Activity
				  WHEN AL.ScreenId=30790
				  THEN AL.Activity
				  WHEN AL.ScreenId=20884
				  THEN AL.Activity
				  WHEN AL.ScreenId=20745
				  THEN AL.Activity
				  WHEN AL.ScreenId=31257
				  THEN AL.Activity
				  WHEN AL.ScreenId=31341
				  THEN AL.Activity
			 ELSE SUBSTRING(AL.Activity, CHARINDEX(' ', AL.Activity)+1, LEN(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1))  END) AS  Activity,			
			ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
			ISNULL(AL.RecordDetail,'') AS RecordDetail,
			ISNULL(OS.Title,'') AS OSType
			
       FROM 
		   sAudit.tActivityLog AL
		   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
		   LEFT JOIN sAlert.tOSType OS ON OS.Id = AL.OSTypeId
       WHERE
		   AL.OrgGroupId = @rOrgGroupId
		   AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
		   AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
		   AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
		   AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))
		   AND (AL.AuditDate >= @rFromDate)
		   AND (AL.AuditDate <= @rToDate)
		   AND ((AL.OSTypeId = @rOSTypeId) OR (@rOSTypeId=0))
       ORDER BY 
			AL.AuditDate DESC
	END
END
GO


PRINT N'Altering Procedure [sCertificate].[pRptLeavingCertificateGet]...';


GO


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

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

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


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

--IF(@lOrgId IS NULL)
--BEGIN
--SELECT @lSchoolRemark1=DefaultRemark1,@lSchoolRemark2=DefaultRemark2,@lSchoolRemark3=DefaultRemark3,@lSchoolRequiredSignature=DefaultRequiredSignature FROM sCommon.tReportRemarkGroupMaster WHERE Id=3
--END


SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 178 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	
	
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	

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


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

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




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

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

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


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

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

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

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

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

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

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

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

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

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

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

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

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

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

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

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

DELETE FROM sErp.tCustomerMaster WHERE OrgGroupId = @rOrgGroupId

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

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

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


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


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

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


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

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

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

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


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

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

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


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

	-- special case will come orgwise and orggroupwise

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


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


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

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

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

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

DELETE FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @rOrgGroupId



DELETE FROM sCommon.tOrgGroupDepartmentMaster WHERE OrgGroupId = @rOrgGroupId

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


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

DELETE FROM sErp.tCustomerPlugInLog WHERE OrgGroupId= @rOrgGroupId

DELETE FROM sErp.tScreenFunctionalityTraining WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommon.tPhysicalDisabilityCategoryMaster WHERE OrgGroupId= @rOrgGroupId

DELETE FROM siTax.tForm16SubDetail WHERE CAST(LEFT(Form16Id, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSecurity.tAssignSubRole WHERE CAST(LEFT(RoleId, 4) AS int) = @rOrgGroupId

DELETE FROM sCommunication.tChatGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tChatGroupScope WHERE CAST(LEFT(ChatGroupId, 4) AS int) = @rOrgGroupId


DELETE FROM sAcademic.tOnlineMeetingAccount WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommunication.teContentTypeMaster WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommunication.teContent WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sPayroll.tPayElementHistory WHERE CAST(LEFT([PayrollId], 4) AS int) = @rOrgGroupId

DELETE FROM [sHrm].[tEmployeeCustomFieldMaster] WHERE OrgGroupId= @rOrgGroupId

DELETE FROM [sCommunication].[tDailyThoughtMaster] WHERE OrgGroupId= @rOrgGroupId
DELETE FROM [sCommunication].[tDailyThoughtSubjectMaster] WHERE OrgGroupId= @rOrgGroupId
DELETE FROM [sCommunication].[tDailyThoughtTemp] WHERE OrgGroupId= @rOrgGroupId

DELETE FROM [sErp].[tCustomerMessage] WHERE OrgGroupId= @rOrgGroupId

DELETE FROM[sCommunication].[tPlaylistMaster] WHERE OrgGroupId= @rOrgGroupId
DELETE FROM [sCommunication].[tPlaylistDetails] WHERE CAST(LEFT(PlaylistId, 4) AS int) =  @rOrgGroupId

DELETE FROM sRecruitment.tRecruitmentCriteriaDocument WHERE CAST(LEFT([VacancyId], 4) AS bigint) =  @rOrgGroupId
DELETE FROM sRecruitment.tRecruitmentRecruiterDocument WHERE CAST(LEFT([RecruitmentId], 4) AS bigint) =  @rOrgGroupId
DELETE FROM [sCommon].[tPublishDocumentMaster] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM [sFee].[tApplicablePayType] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateFamilyDetails WHERE OrgGroupId = @rOrgGroupId

DELETE FROM[sCommunication].[tQueryCategoryScope] WHERE CAST(LEFT([QueryCategoryId], 4) AS int) = @rOrgGroupId
DELETE FROM [sTransport].[tVehicleLog] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sIp.tStockChargeMapping  WHERE CAST(LEFT([ChargeId], 4) AS int) = @rOrgGroupId

DELETE FROM [sCommon].[tFamiliySubCasteMaster] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM [sSetup].[tOnlineFormSetup] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM [sLibrary].[tNewspaperMaster] WHERE CAST(LEFT([Id], 4) AS int) = @rOrgGroupId

DELETE FROM [sHrm].[tCommitteeMaster] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM [sHrm].[tHouseMaster] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM [sHrm].[tClubMaster] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHrm.tAssignClub WHERE CAST(LEFT([ClubId], 4) AS int) = @rOrgGroupId
DELETE FROM sHrm.tAssignHouse WHERE CAST(LEFT([HouseId], 4) AS int) = @rOrgGroupId
DELETE FROM sHrm.tAssignCommittee WHERE CAST(LEFT([CommitteeId], 4) AS int) = @rOrgGroupId
DELETE FROM sIp.tStockDefectiveItemMaster WHERE OrgGroupId = @rOrgGroupId
	
DELETE FROM sCommon.tTribeMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM[sCommunication].[tMultiPhotoCategoryMaster] WHERE [OrgGroupId] = @rOrgGroupId
DELETE FROMsCommunication.tMultiPhotoCategoryScope WHERE CAST(LEFT([MultiPhotoCategoryId], 4) AS bigint) = @rOrgGroupId


DELETE FROM [sAssetManagement].[tAssetCustomFieldMaster] WHERE [OrgGroupId] = @rOrgGroupId
DELETE FROM sAssetManagement.tAssetCustomFieldData WHERE CAST(LEFT([AssetCustomFieldId], 4) AS int) = @rOrgGroupId

--remove from VitorTypeMaster
DELETE FROM [sFrontOffice].[tVisitorTypeMaster] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sProcurement.tStockKitMaster WHERE OrgGroupId = @rOrgGroupId

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

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


GO
-- exec sCommonService.pMenuGet 9911000000270,19184029,0,1,98
ALTER PROCEDURE [sCommonService].[pMenuGet]
 @rUserId [bigint],    
 @rMenuId int = 0,    
 @rResourceTypeId int= 0,    
 @rIsCoreMenu bit = 0,
 @rModuleId int = 0   
      
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
    
BEGIN    
 IF(@rIsCoreMenu=0)    
 BEGIN    
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)    
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
    PageURL  AS PagePath,    
    IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermissionUser P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
       WHERE    
        T.IsObsolete = 0 AND P.UserId = @rUserId    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 ELSE     
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
     PageURL  AS PagePath,    
     IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermission P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
        INNER JOIN    
        (    
        SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0    
        ) B ON B.RoleId = P.RoleId    
       WHERE    
        T.IsObsolete = 0    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0 AND TBL2.PermissionValue > 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 END    
 ELSE    
 BEGIN     
 SELECT    
   MenuID,    
   ModuleId,    
   ParentMenuID,    
   MenuTitle,      
   ScreenTitle,       
   PageURL,    
   ScreenId,    
   Permission,    
   OrderNumber,      
   TaskId,      
   PageURL  AS PagePath,    
   MenuIsObsolete,    
   Icon     
  FROM    
  (    

SELECT    
   ISNULL(Menu.Id,0) AS MenuID,     
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
   ISNULL(Menu.Title,'') AS MenuTitle,       
   ISNULL(Screen.Title, '') AS ScreenTitle,        
   ISNULL(Screen.Page, '') AS PageURL,    
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Screen.Id, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen.IconPath,'') AS Icon,
   ISNULL(Screen.OrderIndex,0) As OrderIndex     
  FROM     
  sSecurity.tMenu Menu     
  LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
  LEFT OUTER JOIN     
  (    
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId  AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId      
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id AND  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id        
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId     
  GROUP BY P.TaskId    
  ) TBL2 ON Screen.TaskId = TBL2.TaskId     
  LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
  WHERE 
  --(Menu.IsObsolete = 0)    
  --AND 
  ISNULL(Screen.IsObsolete, 0) = 0    
  AND (Menu.Id  IN (@rMenuId))   
  --OR ParentMenuID  in (24,2711))     
  --AND (
  ----Menu.Id IN (19184027)  
  ----OR ParentMenuID IN (55)
  --)  

  UNION
  

  SELECT     
  
   ISNULL(Menu.Id, 0) AS MenuID,     
   ISNULL(Menu.Id, 0) AS ParentMenuID,     
   ISNULL(Screen1.Title,'') AS MenuTitle,       
   ISNULL(Screen1.Title, '') AS ScreenTitle,        
   ISNULL(Screen1.Page, '')  AS PageURL,    
   ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Screen1.Id, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen1.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen1.IconPath,'') AS Icon,
   ISNULL(Screen1.OrderIndex,0) As OrderIndex    
  FROM     
   sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
   LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId     
   LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId    
   LEFT OUTER JOIN (     
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId   AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId        
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id       
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId    
            
  GROUP BY P.TaskId    
  ) TBL2 ON Screen1.TaskId = TBL2.TaskId    
  WHERE 
  --(Menu.IsObsolete = 0) AND 
  ISNULL(Screen1.IsObsolete, 0) = 0    
  --AND (Menu.ParentMenuID  in (24,2711)   
  --OR Menu.Id  in (24,2711))   
  AND TBL2.PermissionValue > 0
  --AND Screen1.Id IN (31336,31337,31338,31339,31340)
  ) MenuTable      
  WHERE     
  --(MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2)
  --AND   
  ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
  AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
  --AND MenuIsObsolete = 0    
  AND MenuTable.MenuId IN (@rMenuId)   
  AND ModuleId IN (@rModuleId)
  ORDER BY MenuTable.OrderIndex, ParentMenuID
 END    
END
GO
PRINT N'Altering Procedure [sCommonService].[pPermissionGet]...';


GO
-- exec sCommonService.pPermissionGet 9911,9911000000270
ALTER PROCEDURE [sCommonService].[pPermissionGet]
	@rOrgGroupId [int],
	@rUserId [bigint],
	@rModuleId [int]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	
IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@rOrgGroupId)
BEGIN
	SELECT		TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
	FROM
	(
		SELECT 	
			P.TaskId					AS	TaskID,
			(Permission & 1) 		AS	C, --[Create],
			(Permission & 2)/2		AS	R, --[Read],
			(Permission & 4)/4		AS	U, --[Update],
			(Permission & 8)/8		AS	D, --[Delete],
			(Permission & 16)/16 	AS	S, --[Search],
			(Permission & 32)/32 	AS	P, --[Print],
			(Permission & 64)/64 	AS	X --[Execute]
		FROM sSecurity.tPermissionUser P
		INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
		INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
		INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
		WHERE
		P.OrgGroupId = @rOrgGroupId AND P.UserId = @rUserId  AND MP.ModuleId = @rModuleId
	) TP 
	GROUP BY TP.TaskId
END
ELSE
BEGIN
	SELECT		TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
	FROM
	(
		SELECT 	
			P.TaskId					AS	TaskID,
			(Permission & 1) 		AS	C, --[Create],
			(Permission & 2)/2		AS	R, --[Read],
			(Permission & 4)/4		AS	U, --[Update],
			(Permission & 8)/8		AS	D, --[Delete],
			(Permission & 16)/16 	AS	S, --[Search],
			(Permission & 32)/32 	AS	P, --[Print],
			(Permission & 64)/64 	AS	X --[Execute]
		FROM sSecurity.tPermission P
		INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
		INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
		INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
		INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
		ON R.RoleId = P.RoleId 
		WHERE
		P.OrgGroupId = @rOrgGroupId AND MP.ModuleId = @rModuleId
		--AND
	--RoleId 
	
	--IN
	-- (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId )
	) TP 
	GROUP BY TP.TaskId
	
	--SELECT	CAST(MAX(TP.C) AS BIT) AS [Create],
	--		CAST(MAX(TP.R) AS BIT) AS [Read],
	--		CAST(MAX(TP.U) AS BIT) AS [Update],
	--		CAST(MAX(TP.D) AS BIT) AS [Delete],
	--		CAST(MAX(TP.S) AS BIT) AS [Search],
	--		CAST(MAX(TP.P) AS BIT) AS [Print],
	--		CAST(MAX(TP.X) AS BIT) AS [Execute]
	--FROM
	--(
	--	SELECT 	(Permission & 1) AS C,
	--			(Permission & 2)/2 AS R,
	--			(Permission & 4)/4 AS U,
	--			(Permission & 8)/8 AS D,
	--			(Permission & 16)/16 AS S,
	--			(Permission & 32)/32 AS P,
	--			(Permission & 64)/64 AS X
	--	FROM sSecurity.tPermission
	--	WHERE TaskId = @rTaskId AND 
	--		  RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId)
	--) TP
END


END
GO
PRINT N'Altering Procedure [sCommunication].[pQueryCategoryMasterAdd]...';


GO


ALTER PROCEDURE [sCommunication].[pQueryCategoryMasterAdd]
	 
	@rId int,
	@rTitle nvarchar(100),
	@rRemark nvarchar(200),
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupId smallint,
	@rAssignToId smallint,
	@rTempQueryCategoryId nvarchar(100)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	
		IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sCommunication.tQueryCategoryMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
 
	END
	ELSE
	BEGIN
 
		If  Exists(select Id from sCommunication.tQueryCategoryMaster where Title=@rTitle AND OrgGroupId =@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tQueryCategoryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sCommunication.tQueryCategoryMaster
		(
			Id,
			Title,
			Remark,
			OrgGroupId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			AssignedToId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rOrgGroupId,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rAssignToId
		)        
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommunication.tQueryCategoryMaster
	    SET
	      Title=@rTitle,
	      Remark=@rRemark,
	      IsObsolete=@rIsObsolete,
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate(),
	      AssignedToId = @rAssignToId
	      WHERE Id = @rId 	   
	 END  
		-- #Start MantisId : 0030903
		IF(@rId <> 0)
		BEGIN
			DELETE FROM sCommunication.tQueryCategoryScope WHERE QueryCategoryId = @rTempQueryCategoryId	
		END
		-- #End MantisId : 0030903
	 	INSERT INTO sCommunication.tQueryCategoryScope
		SELECT @lNextNumber,SourceTypeId,SourceId,AssigneeToId
		FROM sCommunication.tTempQueryCategoryScope
		WHERE TempQueryCategoryId = @rTempQueryCategoryId
		
		DELETE FROM sCommunication.tTempQueryCategoryScope WHERE TempQueryCategoryId = @rTempQueryCategoryId

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


GO
ALTER PROCEDURE [sCommunication].[pTempQueryCategoryScopeValidate]
	 
        @rTempQueryCategoryId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int,
		@rQueryCategoryId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 
		-- #Start : Committed by MantisId : 0030903
		--IF(@rQueryCategoryId > 0)
		--BEGIN
		--	If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS where CS.SourceId=@rSourceId AND
		--		CS.SourceTypeId=@rSourceTypeId AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId) 
		--	BEGIN
		--		select -101 as Result,'Item Already Exists' AS Msg
		--		RETURN
		--	END 
		--END
		-- #End Committed by MantisId : 0030903
			
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 
			
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sHrm.tEmployeeMaster EM
				ON CS.SourceId=EM.Id AND CS.SourceTypeId= 95
				where EM.OrgId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Employee already Exists' AS Msg
						RETURN
					END 
		
		-- #Start : Committed by MantisId : 0030903		
		--IF(@rQueryCategoryId > 0)	
		--BEGIN
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		--	 INNER JOIN  sSetup.tDepartmentMaster DM 
		--		ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
		--		where DM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -103 as Result,'Department already Exists' AS Msg
		--				RETURN
		--			END 
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		--	 INNER JOIN  sSetup.tClassMaster CM 
		--		ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
		--		where CM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -103 as Result,'Class already Exists' AS Msg
		--				RETURN
		--			END 
					
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		--	 INNER JOIN  sSetup.tDivisionMaster DM 
		--		ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
		--		where DM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -103 as Result,'Division already Exists' AS Msg
		--				RETURN
		--			END 
					
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		--	 INNER JOIN  sStudent.tStudentMaster SM
		--		ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
		--		where SM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -103 as Result,'Student already Exists' AS Msg
		--				RETURN
		--			END 

		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		--			INNER JOIN  sHrm.tEmployeeMaster EM
		--		ON CS.SourceId=EM.Id AND CS.SourceTypeId= 95
		--		where EM.OrgId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -103 as Result,'Employee already Exists' AS Msg
		--				RETURN
		--			END 
		--END
		-- #End Committed by MantisId : 0030903
							
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
			 INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =CS.SourceID AND CS.SourceTypeId= 95
			 INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
			 where  EJD.OrganizationDepartmentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Employee already Exists' AS Msg
					RETURN
				END
			
			-- #Start : Committed by MantisId : 0030903			
			--IF(@rQueryCategoryId > 0)
			--BEGIN
			--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
			--	 INNER JOIN  sSetup.tDepartmentMaster DM
			--		ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			--		where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
			--			BEGIN
			--				select -102 as Result,'Organization already Exists' AS Msg
			--				RETURN
			--			END 
			--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
			--	 INNER JOIN sSetup.tClassMaster CM
			--		ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
			--		where CM.DepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
			--			BEGIN
			--				select -103 as Result,'Class already Exists' AS Msg
			--				RETURN
			--			END 
					
			--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
			--	 INNER JOIN  sSetup.tDivisionMaster DM 
			--		ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			--	 INNER JOIN sSetup.tClassMaster CM
			--		ON CM.Id=DM.ClassId
			--		where CM.DepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
			--			BEGIN
			--				select -103 as Result,'Division already Exists' AS Msg
			--				RETURN
			--			END 
					
			--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
			--	 INNER JOIN sStudent.tAcademic SA 
			--		ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			--	 INNER JOIN sSetup.tClassMaster CM
			--		ON CM.Id=SA.ClassId
   --				 INNER JOIN sSetup.tBatchMaster BM 
   --					ON BM.Id = SA.BatchId AND BM.IsActive=1
			--		where CM.DepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
			--			BEGIN
			--				select -103 as Result,'Student already Exists' AS Msg
			--				RETURN
			--			END 
			
			--If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
			--	INNER JOIN sHrm.tEmployeeMaster  EM ON EM.Id =CS.SourceID AND CS.SourceTypeId= 95
			--	INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId 			
			--	where  EJD.OrganizationDepartmentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId AND AssigneeToId=@rAssigneeToId)
			--	BEGIN
			--		select -103 as Result,'Employee already Exists' AS Msg
			--		RETURN
			--	END	
			--END	
			-- #End Committed by MantisId : 0030903	
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 		
		
		-- #Start : Committed by MantisId : 0030903		
		--IF(@rQueryCategoryId > 0)
		--BEGIN	
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		--	 INNER JOIN  sSetup.tClassMaster CM
		--		ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
		--		where CM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -102 as Result,'Organization already Exists' AS Msg
		--				RETURN
		--			END 
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		--	 INNER JOIN  sSetup.tClassMaster CM
		--		ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		--		where CM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -102 as Result,'Department already Exists' AS Msg
		--				RETURN
		--			END 
				
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		--	 INNER JOIN  sSetup.tDivisionMaster DM 
		--		ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
		--		where DM.ClassId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -103 as Result,'Division already Exists' AS Msg
		--				RETURN
		--			END 
				
		--	If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		--	  INNER JOIN sStudent.tAcademic SA 
		--			ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		--	  INNER JOIN sSetup.tBatchMaster BM 
  -- 					ON BM.Id = SA.BatchId AND BM.IsActive=1
		--		where SA.ClassId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--			BEGIN
		--				select -103 as Result,'Student already Exists' AS Msg
		--				RETURN
		--			END 
		--END
		-- #End Committed by MantisId : 0030903
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 

		-- #Start : Committed by MantisId : 0030903
		--IF(@rQueryCategoryId > 0)
		--BEGIN
		--If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		-- INNER JOIN  sSetup.tDivisionMaster DM 
		--	ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
		--	where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Organization already Exists' AS Msg
		--			RETURN
		--		END 
		--If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		-- INNER JOIN sSetup.tClassMaster CM 
		--	ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		-- INNER JOIN  sSetup.tDivisionMaster DM 
		--	ON DM.ClassId=CM.Id
		--	where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Department already Exists' AS Msg
		--			RETURN
		--		END 
				
		--If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		-- INNER JOIN  sSetup.tDivisionMaster DM 
		--	ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
		--	where DM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Class already Exists' AS Msg
		--			RETURN
		--		END 
				
		--If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		--  INNER JOIN sStudent.tAcademic SA 
		--		ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		--  INNER JOIN sSetup.tBatchMaster BM 
  -- 			    ON BM.Id = SA.BatchId AND BM.IsActive=1
		--	where SA.DivisionId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -103 as Result,'Student already Exists' AS Msg
		--			RETURN
		--		END 
				
		--If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		--  INNER JOIN sStudent.tAcademic SA 
		--		ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		--  INNER JOIN sSetup.tBatchMaster BM 
  -- 			    ON BM.Id = SA.BatchId AND BM.IsActive=1
		--	where SA.DivisionId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -103 as Result,'Student already Exists' AS Msg
		--			RETURN
		--		END 
		--END	
		-- #End Committed by MantisId : 0030903
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 	
				
		-- #Start : Committed by MantisId : 0030903
		--IF(@rQueryCategoryId > 0)
		--BEGIN	

		--If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		-- INNER JOIN  sStudent.tStudentMaster SM 
		--	ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
		--	where SM.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Organization already Exists' AS Msg
		--			RETURN
		--		END 
		--If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		-- INNER JOIN  sSetup.tClassMaster CM 
		--	ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		-- INNER JOIN sStudent.tAcademic SA 
		--		ON CM.Id=SA.ClassId 
		-- INNER JOIN sSetup.tBatchMaster BM 
  -- 			    ON BM.Id = SA.BatchId AND BM.IsActive=1
		--	where SA.StudentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Department already Exists' AS Msg
		--			RETURN
		--		END 
				
		--If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		-- INNER JOIN sStudent.tAcademic SA 
		--		ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		-- INNER JOIN sSetup.tBatchMaster BM 
  -- 			    ON BM.Id = SA.BatchId AND BM.IsActive=1
		--	where SA.StudentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Class already Exists' AS Msg
		--			RETURN
		--		END 
				
		--If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		-- INNER JOIN sStudent.tAcademic SA 
		--		ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		-- INNER JOIN sSetup.tBatchMaster BM 
  -- 			    ON BM.Id = SA.BatchId AND BM.IsActive=1
		--	where SA.StudentId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Division already Exists' AS Msg
		--			RETURN
		--		END 	
		--END	
		-- #End Committed by MantisId : 0030903
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempQueryCategoryScope CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		-- #Start : Committed by MantisId : 0030903
		--IF(@rQueryCategoryId > 0)
		--BEGIN	
		--If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS 
		-- INNER JOIN  sHrm.tEmployeeMaster EM 
		--	ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
		--	where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Organization already Exists' AS Msg
		--			RETURN
		--		END 
				
		--If EXISTS(select 1 from sCommunication.tQueryCategoryScope CS 
		-- INNER JOIN  sHrm.tEmployeeJobDetail EJD
		--	ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
		--	where  EJD.EmployeeId=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Department already Exists' AS Msg
		--			RETURN
		--		END 
		--END
		-- #End Committed by MantisId : 0030903
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempQueryCategoryScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempQueryCategoryId=@rTempQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 
		-- #Start : Committed by MantisId : 0030903	
		--IF(@rQueryCategoryId > 0)
		--BEGIN
		--	If EXISTS(select 1 from  sCommunication.tQueryCategoryScope CS
		-- INNER JOIN sStudent.tAcademic SA 
		--		ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		-- INNER JOIN sSetup.tBatchMaster BM 
  -- 			    ON BM.Id = SA.BatchId AND BM.IsActive=1
		--	where SA.Id=@rSourceId  AND CS.QueryCategoryId=@rQueryCategoryId  AND AssigneeToId=@rAssigneeToId)
		--		BEGIN
		--			select -102 as Result,'Division already Exists' AS Msg
		--			RETURN
		--		END 	
		--END	
		-- #End Committed by MantisId : 0030903
	END
			select 1 as Result,'' AS Msg
	
END
GO
PRINT N'Altering Procedure [sFee].[pDeleteFee]...';


GO
 
ALTER PROCEDURE [sFee].[pDeleteFee]
	 
		@rReceiptBookId int=0,	 
		@rClassId int=0,
		@rDivisionId int=0,	 
		@rBatchId int=0,	 
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0, 
	    @rCode nvarchar(20)='',
	    @rSourceId bigint,
	    @rDeleteType nvarchar(20)='',
	    @rSourceTypeId smallint=0,
	    @rFromReceiptNo int,
	    @rToReceiptNo int,
		@rMultiReceiptNo nvarchar(max) = ''
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

IF (@rDeleteType = 'Receipt')
BEGIN
DELETE sFee.tReceiptDetail 
		FROM sFee.tReceiptDetail RD
		INNER JOIN sFee.tReceipt R  
		ON R.Id=RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=R.SourceId
	WHERE 
		R.ReceiptBookId=@rReceiptBookId
		AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
		AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
		AND ((R.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (R.ReceiptNumber IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMultiReceiptNo,',')) OR @rMultiReceiptNo='')

	-- For Mantis 0023321 By Foram on 14/03/2024 START
	SELECT R.Id INTO #TempReceiptId
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=R.SourceId
	WHERE 
		R.ReceiptBookId=@rReceiptBookId
		AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
		AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
		AND ((R.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (R.ReceiptNumber IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rMultiReceiptNo,',')) OR @rMultiReceiptNo='')
	-- For Mantis 0023321 By Foram on 14/03/2024 END
	
	DELETE sFee.tReceipt 
		FROM sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=R.SourceId
	WHERE 
		R.ReceiptBookId=@rReceiptBookId
		AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
		AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
		AND ((R.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (R.ReceiptNumber IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMultiReceiptNo,',')) OR @rMultiReceiptNo='')

	-- For Mantis 0023321 By Foram on 14/03/2024 START
	UPDATE sFee.tPostDatePayment SET ReceiptId = 0, StatusId = 751
	WHERE ReceiptId IN (SELECT Id FROM #TempReceiptId)
	-- For Mantis 0023321 By Foram on 14/03/2024 END

	SELECT 1 AS Result
END

IF(@rDeleteType = 'FeeAllocation')
BEGIN

	IF EXISTS
	(
	SELECT 1 FROM 
	    sFee.tFeeAllocation FA
		INNER JOIN sFee.tFeeSetup FS 
		ON FS.Id=FA.FeeSetupId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=FA.SourceId
		INNER JOIN sFee.tReceipt R 
		ON FA.SourceId = R.SourceId AND FA.SourceTypeId = R.SourceTypeId
	WHERE 
		((R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((R.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
    )
    BEGIN
		SELECT -101 AS Result
		RETURN
	END 

    DELETE sFee.tFeeAllocation
		FROM sFee.tFeeAllocation FA
		INNER JOIN sFee.tFeeSetup FS 
		ON FS.Id=FA.FeeSetupId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=FA.SourceId
	WHERE 
		((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FA.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((FA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
SELECT 2 AS Result
END	
		
IF(@rDeleteType = 'FeeOptional')
BEGIN
	
	IF EXISTS
	( 
    SELECT 1 FROM
        sFee.tFeeOptional FO
		INNER JOIN sFee.tFeeSetup FS 
		ON FS.Id=FO.FeeSetupId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=FO.SourceId
		INNER JOIN sFee.tReceipt R 
		ON FO.SourceId = R.SourceId AND FO.SourceTypeId = R.SourceTypeId
	WHERE 
		((R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((R.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((R.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
    )
    BEGIN
		SELECT -102 AS Result
		RETURN
	END 

    DELETE sFee.tFeeOptional
		FROM sFee.tFeeOptional FO
		INNER JOIN sFee.tFeeSetup FS 
		ON FS.Id=FO.FeeSetupId
		INNER JOIN sStudent.vStudentAcademic vSA 
		ON vSA.AcademicId=FO.SourceId
	WHERE 
		((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FO.SourceId=@rSourceId) OR (@rSourceId=0))
		AND ((FO.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		AND ((vSA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND vSA.BatchId=@rBatchId
		AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))		
SELECT 3 AS Result
END
END
GO
PRINT N'Altering Procedure [sFee].[pFeeSetupGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeSetupGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		   @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(FS.Id,0)AS Id,
			ISNULL(CM.Id,0)AS ClassId,
			ISNULL(CM.Title,'') AS ClassName,
			ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
			FM.Title AS FeeTitle,
			ISNULL(FS.BatchId,0)AS BatchId,
			ISNULL(FM.Id,0)AS FeeId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'0001-01-01 00:00:00.00')AS StartDate,
			ISNULL(FS.EndDate,'0001-01-01 00:00:00.00')AS EndDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(FHM.Id,0) AS FeeHeadId,
			ISNULL(FHM.Title,'') AS FeeHeadName,
			(SELECT COUNT(*) FROM sFee.tReceiptDetail WHERE FeeSetupId=FS.Id) AS test,
			(SELECT COUNT(1) FROM sFee.tPostDatePayment WHERE ReceiptBookId=FS.ReceiptBookId) AS test1,
			CASE WHEN ((SELECT COUNT(*) FROM sFee.tReceiptDetail WHERE FeeSetupId=FS.Id) <= 0) AND ((SELECT COUNT(1) FROM sFee.tPostDatePayment WHERE ReceiptBookId=FS.ReceiptBookId) <=0) THEN 'True' 
				--WHEN (SELECT COUNT(1) FROM sFee.tPostDatePayment WHERE ReceiptBookId=FS.ReceiptBookId) <= 0 THEN 'True'
			ELSE 'False' END AS IsReceiptBookChange,
			ISNULL(FS.IsServiceTax,0)AS IsServiceTax,
			ISNULL(FS.CollectionGroupId,0) AS CollectionGroupId,
			ISNULL(FS.FeeDuration,'')  AS FeeDuration,
			ISNULL(FS.LevelAmount,0) AS LevelAmount,
			ISNULL(FHM.Number,0) AS FeeHeadNumber,
			ISNULL(CGM.Title,'') AS CollectionGroupTitle,
			ISNULL(FS.LateFeeRuleId, 0) AS LateFeeRuleId
  FROM 
			sFee.tFeeMaster FM
		LEFT JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId 
		AND (FS.ClassId=@rClassId OR @rClassId= 0) 
		AND (FS.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId= 0) 
		AND (FS.BatchId=@rBatchId)
		LEFT JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id=FS.ClassId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId
WHERE 
		FM.OrgGroupId=@rOrgGroupId
		ORDER BY FS.StartDate,FHM.OrderIndex,FM.OrderIndex
END
GO
PRINT N'Altering Procedure [sFee].[pFeeSetupRemove]...';


GO
ALTER PROCEDURE [sFee].[pFeeSetupRemove] 
	@rId INT
	,@rClassId INT
	,@rAdmissionCategoryId INT
	,@rBatchId INT
	,@rCheck BIT
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF (@rCheck = 1)
	BEGIN
		IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tFeeAllocation
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 50 AS Result

			RETURN
		END
		ELSE IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tReceiptDetail
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 51 AS Result

			RETURN
		END
		ELSE IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tFeeOptional
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 52 AS Result

			RETURN
		END
		ELSE IF EXISTS (
				SELECT FeeSetupId
				FROM sFee.tOnlineFeeDetail
				WHERE FeeSetupId = @rId
				)
		BEGIN
			SELECT - 53 AS Result

			RETURN
		END
		ELSE IF EXISTS (
				SELECT 1
				FROM [sFee].[tPostDatePayment]
				WHERE ReceiptBookId = (SELECT ReceiptBookId FROM sFee.tFeeSetup WHERE Id = @rId)
			)
		BEGIN
			SELECT - 54 AS Result

			RETURN
		END

		--else If Exists(select FeeSetupId from sFee.tFeeAllocationStudent where FeeSetupId=@rId)
		--	    BEGIN
		--			select -50 as Result
		--			RETURN
		--		END 
		SELECT 0 AS Result
	END
	ELSE
	BEGIN
		BEGIN TRY
			BEGIN TRANSACTION

			ALTER TABLE sfee.tReceiptDetail
				WITH CHECK CHECK CONSTRAINT FK_sFee_tReceiptDetail_FeeSetupId

			ALTER TABLE sFee.tFeeOptional
				WITH CHECK CHECK CONSTRAINT FK_sFee_tFeeOptional_tFeeSetupId

			ALTER TABLE sFee.tFeeAllocation
				WITH CHECK CHECK CONSTRAINT FK_sFee_tFeeAllocation_FeeSetupId

			DELETE
			FROM sFee.tFeeSetup
			WHERE ClassId = @rClassId
				AND AdmissionCategoryId = @rAdmissionCategoryId
				AND BatchId = @rBatchId
				AND (
					(Id = @rId)
					OR (@rId = 0)
					)

			COMMIT TRANSACTION
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION

			SELECT - 1 AS Result
		END CATCH

		SELECT 11 AS Result
	END
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptAddValidate]...';


GO
ALTER PROCEDURE [sFee].[pReceiptAddValidate]
 
		 @rAcademicId bigint,
		 @rFeeSetupIds nvarchar(max) = '',
		 @rReceiptDetailXml [nvarchar](max),
		 @rPayTypeId tinyint = 0,
		 @rPaymentTransactionId bigint = 0,
		 @rIsCreated int OUTPUT
	    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml
	 
create table #temptable (FeeId int,Id int,Amount decimal(12,2), AcademicId bigint ) 
INSERT INTO #temptable (FeeId,Id ,Amount , AcademicId)
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			 
			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 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
			WHERE 
			    (FS1.IsOptional=0)
			    AND SA1.Id = @rAcademicId				
				AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				
				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				
			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 sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId

		WHERE
				  (FS1.IsOptional=1)
				   AND SA1.Id = @rAcademicId	
				  	
				AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='') 

create table #temptable1 (PaidAmount decimal(12,2),FeeSetupId int, SourceId bigint ) 
INSERT INTO #temptable1 (PaidAmount ,FeeSetupId , SourceId )
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 AND R.SourceTypeId = 2001
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId	 
				
			WHERE	
			
			(R.SourceTypeId = 2001)
				 AND R.SourceId = @rAcademicId				
				AND (R.IsObsolete = 0) 
				AND (ISNULL(FS.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				GROUP BY FeeSetupId,R.SourceId	


	
	IF EXISTS(	
	SELECT 1
	FROM 
		sStudent.tAcademic SA
		INNER JOIN #temptable
		--(
		--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			 
		--	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 
		--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--	--INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
		--	WHERE 
		--	    (FS1.IsOptional=0)
		--	    AND SA1.Id = @rAcademicId				
		--		AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
			
		--		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				
		--	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 sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
		--		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId 
		--		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId

		--WHERE
		--		  (FS1.IsOptional=1)
		--		   AND SA1.Id = @rAcademicId	
			  	
		--		AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='') 
		--)
		 FS ON FS.AcademicId=SA.Id
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
		LEFT JOIN #temptable1
		--(
		--	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 AND R.SourceTypeId = 2001
		--		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId	 
			
		--	WHERE	
		
		--	(R.SourceTypeId = 2001)
		--		 AND R.SourceId = @rAcademicId				
		--		AND (R.IsObsolete = 0) 
		--		AND (ISNULL(FS.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
		--		GROUP BY FeeSetupId,R.SourceId	
		--)
		R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId			
		LEFT JOIN
		(
			SELECT 	    
			FeeSetupId,
			Amount
			FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
			WITH ( 
					FeeSetupId int,
					Amount decimal(12,2)
				  ) 
		 ) AS RD ON RD.FeeSetupId = FS.Id			
		 WHERE 
		 SA.Id =   @rAcademicId         
		 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) - RD.Amount < 0)			
	)
	BEGIN
		SELECT @rIsCreated = 1
	END 
	ELSE
	BEGIN
		--Start for mantis 0031290 By Foram
		IF(@rPayTypeId = 8)
		BEGIN
			IF EXISTS (SELECT 1
				FROM
					sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id AND R.SourceTypeId = 2001
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId	 
				WHERE	
					(R.SourceTypeId = 2001)
					AND R.SourceId = @rAcademicId				
					AND (R.IsObsolete = 0) 
					AND (ISNULL(FS.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
					AND R.PaymentTransactionId = @rPaymentTransactionId
					AND R.PayTypeId = 8
				)
			BEGIN
				SELECT @rIsCreated = 1
			END
			ELSE
			BEGIN
				SELECT @rIsCreated = 0
			END
		END
		--end for mantis 0031290 By Foram
		ELSE
		BEGIN
			SELECT @rIsCreated = 0
		END
 END 
 
 	EXEC sp_xml_removedocument @loDoc
END
GO
PRINT N'Altering Procedure [sFee].[pRptFeePendingDetailListGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeePendingDetailListGet]

	@rReportId int=0,
	@rReceiptBookId int=0,
	@rReceiptBookIds nvarchar(max) = '',
	@rAdmissionCategoryId int=0,
	@rAdmissionCategoryIds nvarchar(max) = '',
	@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,
	@rReportType int=0,
	@rClassStatusId int=0 ,
	@rCollectionGrupId nvarchar(max) ='',
	@rClassIds nvarchar(max) = '',
	@rDivisionIds nvarchar(max) = ''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	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,
		CollectionGroupId int,
		CollectionGroup nvarchar(max),
		FeeOrderIndex int,
		CollectionGroupOrderIndex int,
		CollectionGroupMasterRemark nvarchar(500),
		FeeDuration nvarchar(100)						--add
	)

	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,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup,
			FM.OrderIndex,
			CGM.OrderIndex  AS CollectionGroupOrderIndex,
			CGM.Remark AS CollectionGroupMasterRemark,
			FS1.FeeDuration AS FeeDuration							--add
		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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			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
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id
			--AND RBM.Id = CGM.ReceiptBookId
			AND CGM.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.AdmissionCategoryId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryIds,',')) OR @rAdmissionCategoryIds='')
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND (FS1.ReceiptBookId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
			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='')
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')

	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,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup,
			FM.OrderIndex,
			CGM.OrderIndex  AS CollectionGroupOrderIndex,
			CGM.Remark AS CollectionGroupMasterRemark,
			FS1.FeeDuration AS FeeDuration					--add
		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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id
			--AND RBM.Id = CGM.ReceiptBookId
			AND CGM.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.AdmissionCategoryId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryIds,',')) OR @rAdmissionCategoryIds='')
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND (FS1.ReceiptBookId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
			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='')
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')

	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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		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))

	IF(@rReportType=1)
	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,
		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,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate,
		FS.CollectionGroupId,
		FS.CollectionGroup,
		SA.BatchName,
		ISNULL(SSF.FatherName, '') AS FatherName,
		ISNULL(SSF.FatherContactNo, '') AS FatherContactNo,
		ISNULL(SSF.MotherName, '') AS MotherName,
		ISNULL(SSF.MotherContactNo, '') AS MotherContactNo,
		FS.FeeOrderIndex AS FeeOrderIndex,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
	 SA.GenderId,
	 SA.FirstName as StudentName,
	 FS.CollectionGroupOrderIndex,
	 SA.SUId AS SUId,
	 FS.CollectionGroupMasterRemark,
	 SA.LastName as LastName,
	 FS.FeeDuration as FeeDuration,	--add
	 --Mantis: 31868, start
	 case when @rReportId=10147
		then O.OrgLogo
		else null end AS OrgLogo,
	 O.SmallAddress1 AS OrgAddress
	 --Mantis: 31868, end

	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))
		LEFT JOIN sStudent.tStudentFamily SSF ON SSF.StudentId = SA .StudentId
	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))
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	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,
		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(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0.00) PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		--FS.FeeName,
		FM.Title AS 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,
		ISNULL(FS.ReceiptBookId,'0') As 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,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		SA.BatchName,
		ISNULL(SSF.FatherName, '') AS FatherName,
		ISNULL(SSF.FatherContactNo, '') AS FatherContactNo,
		ISNULL(SSF.MotherName, '') AS MotherName,
		ISNULL(SSF.MotherContactNo, '') AS MotherContactNo,
		FM.OrderIndex AS FeeOrderIndex,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		CGM.OrderIndex  AS CollectionGroupOrderIndex,
		SA.SUId AS SUId
	FROM
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		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=FM.FeeHeadId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FAS.FeeSetupId AND FA.SourceId=SA.AcademicId
		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
		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))
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
		AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sStudent.tStudentFamily SSF ON SSF.StudentId = SA .StudentId
	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 ISNULL(FAS.ToPayAmount,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))
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
	Order by SA.RollNo
	END

	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
	DROP TABLE #TempAssignRoute



	--SELECT
	--    '' as Builder1,
	--	'' as Builder2,
	--	Convert(bit,0) as IsDetail,
	--	Convert(bit,0) as IsFilter,
	--	Convert(bit,0) as IsHeader,
	--	Convert(bit,0) as IsDisplayOrgGroup,
	--	Convert(bigint,0) as AcademicId,
	--	0 As RollNo,
	--	'' as Name,
	--	'' As Code,
	--	0 as ClassId,
	--	0 as DivisionId,
	--	'' as ClassName,
	--	'' as DivisionName,
	--	0 as DivisionOrder,
	--	 '' as ClassDivision,
	--	0 as FeeSetupId,
	--	Convert(bit,0) as IsVariable,
	--	 0.00 As Amount,
	--	'2001-01-30' AS StartDate,
	--	'2001-01-30' As EndDate,
	--	0.00 As FAAmount,
	--	0.00 As DiscountAmount,
	--	0.00 As AdditionalAmount,
	--	0.00 As PaidAmount,
	--	0.00 As  PendingAmount,
	--	'' AS Remark,
	--	--FS.FeeName,
	--	'' AS FeeName,
	--	0 AS FeeHeadId,
	--	'' AS FeeHeadName,
	--	0 As FeeHeadOrderIndex,
	--	0 As OrgId,
	--	'' AS OrgName,
	--	0 AS OrgOrderIndex,
	--	0 AS ReceiptBookId,
	--	'' AS ReceiptBookTitle,
	--	0 AS ReceiptOrderIndex,
	--	'' AS ReceiptBookFullTitle,
	--	'' AS RecieptBookAddress1,
	--	'' AS RecieptBookAddress2,
	--	'' As Remark1,
	--	0 As OrgGroupBatchId,
	--	0 As DepartmentId,
	--	'' AS DepartmentName,
	--	'' AS ParentContactNo,
	--	'' AS ReferenceRemark,
	--	'2001-01-30' AS PayDate ,
	--	0 AS CastCategoryId,
	--	'' AS CastCategoryName,
	--	0 AS CastCategoryOrderIndex,
	--	'' AS ReportTemplate,
	--	0 AS CollectionGroupId,
	--	'' AS CollectionGroup,
	--	'' AS BatchName,
	--	'' AS FatherName,
	--	 '' AS FatherContactNo,
	--	 '' AS MotherName,
	--	 '' AS MotherContactNo,
	--	0 AS FeeOrderIndex,
	--	'' AS Address,
	--	'' AS StudentContactNo,
	--    '' as StudentName,
	--	0 As GenderId,
	-- 0 AS CollectionGroupOrderIndex,
	-- '' AS SUId,
	-- '' AS CollectionGroupMasterRemark,
	-- '' AS LastName,
	-- '' AS FeeDuration,
	----Mantis: 31868, start
	-- Convert(varbinary(max),'') AS OrgLogo,
	-- '' AS OrgAddress
	----Mantis: 31868, end

END
GO
PRINT N'Altering Procedure [sFee].[pRptFeePendingWithFeeNameGet]...';


GO

 
ALTER PROCEDURE [sFee].[pRptFeePendingWithFeeNameGet]
		@rReportId int=0,
		@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,
		@rStatusId int,
		@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) = '' ,
		@rReportType int=1,
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = '',
		@rFromAmount decimal = 0.00,
		@rToAmount decimal = 0.00
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	IF(@rReportType=1)

		BEGIN

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

 
	--CREATE TYPE  TempPendingFee AS TABLE
	--(
	--AcademicId bigint
	--,
	--RollNo int,
	--Name nvarchar(200),
	--Code nvarchar(20),
	--ClassId int,
	--DivisionId int,
	--ClassName nvarchar(100),
	--DivisionName nvarchar(100),
	--ClassDivision nvarchar(100),
	--FeeSetupId int,
	--IsVariable int,
	--Amount Decimal(12,2),
	--StartDate date,
	--EndDate date,
	--FAAmount Decimal(12,2),
	--DiscountAmount Decimal(12,2),
	--AdditionalAmount Decimal(12,2),
	--PaidAmount Decimal(12,2),
	--PendingAmount Decimal(12,2),
	--Remark nvarchar(200),
	--ReceiptBookId int,
	--FeeName nvarchar(100),
	--FeeCode nvarchar(100),
	--OrgId int,
	--OrgName nvarchar(200),
	--OrgOrderIndex int,
	--ReceiptBookTitle nvarchar(200),
	--ReceiptOrderIndex int	
	--)
	
	DECLARE @p as TempPendingFee
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId		,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		0 AS FeeOrderIndex,	-- Pass static 0 for MantisId : 0032054
		--change by megha for 0027384
	    ISNULL(SF.FatherContactNo,'')AS FatherContactNo,
		ISNULL(SF.MotherContactNo,'')AS MotherContactNo
			
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex AS FeeOrderIndex
			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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (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='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex AS FeeOrderIndex
			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 = FS1.ClassId 
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (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='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		) 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.ClassId=@rClassId OR @rClassId=0) 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (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) 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 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)) 
		    --change by megha for 0027384
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
	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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
			Order by SA.RollNo

	SELECT
			@rBuilder1 as Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookId
			 END) AS ReceiptBookId,	
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookTitle
			 END) AS ReceiptBookTitle,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptOrderIndex
			 END) AS ReceiptOrderIndex,	 
			
			OrgId,			 
			--ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,RollNo, Name,Code,
			--ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			Pickup AS ParentContactNo,
			DRoppoint AS StudentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			FeeOrderIndex,
			ReceiptOrderIndex,
			FatherContactNo,
		    MotherContactNo
			FROM @p 
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,
			ClassDivision,RollNo, Name,Code,
			ReceiptBookTitle,OrgName,ReceiptOrderIndex,Pickup,DRoppoint,SUID,ClassOrderIndex,
			DivisionOrderIndex,
			FeeOrderIndex,
			FatherContactNo,MotherContactNo
			HAVING
			((SUM(PendingAmount) >= @rFromAmount) OR (@rFromAmount=0.00))
			AND (( SUM(PendingAmount)<= @rToAmount) OR (@rToAmount=0.00))
			ORDER BY AcademicId

END

	ELSE
		BEGIN

	INSERT INTO  @p
SELECT 

		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0) AS PendingAmount,
		--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(FAS.Remark,'') AS Remark,
		FS.ReceiptBookId,
		--FS.FeeName,
		--FS.FeeCode,
		FM.Title AS FeeName, 
		FM.Code AS FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		0 AS FeeOrderIndex, -- Pass static 0 for MantisId : 0032054
	    ISNULL(SF.FatherContactNo,'')AS FatherContactNo,
		ISNULL(SF.MotherContactNo,'') AS MotherContactNo
  FROM  sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		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=FM.FeeHeadId
		--LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=SF.FeeSetupId AND FA.SourceId=SA.AcademicId
		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))
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId 
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
		
	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 ISNULL(FAS.ToPayAmount,0) !=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 (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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
			Order by   SA.RollNo
			--FM.OrderIndex 
			

	SELECT
			@rBuilder1 as Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookId
			 END) AS ReceiptBookId,	
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookTitle
			 END) AS ReceiptBookTitle,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptOrderIndex
			 END) AS ReceiptOrderIndex,	 
			
			OrgId,			 
			--ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,RollNo, Name,Code,
			--ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			Pickup AS ParentContactNo,
			DRoppoint AS StudentContactNo,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex,
			--ReceiptOrderIndex,
			FeeOrderIndex,
			FatherContactNo,
		    MotherContactNo
			FROM @p 
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,
			ClassDivision,RollNo, Name,Code,
			ReceiptBookTitle,OrgName,ReceiptOrderIndex,Pickup,DRoppoint,SUID,ClassOrderIndex,
			DivisionOrderIndex,FeeOrderIndex,FatherContactNo,MotherContactNo
			HAVING
			((SUM(PendingAmount) >= @rFromAmount) OR (@rFromAmount=0.00))
			AND (( SUM(PendingAmount)<= @rToAmount) OR (@rToAmount=0.00))
			ORDER BY AcademicId

END 
END
GO
PRINT N'Altering Procedure [sFee].[pRptFeeReceiptDetailListGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailListGet]  
  @rReportId int,  
  @rReceiptBookId int,  
  @rAdmissionCategoryId int,  
  @rClassId int,  
  @rDivisionId int,  
  @rFromDate date,  
  @rToDate date,  
  @rFromReceiptNo int,  
  @rToReceiptNo int,  
  @rBatchId int,  
  @rUserId bigint,  
  @rBuilder1 nvarchar(max),  
  @rBuilder2 nvarchar(max),  
  @rIsCancel bit,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int,  
  @rCommonBatch nvarchar(100),  
  @rDepartmentId int,  
  @rFromRollNo int,  
     @rToRollNo int,  
     @rCode nvarchar(20),  
     @rIsDetail bit=0,  
  @rIsFilter bit,  
  @rIsHeader bit,  
  @rCreatedUserName nvarchar(100)='',  
  @rFeeHeadId nvarchar(max) = '',  
  @rIsDisplayOrgGroup bit=0,  
  @rPayTypeId int=0,  
  @rFeeId nvarchar(max) = '',  
  @rFilterId int=0,
  @rOrgIds nvarchar(max) = '',
  @rClassStatusId int=0,
  @rPayTypeIds nvarchar(max) = '' ,
  @rBankName nvarchar(200)='' ,
  @rUserAcessUserId bigint = 0  
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN  
SET @rBankName = sCommon.fSearchStringGet(@rBankName)  
IF(@rReportId=10145)
	BEGIN
	SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.AcademicId,  
  SA.FirstName,  
  SA.MiddleName,  
  SA.LastName,  
  SA.Code,  
  SA.Name,
  PTM.Title AS PayType,  
  --R.ChequeNo,  
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
  R.BankName,  
  --R.ReceiptAmount,  ,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
  R.ReceiptDate,  
  FM.Title AS FeeDetail,  
  FM.Code AS FeeCode,  
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
  ISNULL(FHM.Title,'') AS FeeHead,  
  ISNULL(FHM.Code,'') AS FeeHeadCode,  
  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
  SA.OrgId,  
  O.DisplayTitle AS OrgName,  
  O.OrderIndex AS OrgOrderIndex,  
  ISNULL(R.Remark,'') AS Remark,  
  DM.Id AS DepartmentId,  
  DM.Title AS DepartmentName,  
  SA.ClassOrderIndex,  
  ISNULL(SO.GenderId,0) AS GenderId,  
  ISNULL(SA.BatchName,'') BatchName,  
  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
  R.ChequeDate,  
  ISNULL(FM.Id,0) AS FeeId,  
  ISNULL(FM.Title,'') AS Fee,  
  ISNULL(SF.FatherName,'' ) AS FatherName,  
  ISNULL(SF.MotherName,'' ) AS MotherName,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
  RD.Amount AS PaidAmount,
  ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex,
  PTM.Id AS PayTypeId,
  ISNULL(SA.SUID,'') AS SUID,
  ISNULL(U.DisplayTitle,'') AS CreatedUser
  ,TBM.FromDate AS FromDate
  ,TBM.ToDate AS ToDate
	 ,'' as PermanentStreetOne         -- Start Mentis 29588
	  ,'' as PermanentStreetTwo
	  ,'' as PermanentStreetThree 
	  ,'' as PermanentCountry
	  ,'' as PermanentState
	  ,'' as PermanentCity
	  ,'' as PermanentZipCode
	  ,'' as PermanentContactNo    
	  ,'' as AdmissionNumber 
	  ,SO.DateOfBirth  
	  ,Convert(Decimal,0) as TotalAmount    
	  ,convert(varbinary(max),'') as StudentPhoto                -- #End Mentis 29588
	  ,'' as PresentStreetOne  --Mentis 0030332
	  ,'' as PresentStreetTwo
	  ,'' as PresentCity		--Mentis 0030332
	  ,convert(varbinary(max),'') as CertificateHeaderA4  --mantis - 0030332
  FROM   
   sFee.tReceipt R  
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  INNER JOIN sFee.tFeeSetup FS  
   ON FS.Id=RD.FeeSetupId  
  INNER JOIN sFee.tFeeMaster FM  
   ON FM.Id=FS.FeeId  
  INNER JOIN sFee.tFeeHeadMaster FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId 
    --for UserAccess Wise (in ReceiptListFeeHeadHeadwise report)
  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND O.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  
 
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.StudentId = SA.StudentId  
    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))   
 INNER JOIN sSetup.tBatchMaster TBM ON TBM.Id=R.BatchId AND ((TBM.OrgId=@rOrgId) OR (@rOrgId=0))
 INNER JOIN [sSecurity].[tUser] U ON U.Id=R.CreatedUserId 
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 --AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND (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 ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')   
	AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    
 ORDER BY R.ReceiptNumber  

	END


ELSE
	BEGIN
	SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.AcademicId,  
  SA.FirstName,  
  SA.MiddleName,  
  SA.LastName,  
  SA.Code,  
  SA.Name,  
  PTM.Title AS PayType,  
  --R.ChequeNo,  
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
  R.BankName,  
  --R.ReceiptAmount,  ,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
  R.ReceiptDate,  
  FM.Title AS FeeDetail,  
  FM.Code AS FeeCode,  
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
  ISNULL(FHM.Title,'') AS FeeHead,  
  ISNULL(FHM.Code,'') AS FeeHeadCode,  
  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
  SA.OrgId,  
  O.DisplayTitle AS OrgName,  
  O.OrderIndex AS OrgOrderIndex,  
  ISNULL(R.Remark,'') AS Remark,  
  DM.Id AS DepartmentId,  
  DM.Title AS DepartmentName,  
  SA.ClassOrderIndex,  
  ISNULL(SO.GenderId,0) AS GenderId,  
  ISNULL(SA.BatchName,'') BatchName,  
  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
  R.ChequeDate,  
  ISNULL(FM.Id,0) AS FeeId,  
  ISNULL(FM.Title,'') AS Fee,  
  ISNULL(SF.FatherName,'' ) AS FatherName,  
  ISNULL(SF.MotherName,'' ) AS MotherName,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
  RD.Amount AS PaidAmount,
  ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex,
  PTM.Id AS PayTypeId,
  ISNULL(SA.SUID,'') AS SUID
  ,ISNULL(U.DisplayTitle,'NA') AS CreatedUser
  ,TBM.FromDate AS FromDate
  ,TBM.ToDate AS ToDate
   ,SC.PermanentStreetOne as PermanentStreetOne          -- Mentis 29588
	  ,SC.PermanentStreetTwo as PermanentStreetTwo
	  ,SC.PermanentStreetThree as PermanentStreetThree
	  ,SC.PermanentCountry as PermanentCountry
	  ,SC.PermanentState as PermanentState
	  ,SC.PermanentCity as PermanentCity
	  ,SC.PermanentZipCode as PermanentZipCode
	  ,SC.PermanentContactNo as PermanentContactNo    
	  ,SAD.AdmissionNumber as AdmissionNumber 
	  ,SO.DateOfBirth as DateOfBirth   
	  ,sFee.fFeeAmountSumGet (SA.AcademicId) AS TotalAmount 
	  --,SI.StudentPhoto as StudentPhoto              -- Mentis 29588 
	  ,CASE WHEN @rReportId=30217 THEN 0x ELSE SI.StudentPhoto END AS StudentPhoto -- mantisid - 0032096
	  ,SC.PresentStreetOne  --Mentis 0030332
	  ,SC.PresentStreetTwo
	  ,SC.PresentCity		--Mentis 0030332
	  ,OI.CertificateHeaderA4Portrait AS CertificateHeaderA4  --mantis - 0030332

	  
  FROM   
   sFee.tReceipt R  
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  INNER JOIN sFee.tFeeSetup FS  
   ON FS.Id=RD.FeeSetupId  
  INNER JOIN sFee.tFeeMaster FM  
   ON FM.Id=FS.FeeId  
  INNER JOIN sFee.tFeeHeadMaster FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId 
  LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = O.Id
  LEFT JOIN [sSecurity].[tUser] U ON U.Id=R.CreatedUserId -- Change innerjoin to left join for mantis id :0029242
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.StudentId = SA.StudentId  
    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))  
 INNER JOIN sSetup.tBatchMaster TBM ON TBM.Id=R.BatchId AND ((TBM.OrgId=@rOrgId) OR (@rOrgId=0))

  LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentID = SA.StudentID   -- Mentis 29588
  LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentID = SA.StudentID      
  LEFT JOIN sStudent.tStudentImages SI ON SI.StudentID = SA.StudentID      -- Mentis 29588
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND (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 ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=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 ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')   
	AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    
 ORDER BY R.ReceiptNumber  
	END
 --ORDER BY R.Id 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeLeaveBulkXMLInsert]...';


GO

ALTER PROCEDURE [sHrm].[pEmployeeLeaveBulkXMLInsert]
	
	@rStrXml nvarchar(MAX),
    @rId bigint =0,
        @rEmployeeId bigint=0,
        @rReportDate date='',
		--@rLeaveDate Date,
        --@rLeavePeriodId tinyint=0,
        --@rLeaveTypeId int=0,
        --@rLeaveReson nvarchar(200)='',
        @rNoOfLeave decimal=1,
        @rBatchId int,
        @rOrgId int,
        @rCreatedUserId bigint,
        @rStatusId int =549,
        @rFromTime datetime ='',
		@rToTime datetime ='',
		@rDepartmentId int
    
    
		
AS
SET NOCOUNT ON

BEGIN
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
DECLARE @lCount INT

    CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		EmployeeId bigint,
		FromDate date,
		ToDate date,
		LeavePeriodId int,
		LeaveTypeId int,
		LeaveReason nvarchar(100),
		LeaveDate Date,
		NoOfLeave decimal(5,2)
	)
	INSERT INTO #tTable
	(
            [EmployeeId]
           ,[FromDate]
           ,[ToDate]
           ,[LeavePeriodId]
           ,[LeaveTypeId]
           ,[LeaveReason]
		   ,NoOfLeave
           )          
           SELECT	
            At.EmployeeId 
           ,At.FromDate 
           ,At.ToDate 
           ,At.LeavePeriodId 
           ,At.LeaveTypeId 
           ,At.LeaveReason 
		   ,At.NoOfLeave
			FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				EmployeeId bigint,
				FromDate date,
				ToDate date,
				LeavePeriodId int,
				LeaveTypeId int,
				LeaveReason nvarchar(100),
				LeaveDate Date,
				NoOfLeave decimal(5,2)
		   ) AS At	


	DECLARE @lItemValue nvarchar(20) = '', @lOrgGroupId int
	
	SELECT @lOrgGroupId = OrgGroupId from [sSetup].[tOrganizationMaster] WHERE Id = @rOrgId

	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 545


	DECLARE @lNextNumber bigint

	SELECT @lCount =  COUNT(Id) FROM #tTable
	WHILE @lCount > 0 
	BEGIN

	    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tLeave', 0, 1, 1,@outNextNumber = @lNextNumber output	
	    
		  INSERT INTO [sHrm].[tLeave]
           (
            [Id]
           ,[EmployeeId]
           ,[ReportDate]
           ,[FromDate]
           ,[ToDate]
           ,[LeavePeriodId]
           ,[LeaveTypeId]
           ,[LeaveReason]
           ,NoOfLeave
           ,BatchId
           ,[OrgId]           
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[StatusId]
           ,[FromTime]
           ,[ToTime]
           )          
           SELECT		
			 @lNextNumber
           ,temp.EmployeeId 
           ,sCommon.fGetDate()
           ,temp.FromDate 
           ,temp.ToDate 
           ,temp.LeavePeriodId 
           ,temp.LeaveTypeId 
           ,temp.LeaveReason 
           ,NoOfLeave
           ,@rBatchId
           ,@rOrgId 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rStatusId      
           ,@rFromTime
           ,@rToTime 
			FROM #tTable temp Where temp.Id= @lCount 
			
			--mantisid - 0031565

			DECLARE @lLeaveTypeId int, @lIsLWP bit
			SELECT @lLeaveTypeId = LeaveTypeId FROM #tTable Where Id= @lCount 

			SELECT @lIsLWP = IsLWP from sHrm.tLeaveTypeMaster Where Id = @lLeaveTypeId AND OrgId = @rOrgId

			IF(@lItemValue = 'True' AND @lIsLWP = 'true')
			BEGIN
				UPDATE sHrm.tLeave SET StatusId = 550 WHERE Id = @lNextNumber
			END

		SET @lCount = @lCount - 1
		END	   		
		
        SELECT 1 AS Result
	 --END	
    
           
            --ELSE
            --SELECT -1 AS Result
            --END	
	
		
	
END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmployeeAttendanceGet]...';


GO

ALTER PROCEDURE [sHrm].[pRptEmployeeAttendanceGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rEmployeeName nvarchar(200),
	@rEmployeeCode nvarchar (200),
	@rEmployeeId bigint,
	@rDepartmentId int,
	@rEmployeeGradeId int,
	@rForYear  smallint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int,
	@rEmployeeStatusId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT 
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2, 
			 EM.Code AS EmployeeCode,
			 EM.EmployeeName,   
			 EM.EmployeeId,
			 EM.DepartmentName,
			 EM.EmployeeGrade,     
			 ISNULL(WD.TotalDays,ISNULL(AT.TotalWorkingDays,0)) As TotalDays,
			 ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays, 
			 ISNULL(AT.LWP,0) AS LWP,
			-- CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
			 (ISNULL(AT.TotalWorkingDays,0) - (ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0))) AS PresentDays,
			 MM.Title AS MonthName,
			 AT.ForYear As YearName,			
			 --L.LeaveReason,
			 --L.NoOfLeave,
			 --L.ReportDate,
			 --L.FromDate,
			 --L.ToDate,
			 --LPM.Title As LeavePeriod,
			 --LTM.Title As LeaveType,
			 --LTM.IsCarryForward,
			 --LTM.IsLWP
			  EM.EmployeeDesignation As Designation, -- Mantis 0030721
			  [sHrm].[fEmployeeNameGet](EM.FirstName, EM.MiddleName, Em.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise --Mantis 0031250
			  --EM.Number -- Added for Mantis : 32040 by Nilesh
        FROM 
			sHrm.vEmployeeCommonDetail EM 
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			LEFT JOIN sCommon.tMonthMaster MM ON MM.Id=AT.ForMonth
			LEFT JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
			AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			--INNER JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId
			--INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id=L.LeavePeriodId
			--INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id=L.LeaveTypeId
    	WHERE 
    			EM.OrgID = @rOrgId 
    		AND (AT.BatchId=@rBatchId)
    		AND ((AT.ForMonth=@rForMonth) OR (@rForMonth=0))
    		AND ((AT.ForYear=@rForYear) OR (@rForYear=0))
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		--AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    		--AND ((L.ToDate>=@rToDate) OR (ISNULL(@rToDate,'')=''))
    		AND EM.IsOtherUser = 0
    		ORDER BY EM.Number
    		
END
GO
PRINT N'Altering Procedure [sLibrary].[pRptBookListGet]...';


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

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

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Code,
		BM.Title As BookTitle,
		BM.Publisher,BM.Supplier,
		BM.BookSubject,
		BM.Code AS BookCode,
		BM.BookLanguage,
		BM.BookCustomTag,
		BM.BookCustomTag,
		BM.Location,
		BM.ISBNNumber,
		LM.ReportOrgTitle,
        LM.SmallAddress1,
        LM.SmallAddress2,
        CASE WHEN BM.BookDepartment is null THEN 'Blank'
            WHEN BM.BookDepartment='' THEN 'Blank'  ELSE BM.BookDepartment END AS  BookDepartment,
        BM.NoOfCopies,
        @rIsDetail AS IsDetail,
        LM.Code AS LibraryCode,	       
         LM.Title AS LibraryTitle,
        BM.AccessionNo AS AccessionNo
		
	FROM 
		sLibrary.tBookMaster BM
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.BookDepartment like @rBookDepartment) OR (@rBookDepartment=''))
		AND ((BM.PurchaseDate >= @rFromPurchaseDate) OR (ISNULL(@rFromPurchaseDate,'') = ''))
		AND ((BM.PurchaseDate <= @rToPurchaseDate) OR (ISNULL(@rToPurchaseDate,'') =''))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((Convert(nvarchar(25),ISNULL(BM.Code,'')) >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
		AND ((Convert(nvarchar(25),ISNULL(BM.Code,'')) <= @rToCode) OR (ISNULL(@rToCode,'') = ''))
		AND ((BM.Code IN(SELECT Code FROM @ListofBookCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		--AND CASE WHEN @BookConfig = 'True' THEN BM.Code >= @rFromCodeString ELSE BM.Code > @rFromCodeInt END AS BM.Code
		--AND CASE WHEN @BookConfig = 'True' THEN BM.Code <= @rToCodeString ELSE BM.Code > @rToCodeInt END AS BM.Code
		AND ((BM.BookEntryDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((BM.BookEntryDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		--Start For Mantis: 31829
		AND (ISNUMERIC(BM.Code) = 1 AND (CAST(BM.Code AS bigint) >= @rFromBookCode OR Convert(bigint, ISNULL(@rFromBookCode, '0')) = 0) OR (ISNUMERIC(BM.Code) = 0 AND Convert(bigint, ISNULL(@rFromBookCode, '0')) = 0))
		AND (ISNUMERIC(BM.Code) = 1 AND (CAST(BM.Code AS bigint) <= @rToBookCode OR Convert(bigint, ISNULL(@rToBookCode, '0')) = 0) OR (ISNUMERIC(BM.Code) = 0 AND Convert(bigint, ISNULL(@rToBookCode, '0')) = 0))
		--End For Mantis: 31829

		ORDER BY
		CASE WHEN BM.Code like '%[0-9]%' 
		 THEN Replicate('0', 100 - Len(BM.Code)) + BM.Code
		 ELSE BM.Code  END
		--ORDER BY CONVERT(INT, BM.Code)
		
	END
GO
PRINT N'Altering Procedure [sPayroll].[pRptPayStatementGet]...';


GO


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

BEGIN 
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1

	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)


	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    ISNULL(ESO.UAN,'') AS UAN,
	    (CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarning,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeduction,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmount,
	    EM.FirstName,
		EM.LastName,
		tEM.Number,
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
		EM.DateOfLeaving,
		tEM.CreatedDateTime,
		ISNULL(PPE.WorkingDays,@lMonthDay) WorkingDays,
		PPE.Lwp,
		ISNULL(PPE.PaidLeave,0) PaidLeave,
		ISNULL(PER.ChequeNo,'') ChequeNo,
		PER.PayDate,
		CASE WHEN ISNULL(PER.PayTypeId,0) = 0 THEN ISNULL(ESO.PayTypeId,0)
			ELSE ISNULL(PER.PayTypeId,0) END AS PayTypeId,
		CASE WHEN ISNULL(PER.PayTypeId,0) = 0 THEN ISNULL(PTM2.Title,'')
			ELSE ISNULL(PTM.Title,'') END AS PayTypeName
		--ESO.AccountNumber -- Added for mantis : 32040 by Nilesh


	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = @rForMonth) OR (@rForMonth = 0))  AND ((AT.ForYear = @rForYear) OR (@rForYear = 0)) 
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
		LEFT JOIN sPayroll.tPayProcessEmployeeRemark PER ON
			PER.SalaryMonth=@rForMonth AND PER.SalaryYear=@rForYear	AND PER.PayrollYearId=@rPayrollYearId AND EM.EmployeeId = PER.EmployeeId
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PER.PayTypeId
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM2 ON PTM2.Id = ESO.PayTypeId
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '' OR ISNULL(@lFirstDate,'')='')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '' OR ISNULL(@lLasteDate,'')='')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering Procedure [sSecurity].[pEmailValidateUser]...';


GO
ALTER PROCEDURE [sSecurity].[pEmailValidateUser]

    @rOrgId int = 0,
    @rUserTitle nvarchar(100)='',
    @rUserEmailId nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		DECLARE @rUserSourceId bigint=0
		DECLARE @rUserId bigint=0
		DECLARE @rUserSourceTypeId smallint=0
		DECLARE @newpwd VARCHAR(100)
		SELECT @rUserId=Id,@rUserSourceId = SourceId,@rUserSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND OrgId = @rOrgId
		
		IF(@rUserSourceTypeId = 95)
		BEGIN
			IF EXISTS (SELECT 1 FROM sHrm.tEmployeeCommunications WHERE CompanyEmail = @rUserEmailId and EmployeeId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				
					EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId

					SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Email Id is wrong' AS [Message],'' AS OTP
			END	
		END
		IF(@rUserSourceTypeId = 2003)
		BEGIN
			IF EXISTS (SELECT 1 FROM sStudent.tStudentCommunication WHERE ParentEmail = @rUserEmailId and StudentId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				
					EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId
					SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId  AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Email Id is wrong' AS [Message],'' AS OTP
			END		
		END
		ELSE
		BEGIN
			SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
		END
END
GO
PRINT N'Altering Procedure [sStudent].[pLeftStudentListGet]...';


GO

ALTER PROCEDURE [sStudent].[pLeftStudentListGet]   
	@rFirstName nvarchar(100)='',
	@rMiddleName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rOrgId int=0,
	@rBatchId int=0,
	@rDepartmentId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=0,
	@rSUId nvarchar(50)='',
	@rCode nvarchar(20)='',
	@rStatusId int = 0
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rMiddleName = sCommon.fSearchStringGet(@rMiddleName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	
	SELECT A.AcademicId,	  
	A.ClassId,A.DivisionId,A.RollNo,A.OrgId,A.BatchId,A.StudentId,A.Code,A.Number,A.FirstName,A.MiddleName,A.LastName,
	A.Name,A.StatusId,A.ClassName,A.DivisionName,A.ClassDivision,A.BatchName,A.DepartmentId,A.DepartmentName,
	A.ClassOrderIndex,A.DisplayTitle,A.SUId ,A.ParentContactNo,A.StudentContactNo,A.ParentEmail,A.Religion,A.FamilyCast,A.FamilySubCast,
	A.LeftDate,A.PreviousSchool,A.DateOfBirth,A.BirthDateInWord,A.LeftReason,A.AdmissionDate,A.AdmissionStandard,A.LeftStandard,
	A.StudentPhoto,A.BloodGroup,A.PresentAddress,A.ContactNo,A.Batch,A.InactiveDate,A.OrgName,A.MotherName,
	A.StudentNumber,A.FatherName,A.Nationality,A.MotherTongue,A.AdhaarNumber,A.ClassStatusId,A.ClassStatusName,A.StatusName

	FROM 
	(SELECT 
	ISNULL(A.Id,0) AS AcademicId,	  
	ISNULL(A.ClassId,0) AS ClassId,
	ISNULL(A.DivisionId,0) AS DivisionId,
	ISNULL(A.RollNo,0) AS RollNo,
	ISNULL(A.OrgId,0) AS OrgId,
	ISNULL(A.BatchId,0) AS BatchId,
	SM.Id AS StudentId,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(SM.Number,0) AS Number,
	ISNULL(SM.FirstName,'') AS FirstName,
	ISNULL(SM.MiddleName,'') AS MiddleName,
	ISNULL(SM.LastName,'') AS LastName,
	[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	ISNULL(SM.StatusId,0) AS StatusId,
	ISNULL(CM.DisplayTitle,'')  AS ClassName,
	ISNULL(DM.DisplayTitle,'') AS DivisionName,
	ISNULL(CM.DisplayTitle +'-'+DM.DisplayTitle,'') AS ClassDivision,
	ISNULL(BM.Title,'') AS BatchName,
	ISNULL(DeptM.Id,0) AS DepartmentId,
	ISNULL(DeptM.Title,'') AS DepartmentName,
	ISNULL(SM.BlackListReason,'') BlackListReason,
	CM.OrderIndex AS ClassOrderIndex,
	ISNULL(OM.DisplayTitle,'')  AS DisplayTitle,
	ISNULL(SM.SUId,'') AS SUId ,
	ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
	ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
	ISNULL(SC.ParentEmail,'') AS ParentEmail,
	ISNULL(SD.Religion,'') AS Religion,
	ISNULL(SD.FamilyCast,'') AS FamilyCast,
	ISNULL(SD.FamilySubCast,'') AS FamilySubCast,
	ISNULL(SD.LeftDate,'') AS LeftDate,
	ISNULL(SD.PreviousSchool,'') AS PreviousSchool,
	ISNULL(SD.DateOfBirth,'') AS DateOfBirth,
	ISNULL(SD.BirthDateInWord,'') AS BirthDateInWord,
	ISNULL(SD.LeftReason,'') AS LeftReason,
	ISNULL(SD.AdmissionDate,'') AS AdmissionDate,
	ISNULL(SD.AdmissionStandard,'') AS AdmissionStandard,
	ISNULL(SD.LeftStandard,'') AS LeftStandard,
	0x AS StudentPhoto,
	ISNULL(SD.BloodGroup,'') AS BloodGroup,
	ISNULL(SD.PresentAddress,'') AS PresentAddress,
	ISNULL(SD.ContactNo,0) AS ContactNo,
	ISNULL(SD.Batch,'') AS Batch,
	ISNULL(SD.InactiveDate,'') AS InactiveDate,
	ISNULL(OM.Title,'') AS OrgName,
	ISNULL(SF.MotherName,'') AS MotherName,
	ISNULL(SD.Number,'') AS StudentNumber,
	ISNULL(SF.FatherName,'') AS FatherName,
	ISNULL(SD.Nationality,'') AS Nationality,
	ISNULL(SD.MotherTongue,'') AS MotherTongue,
    ISNULL(SD.AdhaarNumber,0) AS AdhaarNumber,
    ISNULL(SD.ClassStatusId,0) AS ClassStatusId,
    ISNULL(SD.ClassStatusName,'') AS ClassStatusName,
	--(CASE
	-- WHEN (SELECT ISNULL(R.Id,0) AS Id FROM sAlumni.tRegistration R WHERE R.MappedStudentId = A.Id) = 0 THEN 'Not Converted' ELSE 'Converted' END ) StatusName
	(CASE
        WHEN ISNULL((SELECT TOP 1 1 FROM sAlumni.tRegistration R WHERE R.MappedStudentId = A.Id), 0) = 0 THEN 'Not Converted'
        ELSE 'Converted'
    END )AS StatusName
	--ISNULL(STM.Title,'') AS StatusName

FROM 
		(
SELECT Id 
FROM (select A.ID,
        ROW_NUMBER() over (partition by studentId ORDER BY BM.OrderIndex DESC) as MAX_ID
from sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
) x
WHERE MAX_ID = 1	
) LA INNER JOIN sStudent.tAcademic A ON LA.Id = A.Id
			
	INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = A.Id
LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
	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 SM.OrgId = OM.Id
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SM.Id
	--LEFT JOIN sAlumni.tRegistration R ON A.Id = R.MappedStudentId
WHERE 
	((A.ClassId=@rClassId)OR(@rClassId=0))
	AND((A.DivisionId=@rDivisionId)OR(@rDivisionId=0))
	--AND((SM.Code >= CONVERT(nvarchar(20),@rFromCode)) OR (ISNULL(@rFromCode,0) = 0)) 
	--AND((SM.Code <= CONVERT(nvarchar(20),@rToCode)) OR (ISNULL(@rToCode,0) = 0)) 
	AND((SM.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
	AND((SM.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = ''))
	AND((SM.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
	AND(STM.Id=3)
	AND((A.BatchId=@rBatchId)OR(@rBatchId=0))	
	AND((OM.Id=@rOrgId)OR(@rOrgId=0))
	--AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
	AND((DeptM.Id=@rDepartmentId)OR(@rDepartmentId=0))
	AND((A.RollNo=@rRollNo)OR(@rRollNo=0))	
	AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
	AND ((SM.Code=@rCode) OR (@rCode=''))
	--ORDER BY SM.Number 
	) AS A
	WHERE 
    (@rStatusId = 1 AND A.StatusName = 'Converted')OR (@rStatusId = 2 AND A.StatusName = 'Not Converted')OR (@rStatusId NOT IN (1, 2));
	


END
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentInformationFormGet]...';


GO
ALTER PROCEDURE [sStudent].[pRptStudentInformationFormGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrStudentId nvarchar(max),
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rClassStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rRemark nvarchar(500),
	 @rNote nvarchar(500)

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rRemark AS Remark,
			@rNote AS Note,
			SA.AcademicId,
			SA.StudentId, 			
			SA.Code,						
			SA.Name,		
			SA.ClassDivision AS ClassDiv,	
			SA.ParentEmail,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SA.Religion,'') AS Religion,
			ISNULL(SA.Gender,'') AS Gender,
			SA.DateOfBirth AS DateOfBirth,
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			
			SF.FatherIncome AS FatherIncome,
			SF.MotherIncome AS MotherIncome,
			SD.BankAccountNumber AS BankAccountNo,
			SD.BankName AS BankName,
			SD.BankBranch AS BranchName,
			SD.BankIFSCCode AS BankIFSCCode,
			CM.Id AS CategoryId,
			CM.Title AS Category,
			SF.IsSingleChild,
			SA.FamilyCast AS Cast,
			 CASE WHEN EXISTS (SELECT StudentId FROM sStudent.tStudentSibling AS SS WHERE SS.StudentId = SA.StudentId)
				THEN 'No' 
					ELSE 'Yes'
				 END AS OnlyOneChild,
				 SA.ClassID,
				 SA.DivisionId,
			SA.ClassStatusId,
			SA.UIDNumber,
			SA.ClassStatusName,
			ISNULL(SA.FamilySubCast,'') SubCast,
			ISNULL(SA.BirthPlace,'') BirthPlace,
			ISNULL(SA.BirthTaluka,'') BirthTaluka,
			ISNULL(SA.BirthDistrict,'') BirthDistrict,
			SA.ClassName,
			SA.DivisionName,
			SA.RollNo,
			SA.AdmissionDate,
			ISNULL(SA.AdmissionStandard,'') AdmissionStandard,
			--Mantis Start -0031790
			BM.Title AS BatchName,
			SA.PresentStreetone, 
			SA.PresentStreetTwo,
			SA.PresentStreetThree, 
			SA.PresentCity AS PresentDistrict,
			SA.PresentState AS PresentState,
			SA.PresentZipCode As PresentPINCode
			--Mantis End -0031790
			
	FROM 
		 	 sStudent.vStudentAllDetail SA
		 	 --LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		 	 LEFT JOIN sCommon.tCastCategoryMaster CM ON CM.Id=SA.CastCategoryId
		 	 -- LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 	  LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
		 	  LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=SA.StudentId 
		 	INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassId and BC.BatchId= @rBatchId
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = BC.BatchId --MAntis 0031790
	WHERE 
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentImportExamWiseGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentImportExamWiseGet]
	@rClassId int=0,
	@rDivisionId int=0,
	@rOrgId int,
	@rBatchId int,
	@rExamId int,
	@rStatus int=0	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 
	
	--Changes for Mantis Id : 0031796
	SELECT AR2.Id,AR2.ParticipantSourceId,AR2.ParticipantSourceTypeId,AR2.WorkflowFunctionalityId INTO #Temp_ExamApprovalRequest 
	FROM (Select AR.ParticipantSourceId,
	(SELECT TOP 1 AR1.CreatedDateTime FROM sWorkflow.tApprovalRequest AR1 
	WHERE AR.ParticipantSourceId = AR1.ParticipantSourceId AND AR1.WorkflowFunctionalityId = 1
	ORDER BY AR1.CreatedDateTime DESC) AS CreatedDateTime
	from sWorkflow.tApprovalRequest AR GROUP BY AR.ParticipantSourceId) AR1
	INNER JOIN  sWorkflow.tApprovalRequest AR2 ON AR1.CreatedDateTime = AR2.CreatedDateTime AND AR1.ParticipantSourceId = AR2.ParticipantSourceId
	LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR2.Id
	LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		
	SELECT 
		SA.Id AS AcademicId,
		SA.StudentId,
		ISNULL(SA.RollNo,0) AS RollNo,
		SM.FirstName+' '+SM.LastName AS Name,
		SM.Code,
		STM.Id AS StatusId,
		STM.Title AS StatusName,		
		CM.Id AS ClassId,
		CM.Title AS ClassName,
		DM.Id AS DivisionId,
		DM.Title AS DivisionName,
		 R.Percentage,
		ISNULL(SA.ExemptionTypeId,0) AS ExemptionTypeId,
		ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId ,
		--CASE WHEN ASM.Title IS NULL THEN 'NA' ELSE ASM.Title END AS LCStatus,
		CASE WHEN AR.WorkflowFunctionalityId = 1 THEN (
		CASE WHEN (ASM.Title IS NULL  AND AR.WorkflowFunctionalityId IS NULL)THEN 'NA' 
		WHEN  (ASM.Title IS NULL  AND AR.WorkflowFunctionalityId IS NOT NULL) THEN 'Pending'
		ELSE ASM.Title END)	ELSE 'NA' END AS LCStatus,
		R.ResultStatus			
			
    FROM 
           sStudent.tAcademic SA
           INNER JOIN sStudent.tStudentMaster SM
           ON SM.Id=SA.StudentId
           INNER JOIN sStudent.tStatusMaster STM
           ON STM.Id=SM.StatusId
           INNER JOIN sSetup.tClassMaster CM
           ON CM.Id=SA.ClassId
           INNER JOIN sSetup.tDivisionMaster DM
           ON DM.Id=SA.DivisionId             
           INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id 
           INNER JOIN sAssessment.tResult R ON R.AcademicId= SA.Id AND R.ExamId = EM.Id
		   LEFT JOIN #Temp_ExamApprovalRequest AR ON AR.ParticipantSourceId = SA.Id AND AR.ParticipantSourceTypeId = 2001
		   LEFT JOIN sWorkflow.tApprovalAction AA 
		   ON AA.ApprovalRequestId = AR.Id
		   LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
	WHERE  
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND(SA.OrgId=@rOrgId)
		AND  (R.ExamId =@rExamId)
		AND ((STM.Id=@rStatus) OR (@rStatus=0))		
	ORDER BY R.Percentage desc, SA.RollNo		
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentImportGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentImportGet]
	@rClassId int=0,
	@rDivisionId int=0,
	@rOrgId int,
	@rBatchId int,
	@rStatusId int=0,
	@rCode nvarchar(20)=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	--Changes for Mantis Id : 0031796
	SELECT AR2.Id,AR2.ParticipantSourceId,AR2.ParticipantSourceTypeId,AR2.WorkflowFunctionalityId 
	INTO #Temp_ApprovalRequest
	FROM (Select AR.ParticipantSourceId,
	(SELECT TOP 1 AR1.CreatedDateTime FROM sWorkflow.tApprovalRequest AR1 
	WHERE AR.ParticipantSourceId = AR1.ParticipantSourceId AND AR1.WorkflowFunctionalityId = 1
	ORDER BY AR1.CreatedDateTime DESC) AS CreatedDateTime
	from sWorkflow.tApprovalRequest AR GROUP BY AR.ParticipantSourceId) AR1
	INNER JOIN  sWorkflow.tApprovalRequest AR2 ON AR1.CreatedDateTime = AR2.CreatedDateTime AND AR1.ParticipantSourceId = AR2.ParticipantSourceId
	LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR2.Id
	LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		
	SELECT 
		SA.Id AS AcademicId,
		SA.StudentId,
		ISNULL(SA.RollNo,0) AS RollNo,
		SM.FirstName+' '+SM.LastName AS Name,
		SM.Code,
		STM.Id AS StatusId,
		STM.Title AS StatusName,		
		CM.Id AS ClassId,
		CM.Title AS ClassName,
		DM.Id AS DivisionId,
		DM.Title AS DivisionName,
		ISNULL(SA.ExemptionTypeId,0) AS ExemptionTypeId,
		ISNULL(SA.FeeStructureId,0) AS FeeStructureId,
		ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
		CASE WHEN AR.WorkflowFunctionalityId = 1 THEN (
		CASE WHEN (ASM.Title IS NULL  AND AR.WorkflowFunctionalityId IS NULL)THEN 'NA' 
		WHEN  (ASM.Title IS NULL  AND AR.WorkflowFunctionalityId IS NOT NULL) THEN 'Pending'
		ELSE ASM.Title END)ELSE 'NA' END AS LCStatus			
    FROM 
           sStudent.tAcademic SA
           INNER JOIN sStudent.tStudentMaster SM
           ON SM.Id=SA.StudentId
           INNER JOIN sStudent.tStatusMaster STM
           ON STM.Id=SM.StatusId
           INNER JOIN sSetup.tClassMaster CM
           ON CM.Id=SA.ClassId
           INNER JOIN sSetup.tDivisionMaster DM
           ON DM.Id=SA.DivisionId  
		   LEFT JOIN #Temp_ApprovalRequest AR ON AR.ParticipantSourceId = SA.Id AND AR.ParticipantSourceTypeId = 2001
		   LEFT JOIN sWorkflow.tApprovalAction AA 
		   ON AA.ApprovalRequestId = AR.Id
		   LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId		              
	WHERE  
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND(SA.OrgId=@rOrgId)
		AND ((STM.Id=@rStatusId) OR (@rStatusId=0))
		AND (SM.Code=@rCode OR ISNULL(@rCode,'')='')
	ORDER BY SA.RollNo		
END
GO


PRINT N'Creating Procedure [sAlert].[pForgotPasswordFailureLogGet]...';


GO
CREATE PROCEDURE [sAlert].[pForgotPasswordFailureLogGet]
	@rUserId bigint,
	@rUserSourceTypeId int,
	@rFailureLogId bigint =0 
AS
BEGIN
		DECLARE @lCode nvarchar(100),@lSourceId bigint
		UPDATE sSecurity.tUser set TempPasswordCode = newid() WHERE Id = @rUserId 
		SELECT @lCode = TempPasswordCode,@lSourceId = SourceId from sSecurity.tUser where Id = @rUserId and SourceTypeId = 95
		SELECT @lCode = TempPasswordCode,@lSourceId = SourceId from sSecurity.tUser where Id = @rUserId and SourceTypeId = 2003

		Select @lCode AS Code
end
GO
PRINT N'Creating Procedure [sAssessment].[pReportHistoryAdd]...';


GO
CREATE PROCEDURE [sAssessment].[pReportHistoryAdd]
	 
	        --@rId int,
	        @rScreenId int,
	        @rReportName nvarchar(max),
            @rStatusId int,
            @rUserId bigint

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	INSERT INTO [sAssessment].[tReportHistory]
           (
		    ScreenId
           ,ReportName
           ,StatusId
           ,CreatedUserId
           ,CreatedDateTime
			)
     VALUES
           (
		    @rScreenId
           ,@rReportName
           ,@rStatusId
           ,@rUserId
           ,sCommon.fGetDate()
           )
	--Select 1 AS Result

	SELECT @@Identity AS Result
	--COMMIT TRANSACTION		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS RESULT
	--END CATCH	
		
END
GO
PRINT N'Creating Procedure [sAssessment].[pReportHistoryGet]...';


GO
CREATE PROCEDURE [sAssessment].[pReportHistoryGet]
	 
	        --@rId int,
	        @rScreenId int
	  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	SELECT 
			ReportName,
		   (CASE WHEN StatusId = 1 THEN 'Completed' ELSE 'Pending' END) AS Status,
		   CreatedDateTime
	FROM
			 sAssessment.tReportHistory
	WHERE ScreenId = @rScreenId
	Order By CreatedDateTime DESC
          

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


GO
CREATE PROCEDURE [sAssessment].[pRptResultListFloatingSubCombineExam]
	 
	 @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,
	 @rToRollNo int,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rIsShowWithDetail bit =0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN
 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int , @lIsMarksInDecimal bit , @lDecimalFormat nvarchar(10)
 
SELECT @GradeSetId = GradesetId,@lIsMarksInDecimal = IsMarksInDecimal, @lDecimalFormat = DecimalFormat  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  

 DECLARE @lAbsentRemarkConfig nvarchar(20) = '' , @lOrgId int
 SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id=@rBatchId
 SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId


CREATE TABLE #TempExam
(
	SubCombineExamId int, 
	ExamOrderIndex int,
	CombineExamId int,
	AnnualExamId int, 
	Exam nvarchar(50) 
)


INSERT INTO #TempExam
(
	 SubCombineExamId,
	 ExamOrderIndex,
	 CombineExamId,
	 AnnualExamId,
	 Exam 
	
)
 
SELECT	EM.Id AS SubCombineExamId,
		EC.ExamOrder,
		EC.ExamId AS CombineExamId,
		@rExamId AS AnnualExamId,
		ESGM.Code AS Exam
FROM [sAssessment].[tExamMaster] EM 
		INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId in (select SubExamId 
							  from sAssessment.tExamCombine 
							  where examid=@rExamId) AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId
		--INNER JOIN sAssessment.tExamCombine EC1 ON EC1.SubExamId=EM.Id AND EC1.ExamId =@rExamId
  --WHERE (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId


CREATE TABLE #TempCombineExam
(
	ExamOrderIndex int,
	TermExamId int,
	AnnualExamId int,
	Exam nvarchar(50)
)

INSERT INTO #TempCombineExam
(
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam
)

SELECT EC.ExamOrder,
EM.Id AS TermExamId,
@rExamId AS AnnualExamId,
ESGM.Code AS Exam
  FROM [sAssessment].[tExamMaster] EM 
		INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId =@rExamId  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId

	
	--Select * from #TempExam

		Declare @lAnnualExamMaximum int,@lExamId int
		Select @lExamId= AnnualExamId FROM #TempExam 

		Select @lAnnualExamMaximum=Maximum from sAssessment.tExamDetail Where ExamId=@lExamId
	
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			 @rBuilder1 AS Builder1,
			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,
			(Select R1.TotalObtain from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS TotalMarks,
			(Select R1.Percentage from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS Percentage,
			R.TotalObtain,
			R.RankNumber,
			(Select R1.ResultGrade from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS 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,			
			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,			 	
			@lIsMarksInDecimal AS 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.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,
			EM.TermScopeId,
			RD.IsPresent,
			@GradeString 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,
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			EC.SubCombineExamId,
			EC.ExamOrderIndex,
			EC.AnnualExamId ,
			@lDecimalFormat AS DecimalFormat,
			EC.CombineExamId,
			EC.Exam AS ExamNAme,
			ARD.SubjectGrade AS AnnualSubjectGrade,
			ARD.Obtain As AnnualSubjectObtain,
			TRD.SubjectGrade AS TermSubjectGrade,
			TRD.Obtain AS TermSubjectObtain,
			RD.SubjectGrade AS SubjectGrade,
			ISNULL(ARD.Remark,'')  AS Remark,
			SF.FatherName,
			SF.MotherName,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			R.TotalObtain,
			(Select Exd.Maximum from sAssessment.tExamDetail Exd Where 
			Exd.ExamId=EC.CombineExamId AND CS.Id=Exd.ClassSubjectId
			)AS TermMaximum,
			(Select Exd.Maximum from sAssessment.tExamDetail Exd Where 
			Exd.ExamId=EC.AnnualExamId AND CS.Id=Exd.ClassSubjectId
			)AS AnnualMaximum,
			(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END) AS Gender,
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			RD.AbsentRemark
			,TCE.Exam AS CombineExamName
						
	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 #TempExam EC ON EC.SubCombineExamId = EM.Id 	
			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 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			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			INNER JOIN sAssessment.tResult AR ON AR.AcademicId = A.Id AND AR.ExamId = EC.AnnualExamId 
			INNER JOIN sAssessment.tResultDetail ARD ON AR.Id = ARD.ResultId 
			INNER JOIN sAssessment.tExamDetail AED ON ARD.EXamDetailId = AED.Id 
			INNER JOIN sSetup.tClassSubject ACS ON AED.ClassSubjectId = ACS.Id AND ACS.Id= CS.Id
			INNER JOIN sAssessment.tResult TR ON TR.AcademicId = A.Id AND TR.ExamId = EC.SubCombineExamId 
			INNER JOIN sAssessment.tResultDetail TRD ON TR.Id = TRD.ResultId 
			INNER JOIN sAssessment.tExamDetail TED ON TRD.EXamDetailId = TED.Id 
			INNER JOIN sSetup.tClassSubject TCS ON TED.ClassSubjectId = TCS.Id AND TCS.Id= CS.Id
			
			
			LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.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 sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND  SR.ExamId=EC.AnnualExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
			LEFT JOIN #TempCombineExam TCE ON TCE.TermExamId = EC.CombineExamId
			
	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 ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    ) 
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		
	 drop table #TempExam

--Select
--	      '' AS AcademicIdText,
--			'' AS ExamIdText,
--			'' AS IsDisplayMonthlyAttendanceText,
--			'' AS Exam,
--			'' AS Builder1,
--			'' AS Code,
--			'' AS Name,
--			0 AS RollNo,
--			CONVERT(BigInt, 0) AS AcademicId,			
--			'' AS ResultStatus,
--			'' AS Class,
--			'' AS Division,
--			CONVERT(Decimal, 0) AS TotalMarks,
--			CONVERT(Decimal, 0) AS Percentage,
--			CONVERT(Decimal, 0) AS TotalObtain,
--			0 AS RankNumber,
--			'' AS ResultGrade,
--			CONVERT(Decimal, 0) AS Percentile,			
--			CONVERT(BigInt, 0) AS ResultDetailId,		
--			CONVERT(Bit, 0) AS IsDisplayInMarksheet,
--			CONVERT(Bit, 0) AS IsShowSubjectGrade,
--			CONVERT(Bit, 0) AS IsIncludeInTotal,
--			CONVERT(Decimal, 0) AS SubjectObtain,
--			CONVERT(Decimal, 0) AS SubjectMinimum,
--			CONVERT(Decimal, 0) AS SubjectMaximum,			
--			'' AS SubjectCode,
--			'' AS SubjectName,
--			0 AS SubjectOrderIndex,
--			CONVERT(BigInt, 0) AS ResultId,
--			0 AS SubjectId,			 	
--			CONVERT(Bit, 0) AS IsMarksInDecimal,
--			'' AS Remark1,
--			'' AS Remark2,
--			'' AS Remark3,
--			'' AS DisplayTitle,
--			CONVERT(Bit, 0) AS IsRankNo, 
--			CONVERT(Bit, 0) AS IsGrade,
--			CONVERT(Bit, 0) AS IsPercentile,
--			CONVERT(Bit, 0) AS IsPercentage,
--			CONVERT(Bit, 0) AS IsSubjectPercentile,
--			CONVERT(Bit, 0) AS IsProcessResult,
--			CONVERT(Bit, 0) AS IsNegativeMarks,
--			CONVERT(Bit, 0) AS IsIncludeCoScholastic,
--			CONVERT(Bit, 0) AS IsOnPrePrinted,
--			CONVERT(Bit, 0) AS IsDisplayPhoto,
--			CONVERT(Bit, 0) AS IsDisplayBirthDate,
--			CONVERT(Bit, 0) AS IsLockForEdit,
--			CONVERT(Bit, 0) AS IsDisplaySchoolName,			
--			CONVERT(Bit, 0) AS IsDisplayAttendance,
--			CONVERT(Bit, 0) AS IsDisplayHeightWeight,
--			CONVERT(Bit, 0) AS IsResultStatus,
--			'' AS FooterAdjustmentText,
--			'' AS DetailAdjustmentText,
--			0 AS FooterAdjustment,
--			0 AS DetailAdjustment,
--			0 AS TermScopeId,
--			CONVERT(Bit, 0) AS IsPresent,
--			'' AS GradeString,
--			0 AS IsDisplayGradeString,
--			CONVERT(Decimal, 0) AS HighestDivisionMark,
--			''  AS HighestDivisionGrade,			
--			'' AS SmallAddress1,
--			CONVERT(Bit, 0) AS IsDisplayParentName,
--			CONVERT(Bit, 0) AS IsShowSubjectMark,
--			CONVERT(Bit, 0) AS IsDisplayTeacherSign,
--			CONVERT(Bit, 0) AS IsDisplayPrincipalSign,
--			CONVERT(Bit, 0) AS IsDisplayMonthlyAttendance,
--			CONVERT(Bit, 0) AS IsImageHeader,
--			0 AS SubCombineExamId,
--			0 AS ExamOrderIndex,
--			0 AS AnnualExamId ,
--			'' AS DecimalFormat,
--			0 AS CombineExamId,
--			'' AS ExamNAme, 			 
--			'' AS AnnualSubjectGrade,
--			CONVERT(Decimal, 0) As AnnualSubjectObtain,
--			'' AS TermSubjectGrade,
--			CONVERT(Decimal, 0) As TermSubjectObtain ,
--			'' AS SubjectGrade,
--			'' AS Remark,
--			'' AS FatherName,
--			'' AS	MotherName,
--			CONVERT(Decimal, 0) AS	TotalDays,
--			CONVERT(Decimal, 0) AS PresentDays,
--			CONVERT(Decimal, 0) AS TotalObtain,
--			CONVERT(Decimal, 0) AS TermMaximum,
--			CONVERT(Decimal, 0) AS AnnualMaximum,
--			'' AS Gender,
--			CONVERT(bit,0) AS IsAbsentRemark,
--			'' AS AbsentRemark,
--			'' AS CombineExamName

END
GO
PRINT N'Creating Procedure [sFee].[pClearedPaymentHistoryGet]...';


GO
CREATE PROCEDURE [sFee].[pClearedPaymentHistoryGet]
	@rId bigint = 0,
	@rOrgGroupBatchId int = 0,
	@rOrgId int = 0,
	@rBatchId int = 0,
	@rAdmissionCategoryId int = 0,
	@rIdNo nvarchar(20) = NULL,
	@rDepartmentId int = 0,
	@rClassId int = 0,
	@rDivisionId int = 0,
	@rReceiptBookId int = 0,
	@rCollectionGroupId int = 0,
	@rPayTypeId int = 0,
	@rStatusId int = 0,
	@rFirstName nvarchar(50) = NULL,
	@rFromReceiptNumber nvarchar(50) = NULL,
	@rToReceiptNumber nvarchar(50) = NULL,
	@rChequeNo nvarchar(50) = NULL,
	@rFromPaymentClearanceDate date = NULL,
	@rToPaymentClearanceDate date = NULL,
	@rOrgGroupId int = 0,
	@rSourceId bigint =0,
	@rSourceTypeId smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	SELECT 	 
		 PDP.Id
		,PDP.OrgId
		,PDP.BatchId
		,PDP.OrgGroupBatchId
		,PDP.SourceTypeId
		,PDP.SourceId
		,PDP.ReceiptId
		,PDP.ReceiptBookId
		,PDP.PayTypeId
		,PDP.PaymentClearanceDate
		,PDP.ChequeNo
		,PDP.BankName
		,PDP.Amount AS ReceiptAmount
		,ISNULL(PDP.Remark, '') AS Remark
		,PDP.CreatedUserId
		,PDP.CreatedDateTime
		,PDP.UpdatedUserId
		,PDP.UpdatedDateTime
		,PDP.StatusId
		,ISNULL(R.ReceiptNumber, '') AS ReceiptNumber
		,ISNULL(RBM.Title, '') AS ReceiptBookTitle
		,ISNULL(R.ReceiptDate, '') AS ReceiptDate
		,ISNULL(PTM.Title, '') AS PayType
		,ISNULL(SA.Code, '') AS IdNo
		,ISNULL(SA.ClassDivision, '') AS ClassDivision
		,ISNULL(SA.Name, '') AS StudentName
	FROM
		sFee.tPostDatePayment PDP
		INNER JOIN sFee.tReceipt R ON R.Id = PDP.ReceiptId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PDP.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = PDP.ReceiptBookId
		INNER JOIN sStudent.vStudentAllDetail SA ON SA.AcademicId = PDP.SourceId AND PDP.SourceTypeId = 2001
	WHERE 
		(PDP.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND (PDP.OrgId = @rOrgId OR PDP.OrgId = 0)
		AND (PDP.BatchId = @rBatchId OR @rBatchId = 0)
		AND (PDP.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		AND (PDP.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
		AND (PDP.StatusId = @rStatusId OR @rStatusId = 0)
		AND (PaymentClearanceDate >= @rFromPaymentClearanceDate OR ISNULL(@rFromPaymentClearanceDate, '') = '')
		AND (PDP.PaymentClearanceDate <= @rToPaymentClearanceDate OR ISNULL(@rToPaymentClearanceDate, '') = '')
		AND (PDP.SourceId = @rSourceId OR @rSourceId = 0)
		AND (PDP.SourceTypeId = @rSourceTypeId OR @rSourceTypeId = 0)
END
GO
PRINT N'Creating Procedure [sFee].[pOldPaidFeeToExceptionAdd]...';


GO
CREATE PROCEDURE sFee.pOldPaidFeeToExceptionAdd
	
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldFeeId int,
	@rNewFeeId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rXml  nvarchar(MAX)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 
	IF OBJECT_ID('tempdb..#TempOldPaidFeeImport') IS NOT NULL DROP TABLE #TempOldPaidFeeImport

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lCount int
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	
	CREATE TABLE #TempOldPaidFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[PaidAmount] decimal(12,2) NULL
	)
	
	INSERT INTO #TempOldPaidFeeImport 
	(
		StudentId,
		AcademicId,
		PaidAmount
	)	
	SELECT	
			A.StudentId,
			A.AcademicId,
			A.PaidAmount
	FROM OPENXML (@intDoc, '/Table/OldPaidFeeImport', 1)
	WITH
	(
			StudentId bigint '@StudentId',
			AcademicId bigint '@AcademicId',
			PaidAmount decimal(12,2) '@PaidAmount'
	)A 
	
	SELECT @lCount = COUNT(AutoId) FROM #TempOldPaidFeeImport
	
	SELECT * FROM #TempOldPaidFeeImport
	BEGIN TRANSACTION
	
	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		DECLARE @lPaidAmount decimal(12,2)
		DECLARE @lAdmissionCategoryId int

		SELECT @lStudentId = StudentId,@lPaidAmount=PaidAmount FROM #TempOldPaidFeeImport WHERE AutoId = @lCount
		SELECT @lAcademicId = Id, @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM  sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
		SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId
		
		IF (ISNULL(@lAcademicId,0) > 0 AND ISNULL(@lFeeSetupId, 0) > 0 AND ISNULL(@lClassId, 0) > 0)
		BEGIN
				IF OBJECT_ID('tempdb..#TempFeeSetup') IS NOT NULL DROP TABLE #TempFeeSetup

				SELECT
					FM.Id AS FeeId,
					FS.Id AS FeeSetupId,
					ISNULL(FS.IsOptional,0)AS IsOptional,
					ISNULL(FS.IsVariable,0)AS IsVariable,
					ISNULL(FS.Amount,0)AS Amount,
					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
				INTO #TempFeeSetup 
				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.Id = @lFeeSetupId
				AND FS1.BatchId = @rNewBatchId
					
				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=@lAcademicId) AND(FO.SourceTypeId=2001)
				WHERE FS1.BatchId = @rNewBatchId
				AND FS1.Id = @lFeeSetupId
				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=@lAcademicId) AND(FA.SourceTypeId=2001)
				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= @lAcademicId
					AND (R.SourceTypeId = 2001)
					AND R.IsObsolete = 0 
					AND R.BatchId = @rNewBatchId
					AND FeeSetupId = @lFeeSetupId
					GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id	

				DECLARE @lCount1 int = 0

				SET @lCount1  = (SELECT COUNT(1) FROM #TempFeeSetup)

				IF(@lCount1 > 0)
				BEGIN
					DECLARE @lPendingAmount decimal(12,2) = 0
					SET @lPendingAmount = (SELECT PendingAmount FROM #TempFeeSetup WHERE FeeSetupId = @lFeeSetupId)
					
					IF(@lPendingAmount > @lPaidAmount)
					BEGIN
						IF EXISTS(SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId = 2001 AND SourceId = @lAcademicId AND FeeSetupId = @lFeeSetupId)
						BEGIN
							-- Update Fee Allocation
							UPDATE sFee.tFeeAllocation SET DiscountAmount = DiscountAmount + @lPaidAmount, UpdatedUserId = @rCreatedUserId, UpdatedDateTime = sCommon.fGetDate()
							WHERE SourceTypeId = 2001 AND SourceId = @lAcademicId AND FeeSetupId = @lFeeSetupId
						END
						ELSE
						BEGIN
							-- Insert Fee Allocation
							INSERT INTO sFee.tFeeAllocation
							(
								SourceTypeId,
								SourceId,
								FeeSetupId,
								VariableAmount,
								DiscountAmount,
								AdditionalAmount,
								NotApplicableAmount,
								Remark,
								ReferenceTypeId,
								ReferenceSourceId,
								CreatedUserId,
								CreatedDateTime,
								UpdatedUserId,
								UpdatedDateTime
							)
							VALUES
							(
								2001,
								@lAcademicId,
								@lFeeSetupId,
								0,
								@lPaidAmount,
								NULL,
								NULL,
								'Old Year Paid Fee',
								NULL,
								NULL,
								@rCreatedUserId,
								sCommon.fGetDate(),
								NULL,
								NULL
							)
						END
					END
				END
		END
		 
		SET @lCount = @lCount - 1
	END
	 
	DROP TABLE #TempOldPaidFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
		DROP TABLE #TempOldPaidFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END
GO
PRINT N'Creating Procedure [sFee].[pOldPaidFeeToExceptionGet]...';


GO
CREATE PROCEDURE sFee.pOldPaidFeeToExceptionGet
	
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldFeeId int,
	@rNewFeeId int,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

	BEGIN TRY 

	DECLARE @lCount int
	
	-- Old Paid Fee Import Temp Table
	CREATE TABLE #TempOldPaidFeeImport
	(
		[AutoId] int identity,
		[StudentId] bigint NULL,
		[AcademicId] bigint NULL,
		[Code] nvarchar(20),
		[Name] nvarchar(300),
		[RollNo] int,
		[ClassDivision] nvarchar(300),
		[PaidAmount] decimal(12,2) NULL,
		[NewFeeAmount] decimal(12,2) NULL,
		[Status] nvarchar(max) NULL
	)
	-- End Paid Fee Import Temp Table
	
	INSERT INTO #TempOldPaidFeeImport 
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		SA.Code,
		SA.Name,
		SA.RollNo,
		ISNULL(SA.ClassName, '') + ' - ' + ISNULL(SA.DivisionName, '') AS ClassDivision,
		SUM(ISNULL(FA.DiscountAmount,0.00) + ISNULL(FA.NotApplicableAmount,0.00) + ISNULL(R.PaidAmount,0.00)) AS PaidAmount,
		0,
		''
	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
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
			WHERE 
				(FS1.IsOptional=0)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FM.Id=@rOldFeeId) OR (@rOldFeeId=0))
			
			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
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id
			WHERE
				(FS1.IsOptional=1)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))	
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FM.Id=@rOldFeeId) OR (@rOldFeeId=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 
				R.Id AS ReceiptId, ISNULL((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				
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((FM.Id=@rOldFeeId) OR (@rOldFeeId=0))
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId	 
	WHERE	
		SA.OrgId = @rOrgId 
		AND SA.BatchId=@rOldBatchId
		AND (ISNULL(FA.DiscountAmount,0.00) + ISNULL(FA.NotApplicableAmount,0.00) + ISNULL(R.PaidAmount,0.00)) > 0
	GROUP BY SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.RollNo,ISNULL(SA.ClassName, ''),ISNULL(SA.DivisionName, '')

	SELECT @lCount = COUNT(AutoId) FROM #TempOldPaidFeeImport
	
	BEGIN TRANSACTION
	
		WHILE (@lCount > 0)
		BEGIN
			DECLARE @lAcademicId bigint = NULL
			DECLARE @lStudentId bigint = NULL
			DECLARE @lClassId int = NULL
			DECLARE @lFeeSetupId int = NULL
			DECLARE @lPaidAmount decimal(12,2)
			DECLARE @lAdmissionCategoryId int

			SELECT @lStudentId = StudentId,@lPaidAmount=PaidAmount FROM #TempOldPaidFeeImport WHERE AutoId = @lCount
			SELECT @lAcademicId = Id, @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM  sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
			SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND BatchId=@rNewBatchId AND FeeId = @rNewFeeId
		
			IF (ISNULL(@lAcademicId,0) > 0 AND ISNULL(@lFeeSetupId, 0) > 0 AND ISNULL(@lClassId, 0) > 0)
			BEGIN
				IF OBJECT_ID('tempdb..#TempFeeSetup') IS NOT NULL DROP TABLE #TempFeeSetup

				SELECT
					FM.Id AS FeeId,
					FS.Id AS FeeSetupId,
					ISNULL(FS.IsOptional,0)AS IsOptional,
					ISNULL(FS.IsVariable,0)AS IsVariable,
					ISNULL(FS.Amount,0)AS Amount,
					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
				INTO #TempFeeSetup 
				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.Id = @lFeeSetupId
				AND FS1.BatchId = @rNewBatchId
					
				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=@lAcademicId) AND(FO.SourceTypeId=2001)
				WHERE FS1.BatchId = @rNewBatchId
				AND FS1.Id = @lFeeSetupId
				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=@lAcademicId) AND(FA.SourceTypeId=2001)
				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= @lAcademicId
					AND (R.SourceTypeId = 2001)
					AND R.IsObsolete = 0 
					AND R.BatchId = @rNewBatchId
					AND FeeSetupId = @lFeeSetupId
					GROUP BY FeeSetupId
				) R ON R.FeeSetupId = FS.Id	

				DECLARE @lCount1 int = 0
				SET @lCount1  = (SELECT COUNT(1) FROM #TempFeeSetup)

				IF(@lCount1 > 0)
				BEGIN
					DECLARE @lPendingAmount decimal(12,2) = 0
					SET @lPendingAmount = (SELECT PendingAmount FROM #TempFeeSetup WHERE FeeSetupId = @lFeeSetupId)
					
					DECLARE @lIsReceiptGenerated bit = 0
				
					SET @lIsReceiptGenerated = (
					SELECT 1 FROM 
					sFee.tReceipt R
					INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SA ON R.SourceId = SA.AcademicId AND SA.BatchId = @rNewBatchId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.BatchId = @rNewBatchId AND FS.FeeId = @rNewFeeId 
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
					WHERE (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(RD.Amount,0.00) = 0)
					AND R.SourceId = @lAcademicId
					)

					IF(@lPendingAmount < @lPaidAmount)
					BEGIN
						UPDATE #TempOldPaidFeeImport SET Status = 'Amount assigned in New Fee is less than Old Paid Fee', NewFeeAmount = @lPendingAmount WHERE AutoId = @lCount 
					END
					else if(@lIsReceiptGenerated = 1)
					begin
						UPDATE #TempOldPaidFeeImport SET Status = 'Receipt Generated or Fee Already Paid in New Batch', NewFeeAmount = @lPendingAmount WHERE AutoId = @lCount
					end
					else
					begin
						UPDATE #TempOldPaidFeeImport SET Status = '', NewFeeAmount = @lPendingAmount WHERE AutoId = @lCount
					end
				END
			END
			ELSE
			BEGIN
				UPDATE #TempOldPaidFeeImport SET Status = 'Fee Setup not assigned in New Batch', NewFeeAmount = 0 WHERE AutoId = @lCount
			END
			SET @lCount = @lCount - 1
		END
	 
	 SELECT * FROM #TempOldPaidFeeImport
	--DROP TABLE #TempOldPaidFeeImport
	SELECT 1 AS Result
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH 
		DROP TABLE #TempOldPaidFeeImport
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, ERROR_LINE(), ERROR_MESSAGE()
	END CATCH	
END
GO
PRINT N'Creating Procedure [sFee].[pPostDatedPaymentAdd]...';


GO
CREATE PROCEDURE sFee.pPostDatedPaymentAdd
	@rPostDatedPaymentXML  nvarchar(MAX),
	@rOrgId int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint,
	@rSourceId bigint,
	@rSourceTypeId int

AS
SET NOCOUNT ON
BEGIN

	DECLARE @lInterrorCode INT,@intDoc INT
	DECLARE @lNextNumber BIGINT			
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rPostDatedPaymentXML
	
	BEGIN TRY

	CREATE TABLE #tempTable  
	(
		AutoId bigint identity
		,Id	bigint
		,ReceiptBookId	int
		,PayTypeId	tinyint
		,PaymentClearanceDate	date
		,ChequeNo	nvarchar(40)
		,BankName	nvarchar(200)
		,Amount	decimal
		,Remark	nvarchar(200)
	)

	INSERT INTO #tempTable
	(
		Id
		,ReceiptBookId
		,PayTypeId
		,PaymentClearanceDate
		,ChequeNo
		,BankName
		,Amount
		,Remark
	)
	SELECT	
		A.Id
		,A.ReceiptBookId
		,A.PayTypeId
		,A.PaymentClearanceDate
		,A.ChequeNo
		,A.BankName
		,A.Amount
		,A.Remark
	FROM OPENXML (@intDoc, '/Table/PostDatedPayment', 1)
	WITH
	(
		Id	bigint					 '@Id'
		,ReceiptBookId	int			 '@ReceiptBookId'
		,PayTypeId	tinyint			 '@PayTypeId'
		,PaymentClearanceDate date   '@PaymentClearanceDate'
		,ChequeNo	nvarchar(40)	 '@ChequeNo'
		,BankName	nvarchar(200)	 '@BankName'
		,Amount	decimal				 '@Amount'
		,Remark	nvarchar(200)		 '@Remark'
	)A 

	SELECT * FROM #tempTable

	DECLARE @lCount int,@lId int
	SELECT @lCount = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId=AutoId FROM #tempTable
	
	WHILE @lId <= @lCount 
	BEGIN
		
		DECLARE @lId1 bigint = 0
		SELECT @lId1 = Id FROM #tempTable WHERE AutoId = @lId
		SELECT Id FROM #tempTable WHERE AutoId = @lId
		
		IF(@lId1 = 0)
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tPostDatePayment', 0, 1, 1,@outNextNumber = @lNextNumber output

			INSERT INTO sFee.tPostDatePayment
			(	
				Id
				,OrgId
				,BatchId
				,OrgGroupBatchId
				,SourceTypeId
				,SourceId
				,ReceiptBookId
				,PayTypeId
				,PaymentClearanceDate
				,ChequeNo
				,BankName
				,Amount
				,Remark
				,CreatedUserId
				,CreatedDateTime
				,StatusId
			)
			SELECT 
				@lNextNumber
				,@rOrgId
				,@rBatchId
				,@rOrgGroupBatchId
				,@rSourceTypeId
				,@rSourceId
				,TT.ReceiptBookId
				,TT.PayTypeId
				,TT.PaymentClearanceDate
				,TT.ChequeNo
				,TT.BankName
				,TT.Amount
				,TT.Remark
				,@rCreatedUserId
				,sCommon.fGetDate()
				,751
			FROM 
				#tempTable TT
			WHERE TT.AutoId = @lId

			SELECT @lNextNumber = MAX(Id) FROM sFee.tPostDatePayment Where OrgId=@rOrgId
			EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sFee.tPostDatePayment', @rCurrentNumber = @lNextNumber 
		END
		ELSE
		BEGIN
			SELECT 2
			DECLARE @lReceiptBookId	int = 0
			DECLARE @lPayTypeId	tinyint = 0
			DECLARE @lPaymentClearanceDate date = NULL
			DECLARE @lChequeNo nvarchar(40) = NULL
			DECLARE @lBankName nvarchar(200) = NULL
			DECLARE @lAmount	decimal = 0
			DECLARE @lRemark	nvarchar(200) = NULL
			
			SELECT @lReceiptBookId = ReceiptBookId
				,@lPayTypeId = PayTypeId
				,@lPaymentClearanceDate = PaymentClearanceDate
				,@lChequeNo = ChequeNo
				,@lBankName = BankName
				,@lAmount = Amount
				,@lRemark = Remark
			 FROM #tempTable WHERE Id = @lId1

			UPDATE sFee.tPostDatePayment
			SET 
				OrgId = @rOrgId
				,BatchId = @rBatchId
				,OrgGroupBatchId = @rOrgGroupBatchId
				,SourceTypeId = @rSourceTypeId
				,SourceId = @rSourceId
				,ReceiptBookId = @lReceiptBookId
				,PayTypeId = @lPayTypeId
				,PaymentClearanceDate = @lPaymentClearanceDate
				,ChequeNo = @lChequeNo
				,BankName = @lBankName
				,Amount = @lAmount
				,Remark = @lRemark
				,UpdatedUserId = @rCreatedUserId
				,UpdatedDateTime = sCommon.fGetDate()
			WHERE Id = @lId1
		END
		
		SET @lId=@lId+1
		
	END
	EXEC sp_xml_removedocument @intDoc
	SELECT 1 as Result
	DROP Table #tempTable
	END TRY	

	BEGIN CATCH 
	SELECT -1 AS Result,error_message() AS MSG, ERROR_LINE()
	END CATCH
END
GO
PRINT N'Creating Procedure [sFee].[pPostDatedPaymentDelete]...';


GO
CREATE PROCEDURE sFee.pPostDatedPaymentDelete
	@rId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	
			IF EXISTS (SELECT 1 FROM sFee.tPostDatePayment PDP INNER JOIN sFee.tReceipt R ON R.Id = PDP.ReceiptId WHERE PDP.Id = @rId)
			BEGIN
				SELECT -101 AS RESULT
			END
	
			ELSE
			BEGIN
				DELETE FROM sFee.tPostDatePayment
				WHERE Id=@rId

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


GO
CREATE PROCEDURE sFee.pPostDatedPaymentGet
	@rId bigint = 0,
	@rOrgGroupBatchId int=0,
	@rOrgId int = 0,
	@rBatchId int = 0,
	@rAdmissionCategoryId int = 0,
	@rIdNo nvarchar(20) = NULL,
	@rDepartmentId int = 0,
	@rClassId int = 0,
	@rDivisionId int = 0,
	@rReceiptBookId int = 0,
	@rCollectionGroupId int = 0,
	@rPayTypeId int = 0,
	@rStatusId int = 0,
	@rFirstName nvarchar(50) = NULL,
	@rFromReceiptNumber nvarchar(50) = NULL,
	@rToReceiptNumber nvarchar(50) = NULL,
	@rChequeNo nvarchar(50) = NULL,
	@rFromPaymentClearanceDate date = NULL,
	@rToPaymentClearanceDate date = NULL,
	@rOrgGroupId int = 0,
	@rSourceId bigint =0,
	@rSourceTypeId smallint = 0,
	@rUserId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 		
	BEGIN
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rChequeNo = sCommon.fSearchStringGet(@rChequeNo)  
	END

	SELECT DISTINCT 	 
		 PDP.Id
		,PDP.OrgId
		,ISNULL(OM.Title, '') AS Organization
		,PDP.BatchId
		,ISNULL(BM.Title, '') AS Batch
		,ISNULL(SA.Code, '') AS IdNo
		,ISNULL(SA.ClassName, '') + ' - ' + ISNULL(SA.DivisionName, '') AS ClassDivision
		,ISNULL(SA.Name, '') AS StudentName
		,PDP.OrgGroupBatchId
		,PDP.SourceTypeId
		,PDP.SourceId
		,ISNULL(PDP.ReceiptId, 0) AS ReceiptId
		,PDP.ReceiptBookId
		,PDP.PayTypeId
		,PDP.PaymentClearanceDate
		,PDP.ChequeNo
		,PDP.BankName
		,PDP.Amount AS ReceiptAmount
		,ISNULL(PDP.Remark, '') AS Remark
		,PDP.CreatedUserId
		,PDP.CreatedDateTime
		,PDP.UpdatedUserId
		,PDP.UpdatedDateTime
		,PDP.StatusId
		,ISNULL(R.ReceiptNumber, '') AS ReceiptNumber
		,ISNULL(RBM.Title, '') AS ReceiptBookTitle
		,ISNULL(R.ReceiptDate, '') AS ReceiptDate
		,ISNULL(PTM.Title, '') AS PayType
        ,ISNULL(SM.Title, '') AS StatusTitle
	FROM
		sFee.tPostDatePayment PDP
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = PDP.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = PDP.BatchId
		INNER JOIN [sStudent].[vStudentAcademic] SA ON SA.AcademicId = PDP.SourceId AND PDP.SourceTypeId = 2001
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PDP.PayTypeId
		INNER JOIN sFee.vUserReceiptBook RBM ON RBM.Id=PDP.ReceiptBookId AND RBM.UserId=@rUserId    
		--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = PDP.ReceiptBookId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id = PDP.StatusId
		LEFT JOIN sFee.tReceipt R ON R.Id = PDP.ReceiptId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = RBM.Id
	WHERE
		(PDP.Id = @rId OR @rId = 0)
		AND (PDP.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND (PDP.OrgId = @rOrgId OR @rOrgId = 0)
		AND (PDP.BatchId = @rBatchId OR @rBatchId = 0)
		AND (SA.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
		AND ((SA.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (SA.ClassId = @rClassId OR @rClassId = 0)
		AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
		AND (PDP.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		AND (CGM.Id = @rCollectionGroupId OR @rCollectionGroupId = 0)
		AND (PDP.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
		AND (PDP.StatusId = @rStatusId OR @rStatusId = 0)
		AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
		AND (PDP.ChequeNo like @rChequeNo OR ISNULL(@rChequeNo, '') = '')
		AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(ISNULL(@rFromReceiptNumber, 0) =0))    
		AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(ISNULL(@rToReceiptNumber,0)=0))   
		AND (PDP.PaymentClearanceDate >= @rFromPaymentClearanceDate OR ISNULL(@rFromPaymentClearanceDate, '') = '')
		AND (PDP.PaymentClearanceDate <= @rToPaymentClearanceDate OR ISNULL(@rToPaymentClearanceDate, '') = '')
		AND (PDP.SourceId = @rSourceId OR @rSourceId = 0)
		AND (PDP.SourceTypeId = @rSourceTypeId OR @rSourceTypeId = 0)
END
GO
PRINT N'Creating Procedure [sFee].[pRptPostDatedPaymentGet]...';


GO
CREATE PROCEDURE [sFee].[pRptPostDatedPaymentGet]
	--@rId bigint = 0,
	@rOrgGroupBatchId int = 0,
	@rOrgId int = 0,
	@rBatchId int = 0,
	--@rAdmissionCategoryId int = 0,
	--@rIdNo nvarchar(20) = NULL,
	--@rDepartmentId int = 0,
	--@rClassId int = 0,
	--@rDivisionId int = 0,
	--@rReceiptBookId int = 0,
	--@rCollectionGroupId int = 0,
	--@rPayTypeId int = 0,
	--@rStatusId int = 0,
	--@rFirstName nvarchar(50) = NULL,
	--@rFromReceiptNumber nvarchar(50) = NULL,
	--@rToReceiptNumber nvarchar(50) = NULL,
	--@rChequeNo nvarchar(50) = NULL,
	--@rFromPaymentClearanceDate date = NULL,
	--@rToPaymentClearanceDate date = NULL,
	--@rOrgGroupId int = 0,
	@rSourceId bigint =0,
	@rSourceTypeId smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 		
	--BEGIN
	--	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	--	SET @rChequeNo = sCommon.fSearchStringGet(@rChequeNo)  
	--END

	SELECT DISTINCT 	 
		 PDP.Id
		,PDP.OrgId
		,ISNULL(OM.Title, '') AS Organization
		,PDP.BatchId
		,ISNULL(BM.Title, '') AS Batch
		,ISNULL(SA.Code, '') AS IdNo
		,ISNULL(SA.ClassName, '') + ' - ' + ISNULL(SA.DivisionName, '') AS ClassDivision
		,ISNULL(SA.Name, '') AS StudentName
		,PDP.OrgGroupBatchId
		,PDP.SourceTypeId
		,PDP.SourceId
		,ISNULL(PDP.ReceiptId, 0) AS ReceiptId
		,PDP.ReceiptBookId
		,PDP.PayTypeId
		,PDP.PaymentClearanceDate
		,PDP.ChequeNo
		,PDP.BankName
		,PDP.Amount AS ReceiptAmount
		,ISNULL(PDP.Remark, '') AS Remark
		,PDP.CreatedUserId
		,PDP.CreatedDateTime
		,PDP.UpdatedUserId
		,PDP.UpdatedDateTime
		,PDP.StatusId
		,ISNULL(R.ReceiptNumber, '') AS ReceiptNumber
		,ISNULL(RBM.Title, '') AS ReceiptBookTitle
		,ISNULL(R.ReceiptDate, '') AS ReceiptDate
		,ISNULL(PTM.Title, '') AS PayType
        ,ISNULL(SM.Title, '') AS StatusTitle
		,CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId
		,RBM.ReceiptBookHeader
		,OM.OrgLogo
		,ISNULL(RBM.GroupTitle,'') AS GroupTitle
		,ISNULL(RBM.FullTitle,'') AS FullTitle
		,ISNULL(RBM.Address1,'') AS Address1
		,ISNULL(RBM.Address2,'') AS Address2
		,SA.RollNo
		,ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted

	FROM
		sFee.tPostDatePayment PDP
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = PDP.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = PDP.BatchId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = PDP.SourceId AND PDP.SourceTypeId = 2001
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PDP.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = PDP.ReceiptBookId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id = PDP.StatusId
		LEFT JOIN sFee.tReceipt R ON R.Id = PDP.ReceiptId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = RBM.Id
	WHERE
		--(PDP.Id = @rId OR @rId = 0)
		--(PDP.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		(PDP.OrgId = @rOrgId OR @rOrgId = 0)
		AND (PDP.BatchId = @rBatchId OR @rBatchId = 0)
		--AND (SA.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
		--AND ((SA.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))
		--AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		--AND (SA.ClassId = @rClassId OR @rClassId = 0)
		--AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
		--AND (PDP.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		--AND (CGM.Id = @rCollectionGroupId OR @rCollectionGroupId = 0)
		--AND (PDP.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
		--AND (PDP.StatusId = @rStatusId OR @rStatusId = 0)
		--AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
		--AND (PDP.ChequeNo like @rChequeNo OR ISNULL(@rChequeNo, '') = '')
		--AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(ISNULL(@rFromReceiptNumber, 0) =0))    
		--AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(ISNULL(@rToReceiptNumber,0)=0))   
		--AND (PDP.PaymentClearanceDate >= @rFromPaymentClearanceDate OR ISNULL(@rFromPaymentClearanceDate, '') = '')
		--AND (PDP.PaymentClearanceDate <= @rToPaymentClearanceDate OR ISNULL(@rToPaymentClearanceDate, '') = '')
		AND (PDP.SourceId = @rSourceId OR @rSourceId = 0)
		AND (PDP.SourceTypeId = @rSourceTypeId OR @rSourceTypeId = 0)
END
GO
PRINT N'Creating Procedure [sLibrary].[pRptSpineLabelGet]...';


GO
CREATE PROCEDURE [sLibrary].[pRptSpineLabelGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookSubjectText nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 @rBookSubjectDrop nvarchar(500)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
		
	BEGIN	  
		SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rBookSubjectText = sCommon.fSearchStringGet(@rBookSubjectText)
		SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
		SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
		SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
    END

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Code,
		BM.Title As BookTitle,
		BM.Publisher,BM.Supplier,
		BM.BookSubject,
		BM.Code AS BookCode,
		BM.BookLanguage,
		BM.BookCustomTag,
		BM.BookTag,
		BM.Location,
		BM.ISBNNumber,
		LM.ReportOrgTitle,
        LM.SmallAddress1,
        LM.SmallAddress2,
        CASE WHEN BM.BookDepartment is null THEN 'Blank'
            WHEN BM.BookDepartment='' THEN 'Blank'  ELSE BM.BookDepartment END AS  BookDepartment,
        BM.NoOfCopies,
        LM.Code AS LibraryCode,	       
        LM.Title AS LibraryTitle,
        BM.AccessionNo AS AccessionNo,
		BM.ClassificationNo
		
	FROM 
		sLibrary.tBookMaster BM
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))

		ORDER BY
		CASE WHEN BM.Code like '%[0-9]%' 
			THEN Replicate('0', 100 - Len(BM.Code)) + BM.Code
			ELSE BM.Code  END
		
	END
GO
PRINT N'Creating Procedure [sMis].[pRptResultAnalysisSubjectWiseWithAttendanceGet]...';


GO


CREATE PROCEDURE [sMis].[pRptResultAnalysisSubjectWiseWithAttendanceGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 	
		@rOrgGroupBatchId int,
		@rExamId int,
		@rOrgId int = 0,
		@rClassId int = 0,
		@rDivisionId int = 0,
		@rClassSubjectId int = 0

	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
 
 
 
		Select Distinct
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		OMGM.Id AS OrgMainGroupId,
		OMGM.Code AS OrgMainGroupName,
		OSGM.Id AS OrgSubGroupId,
		OSGM.Code AS SubGroupName,
		OM.Title AS OrgName,
		DM.Id AS DepartmentId,
		stum.OrgId,
		Stum.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		A.Id AS AcademicId,			
		CM.DisplayTitle AS Class,
		CM.Id As ClassId,
		DM.DisplayTitle AS Division,
		DM.Id AS DivisionId,
		ESGM.Title AS Exam,
		CS.Id AS SubjectId,	
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		BM.OrgGroupBatchId,
		RD.Obtain,
		[sAssessment].[fGetConfigGrade](stum.OrgId,RD.Obtain) AS SubjectGrade,
		R.Percentage,
		[sAssessment].[fGetConfigGrade](stum.OrgId,R.Percentage)AS ResultGrade,
		@rExamId AS ExamId,
		(CASE WHEN (SR.PresentDays<>0 AND SR.TotalDays<>0) THEN ROUND(((CAST(SR.PresentDays AS FLOAT)/CAST(SR.TotalDays AS FLOAT))*100),2) ELSE 0 END)AS Attendance,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		ISNULL(SR.TotalDays,0)AS TotalDays
		
		
		 from sStudent.tStudentMaster Stum 
		INNER JOIN  sStudent.tAcademic A ON Stum.Id=A.StudentId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		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 sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		--INNER JOIN sAssessment.tExamTypeMaster ETM ON ETM.Id=ESGM.ExamTypeId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
		INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
		INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId	
		INNER JOIN sSetup.tDepartmentMaster DeptM ON DeptM.Id=CM.DepartmentId
		LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId

		WHERE		
			EM.Id=@rExamId
			AND (OM.Id = @rOrgId OR @rOrgId = 0)
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND CM.Id = @rClassId
			AND (DM.Id = @rDivisionId OR @rDivisionId = 0)
			AND (CS.Id = @rClassSubjectId OR @rClassSubjectId = 0)

END
GO
PRINT N'Creating Procedure [sSecurity].[pForgotPasswordFailureLogGet]...';


GO
CREATE PROCEDURE [sSecurity].[pForgotPasswordFailureLogGet]
	 @rFromDate date='',
     @rToDate date='',
     @rOrgId int=0,
	 @rOrgGroupId smallint = 0,
	 @rOsTypeId smallint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT DISTINCT
		 FL.AutoId  AS FailureLogId
		,U.Id AS UserId
		,FL.UserName
		,FL.Code
		,FL.SourceId AS UserSourceId
		,FL.SourceTypeId AS UserSourceTypeId
		,CASE WHEN FL.SourceTypeId = 95 THEN 'Employee' 
			  WHEN FL.SourceTypeId = 2003 THEN 'Student' ELSE 'Other' END AS SourceType
		,FL.OrgId
		,FL.IsSendAlert
		,FL.IsResetPassword
		,FL.CreatedDateTime AS FailureLogDate
		,SC.Name AS Name
		,SC.ParentContactNo as MobileNo
		,SC.ParentEmail AS EmailId
		,SC.WhatsAppContactNo
		,OM.Title AS OrgName
        ,OST.Title AS OSTypeTitle
            
		FROM  [sSecurity].[tForgotPasswordFailureLog] FL
		INNER JOIN sSecurity.tUser U ON U.Id = FL.UserId
		INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = FL.SourceId AND SC.StudentId = U.sourceId AND U.SourceTypeId = 2003
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
		LEFT JOIN sAlert.tOSType OST ON OST.Id = FL.OSTypeId	
			
        WHERE ((FL.OrgId = @rOrgId) OR (@rOrgId=0))
		    AND (FL.CreatedDateTime >= @rFromDate OR  ISNULL(@rFromDate,'')='')
			AND (FL.CreatedDateTime < @rToDate OR ISNULL(@rToDate,'')='' ) 
			AND ((OST.Id=@rOsTypeId) OR (@rOsTypeId=0)) 
		
	UNION

	SELECT DISTINCT
		 FL.AutoId  AS FailureLogId
		,U.Id AS UserId
		,FL.UserName
		,FL.Code
		,FL.SourceId AS UserSourceId
		,FL.SourceTypeId AS UserSourceTypeId
		,CASE WHEN FL.SourceTypeId = 95 THEN 'Employee' 
			  WHEN FL.SourceTypeId = 2003 THEN 'Student'
			  ELSE 'Other' END AS SourceType
		,FL.OrgId
		,FL.IsSendAlert
		,FL.IsResetPassword
		,FL.CreatedDateTime AS FailureLogDate
		,EC.EmployeeName AS Name
		,EC.MobileNumber as MobileNo
		,EC.CompanyEmail AS EmailId
		,EC.WhatsAppContactNo
		,OM.Title AS OrgName
        ,OST.Title AS OSTypeTitle
		FROM  [sSecurity].[tForgotPasswordFailureLog] FL
		INNER JOIN sSecurity.tUser U ON U.Id = FL.UserId
		INNER JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId = FL.SourceId AND EC.EmployeeId = U.sourceId AND U.SourceTypeId = 95
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId
		LEFT JOIN sAlert.tOSType OST ON OST.Id = FL.OSTypeId	
			
        WHERE ((FL.OrgId = @rOrgId) OR (@rOrgId=0))
		    AND (FL.CreatedDateTime >= @rFromDate OR  ISNULL(@rFromDate,'')='')
			AND (CAST(FL.CreatedDateTime AS DATE) <= @rToDate OR ISNULL(@rToDate,'')='' ) 
			AND ((OST.Id=@rOsTypeId) OR (@rOsTypeId=0)) 	
END
GO
PRINT N'Creating Procedure [sSecurity].[pForgotPasswordFailureLogUpdate]...';


GO
CREATE PROCEDURE [sSecurity].[pForgotPasswordFailureLogUpdate]   
	@rFailureLogIds nvarchar(max),
	@rIsAlert bit
	
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rIsAlert = 1)
	BEGIN
		Update sSecurity.tForgotPasswordFailureLog SET IsSendAlert = 1 
		WHERE AutoId IN (SELECT cast(item AS NVARCHAR(MAX)) FROM  sCommon.fnsplit(@rFailureLogIds,','))
	END
END
GO

PRINT N'Altering Procedure [sFee].[pGSTReceiptAdd]...';


GO
ALTER PROCEDURE [sFee].[pGSTReceiptAdd]
	
	@rId bigint,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rReceiptNumber int,
	@rReceiptDate date,
	@rReceiptAmount decimal(12,2),
	@rTotalReceiptAmount decimal(12,2),
	@rDiscountAmount decimal(12,2),
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(40),
	@rBankName nvarchar(200),
	@rReceiptBookId int,
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rOrgId int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rRemark nvarchar(200),
	@rReceiptDetailXml [nvarchar](max),
	@rChequeDate date,
	@rCharge decimal(12,2)=0,
	@rFeeInvoiceId bigint = NULL,
	@rCollectionGroupId int = 0,
	@rPaymentTransactionId bigint = 0,
	@rIsDiscountCoupon bit = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lItemValue nvarchar(20) = ''
	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 1016 AND SourceId = @rOrgId WHERE CM.Id = 239

	-- GST
	DECLARE @lAmountAfterDiscount decimal(12,2) = NULL
	DECLARE @lCGSTPercentage decimal(12,2)  = NULL
	DECLARE @lSGSTPercentage decimal(12,2)  = NULL
	DECLARE @lCGSTAmount decimal(12,2)  = NULL
	DECLARE @lSGSTAmount decimal(12,2)  = NULL

	IF(@lItemValue='True' AND @rPayTypeId = 1)
	BEGIN 
		SET @lAmountAfterDiscount = 0
		SET @lCGSTAmount = 0
		SET @lSGSTAmount = 0
		SET @lCGSTPercentage = 0
		SET @lSGSTPercentage = 0
	END
	ELSE
	BEGIN 		
		SET @lAmountAfterDiscount = @rTotalReceiptAmount - @rDiscountAmount
		SELECT @lCGSTPercentage = CGSTPercentage,@lSGSTPercentage = SGSTPercentage FROM sFee.tReceiptBookMaster WHERE Id = @rReceiptBookId
		SET @lCGSTAmount = @rReceiptAmount*@lCGSTPercentage / 100
		SET @lSGSTAmount = @rReceiptAmount*@lSGSTPercentage / 100
		SET @rReceiptAmount = @lAmountAfterDiscount + @lCGSTAmount + @lSGSTAmount
	END
-- GST
	
	DECLARE @loDoc INT
	DECLARE @lIsCreated INT
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml

	BEGIN
	BEGIN TRY

	 SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId
	
	 DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 339 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	 IF @lConfigValue IS NULL 
		SET @lConfigValue = 'ReceiptBookWise'
	 
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
	END
	ELSE
	BEGIN
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId,@rPayTypeId,@lConfigValue)
		Print @rReceiptNumber
	END	

	EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rPayTypeId,@rPaymentTransactionId,@rIsCreated = @lIsCreated OUTPUT
 	IF(@lIsCreated = 1)
 		BEGIN
			SELECT -501 AS Result
			RETURN
		END
 
	 BEGIN TRANSACTION	
	 IF(@rId = 0)	
	 BEGIN

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


	 INSERT INTO sFee.tReceipt
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptNumber,
		   ReceiptDate,
		   ReceiptAmount,
		   TotalReceiptAmount,
		   DiscountAmount,
		   PayTypeId,
		   ChequeNo,
		   BankName,
		   ReceiptBookId,
		   Remark,
		   IsObsolete,
		   BatchId,
		   CreatedUserId,
		   CreatedDateTime,
		   OrgGroupBatchId,
		 ChequeDate,
		   FeeInvoiceId,
		   CollectionGroupId,
		   AmountAfterDiscount,
		   CGSTPercentage,
		   SGSTPercentage,
		   CGSTAmount,
		   SGSTAmount,
		   PaymentTransactionId,
		   IsDiscountCoupon  ---Added By Dhruv for Issue . 0011150
        )
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
		    @rReceiptNumber,
		    @rReceiptDate,
		    @rReceiptAmount,
		    @rTotalReceiptAmount,
		    @rDiscountAmount,
		    @rPayTypeId,
		    @rChequeNo,
		    @rBankName,
		    @rReceiptBookId,
		    @rRemark,
		    @rIsObsolete,
		    @rBatchId,
		    @rCreatedUserId,
		    sCommon.fGetDate(),
		    @rOrgGroupBatchId,
		    @rChequeDate,
		    @rFeeInvoiceId,
		    @rCollectionGroupId,
		    @lAmountAfterDiscount,
		    @lCGSTPercentage,
		    @lSGSTPercentage,
		    @lCGSTAmount,
		    @lSGSTAmount,
		    @rPaymentTransactionId,
			@rIsDiscountCoupon
		)
		
		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		
	    FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
		IF (@rCharge > 0)
		BEGIN
			EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
		END
	
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) FROM sFee.tReceiptBookMaster where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
		EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
		END

		SET @rId = @lNextNumber
	END 
	ELSE
	BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
		
		SELECT @rId AS RESULT
	END 
		
	-- For Mantis 0023321 By Foram on 14/03/2024 START
	DECLARE @lSourceId bigint, @lSourceTypeId1 smallint, @lBatchId int, @lOrgGroupBatchId int, @lReceiptBookId int, 
		    @lPayTypeId smallint, @lChequeNo nvarchar(40), @lBankName nvarchar(200), @lTotalReceiptAmount decimal(12,2)

	SELECT 
		@lSourceId = SourceId, 
		@lSourceTypeId1 = SourceTypeId, 
		@lBatchId = BatchId, 
		@lOrgGroupBatchId = OrgGroupBatchId, 
		@lReceiptBookId = ReceiptBookId, 
		@lPayTypeId = PayTypeId, 
		@lChequeNo = ChequeNo, 
		@lBankName = BankName, 
		@lTotalReceiptAmount = TotalReceiptAmount
	FROM sFee.tReceipt WHERE Id = @rId


	IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WHERE BatchId = @lBatchId AND OrgGroupBatchId = @lOrgGroupBatchId 
													AND SourceTypeId = @lSourceTypeId1 AND SourceId = @lSourceId AND ReceiptBookId = @lReceiptBookId 
													AND PayTypeId = @lPayTypeId AND ChequeNo = @lChequeNo AND BankName = @lBankName AND Amount = @lTotalReceiptAmount)
	BEGIN
		UPDATE sFee.tPostDatePayment 
		SET ReceiptId = @rId, StatusId = 752 
		WHERE BatchId = @lBatchId AND OrgGroupBatchId = @lOrgGroupBatchId 
			AND SourceTypeId = @lSourceTypeId1 AND SourceId = @lSourceId AND ReceiptBookId = @lReceiptBookId 
			AND PayTypeId = @lPayTypeId AND ChequeNo = @lChequeNo AND BankName = @lBankName AND Amount = @lTotalReceiptAmount
	END
	ELSE
	BEGIN
		UPDATE sFee.tPostDatePayment SET ReceiptId = 0, StatusId = 751 WHERE ReceiptId = @rId
	END
	-- For Mantis 0023321 By Foram on 14/03/2024 END
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptAdd]...';


GO
ALTER PROCEDURE [sFee].[pReceiptAdd]
	
	@rId bigint,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rReceiptNumber int,
	@rReceiptDate date,
	@rReceiptAmount decimal(12,2),
	@rTotalReceiptAmount decimal(12,2),
	@rDiscountAmount decimal(12,2),
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(40),
	@rBankName nvarchar(200),
	@rReceiptBookId int,
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rOrgId int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rRemark nvarchar(200),
	@rReceiptDetailXml [nvarchar](max),
	@rChequeDate date,
	@rCharge decimal(12,2)=0,
	@rFeeInvoiceId bigint = NULL,
	@rCollectionGroupId int = 0,
	@rDepositedLedgerId int = 0,
	@rPaymentTransactionId bigint = 0,
	@rReceiptPrintGroupId nvarchar(100),
	@rIsDiscountCoupon bit = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
DECLARE @lIsCreated INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml

BEGIN
	BEGIN TRY
	
	 SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId

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

	 IF @lConfigValue = ''
		SET @lConfigValue = 'ReceiptBookWise'

	IF @rChequeDate = '1900-01-01'
		SET @rChequeDate = NULL

	-- Mantis - 0030695
	 DECLARE @lConfigValue1 nvarchar(50)=''
	 SELECT @lConfigValue1 = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 543 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)
	-- Mantis - 0030695	 

	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@rId = 0)--ID Condition Added by dhruv for issue no.0013266	
		BEGIN
			IF(@lConfigValue='ReceiptBookWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			ELSE IF(@lConfigValue='PayTypeWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695
			IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ChequeNo=@rChequeNo)
				BEGIN
					SELECT -103 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695
		END
		ELSE
		BEGIN
			IF(@lConfigValue='ReceiptBookWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId AND Id != @rId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			ELSE IF(@lConfigValue='PayTypeWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId AND Id != @rId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695
			IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ChequeNo=@rChequeNo AND Id != @rId)
				BEGIN
					SELECT -103 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695
		END 
	END
	ELSE
	BEGIN
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId,@rPayTypeId,@lConfigValue)
	END	

	EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rPayTypeId,@rPaymentTransactionId,@rIsCreated = @lIsCreated OUTPUT -- Added ,@rPayTypeId,@rPaymentTransactionId for mantis 0031290 By Foram	

	IF(@lIsCreated = 1)
 		BEGIN
			SELECT -501 AS Result
			RETURN
		END
 
	 BEGIN TRANSACTION	
	IF(@rId = 0)	
	BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output
	
--IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
--			BEGIN
--				SELECT -102 AS Result
--				RETURN	
--			END

		--Added By Dhruv
			IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		--Added By Dhruv
		-- Mantis - 0030695
		IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ChequeNo=@rChequeNo)
			BEGIN
				SELECT -103 AS Result
				RETURN	
			END
		END
		-- Mantis - 0030695

	Declare @lSourceTypeId int 
	SET @lSourceTypeId =(select ISNULL(SourceTypeId,0) from sSecurity.tUser where Id = @rCreatedUserId)

	DECLARE @lCreatedUserId bigint
	IF(@lSourceTypeId = 2001 OR @lSourceTypeId = 2003 OR @rCreatedUserId = 3)
		SET @lCreatedUserId=(Select [sCommon].[fGetBigIntIdForOrg](4,LEFT(@rOrgGroupBatchId,4)))
	ELSE
		SET @lCreatedUserId = @rCreatedUserId 

		INSERT INTO sFee.tReceipt
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptNumber,
		   ReceiptDate,
		   ReceiptAmount,
		   TotalReceiptAmount,
		   DiscountAmount,
		   PayTypeId,
		   ChequeNo,
		   BankName,
		   ReceiptBookId,
		   Remark,
		   IsObsolete,
		   BatchId,
		   CreatedUserId,
		   CreatedDateTime,
		   OrgGroupBatchId,
		   ChequeDate,
		   FeeInvoiceId,
		   CollectionGroupId,
		   DepositedLedgerId,
		   PaymentTransactionId,
		   ReceiptPrintGroupId,
		   IsDiscountCoupon  ---Added By Dhruv for Issue . 0011150
        )
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
		    @rReceiptNumber,
		    @rReceiptDate,
		    @rReceiptAmount,
		    @rTotalReceiptAmount,
		    @rDiscountAmount,
		    @rPayTypeId,
		    @rChequeNo,
		    @rBankName,
		    @rReceiptBookId,
		    @rRemark,
		    @rIsObsolete,
		    @rBatchId,
		    @lCreatedUserId,
		    sCommon.fGetDate(),
		    @rOrgGroupBatchId,
		    @rChequeDate,
		    @rFeeInvoiceId,
		    @rCollectionGroupId,
		    @rDepositedLedgerId,
		    @rPaymentTransactionId,
			@rReceiptPrintGroupId,
			@rIsDiscountCoupon
		)
		
		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		
	FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		
		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
		IF (@rCharge > 0)
		BEGIN
		EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@lCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
	
		END
	
		
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) FROM sFee.tReceiptBookMaster where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
		EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@lCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
		END

		EXEC [sFee].[pFeeProcessGeneratePaidFeeAdd] @rOrgId,@rBatchId,@rSourceId,@lNextNumber,@lCreatedUserId
		
		SET @rId = @lNextNumber
	END 
	ELSE
	
	IF EXISTS(SELECT 1 FROM sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND Id = @rId)
	BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
		
	SELECT @rId AS RESULT
	END 
	ELSE
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		-- Mantis - 0030695
			IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ChequeNo=@rChequeNo AND Id != @rId)
				BEGIN
					SELECT -103 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695

		BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptNumber = @rReceiptNumber,
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
		
	SELECT @rId AS RESULT
	END 
	END
	
	-- For Mantis 0023321 By Foram on 14/03/2024 START
	DECLARE @lSourceId bigint, @lSourceTypeId1 smallint, @lBatchId int, @lOrgGroupBatchId int, @lReceiptBookId int, 
		    @lPayTypeId smallint, @lChequeNo nvarchar(40), @lBankName nvarchar(200), @lTotalReceiptAmount decimal(12,2)

	SELECT 
		@lSourceId = SourceId, 
		@lSourceTypeId1 = SourceTypeId, 
		@lBatchId = BatchId, 
		@lOrgGroupBatchId = OrgGroupBatchId, 
		@lReceiptBookId = ReceiptBookId, 
		@lPayTypeId = PayTypeId, 
		@lChequeNo = ChequeNo, 
		@lBankName = BankName, 
		@lTotalReceiptAmount = TotalReceiptAmount
	FROM sFee.tReceipt WHERE Id = @rId


	IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WHERE BatchId = @lBatchId AND OrgGroupBatchId = @lOrgGroupBatchId 
													AND SourceTypeId = @lSourceTypeId1 AND SourceId = @lSourceId AND ReceiptBookId = @lReceiptBookId 
													AND PayTypeId = @lPayTypeId AND ChequeNo = @lChequeNo AND BankName = @lBankName AND Amount = @lTotalReceiptAmount)
	BEGIN
		UPDATE sFee.tPostDatePayment 
		SET ReceiptId = @rId, StatusId = 752 
		WHERE BatchId = @lBatchId AND OrgGroupBatchId = @lOrgGroupBatchId 
			AND SourceTypeId = @lSourceTypeId1 AND SourceId = @lSourceId AND ReceiptBookId = @lReceiptBookId 
			AND PayTypeId = @lPayTypeId AND ChequeNo = @lChequeNo AND BankName = @lBankName AND Amount = @lTotalReceiptAmount
	END
	ELSE
	BEGIN
		UPDATE sFee.tPostDatePayment SET ReceiptId = 0, StatusId = 751 WHERE ReceiptId = @rId
	END
	-- For Mantis 0023321 By Foram on 14/03/2024 END

	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO

PRINT N'Update complete.';


GO


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

