

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


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


GO
ALTER TABLE [sFee].[tPostDatePayment]
    ADD [ReceiptDate] DATETIME NULL;


GO
PRINT N'Altering Table [sRecruitment].[tCandidateMaster]...';


GO
ALTER TABLE [sRecruitment].[tCandidateMaster]
    ADD [StatusId] SMALLINT NULL;


GO
PRINT N'Altering Table [sSecurity].[tOrgGroupMobileApp]...';


GO
ALTER TABLE [sSecurity].[tOrgGroupMobileApp]
    ADD [MigrationApiUrl] NVARCHAR (200) NULL;


GO
PRINT N'Altering View [sHrm].[vEmployeeCommonDetail]...';


GO

ALTER VIEW [sHrm].[vEmployeeCommonDetail]

AS
	 SELECT EM.OrgID,
	        EM.Id AS EmployeeId,
	        EM.Code,
	        ISNULL(EM.FirstName, '') AS FirstName,
			ISNULL(EM.MiddleName, '') AS MiddleName,
	        ISNULL(EM.LastName, '') AS LastName,
	        ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS  EmployeeName,	 
	        EM.StatusId AS EmployeeStatusId,		
	        EJD.DateOfleaving,				
			--EM.FirstName,
			--EM.MiddleName,
			--EM.LastName,			
			--EM.OrgID,
			--EPD.GenderId,
			--EPD.DateOfBirth,
			 EJD.DateOfJoining,
			--EM.StatusId,
			--EM.CreatedUserId,
			--EM.CreatedDateTime,
			--EM.UpdatedUserId,
			--EM.UpdatedDateTime,
			--EM.IsObsolete,
			ISNULL(EC.PhoneNoCompany,'') AS PhoneNoCompany,
			ISNULL(EC.CompanyEmail,'') AS CompanyEmail,
			ISNULL(EC.ExtensionNo,'') AS ExtensionNo,		 
			ISNULL(ODM.Id,0) AS DepartmentId,  
			--ISNULL(ODM.Title,'') AS DepartmentCode,  
			ISNULL(ODM.Title,'') AS DepartmentName,
		    ISNULL(EC.MobileNumber,'') AS MobileNumber,
		    0 AS EmployeeJobTitleId		    
		    ,ISNULL(EJD.EmployeeDesignationId,0) AS EmployeeDesignationId
			,ISNULL(EJD.OrganizationDepartmentId,0) AS OrganizationDepartmentId
			,ISNULL(EJD.EmployeeTypeId,0) AS EmployeeTypeId
			,ISNULL(EPD.BloodGroupId,0) AS BloodGroupId
			,ISNULL(BG.Title,'UNKNOWN') AS BloodGroup
			,ISNULL(EPD.GenderId,0) AS GenderId			 
			,EPD.DateOfBirth	 
		    ,MSM.Id AS MaritalStatusId
		    ,GM.Title As GenderTitle
		    ,MSM.Title As MaritialStatusTitle
			,EJD.EmployeeGroupId
		    ,EM.IsObsolete
		    ,ISNULL(EDM.Title,'') as EmployeeDesignation 
		    ,0 AS GradeNumber
		    ,ISNULL(EJD.EmployeeGradeId,0) AS EmployeeGradeId
		    ,EGM.Title AS EmployeeGrade
		    --,RM.Title As RelationshipTitle
		    --,RM.Id As RelationshipId
			--ISNULL(EDM.Id,0) AS DesignationId
			,ISNULL(EM.Number,0) As Number
			,ISNULL(EM.IsOtherUser,0) As IsOtherUser
			,ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo
		  
	    FROM 
			sHrm.tEmployeeMaster EM
	    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId AND EM.IsObsolete = 0 
	    INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id AND ODM.IsObsolete = 0					     
	    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId	  	     
	    LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.Id = EC.EmployeeId  
		LEFT JOIN sCommon.tBloodGroupMaster BG ON EPD.BloodGroupId = BG.Id AND BG.IsObsolete = 0			  
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EJD.EmployeeDesignationId  = EDM.Id AND EDM.IsObsolete = 0	
		LEFT JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id = EJD.EmployeeGradeId 
		LEFT JOIN sCommon.tGenderMaster  GM ON EPD.GenderId = GM.Id AND GM.IsObsolete = 0	
        LEFT JOIN sCommon.tMaritalStatusMaster MSM ON EPD.MaritalStatusId= MSM.Id AND MSM.IsObsolete = 0
GO

GO
PRINT N'Altering View [sStudent].[vStudentAutoSearch]...';


GO
  

ALTER VIEW [sStudent].[vStudentAutoSearch]  
AS  
	SELECT
		A.Id AS AcademicId,
		SM.FirstName +' '+SM.MiddleName +' '+SM.LastName+' '+ CM.DisplayTitle+' '+DM.DisplayTitle+' ['+SM.Code+']' AS StudentData,
		SM.FirstName +' '+SM.MiddleName +' '+SM.LastName+' '+ CM.DisplayTitle+' '+DM.DisplayTitle+' '+SM.Code+' '+ISNULL(SC.ParentContactNo,'') AS StudentDataWithMobile,
		A.OrgId,
		A.BatchId	
	FROM 
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id --AND SM.StatusId=1
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId
GO
PRINT N'Altering Function [sCommon].[f_GetCamelCase]...';


GO
ALTER FUNCTION [sCommon].[f_GetCamelCase] (@str AS NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
	WITH EXECUTE AS CALLER
AS
BEGIN
	DECLARE @finalresult NVARCHAR(MAX);

	IF (@str COLLATE SQL_Latin1_General_CP1_CI_AS LIKE '%[A-Za-z]%')
	BEGIN
		DECLARE @bitval BIT;
		DECLARE @result NVARCHAR(MAX);
		DECLARE @i INT;
		DECLARE @j CHAR(1);

		SELECT @bitval = 1
			,@i = 1
			,@result = '';

		WHILE (@i <= len(@str))
			SELECT @j = substring(@str, @i, 1)
				,@result = @result + CASE 
					WHEN @bitval = 1
						THEN UPPER(@j)
					ELSE LOWER(@j)
					END
				,@bitval = CASE 
					WHEN @j LIKE '[a-zA-Z]'
						THEN 0
					ELSE 1
					END
				,@i = @i + 1

		SET @finalresult = @result
	END
	ELSE
	BEGIN
		SET @finalresult = @str
	END

	RETURN @finalresult
END
GO
PRINT N'Creating Function [sFee].[fPaidFeeAmountReceiptBookwiseGet]...';


GO
CREATE FUNCTION [sFee].[fPaidFeeAmountReceiptBookwiseGet] (@rAcademicId bigint,@rReceiptBookId int)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rTotalPaidAmount decimal(12,0),@lClassId int, @lDivisionId int, @lAdmissionCategoryId int, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int
    SELECT @rOrgGroupBatchId=OrgGroupBatchId,@rOrgId=OrgId,@rBatchId=BatchId,@lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
    
    (
    SELECT 
		@rTotalPaidAmount = SUM(ISNULL(R.PaidAmount,0.00))
    FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=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
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.AcademicId = @rAcademicId
				AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (ISNULL(R.PaidAmount,0.00) > 0)
			)
			
	RETURN @rTotalPaidAmount
END
GO
PRINT N'Creating Function [sHrm].[fEmployeeNameGetL]...';


GO
CREATE FUNCTION [sHrm].[fEmployeeNameGetL](@rFirstName nvarchar(100),@rMiddleName nvarchar(100),@rLastName nvarchar(100),@rEmployeeNameFormatId tinyint)
RETURNS [nvarchar](300) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @rEmployeeName Nvarchar(300)
IF @rEmployeeNameFormatId = 1
SELECT @rEmployeeName = COALESCE(@rEmployeeName,'') + ISNULL(@rFirstName,'') +' ' + ISNULL(@rLastName,'')+ ',' 
ELSE IF @rEmployeeNameFormatId = 2
SELECT @rEmployeeName = COALESCE(@rEmployeeName,'') + ISNULL(@rFirstName,'') +' ' + ISNULL(@rMiddleName,'') +' ' + ISNULL(@rLastName,'')+ ',' 
ELSE IF @rEmployeeNameFormatId = 3
SELECT @rEmployeeName = COALESCE(@rEmployeeName,'') + ISNULL(@rLastName,'') +' ' + ISNULL(@rFirstName,'')+ ',' 
ELSE IF @rEmployeeNameFormatId = 4
SELECT @rEmployeeName = COALESCE(@rEmployeeName,'') + ISNULL(@rLastName,'') +' ' + ISNULL(@rFirstName,'') +' ' + ISNULL(@rMiddleName,'')+ ',' 
ELSE IF @rEmployeeNameFormatId = 5
SELECT @rEmployeeName = COALESCE(@rEmployeeName,'') + ISNULL(@rLastName,'')+ ',' 
ELSE
SELECT @rEmployeeName = COALESCE(@rEmployeeName,'') + ISNULL(@rFirstName,'') +' ' + ISNULL(@rLastName,'')+ ','    
RETURN @rEmployeeName
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,
	@rReceiptPrintGroupId nvarchar(100) = ''

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,@rReceiptBookId,@rIsCreated = @lIsCreated OUTPUT
 	
	IF(@lIsCreated = 1)
 	BEGIN
		SELECT -501 AS Result
		RETURN
	END
	
	IF(@lIsCreated = -1)	-- For Mantis 0032370 by Foram
 	BEGIN
		SELECT -502 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,
		   ReceiptPrintGroupId,
		   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,
			@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,@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, ReceiptDate = @rReceiptDate, 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 = CASE WHEN ISNULL(DepositedDate, '') <> '' THEN 753 ELSE 751 END 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].[pPostDatedPaymentGet]...';


GO
ALTER 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,
	@rStatusIds nvarchar(100) = ''

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
		,ISNULL(PDP.DepositedDate, '') AS DepositedDate
		,ISNULL(PDP.ReceiptDate, '') AS PDPReceiptDate	-- Added for mantis 0034852 by Foram
	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)
		AND (PDP.StatusId IN (SELECT item FROM sCommon.fnSplit(@rStatusIds,',')) OR ISNULL(@rStatusIds, '') = '')
END
GO
PRINT N'Altering Procedure [sFee].[pPostDatedPaymentUpdate]...';


GO
ALTER PROCEDURE sFee.pPostDatedPaymentUpdate 
	@rId BIGINT
	,@rDepositedDate DATETIME
	,@rStatusId SMALLINT
	,@rIsDepositeDate BIT	-- Added for mantis 0034852 by Foram
	,@rIsReceiptDate bit	-- Added for mantis 0034852	by Foram
	,@rReceiptDate datetime -- Added for mantis 0034852	by Foram

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRANSACTION
			IF(@rIsDepositeDate = 1)
			BEGIN
				IF(@rStatusId > 0)
				BEGIN
					UPDATE sFee.tPostDatePayment
					SET DepositedDate = @rDepositedDate
					,StatusId = @rStatusId
					WHERE Id = @rId
				END
				ELSE
				BEGIN
					UPDATE sFee.tPostDatePayment
					SET DepositedDate = @rDepositedDate
					WHERE Id = @rId
				END
			END
			IF(@rIsReceiptDate = 1) -- Added for mantis 0034852 by Foram
			BEGIN
				UPDATE sFee.tPostDatePayment
				SET ReceiptDate = @rReceiptDate
				WHERE Id = @rId
			END

			SELECT 1 AS RESULT

		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,@rReceiptBookId,@rIsCreated = @lIsCreated OUTPUT -- Added ,@rPayTypeId,@rPaymentTransactionId for mantis 0031290 By Foram	

	IF(@lIsCreated = 1)
 	BEGIN
		SELECT -501 AS Result
		RETURN
	END
	IF(@lIsCreated = -1)	-- For Mantis 0032370 by Foram
 	BEGIN
		SELECT -502 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, ReceiptDate = @rReceiptDate, 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 = CASE WHEN ISNULL(DepositedDate, '') <> '' THEN 753 ELSE 751 END 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].[pRptPostDatedPaymentGet]...';


GO
ALTER PROCEDURE [sFee].[pRptPostDatedPaymentGet]
	@rOrgGroupBatchId int = 0,
	@rOrgId int = 0,
	@rBatchId int = 0,
	@rSourceId bigint =0,
	@rSourceTypeId smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 		
	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.OrgId = @rOrgId OR @rOrgId = 0)
		AND (PDP.BatchId = @rBatchId OR @rBatchId = 0)
		AND (PDP.SourceId = @rSourceId OR @rSourceId = 0)
		AND (PDP.SourceTypeId = @rSourceTypeId OR @rSourceTypeId = 0)
END
GO
PRINT N'Altering Procedure [sRecruitment].[pCandidateMasterListGet]...';


GO
ALTER PROCEDURE [sRecruitment].[pCandidateMasterListGet]
(
		@rOrgGroupID smallint, 
		@rVacancyId int=0,		
		@rCandidateNumber int=0, 
		@rFirstName nvarchar(100), 
		@rLastName nvarchar(100),
		@rRecruitmentStatusId smallint ,
		@rFromDate date=null,
		@rToDate date=null,
		@rOrgId int = 0
		
	
 )
AS
SET NOCOUNT ON

BEGIN
 
 		--SET @rCandidateNumber = ISNULL( sCommon.fSearchStringGet(@rCandidateNumber),0)
		SET @rFirstname = ISNULL( sCommon.fSearchStringGet(@rFirstname),'')
		SET @rLastName = ISNULL( sCommon.fSearchStringGet(@rLastName),'')
		
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				--RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				--RSL.RecruitmentStatusId AS RecruitmentStatusId
				CM.RecruitmentStatusId,
				ISNULL(OM.Title,'') AS OrganizationTitle,
				ISNULL(CM.StatusId,207) AS StatusId		--Mantis: 34780, add by dhruvik
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			--LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId		
			--LEFT JOIN sRecruitment.tRecruitmentStatusLog  RSL  ON RSL.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			LEFT JOIN sSetup.tOrganizationMaster OM ON CM.OrgId = OM.Id			
		WHERE 
		--RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
		--		AND
				((CM.CandidateNumber=@rCandidateNumber ) OR (@rCandidateNumber = 0))
			AND ((CM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((CM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((VM.Id = @rVacancyId) OR (@rVacancyId = 0))	
			AND ((CM.RecruitmentStatusId = @rRecruitmentStatusId) OR (@rRecruitmentStatusId = 0))	
			AND CM.OrgGroupID = @rOrgGroupID
			AND ((CONVERT(date,CM.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,CM.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))   
			AND ((CM.OrgId = @rOrgId) OR (@rOrgId = 0))	
			ORDER BY CM.CandidateNumber
END
GO
PRINT N'Altering Procedure [sSecurity].[pOrgGroupMobileAppAdd]...';

GO
ALTER PROCEDURE [sSecurity].[pOrgGroupMobileAppAdd]
	 @rOrgGroupId int,
	 @rCode nvarchar(20), 
	 @rTitle nvarchar(100), 
	 @rApiUrl nvarchar(200), 
	 @rIsMobileSiteAccess bit,
	 @rIsStudentPortalAccess bit,
	 @rActivationDate date 	,
	 @rPackageName nvarchar(100),
	 @rSMSProviderId tinyint,
	 @rBundleId nvarchar(100),
	 @rLoginById smallint = 0,
	 @rMigrationApiUrl nvarchar(200) = '' -- For ERP – Add Mingration API URL in Mobile App Registration BY Foram

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF NOT EXISTS(SELECT 1 FROM sSecurity.tOrgGroupMobileApp WHERE OrgGroupId = @rOrgGroupId)
	BEGIN
		IF EXISTS(SELECT OrgGroupId FROM sSecurity.tOrgGroupMobileApp WHERE Code=@rCode)
		BEGIN
			SELECT -102 AS Result
		RETURN
		END 
		IF EXISTS(SELECT OrgGroupId FROM sSecurity.tOrgGroupMobileApp WHERE Title=@rTitle)
		BEGIN
			SELECT -103 AS Result
		RETURN
		END 
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT OrgGroupId FROM sSecurity.tOrgGroupMobileApp WHERE Code=@rCode AND OrgGroupId <> @rOrgGroupId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
		IF  EXISTS(SELECT OrgGroupId FROM sSecurity.tOrgGroupMobileApp WHERE Title=@rTitle  AND OrgGroupId <> @rOrgGroupId)
		BEGIN
			SELECT -103 AS Result
			RETURN
		END
	END
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 
	IF NOT EXISTS(SELECT 1 FROM sSecurity.tOrgGroupMobileApp Where OrgGroupId = @rOrgGroupId )
	BEGIN
		INSERT INTO sSecurity.tOrgGroupMobileApp
		(
			OrgGroupId,
			Code,
			Title,
			ApiUrl,
			IsMobileSiteAccess,
			IsStudentPortalAccess,
			ActivationDate,
			PackageName,
			SMSProviderId,
			BundleId,
			LoginById,
			MigrationApiUrl	-- For ERP – Add Mingration API URL in Mobile App Registration BY Foram
		)
		VALUES
		(
			@rOrgGroupId, 
			@rCode ,
			@rTitle ,
			@rApiUrl,
			@rIsMobileSiteAccess,
			@rIsStudentPortalAccess ,
			@rActivationDate,
			@rPackageName,
			@rSMSProviderId,
			@rBundleId,
			@rLoginById,
			@rMigrationApiUrl	-- For ERP – Add Mingration API URL in Mobile App Registration BY Foram
		)
		SELECT 1 AS Result
	END	 
	ELSE
	BEGIN
	    UPDATE sSecurity.tOrgGroupMobileApp
	    SET 
			--OrgGroupId,
			Code=@rCode,
			Title=@rTitle,
			ApiUrl=@rApiUrl,
			IsMobileSiteAccess=@rIsMobileSiteAccess,
			IsStudentPortalAccess=@rIsStudentPortalAccess,
			ActivationDate=@rActivationDate,
			PackageName = @rPackageName,
			SMSProviderId = @rSMSProviderId,
			BundleId = @rBundleId,
			LoginById = @rLoginById,
			MigrationApiUrl = @rMigrationApiUrl	-- For ERP – Add Mingration API URL in Mobile App Registration BY Foram
	    WHERE OrgGroupId = @rOrgGroupId
		
		SELECT 11 AS Result
	 END  	

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

ALTER PROCEDURE [sAcademic].[pLessonPlanGet]

	 @rId bigint=0,
	 @rClassId int=0,
	 @rSubjectId int=0,
	 @rDivisionId int=0,
	 @rIsCompleted bit=0,
	 @rBatchId int=0,
	 @rEmployeeId bigint=0,
	 @rDepartmentid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rCreatedUserId bigint=0,
	 @rStatus int = 0,
	 @rIsWithHeader bit=0,
	 --Addded by dhananjay mantis - 0035004
	 @rBuilder1 nvarchar(max) = '',
	 @rBuilder2 nvarchar(max)  = ''
	--Addded by dhananjay mantis - 0035004
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	IF(@rStatus = 0)
	BEGIN
	SELECT 
			LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			ISNULL(LP.IsCompleted,0) AS IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			--ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic,
			@rIsWithHeader AS IsWithHeader,
			(CASE WHEN @rIsWithHeader=1 THEN OI.CertificateHeaderA4 ELSE NULL END)AS MarksheetHeaderA4 ,
			ISNULL(LP.[Session] ,'') As [Session] ,
			ISNULL(LP.TrainingMethod,'') As TrainingMethod,
			ISNULL(LP.PeriodCount,0) As PeriodCount ,
			ISNULL(LP.Remark,'') As Remark,
			--Addded by dhananjay mantis - 0035004
			ISNULL(@rBuilder1,'') AS Builder1,
			ISNULL(@rBuilder2,'') AS Builder2 
			--Addded by dhananjay mantis - 0035004
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId   
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = CM.OrgId
			--sAcademic.tLessonPlan LP
			--INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
		((LP.BatchId = @rBatchId) OR (@rBatchId = 0))
		 AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))		
		AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		--AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
		--AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		--OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		--)
		--comment above condition because OR is wrong
		AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		AND (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		)
		--comment above condition due to mantisid - 0029580
		--AND ((LP.StartDate = @rFromDate OR ISNULL(@rFromDate,'')='' ))
		--AND ((LP.EndDate = @rToDate OR ISNULL(@rToDate,'')='' ))
		AND (LP.CreatedUserId=@rCreatedUserId OR ISNULL(@rCreatedUserId,'')='')
		AND ISNULL(EM.IsOtherUser,0) = 0
	ORDER BY
		LP.id 
	END
	ELSE
	BEGIN
	SELECT 
			LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			ISNULL(LP.IsCompleted,0) AS IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			--ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic,
			@rIsWithHeader AS IsWithHeader,
			(CASE WHEN @rIsWithHeader=1 THEN OI.CertificateHeaderA4 ELSE NULL END)AS MarksheetHeaderA4 ,
			ISNULL(LP.Session ,'') As [Session],
			ISNULL(LP.TrainingMethod,'') As TrainingMethod,
			ISNULL(LP.PeriodCount,0) As PeriodCount,
			ISNULL(LP.Remark,'') As Remark,
			--Addded by dhananjay mantis - 0035004
			ISNULL(@rBuilder1,'') AS Builder1,
			ISNULL(@rBuilder2,'') AS Builder2 
			--Addded by dhananjay mantis - 0035004
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId 
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = CM.OrgId  

			--sAcademic.tLessonPlan LP
			--INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			--INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			--INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			--AND vTSD.ClassId = TM.ClassId 
			--AND vTSD.SubjectId = TM.SubjectId 
			--AND vTSD.EmployeeId = LP.EmployeeId
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
		((LP.BatchId = @rBatchId) OR (@rBatchId = 0))
		 AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND ((@rStatus = 2) OR (LP.IsCompleted=@rIsCompleted))
		AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		--AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
	 --   AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		--OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		--)
		--comment above condition because OR is wrong
		AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		AND (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		)
		--comment above condition due to mantisid - 0029580
		--AND ((LP.StartDate = @rFromDate OR ISNULL(@rFromDate,'')='' ))
		--AND ((LP.EndDate = @rToDate OR ISNULL(@rToDate,'')='' ))
		AND (LP.CreatedUserId=@rCreatedUserId OR ISNULL(@rCreatedUserId,'')='')
		AND ISNULL(EM.IsOtherUser,0) = 0
	ORDER BY
		LP.id 
	END
END
GO
PRINT N'Altering Procedure [sAccounting].[pDashboardLedgerwiseClosingBalanceGet]...';


GO
ALTER Procedure [sAccounting].[pDashboardLedgerwiseClosingBalanceGet]
	@rOrgGroupId int,
	@rAccountYearTitle nvarchar(100)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
Declare @OpeningBalance decimal(25,5)
Declare @AccOpBalance decimal(25,5) = 0
Declare @ClosingBalance decimal(25,5)
Declare @TransactionBalance decimal(25,5)
Declare @LedgerId int 
Declare @lCount int
Declare @LedgerTypeId int,@lAccountYearId int,@lAccountId int
declare @lStartDate Date,	@lEndDate Date
	
	Declare @DecimalCount INT
	SELECT @DecimalCount = 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 = @rOrgGroupId WHERE CM.Id = 548

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

	CREATE TABLE #tempClosingBalance
 		(	
 		    Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(25,5),
 			Closing_Balance decimal(25,5),
 			Trasaction_Balance decimal(25,5) not null,
			AccountId int null,
			AccountingYearId int null
  		) 
	
	CREATE TABLE #tempLedger
 	    (
 	        Id INT IDENTITY (1, 1),
 			LedgerId int,
			LedgerName Nvarchar(100),
			AccountId int,
			AccountingYearId int,
 			AccOpBalance decimal(25,5),
 			LedgerTypeId int,
			StartDate DATE,
			EndDate DATE				 
 		) 

 	INSERT INTO #tempLedger
	SELECT LM.Id AS LedgerId ,LM.Title AS LedgerName ,AM.Id AS AccountId, LM.AccountingYearId, LM.OpeningBalance, LM.LedgerTypeId,AYM.FromDate,AYM.ToDate
	FROM sAccounting.tLedgerMaster LM
	INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id = LM.AccountingYearId
	INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
	WHERE LM.AccountingYearId IN (select Id from sAccounting.tAccountingYearMaster where Title = @rAccountYearTitle AND OrgGroupId = @rOrgGroupId AND IsLocked = 0) 
	AND AM.IsActive = 0 AND LM.IsObsolete = 0
	ORDER BY LM.Id Asc
	
	SELECT @lCount =  COUNT(Id) FROM #tempLedger
	
	WHILE (@lCount > 0)
	BEGIN
		SELECT @AccOpBalance =AccOpBalance,@LedgerTypeId= LedgerTypeId,@lAccountYearId=AccountingYearId,
		@lAccountId = AccountId, @lStartDate = StartDate, @lEndDate = EndDate, @LedgerId =LedgerId 
		FROM #tempLedger WHERE Id = @lCount

		INSERT INTO #tempClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Trasaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @lStartDate,@lEndDate,@rOrgGroupId,@lAccountYearId,@LedgerId,''
		
		UPDATE #tempClosingBalance SET AccountingYearId = @lAccountYearId, AccountId = @lAccountId WHERE  LedgerId = @LedgerId 

		SET @lCount = @lCount - 1
	END
	
	DECLARE  @columns NVARCHAR(MAX) = '', @sql     NVARCHAR(MAX) = '';	
	SET @columns =(SELECT STUFF(
    ( SELECT  distinct ',' +  QUOTENAME(title) FROM sAccounting.tLedgerMaster where OrgGroupId = @rOrgGroupId AND IsObsolete = 0
	FOR XML PATH('')), 1, 1, '') AS Ledgers)

	DECLARE  @columnsum NVARCHAR(MAX) = ''	
	SET @columnsum =(SELECT STUFF(
    (
        SELECT  distinct '+ ISNULL(' + QUOTENAME(Title) + ', 0) '
         FROM sAccounting.tLedgerMaster where OrgGroupId = @rOrgGroupId AND IsObsolete = 0
        FOR XML PATH('')
    ), 1, 1, '') AS Ledgers)
	
	DECLARE  @columnisnull NVARCHAR(MAX) = ''	
	SET @columnisnull =(SELECT STUFF(
    (
        SELECT  distinct ', [sAccounting].[fDecimalValueGet](ISNULL(' + QUOTENAME(Title) + ', 0), '+CAST(@DecimalCount AS NVARCHAR(20)) +') AS ' + QUOTENAME(Title)
         FROM sAccounting.tLedgerMaster where OrgGroupId = @rOrgGroupId AND IsObsolete = 0
        FOR XML PATH('')
    ), 1, 2, '') AS Ledgers)
	
	-- construct dynamic SQL
  SET @sql ='
  SELECT AccountId,Account, ' + @columnisnull + ', [sAccounting].[fDecimalValueGet]('+@columnsum + ','+CAST(@DecimalCount AS NVARCHAR(20))+') AS Total FROM ( 
  SELECT * FROM
  (
  SELECT  
		TCB.Closing_Balance AS Closing_Balance
		,AM.Title AS Account, AM.Id AS AccountId, LM.LedgerName
		FROM #tempClosingBalance TCB
		INNER JOIN #tempLedger LM ON LM.LedgerId=TCB.LedgerId AND TCB.AccountingYearId= LM.AccountingYearId AND TCB.AccountId = LM.AccountId
		INNER JOIN sAccounting.tAccountingYearMaster AY ON AY.Id = LM.AccountingYearId
		INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AY.AccountId
		where AM.IsActive = 0
		) AS Table1
  PIVOT(
    SUM(Closing_Balance)
    FOR LedgerName IN ('+ @columns +')
  ) AS pivot_table ) AS A';
  print @sql
  EXECUTE sp_executesql @sql;

	drop table #tempClosingBalance
	drop table #tempLedger
END
GO
PRINT N'Altering Procedure [sAccounting].[pTransactionBulkAdd]...';


GO
ALTER PROC [sAccounting].[pTransactionBulkAdd]
	@rXmlDoc nvarchar(MAX)		
	
AS
SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','&amp;')
DECLARE @lInterrorCode INT,
			@intDoc INT

DECLARE @lCount int = 0, @lResult bigint = 0
DECLARE @lOrgGroupId bigint = 0,
		@lAccountingYearId int = 0,
		@lVoucherDate date = '',
		@lNarration nvarchar(150) = '',
		@lVoucherNumber bigint = 0,
		@lVoucherType nvarchar(50) = '',
		@lVoucherTypeId tinyint = 0,		 
		@lCreatedUserId bigint = 0,
		@lCreatedDateTime datetime = '',
		@lAccountId int = 0,
		@lChequeNo nvarchar(20) = '',		
		@lChequeDate date = '',
		@lTransactionApproveId bigint = NULL,
		@lCreditAmount decimal(12,2) = 0,
		@lDebitAmount decimal(12,2) = 0,
		@lToLedger nvarchar(50) = '',
		@lByLedger nvarchar(50) = '',
		@lToLedgerId bigint = 0,
		@lByLedgerId bigint = 0

			
BEGIN TRY
BEGIN TRANSACTION												
	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	
	CREATE TABLE #tTable  
	(
		 Id bigint identity
		,OrgGroupId smallint null
		,[AccountingYearId] int not null
		,[VoucherDate] date null
		,[Narration] nvarchar(150) null
		,[VoucherNumber] bigint null
		,[VoucherType] nvarchar(50) null		 
		,[CreatedUserId] bigint not null		 		
		,[ChequeNo] nvarchar(20) null		 
		,[ChequeDate] date null
		,CreditAmount decimal(12,2) null
		,DebitAmount decimal(12,2) null
		,ToLedger nvarchar(50) null
		,ByLedger nvarchar(50) null	
		,AccountId int null
	)


	INSERT INTO #tTable
			   (			    
			   OrgGroupId
			   ,[AccountingYearId]
			   ,[VoucherDate]
			   ,[Narration]
			   ,[VoucherNumber]
			   ,[VoucherType]			    
			   ,[CreatedUserId]			   	   
			   ,[ChequeNo]			   
			   ,[ChequeDate]
			   ,CreditAmount
			   ,DebitAmount
			   ,ToLedger
			   ,ByLedger
			   ,AccountId			   
			   )
	SELECT		
		A.OrgGroupId,
		A.AccountingYearId,			
		A.VoucherDate,
		A.Narration,
		A.VoucherNumber,
		A.VoucherType,		 
		A.CreatedUserId,				
		A.ChequeNo,		
		A.ChequeDate,
		A.CreditAmount,
		A.DebitAmount,
		A.ToLedger,
		A.ByLedger,
		A.AccountId			
		
	FROM OPENXML (@intDoc, '/Table/VoucherEntryBulk', 1)
	WITH
	(						
		OrgGroupId smallint '@OrgGroupId',
		AccountingYearId int '@AccountingYearId',
		VoucherDate date '@VoucherDate',
		Narration NVARCHAR(150) '@Narration',		
		VoucherNumber bigint '@VoucherNo',
		VoucherType nvarchar(50) '@VoucherType',		 		
		CreatedUserId bigint '@CreatedUserId',		
		ChequeNo nvarchar(20) '@ChequeNo',		
		ChequeDate date '@ChequeDate',
		CreditAmount decimal(12,2) '@CreditAmount',
		DebitAmount decimal(12,2) '@DebitAmount',
		ToLedger nvarchar(50) '@ToLedger',
		ByLedger nvarchar(50) '@ByLedger',
		AccountId int '@AccountId'			
	)A 

	EXEC sp_xml_removedocument @intDoc
	
SELECT @lCount =  COUNT(Id) FROM #tTable
WHILE @lCount > 0 

BEGIN
	SELECT
	@lOrgGroupId = OrgGroupId,
	@lAccountingYearId = AccountingYearId,
	@lVoucherDate = VoucherDate,
	@lNarration = Narration,
	@lVoucherNumber = VoucherNumber,
	@lVoucherType = VoucherType,	 
	@lCreatedUserId = CreatedUserId,		
	@lChequeNo = ChequeNo,	
	@lChequeDate = ChequeDate,
	@lCreditAmount = CreditAmount,
	@lDebitAmount = DebitAmount,
	@lToLedger = ToLedger,
	@lByLedger = ByLedger,
	@lAccountId = AccountId	
	FROM #tTable WHERE Id = @lCount

	SELECT @lVoucherTypeId = Id FROM sAccounting.tVoucherTypeMaster WHERE Title = @lVoucherType
	SELECT @lToLedgerId = Id FROM sAccounting.tLedgerMaster WHERE Title = @lToLedger AND AccountingYearId = @lAccountingYearId  -- Added AccountingYearId for mantis 0035071 by Foram
	SELECT @lByLedgerId = Id FROM sAccounting.tLedgerMaster WHERE Title = @lByLedger AND AccountingYearId = @lAccountingYearId  -- Added AccountingYearId for mantis 0035071 by Foram
	
	IF(@lVoucherNumber = '' OR @lVoucherNumber is null)
	BEGIN
		SELECT @lVoucherNumber =  ISNULL(Max(VoucherNumber),0) + 1
		   FROM sAccounting.tTransaction
		  WHERE
		   (VoucherTypeId=@lVoucherTypeId OR @lVoucherTypeId=0)
			AND 	AccountingYearId  = @lAccountingYearId
	END 
	--print(@lVoucherNumber)

	EXEC sAccounting.pTransactionAdd 0,@lOrgGroupId,@lAccountingYearId,@lVoucherDate,@lNarration,@lVoucherNumber,@lVoucherTypeId,0,0,@lCreatedUserId,@lChequeNo,'',@lChequeDate,@lTransactionApproveId,@lResult OUTPUT 	
	IF(@lResult > 0)
	BEGIN			
		SET @lCreditAmount = -1*@lCreditAmount
		IF(@lVoucherTypeId != 2)
		BEGIN			
			exec sAccounting.pTransactionDetailAdd 0,@lResult,0,2,@lByLedgerId,@lDebitAmount,@lOrgGroupId
			exec sAccounting.pTransactionDetailAdd 0,@lResult,0,1,@lToLedgerId,@lCreditAmount,@lOrgGroupId
		END
		ELSE
		BEGIN		
			exec sAccounting.pTransactionDetailAdd 0,@lResult,0,2,@lToLedgerId,@lDebitAmount,@lOrgGroupId
			exec sAccounting.pTransactionDetailAdd 0,@lResult,0,1,@lByLedgerId,@lCreditAmount,@lOrgGroupId
		END
	END


	SET @lCount = @lCount - 1		
END

SELECT 1
	
	COMMIT TRANSACTION	

	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1
	END CATCH	
END
GO
PRINT N'Altering Procedure [sAdmission].[pGetDropDownLists]...';


GO
ALTER PROCEDURE  [sAdmission].[pGetDropDownLists]
	-- Add the parameters for the stored procedure here
	@rOrgId int =0,
	@rOrgGroupId int = 0,
	@rUserId bigint,
	@rBatchId int = 0,
	@rClassId int = 0,
	@rType int = 0
AS

	DECLARE @lGenderType nvarchar(20) = ''
	SELECT @lGenderType =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 557 AND SourceTypeId = 1016 AND SourceId = @rOrgId

if(@rType = 1)
BEGIN
	declare  @lStatusRes nvarchar(max)='', @lOrganizationRes nvarchar(max)='',@lStatusdropdown nvarchar(max)=''
	declare @lGenderdropdown nvarchar(max)='',@lReligiondropdown nvarchar(max)='',@lcastdropdown nvarchar(max)=''
	declare @lblooddropdown nvarchar(max)='', @lClassRes nvarchar(max)='', @lDivisionRes nvarchar(max)=''
	declare @lSavedReport nvarchar(max)='', @lclassdropdown2 nvarchar(max)='', @lAvailableRes nvarchar(max)=''
	declare @lReportList nvarchar(max)=''
	 
    -- Insert statements for procedure here

	
	select @lStatusRes = @lStatusRes + '<option value="207">Open</option>'
	select @lStatusRes = @lStatusRes + '<option value="208">Closed</option>'



	select @lOrganizationRes = @lOrganizationRes + '<option value="0"> -- ALL -- </option>'
	select @lOrganizationRes = @lOrganizationRes + '<option ' + case when Id = @rOrgId then 'selected="selected"' else '' end + ' value="' + convert(varchar,Id) + '">' + DisplayTitle + '</option>'
	from sSetup.vUserOrganization where IsObsolete = 0 AND OrgGroupId = isnull(@rOrgGroupId,0) and UserId = @rUserId
	order by OrderIndex


	select @lClassRes = @lClassRes + '<option value="0"> -- ALL -- </option>'
	
	
	select @lclassdropdown2 = @lclassdropdown2 + '<option value="' + convert( NVARCHAR,DivisionId) + '">' + convert( NVARCHAR,ClassName) + '</option>'
	from sSetup.vBatchClassDivision where IsObsolete = 0 and BatchId = 0 order by OrderIndex

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

	select @lGenderdropdown = @lGenderdropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
	from sCommon.tGenderMaster where IsObsolete = 0
													AND Id = CASE						-- Add Id condition MantisId : 0034447
													WHEN @lGenderType = 'Male' THEN 1
													WHEN @lGenderType = 'Female' THEN 2
													ELSE Id
													END

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

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

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

	select @lSavedReport = @lSavedReport + '<option value="0"> -- Select -- </option>'
					select @lSavedReport =  @lSavedReport + '<option value="' + convert(varchar,ACS.Id)+ '">' + ACS.Title + '</option>'
					from sAdmission.tAdmissionCustomSearch ACS
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ACS.OrgId AND OM.OrgGroupId = @rOrgGroupId
					LEFT JOIN sSecurity.tUser U ON U.Id=ACS.CreatedUserId 
					WHERE (ACS.CreatedUserId = @rUserId) OR (ACS.IsCommonUsers = 1) OR (ACS.IsCommonForOrg = 1)
	
			 --SELECT 
			 --ISNULL(DM.Id,0) AS DisplayFieldId
			--,ISNULL(DM.Name,'') AS Name
			 -- ,ISNULL(DM.FieldSource,'') AS FieldSource 
			--,(CASE WHEN DO.DisplayFieldId Is Null THEN 'False'  ELSE 'True' END) AS Selected 
			--,(CASE WHEN DO.IsFieldMandatory Is Null THEN 'False' WHEN DO.IsFieldMandatory = 1 THEN 'True' ELSE 'False' END) AS IsMandatory 
      
			--FROM sConfig.tDisplayFieldMaster DM
			-- LEFT JOIN sConfig.tDisplayFieldOrg DO ON DM.Id=DO.DisplayFieldId
				--AND DO.OrgId=@rOrgId
			--WHERE (DM.FieldSource=@rFieldSource) 
			SET @lAvailableRes = @lAvailableRes + '<option value="1">Organization</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="2">Batch</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="3">FormNo</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="4">StudentName</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="5">Class</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="6">Gender</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="7">BirthDate</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="8">Status</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="9">City</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="10">ContactNo</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="11">ContactEmail</option>'
		   select @lAvailableRes = @lAvailableRes + '<option value="' + Convert(varchar(max), ISNULL(DM.Id,0)) + '">' + Convert(varchar(max),ISNULL(DM.Name,'')) + '</option>'
				FROM sConfig.tDisplayFieldMaster DM				
				WHERE (DM.FieldSource='Admission Form' AND DM.Id NOT IN(312,316))
				
				--DECLARE @lAvailableAdmissionColumns nvarchar(max)=''
				--DECLARE @lAvailableAdmissionCustomRes nvarchar(max)=''
				--Declare @Title as nvarchar(max)
				--select @lAvailableAdmissionCustomRes = @lAvailableAdmissionCustomRes + '<option value="' + Convert(varchar(max), ISNULL(AC.Id,0)) + '">' + Convert(varchar(max),ISNULL(AC.FieldRemark,'')) + '</option>'
				--FROM sAdmission.tAdmissionCriteriaForm AC 
				--WHERE ((AC.ClassId= @rClassId) OR (AC.ClassId=0)) AND ((AC.BatchId= @rBatchId) OR (AC.BatchId=0))			
				

				--SET @lAvailableAdmissionColumns=   STUFF((SELECT ',' + QUOTENAME(AC.FieldRemark,'[]'), '' AS FieldRemark, '' AS SalaryMonth
						--from sAdmission.tAdmissionCriteriaForm AC WHERE ((AC.ClassId= @rClassId) OR (AC.ClassId=0)) AND ((AC.BatchId= @rBatchId) OR (AC.BatchId=0))
				--FOR XML PATH(''), TYPE
				--).value('.', 'NVARCHAR(MAX)') 
			--,1,1,'')
	        
		--DECLARE @lAdmissionCustomFields TABLE
		--(
		  --Title nvarchar(max)
		--)
		 --INSERT INTO  @lAdmissionCustomFields      
		--select Item AS Title from sCommon.fnSplit(@lAvailableAdmissionColumns , ',')
	        
		--select @lAvailableAdmissionCustomRes = @lAvailableAdmissionCustomRes +'<option class=StudentCustom value="|' + Title + '||">|' + Title + '||</option>'
		--from @lAdmissionCustomFields
		
		--print @lAvailableAdmissionCustomRes



			select @lReportList = @lReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + ACS.Title + '</td>
	<td style="width:670px; word-wrap:break-word;">' + ACS.ColumnName + '</td>
	<td style="width:80px; word-wrap:break-word;"><a onclick="ViewReport(' + convert(varchar(20),ACS.Id) + ');">View</a></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;text-align: center;"><a onclick="DeleteReport(' + convert(varchar,ACS.Id) + ');"><img src="../../Images/Del.png"></a></td></tr>'
	from sAdmission.tAdmissionCustomSearch ACS
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ACS.OrgId
	LEFT JOIN sSecurity.tUser U ON U.Id = ACS.CreatedUserId   
	WHERE ACS.CreatedUserId = @rUserId OR (ACS.IsCommonUsers = 1) OR (ACS.IsCommonForOrg = 1)


	select  @lClassRes as ClassRes, @lStatusRes as StatusRes,@lGenderdropdown As Gendercheckboxlist,@lReligiondropdown As Religionchklist,@lcastdropdown as castcategorychklist,
	@lblooddropdown AS bloodgrpchklist,@lOrganizationRes as OrganizationRes,@lSavedReport AS SavedReportList, @lclassdropdown2 AS classdivRes, @lAvailableRes AS AvailableRes,
	@lReportList as ReportList
END	


If(@rType = 2)
BEGIN			
declare @lBatchId int =0, @lBatchRes1 nvarchar(max)='', @lBatchdropdown nvarchar(max)='',  @lclassdropdown nvarchar(max)=''
declare  @lclassdivRes nvarchar(max)=''
		select @lBatchRes1 = @lBatchRes1 + '<option value="0"> -- ALL -- </option>'
		select @lBatchRes1 = @lBatchRes1 + '<option value="' + convert( NVARCHAR, Id) + '">' + Title + '</option>'
		from sSetup.tBatchMaster   WHERE OrgId = @rOrgId

		select @lclassdivRes = @lclassdivRes + '<option value="0"> -- ALL -- </option>'

		 
		select @lclassdropdown = @lclassdropdown + '<option value="' + convert( NVARCHAR,DivisionId) + '">' + convert( NVARCHAR,ClassName) + '</option>'
		from sSetup.vBatchClassDivision where IsObsolete = 0 and BatchId = @lBatchId order by OrderIndex

		select @lBatchRes1 as BatchRes, @lclassdivRes as classdivRes,  @lclassdropdown as ClassCheckBoxList
END

If(@rType = 3)
BEGIN
declare @lBatchId1 int =0 
select @rBatchId = Id from sSetup.tBatchMaster WHERE OrgId = @rOrgId   
declare	 @lBatchRes2 nvarchar(max)='', @lClassRes1 nvarchar(max)='', @lclassdropdown1 nvarchar(max)=''
	select @lClassRes1 = @lClassRes1 + '<option value="0"> -- ALL -- </option>'
	select @lClassRes1 = @lClassRes1	 + '<option value="' + convert(varchar,ClassId) + '">' + ClassName + '</option>'
	from sSetup.vBatchClass where IsObsolete = 0 and BatchId = @rBatchId  order by OrderIndex

	select @lclassdropdown1 = @lclassdropdown1 + '<option value="' + convert( NVARCHAR,ClassId) + '">' + convert( NVARCHAR,ClassName) + '</option>'
	from sSetup.vBatchClass where IsObsolete = 0 and BatchId = @rBatchId order by OrderIndex
	
	select @lClassRes1 as ClassRes, @lclassdropdown1 as ClassCheckBoxList
END

If(@rType = 4)
BEGIN
declare @lAvailableRes1 nvarchar(max)='', @lAvailableAdmissionCustomRes1 nvarchar(max)=''

	SET @lAvailableRes1 = @lAvailableRes1 + '<option value="1">Organization</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="2">Batch</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="3">FormNo</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="4">StudentName</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="5">Class</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="6">Gender</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="7">BirthDate</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="8">Status</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="9">City</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="10">ContactNo</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="11">ContactEmail</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="12">AdmissionFormDate</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="13">AdmissionHandledBy</option>'
			SET @lAvailableRes1 = @lAvailableRes1 + '<option value="14">AdmissionFormConvertedDate</option>'
			select @lAvailableRes1 = @lAvailableRes1 + '<option value="' + Convert(varchar(max), ISNULL(DM.Id,0)) + '">' + Convert(varchar(max),ISNULL(DM.Name,'')) + '</option>'
				FROM sConfig.tDisplayFieldMaster DM  		
				WHERE (DM.FieldSource='Admission Form' AND DM.Id NOT IN(312,316))

				--select Distinct AC.FieldRemark
				--FROM sAdmission.tAdmissionCriteriaForm AC
				--WHERE ((AC.BatchId= @rBatchId) OR (AC.BatchId=0)) --((AC.ClassId= @rClassId) OR (AC.ClassId=0)) AND 	
			
			DECLARE @lAvailableAdmissionColumns nvarchar(max)=''
			DECLARE @lAvailableAdmissionCustomRes nvarchar(max)=''
			--DECLARE @lAvailbleStudentColumns nvarchar(max)=''
			Declare @Title as nvarchar(max)


			SET @lAvailableAdmissionColumns=   STUFF((SELECT Distinct',' + QUOTENAME(AC.FieldRemark,'[]'), '' AS FieldTitle, '' AS SalaryMonth
						from sAdmission.tAdmissionCriteriaForm AC Where BatchId = @rBatchId
				FOR XML PATH(''), TYPE
				).value('.', 'NVARCHAR(MAX)') 
			,1,1,'')
	        print @lAvailableAdmissionColumns
		DECLARE @lStudentCustomFields TABLE
		(
		  Title nvarchar(max)
		)
		 INSERT INTO  @lStudentCustomFields      
		select Item AS Title from sCommon.fnSplit(@lAvailableAdmissionColumns , ',')
    
		select  @lAvailableAdmissionCustomRes = @lAvailableAdmissionCustomRes +'<option class=AdmissionCustom value="|' + Title + '||">|' + Title + '||</option>'
		from @lStudentCustomFields

		

		Select @lAvailableRes1 AS AvailableResCust1,@lAvailableAdmissionCustomRes1 as AvailableAdmissionCustomRes1,@lAvailableAdmissionCustomRes as AvailableAdmissionCustomResCust
END
If(@rType = 5)
BEGIN
declare @lAvailableResCust1 nvarchar(max)='', @lAvailableAdmissionCustomResCust1 nvarchar(max)=''

	SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="1">Organization</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="2">Batch</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="3">FormNo</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="4">StudentName</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="5">Class</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="6">Gender</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="7">BirthDate</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="8">Status</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="9">City</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="10">ContactNo</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="11">ContactEmail</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="12">AdmissionFormDate</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="13">AdmissionHandledBy</option>'
			SET @lAvailableResCust1 = @lAvailableResCust1 + '<option value="14">AdmissionFormConvertedDate</option>'
			select @lAvailableResCust1 = @lAvailableResCust1 + '<option value="' + Convert(varchar(max), ISNULL(DM.Id,0)) + '">' + Convert(varchar(max),ISNULL(DM.Name,'')) + '</option>'
				FROM sConfig.tDisplayFieldMaster DM				
				WHERE (DM.FieldSource='Admission Form' AND DM.Id NOT IN(312,316))

				--select Distinct AC.FieldRemark
				--FROM sAdmission.tAdmissionCriteriaForm AC
				--WHERE ((AC.BatchId= @rBatchId) OR (AC.BatchId=0)) --((AC.ClassId= @rClassId) OR (AC.ClassId=0)) AND 	
			
			DECLARE @lAvailableAdmissionColumnsCust nvarchar(max)=''
			DECLARE @lAvailableAdmissionCustomResCust nvarchar(max)=''
			--DECLARE @lAvailbleStudentColumns nvarchar(max)=''
			Declare @TitleCust as nvarchar(max)


			SET @lAvailableAdmissionColumnsCust= STUFF((SELECT Distinct ',' + QUOTENAME(AC.FieldRemark,'[]'), '' AS FieldTitleCust, '' AS SalaryMonthCust
						from sAdmission.tAdmissionCriteriaForm AC Where  ClassId = @rClassId
				FOR XML PATH(''), TYPE
				).value('.', 'NVARCHAR(MAX)') 
			,1,1,'')
			print(@rClassId)
	        print @lAvailableAdmissionColumnsCust
			print(1)
		DECLARE @lStudentCustomFieldsCust TABLE
		(
		  Title nvarchar(max)
		)
		 INSERT INTO  @lStudentCustomFieldsCust      
		select Item AS Title from sCommon.fnSplit(@lAvailableAdmissionColumnsCust , ',')
    
		select  @lAvailableAdmissionCustomResCust = @lAvailableAdmissionCustomResCust +'<option class=AdmissionCustom value="|' + Title + '||">|' + Title + '||</option>'
		from @lStudentCustomFieldsCust

		

		Select @lAvailableResCust1 AS AvailableResCust1,@lAvailableAdmissionCustomResCust as AvailableAdmissionCustomResCust
END
GO
PRINT N'Altering Procedure [sAlert].[pFeedbackGet]...';


GO

ALTER PROCEDURE [sAlert].[pFeedbackGet]
	  
        @rFeedbackId bigint=0,
        @rOrgId int,
	 	@rTemplate nvarchar(max),
		@rSubject nvarchar(100)=''
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
		 (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			 FirstName +' ' + MiddleName+' ' + LastName
			From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 FirstName +' ' + MiddleName+' ' + LastName
			   
			From sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 END) AS Name,
		 
		 (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			 Code
			From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 Code
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 END) AS Code,

		 (CASE AssignToSourceTypeId WHEN  95
		 THEN
			(Select 
			 EC.MobileNumber
			From sHrm.tEmployeeMaster EM
			Inner Join sHrm.vEmployeeCommunication EC ON EC.Id=EM.Id
			Where  EM.Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(EM.IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 AC.ParentContactNo 
			From sStudent.tAcademic A
			INNER JOIN sStudent.vStudentCommunication AC  ON A.Id=AC.AcademicId 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 END) AS MobileNo,

		 (CASE AssignToSourceTypeId WHEN  95
		 THEN
			(Select 
			 EC.CompanyEmail
			From sHrm.tEmployeeMaster EM
			Inner Join sHrm.vEmployeeCommunication EC ON EC.Id=EM.Id
			Where  EM.Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(EM.IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 AC.ParentEmail 
			From sStudent.tAcademic A
			INNER JOIN sStudent.vStudentCommunication AC  ON A.Id=AC.AcademicId 
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 END) AS EmailId,

		 (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			EC.WhatsAppContactNo
			From sHrm.tEmployeeMaster EM
			Inner Join sHrm.vEmployeeCommunication EC ON EC.Id=EM.Id
			Where  EM.Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(EM.IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			  AC.WhatsAppContactNo
			From sStudent.tAcademic A 
			INNER JOIN sStudent.vStudentCommunication AC  ON A.Id=AC.AcademicId 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 END) AS WhatsAppContactNo,

		replace(@rTemplate,'[Title]',F.Title) AS MsgText,
		@rSubject AS Subject,

		  (CASE AssignToSourceTypeId WHen  95
		 THEN
			(Select 
			 Id
			From sHrm.tEmployeeMaster Where  Id=FB.AssignToSourceId And FB.AssignToSourceTypeId=95 AND ISNULL(IsOtherUser,0) = 0 )
		 WHEN  2001
		 THEN
			(Select
			 A.Id
			From sStudent.tAcademic A
			INNER JOIN  sStudent.tStudentMaster SM ON SM.Id=A.StudentID
			Where A.Id=FB.AssignToSourceId ANd FB.AssignToSourceTypeId=2001)
		 END) AS SourceId,
		Isnull(AssignToSourceTypeId,0) AS ReceiverSourceTypeId,
		Isnull(AssignToSourceId,0)AS ReceiverSourceId,
		FeedbackId AS FeedbackId,
		ISNULL(OM.OrgGroupId,0) AS OrgGroupId,
		ISNULL(OM.Id,0) AS OrgId,
		Isnull(AssignToSourceTypeId,0) AS SourceTypeId
		
	from sCommunication.tFeedbackAssign FB
	INNER JOIN sCommunication.tFeedback F ON F.Id=FB.FeedbackId
	LEFT JOIN sStudent.tAcademic A ON FB.AssignToSourceId = A.Id AND FB.AssignToSourceTypeId = 2001		-- MantisId : 0034843
	LEFT JOIN sHrm.tEmployeeMaster EM ON FB.AssignToSourceId = EM.Id AND FB.AssignToSourceTypeId = 95	-- MantisId : 0034843
	INNER JOIN  sSetup.tOrgGroupBatchMaster OGM ON OGM.Id=F.OrgGroupBatchId
	--INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id =  OGM.OrgGroupId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.OrgGroupId 
	AND ((FB.AssignToSourceTypeId = 2001 AND OM.Id = A.OrgId) OR (FB.AssignToSourceTypeId = 95 AND OM.Id = EM.OrgId))	-- MantisId : 0034843
	Where  ((FB.FeedbackId=@rFeedbackId) OR (@rFeedbackId=0))
	--AND (OM.Id=@rOrgId OR @rOrgId=0)  -- Commented for Mantis 0029364 By Foram
	 
END
GO
PRINT N'Altering Procedure [sAlert].[pNotificationLogGet]...';


GO
ALTER PROCEDURE [sAlert].[pNotificationLogGet]

		@rOSTypeId tinyint,
		@rUserId bigint,
		@rUserSourceTypeId smallint,
		@rUserSourceId bigint,
		@rSyncedNotificationId bigint,
		@rFromDate Date='',
		@rToDate Date='',
		@rEventId int=0
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lAcademicId bigint
	DECLARE @lEmployeeId bigint
	DECLARE @lStudentId bigint
	DECLARE @lDivisionId int
	DECLARE @lClassId int
	DECLARE @lDepartmentId int
	DECLARE @lOrgId int
	
	IF(@rUserSourceTypeId=2003)
	BEGIN
		SELECT 
		@lAcademicId=AcademicId,
		@lStudentId=StudentId,
		@lDivisionId=DivisionId,
		@lClassId=ClassId,
		@lDepartmentId=DepartmentId,
		@lOrgId=OrgId
		FROM sStudent.vStudentAcademic WHERE StudentId = @rUserSourceId AND IsActiveBatch=1
	 
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName -- This changes done by parth as discussed with rajendrasir (Just added createdname)
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId NOT IN (14,15)
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND (NL.EventId = 14) AND (NL.SourceTypeId=2001 OR NL.SourceTypeId=2003 OR  NL.SourceTypeId=2005 OR NL.SourceTypeId=2016)
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 2
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId  AND (C.AssigneeId=2 OR C.AssigneeId=1) 
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2021
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		 
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 2
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId AND (C.AssigneeId=2 OR C.AssigneeId=1)
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2017
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )

		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			INNER JOIN sCommunication.tAssignmentScope AC ON AC.SourceTypeId = NL.SourceTypeId AND AC.SourceId = NL.SourceId AND AC.AssignmentId=NL.DocumentId
			INNER JOIN sCommunication.tAssignment A ON A.Id = AC.AssignmentId AND AC.AssignmentId=NL.DocumentId 
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 15 AND NL.SourceTypeId=2005
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
	END
		
	IF(@rUserSourceTypeId=95)
	BEGIN
	
		SELECT 
		@lEmployeeId=EmployeeId,
		@lDepartmentId=OrganizationDepartmentId,
		@lOrgId=OrgId
		FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId != 14
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND (NL.EventId = 14 AND NL.SourceTypeId=95)
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 3
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId  AND (C.AssigneeId=3 OR C.AssigneeId=1)
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2021
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )

		UNION ALL
		
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
				EM.Title as EventName,
				u.DisplayTitle as CreatedName
		FROM 
			sAlert.tNotificationLog NL
			Inner join [sSecurity].[tUser] u ON u.Id = NL.CreatedUserId
			INNER JOIN sCommunication.tCircularScope CS ON CS.SourceTypeId = NL.SourceTypeId AND CS.SourceId = NL.SourceId AND CS.CircularId=NL.DocumentId AND CS.AssigneeToId = 3
			INNER JOIN sCommunication.tCircular C ON C.Id = CS.CircularId AND CS.CircularId=NL.DocumentId AND (C.AssigneeId=3 OR C.AssigneeId=1)
			LEFT JOIN sAlert.tEventMaster EM ON EM.Id = NL.EventId
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND NL.Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
		AND ((NL.EventId = @rEventId) OR (@rEventId = 0))
		AND NL.EventId = 14 AND NL.SourceTypeId=2017
		AND (convert(date,NL.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (convert(date,NL.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='' )
		
	END
END
GO
PRINT N'Altering Procedure [sAlert].[pQueryStatusGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pQueryStatusGet]
	 	 
		 @rOrgId int,
	 	 @rQueryId bigint,	 	 
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rFromSourceTypeId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rFromSourceTypeId=2003)
		BEGIN
	
		 SELECT 
			QM.Id AS QueryId,
		    ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			replace (	
				replace (
				    replace (
				         replace(
						  replace(
									@rTemplate,'[Number]',QM.Number),
									'[Query Category]',QCM.Title),
								    '[Title]',QM.Title),
								    '[Name]',SC.Name) ,
								    '[Status]',(CASE WHEN QM.StatusId = 209 THEN 'Open' WHEN QM.StatusId = 210 THEN 'Closed' ELSE '' END))
								 
				            AS MsgText,
		     
		       @rSubject AS Subject,
			   2003 AS ReceiverSourceTypeId,
			   SC.StudentId AS ReceiverSourceId,
			   QM.OrgGroupId,
			   @rOrgId AS OrgId, 
			   2003 AS SourceTypeId,
			   SC.StudentId AS SourceId,
			   ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id = QM.QueryCategoryId
			INNER JOIN sStudent.vStudentCommunication SC ON QM.FromSourceId=SC.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId

	      WHERE
		    QM.Id = @rQueryId AND BM.IsActive=1 
		
		END
   
   IF(@rFromSourceTypeId=95)
		BEGIN
			SELECT 
			QM.Id AS QueryId,
		    ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		    ISNULL(EM.MobileNumber,'') AS MobileNo,
		   replace (	
				replace (
				    replace (
				         replace(
						  replace(
									@rTemplate,'[Number]',QM.Number),
									'[Query Category]',QCM.Title),
								    '[Title]',QM.Title),
								    '[Name]',EM.EmployeeName) ,
								    '[Status]',(CASE WHEN QM.StatusId = 209 THEN 'Open' WHEN QM.StatusId = 210 THEN 'Closed' ELSE '' END))
								 
				            AS MsgText,
		     
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId,
			 QM.OrgGroupId,
			 @rOrgId AS OrgId, 
			 95 AS SourceTypeId,
			 EM.EmployeeId AS SourceId,
			 ISNULL(EM.WhatsAppContactNo,'') AS WhatsAppContactNo 
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id = QM.QueryCategoryId
		
	      WHERE
		    QM.Id = @rQueryId 

		END
	--END
	
		
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricAbsentTimeGet]...';


GO
ALTER PROCEDURE [sAlert].[pStudentBiometricAbsentTimeGet]
	@rOrgId int,
	@rOrgGroupId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)='',
	@rIntervalTime int=0,
	@rToDateTime dateTime=null,
	@rFromDateTime DateTime=null,
	@rEventId int=136

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare  @lBatchID INT
			SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1
			
			--For Optimization
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=2001),0)		--Mantis: 34829, change 2003 => 2001 by dhruvik

			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			--For Optimization

			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL
				)

			insert #tShift
			Select 
				ShiftCode
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			--AND IsOutTimeAlertTime=1
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<cast([sCommon].[fGetDate]() as Time)
			--AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(DATEADD(MINUTE,-@rIntervalTime,[sCommon].[fGetDate]()) as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<cast(@rToDateTime as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(@rFromDateTime as Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL,
						CreatedDateTime [datetime] NOT NULL,--For Optimization
						AutoId bigint not null--For Optimization
					)

			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MIN(In_Out_Time),SourceTypeId,
				min(CDT.CreatedDateTime),min(CDT.Autoid) --For Optimization
				from [sBiometric].[tCloudTransactionData] CDT with (nolock) 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode 
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2001		--Mantis: 34829, change 2003 => 2001 by dhruvik
				-- For Optimization
				AND CDT.Autoid>@lCloudTransactionDataId
				AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=136 and SourceTypeId=2001 and cast(CreatedDateTime as date)=CONVERT(date,[sCommon].[fGetDate]()))		--Mantis: 34829, change 2003 => 2001 by dhruvik
				-- For Optimization
				Group by SourceId,SourceTypeId
			END

			-- For Optimization
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				'' as MsgText,
				@rSubject AS Subject,
				2001 AS ReceiverSourceTypeId,		--Mantis: 34829, change 2003 => 2001 by dhruvik
				SC.AcademicId AS ReceiverSourceId,		--Mantis: 34829, change SC.StudentId => SC.AcademicId by dhruvik
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2001 AS SourceTypeId,		--Mantis: 34829, change 2003 => 2001 by dhruvik
				SC.AcademicId AS SourceId,		--Mantis: 34829, change SC.StudentId => SC.AcademicId by dhruvik
				SC.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				@rEventId,
				@AlertUniqueId
			FROM 
				sStudent.vStudentCommunication SC 
				Inner Join  [sStudent].[tStudentMaster] SM on SM.Id=SC.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
				INNER JOIN #tShift tempshift ON tempshift.ShiftCode=SM.ShiftId
				LEFT JOIN #tTable temp ON  temp.SourceId=SC.AcademicId		--Mantis: 34829, change SC.StudentId => SC.AcademicId by dhruvik
				where 
					SC.OrgID =@rOrgId
					AND SC.IsActiveBatch=1
					AND SC.StatusId = 1
					AND temp.In_Out_Time is null
					AND ([sAttendance].[fWeekHOffGet](YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),SC.BatchId,SC.ClassId,SC.DivisionId, '',@rOrgId)<>'W')
					AND ([sAttendance].[fWeekHOffGet](YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),SC.BatchId,SC.ClassId,SC.DivisionId, '',@rOrgId)<>'H')
		
				select 
					MobileNo,	
					EmailId,
					replace (
					replace(@lSMSTemplete,'[StudentName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS SMSText,
					replace (
					replace(@lMailTemplete,'[StudentName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS MailText,
					replace (
					replace(@lNotificationTemplete,'[StudentName]',StudentName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS NotificationText,
					replace (
					replace(@lWhatsappTemplete,'[StudentName]',StudentName),					
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS WhatsappText,
					Subject,
					ReceiverSourceTypeId,
					ReceiverSourceId,
					StudentName,
					Code,
					WhatsAppContactNo,
					SourceTypeId,
					SourceId,
					OrgId,
					OrgGroupId,
					OrganizationTitle
				FROM  
					sBiometric.tTempBiometricAlertData
				where 
					AlertUniqueId=@AlertUniqueId
			--For Optimization

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricFirstInTimeGet]...';


GO
ALTER PROCEDURE [sAlert].[pStudentBiometricFirstInTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime,
	@rEventId int=129

	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare @lDateTimeNow datetime=[sCommon].[fGetDate]()
			declare @lLastStudentFirstInAlertSendTime datetime

			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=2003 AND CAST(CreatedDateTime as date)=CAST(@lDateTimeNow as date)),0)
			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 ),'')
		
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
				SourceId bigint NOT NULL,
				In_Out_Time [datetime] NOT NULL,
				SourceTypeId int NOT NULL,
				CreatedDateTime [datetime] NOT NULL,
				AutoId bigint not null,

			)
			insert into #tTable
			select CDT.SourceId,min(CDT.In_Out_Time),CDT.SourceTypeId,min(CDT.CreatedDateTime),min(CDT.Autoid)
			from [sBiometric].[tCloudTransactionData] CDT with (nolock) 
			inner join sBiometric.tShiftMasterCloud SMC ON SMC.ShiftCode=CDT.ShiftCode
			WHERE CDT.Attn_Dt=CONVERT(date,@lDateTimeNow)  AND CDT.SourceTypeId=2003
				AND (isnull(SMC.IsStopInTimeAlertTime,0)=0 OR (SMC.IsStopInTimeAlertTime=1 
				--AND CAST(SMC.StopInTimeAlertTime as Time)>=CAST(@rFromDateTime AS Time)
				AND  CAST(SMC.StopInTimeAlertTime as Time)>=CAST(CDT.In_Out_Time AS Time))
				
				)
				AND CDT.Autoid>@lCloudTransactionDataId
				AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=@rEventId and SourceTypeId=2003 AND cast(CreatedDateTime as date)=CONVERT(date,@lDateTimeNow))
			 Group by CDT.SourceId,CDT.SourceTypeId
	
			--select * from #tTable 
			print @lCloudTransactionDataId
			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				'' as MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.AcademicId AS ReceiverSourceId,		--Mantis: 34829, change SC.StudentId => SC.AcademicId by dhruvik
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.AcademicId AS SourceId,		--Mantis: 34829, change SC.StudentId => SC.AcademicId by dhruvik
				SC.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				@rEventId,
				@AlertUniqueId
			FROM 
				#tTable temp
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.AcademicId AND SC.IsActiveBatch=1		--Mantis: 34829, change SC.StudentId => SC.AcademicId by dhruvik
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				--temp.CreatedDateTime < @rToDateTime
				--AND temp.CreatedDateTime >= @rFromDateTime
				--AND 
				SC.OrgID =@rOrgId
				AND SC.StatusId = 1

			SELECT 
				MobileNo AS MobileNo,	
				EmailId AS EmailId,
				replace (
				replace (
				replace (
				replace(@lSMSTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS SMSText,
				 replace (
				replace (
				replace (
				replace(@lMailTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MailText,
				  replace (
				replace (
				replace (
				replace(@lNotificationTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS NotificationText,
				 replace (
				replace (
				replace (
				replace(@lWhatsappTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS WhatsappText,
				Subject AS Subject,
				2003 AS ReceiverSourceTypeId,
				ReceiverSourceId AS ReceiverSourceId,
				StudentName AS StudentName,
				Code AS Code,
				WhatsAppContactNo AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SourceId AS SourceId,
				OrgId,
				OrgGroupId,
				Time,
				OrganizationTitle
			FROM 
				sBiometric.tTempBiometricAlertData
			WHERE
			   AlertUniqueId=@AlertUniqueId


			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH

END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricLastOutTimeGet]...';


GO
ALTER PROCEDURE [sAlert].[pStudentBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int=0,
	@rToDateTime dateTime,
	@rFromDateTime DateTime
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare @lCloudTransactionDataId bigint=0
			set @lCloudTransactionDataId= isnull((select Max(isnull(CloudTransactionDataId,0)) From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=130 and SourceTypeId=2001),0)	   --Mantis: 34829, change 2003 => 2001 by dhruvik
			declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
			set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
			set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
			set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
			set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
			set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=130 AND OrgId=@rOrgId and AlertModeId = 1),'')
			

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
				SourceId bigint NOT NULL,
				In_Out_Time [datetime] NOT NULL,
				SourceTypeId int NOT NULL,
				OutTimeAlertTime time NOT NULL,
				CreatedDateTime [datetime] NOT NULL,
				LastOutAlertBasedOnId int NOT NULL,
				ShiftCode int NOT NULL,
				AutoId bigint not null,
			)
			
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,SMC.OutTimeAlertTime,Max(CreatedDateTime),SMC.LastOutAlertBasedOnId,CDT.ShiftCode,max(CDT.Autoid)
				from [sBiometric].[tCloudTransactionData] CDT with (nolock)  
				--inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				 INNER JOIN sBiometric.tShiftMasterCloud SMC on SMC.ShiftCode=CDT.ShiftCode
				where  Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())
					AND	((SMC.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
					AND SMC.IsOutTimeAlertTime=1
					AND CDT.SourceTypeId=2001		--Mantis: 34829, change 2003 => 2001 by dhruvik
					AND (
							(
								(LastOutAlertBasedOnId=1 OR (LastOutAlertBasedOnId=2  and CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time)<=cast(CDT.In_Out_Time as Time)
								AND CAST(OutTimeAlertTime AS Time) > CAST(CDT.In_Out_Time AS Time)))
								 AND CAST(OutTimeAlertTime AS Time)<cast(@rToDateTime as Time) 
								AND CAST(OutTimeAlertTime AS Time) > CAST(@rFromDateTime AS Time) 
							)
							OR
							(
							LastOutAlertBasedOnId=3 AND CAST(DATEADD(minute,-(GraceBefore),EndTime) AS Time)<=cast(CDT.In_Out_Time as Time)
							AND CAST(OutTimeAlertTime AS Time) > CAST(CDT.In_Out_Time AS Time)
							--AND CDT.Autoid>@lCloudTransactionDataId 
							AND CDT.SourceId not in (select ReceiverSourceId From sBiometric.tTempBiometricAlertData where  OrgID =@rOrgId and AlertId=130 and SourceTypeId=2001 and cast(CreatedDateTime as date)=CONVERT(date,[sCommon].[fGetDate]()))		--Mantis: 34829, change 2003 => 2001 by dhruvik
							)
						)
				Group by SourceId,SourceTypeId,SMC.OutTimeAlertTime,SMC.LastOutAlertBasedOnId,CDT.ShiftCode
				--select * from #tTable

			DECLARE @AlertUniqueId uniqueidentifier = NEWID();
			Insert Into sBiometric.tTempBiometricAlertData
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				'' as MsgText,
				@rSubject AS Subject,
				2001 AS ReceiverSourceTypeId,		--Mantis: 34829, change 2003 => 2001 by dhruvik
				SC.AcademicId AS ReceiverSourceId,		--Mantis: 34829, change SC.StudentId => SC.AcademicId by dhruvik
				SC.Name AS StudentName,
				SC.Code AS Code,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2001 AS SourceTypeId,		--Mantis: 34829, change 2003 => 2001 by dhruvik
				SC.AcademicId AS SourceId,		--Mantis: 34829, change SC.StudentId => SC.AcademicId by dhruvik
				SC.OrgId,
				OM.OrgGroupId,
				ISNULL(Convert(varchar,temp.In_Out_Time,108),'') as Time,
				OM.DisplayTitle AS OrganizationTitle,
				temp.AutoId,
				@rFromDateTime,
				@rToDateTime,
				sCommon.fGetDate(),
				130,
				@AlertUniqueId
			FROM 
				#tTable temp
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.AcademicId AND SC.IsActiveBatch=1		--Mantis: 34829, change SC.StudentId => SC.AcademicId by dhruvik
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				 
				SC.OrgID =@rOrgId
				AND SC.StatusId = 1



			SELECT 
				MobileNo AS MobileNo,	
				EmailId AS EmailId,
				replace (
				replace (
				replace (
				replace(@lSMSTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS SMSText,
				 replace (
				replace (
				replace (
				replace(@lMailTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MailText,
				  replace (
				replace (
				replace (
				replace(@lNotificationTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS NotificationText,
				 replace (
				replace (
				replace (
				replace(@lWhatsappTemplete,'[StudentName]',StudentName),
				'[TimeStamp]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS WhatsappText,
				Subject AS Subject,
				2001 AS ReceiverSourceTypeId,		--Mantis: 34829, change 2003 => 2001 by dhruvik
				ReceiverSourceId AS ReceiverSourceId,
				StudentName AS StudentName,
				Code AS Code,
				WhatsAppContactNo AS WhatsAppContactNo,
				2001 AS SourceTypeId,		--Mantis: 34829, change 2003 => 2001 by dhruvik
				SourceId AS SourceId,
				OrgId,
				OrgGroupId,
				 Time,
				 OrganizationTitle
			FROM 
				sBiometric.tTempBiometricAlertData
			WHERE
			   AlertUniqueId=@AlertUniqueId

			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricLateTimeGet]...';


GO
ALTER PROCEDURE [sAlert].[pStudentBiometricLateTimeGet]
	 	 
	 	 @rOrgId int,
		@rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)='',
		@rEventId int=137,
		@rShiftCode int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lDate date = ''
	SET @lDate = sCommon.fGetDate()

	DECLARE @lDay as nvarchar(3)
	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

	DECLARE @lColumnName varchar(10) = '',@lShiftColumntName varchar(10) = ''
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'
	SET @lShiftColumntName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_S'

	DECLARE @lGetConfigTime nvarchar(20) = ''
	SELECT @lGetConfigTime =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 399 AND SourceId = @rOrgId

	declare @lSMSTemplete nvarchar(max)='',@lMailTemplete nvarchar(max)='', @lWhatsappTemplete nvarchar(max)='',@lNotificationTemplete nvarchar(max)=''
	set @lMailTemplete=isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 and IsAutoSend=1),'')
	set @lSMSTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 2 and IsAutoSend=1),'')
	set @lNotificationTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 3 and IsAutoSend=1),'')
	set @lWhatsappTemplete =isnull((select isnull(Template,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 4 and IsAutoSend=1),'')
	set @rSubject=isnull((select isnull(MailSubject,'') from sAlert.tEventTemplate where EventId=@rEventId AND OrgId=@rOrgId and AlertModeId = 1 ),'')
	--IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime) > 0)
	--BEGIN
	DECLARE @Query NVARCHAR(MAX) = ''
	SET @Query ='SELECT
					SC.ParentContactNo AS MobileNo,	
					SC.ParentEmail AS EmailId,
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MsgText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lSMSTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS SMSText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lMailTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MailText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lNotificationTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS NotificationText,
					 replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@lWhatsappTemplete)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS WhatsappText,
					'''+CONVERT(nvarchar(20),@rSubject)+''' AS Subject,
					2001 AS ReceiverSourceTypeId,		--Mantis: 34829, change 2003 => 2001 by dhruvik
					AC.Id AS ReceiverSourceId,		--Mantis: 34829, change SC.StudentId => AC.Id by dhruvik
					sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId) AS StudentName,
					ISNULL(SC.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					2001 AS SourceTypeId,		--Mantis: 34829, change 2003 => 2001 by dhruvik
					AC.Id AS SourceId,		--Mantis: 34829, change SC.StudentId => AC.Id by dhruvik
					SM.OrgId,
					OM.OrgGroupId,
					SM.Id AS StudentId,
					SM.Code,
					sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId) AS  StudentName,
					 '+@lColumnName+' AS Time,
					OM.DisplayTitle AS OrganizationTitle	
		FROM 
				sStudent.tStudentMaster SM
				Inner join sStudent.tStudentCommunication SC ON SM.Id=SC.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgID = OM.Id
				INNER JOIN sStudent.tAcademic AC ON AC.StudentId = SM.Id		--Mantis: 34829, add INNER JOIN by dhruvik
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AC.BatchId		--Mantis: 34829, add INNER JOIN by dhruvik
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = AC.Id AND MT.SourceTypeId = 2003		--Mantis: 34829, change SM.Id => AC.Id by dhruvik
				INNER Join sBiometric.tShiftMasterCloud SMC ON SMC.ShiftName='+@lShiftColumntName+' And (SMC.ShiftCode='+CONVERT(nvarchar(20),@rShiftCode)+' OR '+CONVERT(nvarchar(20),@rShiftCode)+'=0)
		WHERE
				SM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MONTH(MT.Attn_dt) = MONTH('''+CONVERT(nvarchar(20),@lDate)+''')
				--AND '+@lColumnName+' > '''+@lGetConfigTime+'''
				AND '+@lColumnName+' > DATEADD(minute, SMC.GraceAfter,SMC.StartTime)
				AND SM.StatusId = 1
				--add for 29339 mantis
				AND YEAR(MT.Attn_dt) = YEAR('''+CONVERT(nvarchar(20),@lDate)+''')
				AND BM.IsActive = 1		--Mantis: 34829, add condition by dhruvik'
				
		print (@Query)
		execute (@Query)			
	--END

END
GO
PRINT N'Altering Procedure [sAlumni].[pRegistrationAdd]...';

GO


ALTER PROCEDURE [sAlumni].[pRegistrationAdd] 
		@rId bigint = 0, 
		@rFirstName nvarchar(100),
		@rMiddleName nvarchar(100),
		@rLastName nvarchar(100),
		@rGenderId tinyint,
		@rRegistrationDate date,
		@rEmailId nvarchar(150),
		@rMobileNo nvarchar(11),
		@rOrgId int,
		@rPassingBatchId int,
		@rPassingClassId int,
		@rMappedStudentId bigint=0,
		@rEmployeementTypeId int,
		@rEmployerName nvarchar(150),
		@rDesignation nvarchar(150),
		@rEmployeementCountry nvarchar(150),
		@rEmployeementState nvarchar(150),
		@rEmployeementCity nvarchar(150),
		@rSpecialAchievement nvarchar(500),
		@rUniversityName nvarchar(200),
		@rHigherStudyCountry nvarchar(150),
		@rHigherStudyState nvarchar(150),
		@rHigherStudyCity nvarchar(150),
		@rResidentialCountry nvarchar(150),
		@rResidentialState nvarchar(150),
		@rResidentialCity nvarchar(150),
		@rOfficePhone nvarchar(150),
		@rResidentialPhone nvarchar(150),
		@rCreatedUserId bigint=0  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION		
	DECLARE @lNextNumber BIGINT 
		
	IF(@rId = 0)	
	BEGIN		
		--If Exists(select Id from sAlumni.tRegistration where MobileNo = @rMobileNo AND EmailId = @rEmailId)		-- Comment for Mantis : 0034447	
		--	BEGIN
		--	select -103 as Result
		--	RETURN
		--END 
		If Exists(select Id from sAlumni.tRegistration where MobileNo = @rMobileNo)			-- Add for Mantis : 0034447	
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sAlumni.tRegistration where EmailId = @rEmailId)			-- Add for Mantis : 0034447	
			BEGIN
			select -102 as Result
			RETURN
		END 
	END
	 
	IF(@rId = 0)	
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAlumni.tRegistration', 0, 1, 1,@outNextNumber = @lNextNumber output
		Print @lNextNumber
		INSERT INTO sAlumni.tRegistration
		(
			Id,FirstName,MiddleName,LastName,GenderId,RegistrationDate ,EmailId,MobileNo,OrgId,PassingBatchId,
			PassingClassId,MappedStudentId,EmployeementTypeId,EmployerName,Designation,EmployeementCountry,
			EmployeementState,EmployeementCity,SpecialAchievement,UniversityName,HigherStudyCountry,HigherStudyState,
			HigherStudyCity,ResidentialCountry,ResidentialState,ResidentialCity,OfficePhone,ResidentialPhone,
			CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
		)
	    VALUES
		(
			@lNextNumber,@rFirstName,@rMiddleName,@rLastName,@rGenderId,@rRegistrationDate,@rEmailId,@rMobileNo,
			@rOrgId,@rPassingBatchId,@rPassingClassId,@rMappedStudentId,@rEmployeementTypeId,@rEmployerName,
			@rDesignation,@rEmployeementCountry,@rEmployeementState,@rEmployeementCity,@rSpecialAchievement,
			@rUniversityName,@rHigherStudyCountry,@rHigherStudyState,@rHigherStudyCity,@rResidentialCountry,
			@rResidentialState,	@rResidentialCity,@rOfficePhone,@rResidentialPhone,@rCreatedUserId,	sCommon.fGetDate() ,
			@rCreatedUserId,sCommon.fGetDate()
		)
	END
	ELSE
	BEGIN
		   UPDATE sAlumni.tRegistration
		   SET Id=@rId,FirstName=@rFirstName,MiddleName=@rMiddleName,LastName=@rLastName,GenderId=@rGenderId ,
		   RegistrationDate=@rRegistrationDate,EmailId=@rEmailId,MobileNo=@rMobileNo,OrgId=@rOrgId,
		   PassingBatchId=@rPassingBatchId,PassingClassId=@rPassingClassId,MappedStudentId=@rMappedStudentId,
		   EmployeementTypeId=@rEmployeementTypeId,EmployerName=@rEmployerName,Designation=@rDesignation,
		   EmployeementCountry=@rEmployeementCountry,EmployeementState=@rEmployeementState,
		   EmployeementCity=@rEmployeementCity,SpecialAchievement=@rSpecialAchievement,UniversityName=@rUniversityName,
		   HigherStudyCountry=@rHigherStudyCountry, HigherStudyState=@rHigherStudyState,HigherStudyCity=@rHigherStudyCity,
		   ResidentialCountry=@rResidentialCountry,ResidentialState=@rResidentialState,ResidentialCity=@rResidentialCity,
		   OfficePhone=@rOfficePhone,ResidentialPhone=@rResidentialPhone,CreatedUserId=@rCreatedUserId,
		   CreatedDateTime=sCommon.fGetDate(),UpdatedUserId=@rCreatedUserId,UpdatedDateTime=sCommon.fGetDate()
		   
	END
		
		
	    SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptBrightStudentAnalysisListGet]...';


GO
ALTER  PROCEDURE [sAssessment].[pRptBrightStudentAnalysisListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass NVARCHAR(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0,
	 @rDepartmentId int = 0,
	 @rFromRank int = 0,
	 @rToRank int = 0,
	 @rResultStatus nvarchar(20)=''  --Mantis - 34666

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT r1.*
FROM
(	SELECT 	
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			ROW_NUMBER() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END  ORDER BY R.Percentage DESC) rn,
			
			
			ESGM.Title AS Exam,
			SM.Code,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId )  AS Name,
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			R.TotalMarks,
			R.TotalObtain,
			R.ResultGrade,
			R.RankNumber,
			R.ResultStatus -- Add for mantis id : 0034777
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId=A.AcademicId
			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 A.DivisionId=DM.Id
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
	WHERE 
		    ((EM.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((ESGM.Id=@rExamSubGroupId ) OR (@rExamSubGroupId = 0))
			AND ((SM.Code=@rCode) OR (@rCode=''))
			AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
			AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))		
			AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
			AND ((Dept.Id = @rDepartmentId) OR (@rDepartmentId =0))
			AND ((R.RankNumber>= @rFromRank) OR (@rFromRank=0))
			AND ((R.RankNumber<= @rToRank) OR (@rToRank=0))
			AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))	  --Mantis - 34666
	)r1
	WHERE ((r1.rn <= @rTop) Or (@rTop = 0))
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptWeekStudentAnalysisListGet]...';


GO
ALTER  PROCEDURE [sAssessment].[pRptWeekStudentAnalysisListGet]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 --@rGrade nvarchar(20)='',
	 --@rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0,
	 @rDepartmentId int = 0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rResultStatus nvarchar(20)=''  --Mantis - 34666

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

SELECT r1.* from 
(
	SELECT 
	 
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
		 
			ROW_NUMBER() OVER(PARTITION BY 
							CASE WHEN @rGroupId=1 THEN DM.Id 
							WHEN @rGroupId=2 THEN CM.Id 
							WHEN @rGroupId =3 THEN Dept.Id 
							WHEn @rGroupId =4 THEN OM.Id END  
					 ORDER BY R.Percentage ASC) rn,
			
			ESGM.Title AS Exam,
			SM.Code,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId )  AS Name,
			
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			R.TotalMarks,
			R.TotalObtain,
			R.ResultGrade,
			R.ResultStatus   --Mantis - 34666
			  
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId=A.AcademicId
			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 A.DivisionId=DM.Id
			  INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		AND ((Dept.Id = @rDepartmentId) OR (@rDepartmentId =0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank = 0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank = 0))
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))  --Mantis - 34666
		) r1
		
	WHERE ( r1.rn <= @rTop Or @rTop = 0)
END
GO
PRINT N'Altering Procedure [sAttendance].[pAttendanceSummaryDashboard]...';


GO

ALTER  PROCEDURE [sAttendance].[pAttendanceSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rAttendanceDate date ='',
	@rClassId int=0,
	@rDepartmentId int =0,
	@rDivisionId int=0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'AttendanceList')
		BEGIN
			SELECT COUNT(SR.AcademicId)
					,ISNULL((SELECT COUNT(SR.AcademicId)
						FROM sStudent.tAcademic A 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId	 
							 AND SR.AttendanceDate = @rAttendanceDate WHERE SR.IsPresent=1 AND ((A.OrgId=@rOrgId)OR(@rOrgId=0))
							 AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS PresentCount,
					ISNULL((SELECT COUNT(SR.AcademicId)
					FROM sStudent.tAcademic A 
						INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id AND SR.AttendanceDate = @rAttendanceDate
						INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId	 
						  WHERE SR.IsPresent=0 AND  ((CM.Id =@rClassId)OR(@rClassId=0)) AND ((A.OrgId=@rOrgId)OR(@rOrgId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0)) ),0) AS AbsentCount,
				ISNULL((SELECT COUNT(SLR.AcademicId)			-- Changed SR.AcademicId to SLR.AcademicId For MantisId : 0035067
				FROM  sStudent.tAcademic A 
				INNER JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=A.Id  AND SLR.LeaveFromDate = @rAttendanceDate AND  SLR.LeaveToDate = @rAttendanceDate
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId	 
				WHERE ((CM.Id =@rClassId)OR(@rClassId=0)) AND ((A.OrgId=@rOrgId)OR(@rOrgId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS LeaveCount
				FROM sStudent.tAcademic A 
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id  AND SR.AttendanceDate = @rAttendanceDate
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
			WHERE ((A.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
		END
	ELSE IF(@rType = 'ClassWiseAttendance')
		BEGIN 
			SELECT CM.Id,CM.Title,ISNULL(T.PresentCount,0) AS PresentCount ,ISNULL(T1.AbsentCount,0) As AbsentCount,CM.OrderIndex
				FROM sSetup.tClassMaster CM
						LEFT JOIN sStudent.tAcademic A ON CM.Id = A.ClassId	
						LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id  AND SR.AttendanceDate = @rAttendanceDate
						LEFT JOIN 
							(SELECT COUNT(A.Id) AS PresentCount,A.ClassId FROM sStudent.tAcademic A 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
							WHERE SR.IsPresent=1 AND  AttendanceDate = @rAttendanceDate
							GROUP BY A.ClassId 
						)T ON T.ClassId = A.ClassId
						
						LEFT JOIN 
							(SELECT COUNT(A.Id) AS AbsentCount,A.ClassId FROM sStudent.tAcademic A 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
							WHERE SR.IsPresent=0 AND  AttendanceDate = @rAttendanceDate
							GROUP BY A.ClassId 
						)T1 ON T1.ClassId = A.ClassId 
						--AND T.ClassId = T1.ClassId
			WHERE ((CM.OrgId=@rOrgId)OR (@rOrgId=0))
			AND ((CM.Id =@rClassId)OR(@rClassId=0))
			AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
				GROUP BY CM.Title, CM.Id,T.PresentCount,T1.AbsentCount,CM.OrderIndex
				ORDER BY CM.OrderIndex
		END
	
	ELSE
		BEGIN
		--create temp table for 29257 mantis
			CREATE TABLE #tempPresentAbsentCount
					(PresentCount int,
					AbsentCount int,
					ClassId int,
					DivisionId int
					)

			INSERT INTO #tempPresentAbsentCount
					(PresentCount,
					AbsentCount,
					ClassId,
					DivisionId
					)
			SELECT COUNT(CASE WHEN SR.IsPresent=1 THEN 1 END),
					COUNT(CASE WHEN SR.IsPresent=0 THEN 1 END),
					A.ClassId,
					A.DivisionId
			FROM sStudent.tAcademic A
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id AND DM.Id = A.DivisionId
			WHERE AttendanceDate = @rAttendanceDate
			GROUP BY A.ClassId,A.DivisionId

			SELECT CM.Id,(CM.Title +' - '+ DM.Title) AS  Title ,ISNULL(T.PresentCount,0) AS PresentCount ,ISNULL(T.AbsentCount,0) As AbsentCount,DM.OrderIndex
			FROM sSetup.tClassMaster CM
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id
				LEFT JOIN sStudent.tAcademic A  ON CM.Id = A.ClassId AND DM.Id = A.DivisionId
				LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id  AND SR.AttendanceDate = @rAttendanceDate
				--comment for 29257 mantis and also add new left join for temp table, it will done for query time optimization
				--LEFT JOIN
				--	(SELECT COUNT(A.Id) AS PresentCount,A.ClassId,A.DivisionId FROM sStudent.tAcademic A
				--	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
				--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				--	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id AND DM.Id = A.DivisionId
				--	WHERE SR.IsPresent=1 AND  AttendanceDate = @rAttendanceDate
				--	GROUP BY A.ClassId,A.DivisionId
				--)T ON T.ClassId = A.ClassId AND T.DivisionId = A.DivisionId

				--LEFT JOIN
				--	(SELECT COUNT(A.Id) AS AbsentCount,A.ClassId,A.DivisionId FROM sStudent.tAcademic A
				--	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
				--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				--	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id AND DM.Id = A.DivisionId
				--	WHERE SR.IsPresent=0 AND  AttendanceDate = @rAttendanceDate
				--	GROUP BY A.ClassId,A.DivisionId
				--)T1 ON T1.ClassId = A.ClassId AND T1.DivisionId = A.DivisionId
				----AND T.ClassId = T1.ClassId
				LEFT JOIN #tempPresentAbsentCount T ON T.ClassId = A.ClassId AND T.DivisionId = A.DivisionId
			WHERE ((CM.OrgId=@rOrgId)OR (@rOrgId=0))
				AND ((CM.Id =@rClassId)OR(@rClassId=0))
				AND ((DM.Id =@rDivisionId)OR(@rDivisionId=0))
				AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
			GROUP BY CM.Title, CM.Id,T.PresentCount,T.AbsentCount,DM.OrderIndex,DM.Title
			ORDER BY DM.OrderIndex

			DROP TABLE #tempPresentAbsentCount
		END
END
GO
PRINT N'Altering Procedure [sBiometric].[pCloudTransactionDataAdd]...';


GO
ALTER PROCEDURE [sBiometric].[pCloudTransactionDataAdd]

@rXmlDoc nvarchar(max) = ''

AS
SET NOCOUNT ON

BEGIN
	SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
	DECLARE @lInterrorCode INT,
			@intDoc INT
	BEGIN TRANSACTION					
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	CREATE TABLE #tTable(
		TransactionId bigint NOT NULL,
		[PunchId] [nvarchar](50) NOT NULL,
		TransactionDateTime [datetime] NOT NULL,
		[DeviceIP] [nvarchar](20) NOT NULL,
		[Mode] [nvarchar](10) NOT NULL,
		[CreatedDateTime] [datetime] NOT NULL
	)
	INSERT INTO #tTable
	SELECT 
		A.TransactionId,
		A.PunchId,
		A.TransactionDateTime,
		A.DeviceIP,
		A.Mode,
		sCommon.fGetDate()
	FROM OPENXML (@intDoc, '/Table/CloudTransactionData', 1)
	WITH
	(
		TransactionId bigint '@TransactionId',
		PunchId nvarchar(50) '@PunchId',
		TransactionDateTime datetime '@TransactionDateTime',
		DeviceIP nvarchar(20) '@DeviceIP',		
		Mode nvarchar(10) '@Mode'	
	) A	

	INSERT INTO sBiometric.tCloudTransactionRawData
	SELECT 
		A.TransactionId,
		A.PunchId,
		A.TransactionDateTime,
		A.DeviceIP,
		A.Mode,
		A.CreatedDateTime
	From #tTable A 
	Where NOT EXISTS 
		(SELECT 1 FROM  sBiometric.tCloudTransactionRawData CRD where  A.TransactionDateTime=CRD.TransactionDateTime AND A.PunchId=CRD.PunchId AND A.DeviceIP=CRD.DeviceIP)
	
	INSERT INTO [sBiometric].[tCloudTransactionData] with (rowlock)
	--Employee
	SELECT 
		EM.Id,
		CRD.TransactionDateTime,
		CASE WHEN (SELECT 1 FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = EM.Id AND SourceTypeId = 95) IS NOT NULL THEN 
		(SELECT top 1 ShiftCode FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = EM.Id AND SourceTypeId = 95 order by fromShiftDate desc)
		ELSE EM.ShiftId END AS ShiftCode,
		CONVERT(DATE,CRD.TransactionDateTime) AS Attn_Dt,
		CASE WHEN (SELECT TOP 1 ISNULL(Mode,'IN') FROM [sBiometric].[tCloudTransactionData] WHERE SourceId = EM.Id AND Attn_Dt = CONVERT(DATE,CRD.TransactionDateTime) ORDER BY In_Out_Time DESC) = 'IN' THEN 'OUT' ELSE 'IN' END AS Mode,
		sCommon.fGetDate(),
		CRD.DeviceIP,
		0,
		CRD.PunchId,
		CRD.TransactionId,
		95,
		0
	FROM 
		sBiometric.tCloudTransactionRawData CRD 		
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.PunchId = CRD.PunchId
	WHERE
		CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData)

	UNION ALL

	--Student
	SELECT 
		AC.Id,		--Mantis: 34829, change SM.Id => AC.Id by dhruvik
		CRD.TransactionDateTime,
		CASE WHEN (SELECT 1 FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = SM.Id AND SourceTypeId = 2003) IS NOT NULL THEN 
		(SELECT top 1 ShiftCode FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR cast(CRD.TransactionDateTime as Date) BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = SM.Id AND SourceTypeId = 2003 order by fromShiftDate desc)
		ELSE SM.ShiftId END AS ShiftCode,
		CONVERT(DATE,CRD.TransactionDateTime) AS Attn_Dt,
		CASE WHEN (SELECT TOP 1 ISNULL(Mode,'IN') FROM [sBiometric].[tCloudTransactionData] WHERE SourceId = AC.Id AND Attn_Dt = CONVERT(DATE,CRD.TransactionDateTime) ORDER BY In_Out_Time DESC) = 'IN' THEN 'OUT' ELSE 'IN' END AS Mode,		--Mantis: 34829, change SM.Id => AC.Id by dhruvik
		sCommon.fGetDate(),
		CRD.DeviceIP,
		0,
		CRD.PunchId,
		CRD.TransactionId,
		2001,		--Mantis: 34829, change 2003 => 2001 by dhruvik
		0
	FROM 
		sBiometric.tCloudTransactionRawData CRD 		
		INNER JOIN sStudent.tStudentMaster SM ON SM.PunchId = CRD.PunchId
		INNER JOIN sStudent.tAcademic AC ON AC.StudentId = SM.Id		--Mantis: 34829, add INNER JOIN by dhruvik
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AC.BatchId		--Mantis: 34829, add INNER JOIN by dhruvik
	WHERE
		CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData)
		AND BM.IsActive = 1		--Mantis: 34829, add condition by dhruvik

	DROP TABLE #tTable
	COMMIT TRANSACTION
	SELECT 1 AS Result
END
GO
PRINT N'Altering Procedure [sBiometric].[pRptMonthlySummaryListDateWiseGet]...';


GO
ALTER PROCEDURE [sBiometric].[pRptMonthlySummaryListDateWiseGet]
	@rOrgGroupId int,
	@rOrgId int,
	@rFromDate DateTime,
	@rToDate DateTime, 
	@rStudentId bigint=0,
	@rClassId int=0,
	@rDivisionId int=0,
	--@rAttendanceTypeId tinyint,
	--@rAttendanceDate date=0,
	-- @rRepeatCount tinyint,
	@rOrgGroupBatchId int=0,
	@rTimeSheetStatus nvarchar(10) = '0',
	@rDepartmentId int=0,
	@rStatusId int=0,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit=0,
	@rAcademicId bigint=0		--Mantis: 34829, add by dhruvik
	
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
DECLARE @lBatchID int
CREATE TABLE #TempMonthTrans (
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20),
 ShiftName nvarchar(25) 
	
	)
	SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId = 2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E,D05_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	--IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	--BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
		 AND (((Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) 
		OR ((Month(@rToDate) <> 2 or (((YEAR(@rToDate) % 4 = 0 AND YEAR(@rToDate) % 100 <> 0) OR YEAR(@rToDate) % 400 = 0 And Month(@rToDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
		AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END
	
	--IF Month(@rFromDate) <> 2
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ((Month(@rFromDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) Or (Month(@rToDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END
	
	--IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ((Month(@rFromDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) OR (Month(@rToDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END
	CREATE TABLE #TempMonthTransWitIoOutTime (EmployeeId bigint,Attn_Date DateTime,InTime nvarchar(20),OutTime nvarchar(20))
	if(@rIsDetail=1)
	BEGIN
	INSERT INTO #TempMonthTransWitIoOutTime
		SELECT  SourceId,Attn_Dt,CONVERT(VARCHAR(10), I.In_Out_Time, 108),CONVERT(VARCHAR(10), O.In_Out_Time, 108)
        FROM [sBiometric].[tCloudTransactionData] I
		OUTER APPLY (
						SELECT TOP 1    In_Out_Time,
										Mode
						FROM [sBiometric].[tCloudTransactionData] t
						WHERE       t.SourceId = I.SourceId
								AND t.In_Out_Time > I.In_Out_Time
								AND SourceTypeid=2001		--Mantis: 34829, change by dhruvik, from 2003 => 2001
								AND t.Attn_Dt =I.Attn_Dt
								AND Mode = 'OUT'
						ORDER BY t.In_Out_Time
					) O
		WHERE I.Mode = 'IN'
		AND SourceTypeid=2001		--Mantis: 34829, change by dhruvik, from 2003 => 2001
		AND I.Attn_Dt>=@rFromDate
		AND I.Attn_Dt<=@rToDate
		--select * from #TempMonthTransWitIoOutTime
	END

	Select 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2 ,
		SA.AcademicId AS AcademicId,
		SA.StudentId AS StudentId,
		SA.Code AS StudentCode,
		SA.Name AS StudentName,
		ISNULL(SA.RollNo,0) as RollNo,
		ISNULL(TM.FirstIn,'00:00') AS FirstIn,
		ISNULL(TM.LastOut,'00:00') AS LastOut,
		ISNULL(TM.LateBy,'00:00') AS LateBy,
		ISNULL(TM.EarlyBy,'00:00') AS EarlyBy,
		 ISNULL(TM.Duration,'00:00') AS Duration,
		 ISNULL(TM.PresentStatus,'XX') AS OldPresentStatus ,
		  CASE When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
		 When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='PW')AND ([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(TM.Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
		 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW' 
		 ELSE
		TM.PresentStatus END as PresentStatus,
		TM.Attn_Date,
		OM.DisplayTitle AS Organization,
		CM.DisplayTitle AS ClassName,
		CM.Id AS ClassId,
		DM.DisplayTitle AS DivisionName,
		DM.Id AS DivisionId,
		Dept.DisplayTitle AS Department,
		Dept.Id AS DepartmentId,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		Dept.OrderIndex AS OrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.OrgId AS OrgId,
		TM.ShiftName,
		CTD.*,
		@rIsDetail AS IsDetail
				
		From #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND SourceTypeId = 2001		--Mantis: 34829, change by dhruvik, from 2003 => 2001  
	 INNER JOIN sStudent.vStudentAcademic SA  ON SA.AcademicId = TM.EmployeeId AND MT.SourceTypeId=2001 --AND MT.ATTN_DT = cast(rtrim(YEAR(@rAttendanceDate) *10000+ Month(@rAttendanceDate)  *100+ 01) as datetime)		--Mantis: 34829, change by dhruvik, from SA.StudentId => SA.AcademicId and 2003 => 2001
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
	INNER JOIN sSetup.tDivisionMaster DM  ON  SA.DivisionId=DM.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
	Left Join #TempMonthTransWitIoOutTime CTD ON  CTD.EmployeeId=TM.EmployeeId AND CTD.Attn_Date=TM.Attn_Date  
	INNER JOIN sSetup.tBatchMaster BM ON BC.BatchId = BM.Id AND BM.OrgGroupBatchId=@rOrgGroupBatchId --AND BM.IsActive=1
	WHERE 
		((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND OM.OrgGroupId=@rOrgGroupId
			AND (SA.OrgId=@rOrgId OR @rOrgId=0)
			AND (SA.StudentId=@rStudentId OR @rStudentId=0)
			--AND (SA.BatchId = @rBatchId)
			AND ( (SA.StatusId =  @rStatusId) OR @rStatusId=0)
			AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rToDate)
			 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			 AND (( @rTimeSheetStatus = '1' AND (TM.Duration < '09:30')) OR ( @rTimeSheetStatus != '1' AND ((PresentStatus = @rTimeSheetStatus OR @rTimeSheetStatus='0'))))
			AND (SA.OrgId = @rOrgId OR @rOrgId = 0)
			 AND((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			 AND(( SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			 AND (TM.Attn_Date>=@rFromDate )
			 AND (TM.Attn_Date<=@rToDate)
			AND (SA.AcademicId = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, add by dhruvik
	ORDER BY SA.RollNo

	DROP Table #TempMonthTrans	

	--Select 
	--	@rBuilder1 AS Builder1,
	--	@rBuilder2 AS Builder2 ,
	--	@rIsDetail AS IsDetail,
	--	CAST(0 AS bigint) AS AcademicId,
	--	'' AS StudentCode,
	--	'' AS StudentName,
	--	0 as RollNo,
	--	'' AS FirstIn,
	--	'' AS LastOut,
	--	'' AS LateBy,
	--	'' AS EarlyBy,
	--	 '' AS Duration,
	--	'' AS OldPresentStatus ,
	--	'' AS PresentStatus,
	--	CAST('' AS Date) AS Attn_Date, 
	--	'' AS Organization,
	--	'' AS ClassName,
	--	0 AS ClassId,
	--	'' AS DivisionName,
	--	0 AS DivisionId,
	--	'' AS Department,
	--	0 AS DepartmentId,
	--	'' As ClassDivision,
	--	0 AS OrderIndex,
	--	0 AS DivisionOrderIndex,
	--	0 AS OrgId,
	--	'' AS ShiftName,
	--	'' AS OutTime,
	--	'' as InTime

END
GO
PRINT N'Altering Procedure [sBiometric].[pRptStudentMonthlySummaryListGet]...';


GO
ALTER PROCEDURE [sBiometric].[pRptStudentMonthlySummaryListGet]
	@rOrgGroupId int,
	@rOrgId int,
	@rForYear int,
	@rForMonth int, 
	@rStudentId bigint,
	@rClassId int,
	@rDivisionId int,
	--@rAttendanceTypeId tinyint,
	--@rAttendanceDate date=0,
	-- @rRepeatCount tinyint,
	@rOrgGroupBatchId int=0,
	@rTimeSheetStatus nvarchar(10) = '0',
	@rDepartmentId int=0,
	@rStatusId int=0,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rAcademicId bigint=0		--Mantis: 34829, add by dhruvik
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
DECLARE @lBatchID int
declare @Days int
Declare @rFromDate datetime
Declare @rToDate datetime
CREATE TABLE #TempMonthTrans (
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20)
	
	)

	 select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
 set @rFromDate=CONVERT(nvarchar(20), @rForYear)+ '-' +  CONVERT(nvarchar(20), @rForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @rToDate=CONVERT(nvarchar(20), @rForYear)+ '-' +  CONVERT(nvarchar(20), @rForMonth) + '-' + CONVERT(nvarchar(20), @Days)
	SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId = 2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	--IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	--BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
		 AND (((Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) 
		OR ((Month(@rToDate) <> 2 or (((YEAR(@rToDate) % 4 = 0 AND YEAR(@rToDate) % 100 <> 0) OR YEAR(@rToDate) % 400 = 0 And Month(@rToDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime))) 
		AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END
	
	--IF Month(@rFromDate) <> 2
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ((Month(@rFromDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) Or (Month(@rToDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END
	
	--IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ((Month(@rFromDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) OR (Month(@rToDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END

	Update TM set PresentStatus = CASE When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='PW')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
		 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW' 
		 ELSE TM.PresentStatus END
		From #TempMonthTrans TM
		INNER JOIN sStudent.vStudentAcademic SA  ON SA.AcademicId = TM.EmployeeId		--Mantis: 34829, change by dhruvik, from SA.StudentId => SA.AcademicId


	Select 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2 ,
		SA.AcademicId AS AcademicId,
		SA.Code AS StudentCode,
		SA.Name AS StudentName,
		ISNULL(SA.RollNo,0) as RollNo,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='A') AS TotalAbsentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='W') AS TotalWeekOffs,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='H') AS TotalHolidays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND (PresentStatus='P' OR PresentStatus='PW')) AS TotalPresentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='HD') AS TotalHalfDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='LH') AS TotalLessHours,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='E') AS TotalErrorCase,
		OM.DisplayTitle AS Organization,
		CM.DisplayTitle AS ClassName,
		CM.Id AS ClassId,
		DM.DisplayTitle AS DivisionName,
		DM.Id AS DivisionId,
		Dept.DisplayTitle AS Department,
		Dept.Id AS DepartmentId,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		Dept.OrderIndex AS OrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.OrgId AS OrgId,
		DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays
				
		From sBiometric.tMonthTrans MT  
	 INNER JOIN sStudent.vStudentAcademic SA  ON SA.AcademicId = MT.EmployeeId AND MT.SourceTypeId=2001 --AND MT.ATTN_DT = cast(rtrim(YEAR(@rAttendanceDate) *10000+ Month(@rAttendanceDate)  *100+ 01) as datetime)		--Mantis: 34829, change by dhruvik, from SA.StudentId => SA.AcademicId and 2003 => 2001
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
	INNER JOIN sSetup.tDivisionMaster DM  ON  SA.DivisionId=DM.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BC.BatchId = BM.Id  AND BM.OrgGroupBatchId=@rOrgGroupBatchId --AND BM.IsActive=1
	WHERE 
		((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND OM.OrgGroupId=@rOrgGroupId
			AND (SA.OrgId=@rOrgId OR @rOrgId=0)
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND (SA.StudentId=@rStudentId OR @rStudentId=0)
			AND ( (SA.StatusId =  @rStatusId) OR @rStatusId=0)
			AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rToDate)
			 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			 --AND (( @rTimeSheetStatus = '1' AND (TM.Duration < '09:30')) OR ( @rTimeSheetStatus != '1' AND ((PresentStatus = @rTimeSheetStatus OR @rTimeSheetStatus='0'))))
			AND (SA.OrgId = @rOrgId OR @rOrgId = 0)
			 AND((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (SA.AcademicId = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, add by dhruvik
	ORDER BY SA.RollNo

	DROP Table #TempMonthTrans	


	--Select
	--	@rBuilder1 AS Builder1,
	--	@rBuilder2 AS Builder2 , 
	--	CAST(0 AS bigint) AS AcademicId,
	--	'' AS StudentCode,
	--	'' AS StudentName,
	--	0 as RollNo,
	--	0 AS TotalAbsentDays,
	--	0 AS TotalWeekOffs,
	--	0 AS TotalHolidays,
	--	0 AS TotalPresentDays,
	--	0 AS TotalHalfDays,
	--	0 AS TotalLessHours,
	--	0 AS TotalErrorCase,
	--	'' AS ClassName,
	--	0 AS ClassId,
	--	'' AS DivisionName,
	--	0 AS DivisionId,
	--	'' AS Department,
	--	0 AS DepartmentId,
	--	'' As ClassDivision,
	--	0 AS OrderIndex,
	--	0 AS DivisionOrderIndex,
	--	'' AS Organization,
	--	0 AS OrgId,
	--	0 AS TotalDays
END
GO
PRINT N'Altering Procedure [sBiometric].[pTimeSheetListStudentGet]...';


GO
ALTER PROCEDURE [sBiometric].[pTimeSheetListStudentGet]
	@rOrgId int,
	@rFromDate DateTime,  
    @rToDate DateTime, 
	@rStudentId bigint,
	@rClassId int=0,
	@rDivisionId int=0,
	@rStatusId int=0,
	@rBatchId  int,
	@rAcademicId bigint=0		--Mantis: 34829, add by dhruvik
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   

----
CREATE TABLE #TempMonthTrans (
	Id int Identity,
	EmployeeId bigint,	
	Attn_Date DateTime,
	PresentStatus nvarchar(5),
	FirstIn nvarchar(20),
	LastOut nvarchar(20),
	OverTime nvarchar(20),
	LateBy nvarchar(20),
	Duration nvarchar(20),	
	EarlyBy nvarchar(20),
    ShiftName nvarchar(25) 
	
	)

	
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId = 2001)	  --Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E,D05_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT @rStudentId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001

	--IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	--BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
		 AND (((Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) 
		OR ((Month(@rToDate) <> 2 or (((YEAR(@rToDate) % 4 = 0 AND YEAR(@rToDate) % 100 <> 0) OR YEAR(@rToDate) % 400 = 0 And Month(@rToDate)  =2))) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime))) 
		AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END
	
	--IF Month(@rFromDate) <> 2
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ((Month(@rFromDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) Or (Month(@rToDate) <> 2 AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END
	
	--IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	--BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeID = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, change by dhruvik, from @rStudentId => @rAcademicId
	AND ((Month(@rFromDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)) OR (Month(@rToDate) NOT IN (2,4,6,9,11) AND ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)))
	 AND ( SourceTypeId =2001)		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	--END

	Update TM set PresentStatus = CASE When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
		 When (([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='PW')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
		 When ((TM.PresentStatus='W')AND ([sAttendance].[fWeekHOffGet]( YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,SA.BatchID,SA.ClassId,SA.DivisionId ,'' ,SA.OrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
		 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW' 
		 --When ((TM.PresentStatus='XX')AND (Cast(TM.Attn_Date as date)<GETDATE()) And (cast(AD.AdmissionDate as date)<= Cast(TM.Attn_Date as date) OR ISNULL(AD.AdmissionDate,'')='')AND (AD.LeftDate>= Cast(TM.Attn_Date as date) OR ISNULL(AD.LeftDate,'')='') AND (TM.FirstIn ='00:00'))  then 'A'
		 ELSE TM.PresentStatus END
		From #TempMonthTrans TM
		INNER JOIN sStudent.vStudentAcademic SA  ON SA.AcademicId = TM.EmployeeId		--Mantis: 34829, change by dhruvik, from SA.StudentId => SA.AcademicId
		--INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId

--select * from #TempMonthTrans 
	Select 
		SA.AcademicId AS AcademicId,
		SA.StudentId AS StudentId,
		TM.Attn_Date AS  Attn_Date,
		TM.FirstIn,
		TM.LastOut,
		TM.OverTime,
		TM.LateBy,
		TM.Duration,
		TM.EarlyBy,
		TM.ShiftName,
		TM.PresentStatus as PresentStatus,
		SA.Code AS StudentCode,
		SA.Name AS StudentName,
		ISNULL(SA.RollNo,0) as RollNo,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='A') AS TotalAbsentDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='W') AS TotalWeekOffs,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='H') AS TotalHolidays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND (PresentStatus='P' OR PresentStatus='PW')) AS TotalPresentDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='HD') AS TotalHalfDays,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='LH') AS TotalLessHours,
		--(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='E') AS TotalErrorCase,
		 OM.DisplayTitle AS Organization,
		CM.DisplayTitle AS ClassName,
		CM.Id AS ClassId,
		DM.DisplayTitle AS DivisionName,
		DM.Id AS DivisionId,
		Dept.DisplayTitle AS Department,
		Dept.Id AS DepartmentId,
		CM.Title+'-'+DM.DisplayTitle As ClassDivision,
		Dept.OrderIndex AS OrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.OrgId AS OrgId--,
		--DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays
				
		 From #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND SourceTypeId = 2001		--Mantis: 34829, change by dhruvik, from 2003 => 2001
	 INNER JOIN sStudent.vStudentAcademic SA  ON SA.AcademicId = MT.EmployeeId AND MT.SourceTypeId=2001		--Mantis: 34829, change by dhruvik, from SA.StudentId => SA.AcademicId and 2003 => 2001
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
	INNER JOIN sSetup.tDivisionMaster DM  ON  SA.DivisionId=DM.Id
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
	--INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
	
	WHERE 
			SA.OrgId=@rOrgId 
			AND	((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (SA.StudentId=@rStudentId OR @rStudentId=0)
			AND ((SA.StatusId =  @rStatusId) OR @rStatusId=0)
			AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rToDate)
			AND SA.BatchId = @rBatchId
			AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			AND (SA.AcademicId = @rAcademicId OR @rAcademicId = 0)		--Mantis: 34829, add by dhruvik
			 
	ORDER BY SA.RollNo



	DROP Table #TempMonthTrans	
END
GO
PRINT N'Altering Procedure [sCertificate].[pRptTransferCertificateNewGet]...';


GO
ALTER PROCEDURE [sCertificate].[pRptTransferCertificateNewGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rNumber nvarchar(20)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromDate date='',
     @rToDate date='',
     @rCode nvarchar(20)='',
     @rName nvarchar(20)=''
	
	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 @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 @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 218 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

	--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  
		T.Number,
		T.TCDate AS TransferDate,
		T.ExamName,
		T.ExamSeatNo,
		T.ExamYear,
		T.ExamResult,
		T.PromotedClass,
		T.TransferConduct,
		T.OptionalSubject,
		T.Remark,
		A.Name,
		A.OrganiZationName,
	    SO.GenderId,
	    SO.DateOfBirth,
	    A.ClassName AS ClassName,
		A.DivisionName AS DivisionName,
		A.Code As StudentCode,
		SO.AdhaarNumber,
		T.SemesterDuration,
		A.StudentId,
		@lIsOnPrePrinted AS IsOnPrePrinted,
		@lIsDisplayImageHeader AS IsDisplayImageHeader,
		OM.OrgLogo,
		OM.ReportOrgTitle AS OrgTitle,
		OM.SmallAddress1,
		OM.SmallAddress2,
		OM.RegistrationDetail,
		--OI.CertificateHeaderA4,
		@lIDConfigValue AS ItemValue,
		OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
		ISNULL(SF.FatherName,'') As FatherName,			--add for 27638 mantis start
		ISNULL(SF.MotherName,'') As MotherName,
		A.StatusId,
		SI.StudentPhoto,
		@lIsShowPhoto AS IsShowPhoto,
		CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
		ISNULL(SI.QRCode,'') AS QRCode,
		SC.PresentStreetOne,
		SC.PresentStreetTwo,
		SC.PresentStreetThree,
		SC.PresentCountry,
		SC.PresentState,
		SC.PresentCity,
		SC.PresentZipCode,
		SC.PresentContactNo,
		SC.PermanentStreetOne,
		SC.PermanentStreetTwo,
		SC.PermanentStreetThree,
		SC.PermanentCountry,
		SC.PermanentState,
		SC.PermanentCity,
		SC.PermanentZipCode,
		SC.PermanentContactNo,		--add for 27638 mantis end
		SO.UIDNumber,  --add for 0032936 mantis end
		ISNULL(SO.BirthDateInWord,'') AS DOBInWords  --add for mantis : 0035007
		
	From sCertificate.tTransfer T 
	INNER JOIN sStudent.vStudentAcademic A On A.AcademicId=T.AcademicId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId  
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId 
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId		--add for 27638 mantis
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId			--add for 27638 mantis
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId		--add for 27638 mantis
	WHERE 
		T.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((A.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((T.TCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((T.TCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((A.ClassId=@rClassId) OR(@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((T.Number=@rNumber) OR (@rNumber=''))
		AND ((T.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((T.Number <= @rToNo) OR (@rToNo=''))
	
END
GO
PRINT N'Altering Procedure [sCommon].[pAutoCompleteMasterGet]...';


GO

ALTER PROCEDURE [sCommon].[pAutoCompleteMasterGet]
	@rContextKey [nvarchar](100) = '',
	@rPrefixText [nvarchar](100) = '',
	@rSearchCondition [nvarchar](max) = '',
	@rObsoletedId [nvarchar](300) = '',
	@rExcludingIds [nvarchar](300) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lQueryString Nvarchar(Max)
	
	
	-- Excluding Id START
	DECLARE @lQueryStringTemp Nvarchar(Max)
	DECLARE @lIndexOfComma SmallInt
	DECLARE @lIndexOfDistinct SmallInt
	DECLARE @lLengthOfSelect SmallInt
	DECLARE @lIdColmnName Nvarchar(300)
			
	SELECT	@lQueryStringTemp = QueryString
	FROM	sCommon.tAutoCompleteMaster
	WHERE	((ContextKey = @rContextKey) OR (ISNULL(@rContextKey, '') = ''))
	
	
	-- Find Out the Id Column Name
	SELECT @lIndexOfComma = CHARINDEX(',', @lQueryStringTemp)
	SELECT @lIndexOfDistinct = CHARINDEX(' Distinct ', @lQueryStringTemp)
	IF @lIndexOfDistinct > 0 
		SELECT @lLengthOfSelect = LEN('SELECT DISTINCT')
	ELSE
		SELECT @lLengthOfSelect = LEN('SELECT')	

	--PRINT @lIndexOfComma - 1 - @lLengthOfSelect
	SELECT @lIdColmnName = SUBSTRING (@lQueryStringTemp, @lLengthOfSelect + 1, @lIndexOfComma - 1 - @lLengthOfSelect) 
	PRINT(@lIdColmnName)

		
	
	IF ISNULL(@rExcludingIds, '') ! = ''
	BEGIN
		SET @rSearchCondition = @rSearchCondition + ' AND ' + @lIdColmnName + ' NOT IN ' + @rExcludingIds
	END
	
	-- Excluding Id END
	
	
	
	IF ISNULL(@rObsoletedId, '') = ''
	SET @rObsoletedId = '0'
	
	IF @rObsoletedId = '0'
	BEGIN
	SELECT @lQueryString = QueryString
	FROM sCommon.tAutoCompleteMaster
	WHERE ((ContextKey = @rContextKey) OR (ISNULL(@rContextKey, '') = ''))
	
	--SELECT @lQueryString
	--want to search all words middle words also mantisid : 0034857
	SET @lQueryString = REPLACE(@lQueryString, '{0}', '''%' + @rPrefixText + '%''' + ISNULL(@rSearchCondition, ''))
	--SELECT @lQueryString
	END
	ELSE
	BEGIN
	
	PRINT (@lQueryString)

	DECLARE @lQueryStringMain	Nvarchar(Max)
	DECLARE @lOrderPos			Int
	DECLARE @lObsFrontAndPos	Int
	DECLARE @lObsBackAndPos		Int
	DECLARE @lObsPos			Int
	DECLARE @lDeleted			Bit


SELECT	@lQueryStringMain = QueryString
FROM	sCommon.tAutoCompleteMaster
WHERE	((ContextKey = @rContextKey) 
		OR (ISNULL(@rContextKey, '') = ''))
	
SET @lObsPos = (SELECT CHARINDEX('IsObsolete = 0', @lQueryStringMain))
SET @lObsBackAndPos = (SELECT CHARINDEX('IsObsolete = 0 AND', @lQueryStringMain))
SET @lObsFrontAndPos = (SELECT CHARINDEX('AND IsObsolete = 0', @lQueryStringMain))

SET @lDeleted = 0
IF @lObsBackAndPos > 0
BEGIN
SELECT @lQueryString = STUFF (@lQueryStringMain, @lObsBackAndPos, LEN('IsObsolete = 0 AND'), '')
SET @lDeleted = 1
END
PRINT (@lQueryString)
IF @lObsFrontAndPos > 0
BEGIN
IF @lDeleted = 0
SELECT @lQueryString = STUFF (@lQueryStringMain, @lObsFrontAndPos, LEN('AND IsObsolete = 0'), '') 
SET @lDeleted = 1
END
--PRINT (@lQueryString)
IF @lObsPos > 0
BEGIN
IF @lDeleted = 0
SELECT @lQueryString = STUFF (@lQueryStringMain, @lObsPos, LEN('IsObsolete = 0'), '') WHERE @lDeleted = 0
SET @lDeleted = 1
END

IF @lDeleted = 0
SET @lQueryString = @lQueryStringMain 

SET @lOrderPos = (SELECT CHARINDEX('ORDER BY', @lQueryStringMain))
SELECT @lQueryStringMain = SUBSTRING(@lQueryStringMain, 0, @lOrderPos )

--want to search all words middle words also mantisid : 0034857
SET @lQueryStringMain = REPLACE(@lQueryStringMain, '{0}', '''%' + @rPrefixText + '%''' + ISNULL(@rSearchCondition, ''))




IF ISNULL(@rObsoletedId, '') = ''
SET @rObsoletedId = '0'

--PRINT (@lQueryString)
--want to search all words middle words also mantisid : 0034857
SET @lQueryString = REPLACE(@lQueryString, '{0}', '''%' + @rPrefixText + '%''' + ISNULL(@rSearchCondition, '') + ' AND ID = ' + @rObsoletedId)

SELECT @lQueryString = @lQueryStringMain + ' UNION ' + @lQueryString 
	
	END
		
EXEC(@lQueryString)
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
	 ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,       --Mantis - 0032963
	 ISNULL(ACM.Title,'') AS FeeCategory -- Added by Dhananjay for Mantis Id - 35029

	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
		INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id = SA.AdmissionCategoryId -- Added by Dhananjay for Mantis Id - 35029

	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,
		ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo, --Mantis - 0032963
		ISNULL(ACM.Title,'') AS FeeCategory -- Added by Dhananjay for Mantis Id - 35029


	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
		INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id = SA.AdmissionCategoryId -- Added by Dhananjay for Mantis Id - 35029
	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
	--'' As WhatsAppContactNo,
	--'' As FeeCategory

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

GO

ALTER PROCEDURE [sFee].[pRptFeePendingDetailWithScholarshipListGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId  int=0,
		@rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0,
		@rClassIds nvarchar(max) = '',
		@rDivisionIds nvarchar(max) = ''  
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	DECLARE @p as TempPendingFee
	
	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,
		0 AS FeeSetupId,		
		0 AS IsVariable,
		0 AS Amount,
		'1900-01-01' AS StartDate,
		'1900-01-01' AS EndDate,
	    0.00 AS FAAmount,
		0.00 AS DiscountAmount,
		0.00 AS AdditionalAmount,
		0 AS PaidAmount,
		SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount,
		'' AS Remark,
		0 ReceiptBookId,
		'' AS FeeName,
		'' AS FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		'' AS ReceiptBookTitle,
		0 AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName,
		'',
		'',
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.FeeOrderIndex,
		'' AS FatherContactNo, --Added for mantis : 34972 by Nilesh
		'' AS MotherContactNo --Added for mantis : 34972 by Nilesh
  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 ((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='')
			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 (SA1.DivisionId=@rDivisionId OR @rDivisionId=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		
				(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 sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
       LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		
	WHERE	
			(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))		     
			GROUP BY 
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName,
			SA.DivisionName,
			OrgId,
			O.Title,
			O.OrderIndex,
			BatchName,
			SA.SUID,
			SA.ClassOrderIndex,
			SA.DivisionOrder,
			FeeOrderIndex
		
			Order by SA.RollNo

			SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsFilter AS IsFilter, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			OrgId,			 
			p.AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			OrgName,
			ISNULL(SUM(PendingAmount),0) AS PendingAmount, 
			ISNULL(SUM(SS.ScholarshipPaid),0) AS ScholarshipPaid,
			ISNULL(SUM(SSE.EligibleAmount),0) AS EligibleAmount,
			ISNULL(SS.ReferenceRemark,'')   AS ReferenceRemark,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex
			--,
			--CASE ISNULL(SS.AcademicId,0) WHEN 0 THEN 0 ELSE 1 END AS IsScholarshipEligible		
			FROM @p p 
			
		LEFT JOIN				
		(SELECT  SE.AcademicId,Sum(PaidAmount) AS ScholarshipPaid,SO.ReferenceRemark FROM 
		sScholarship.tScholarshipEligibleStudent SE
		INNER JOIN sStudent.vStudentAcademic SA1  ON SE.AcademicId = SA1.AcademicId 
		INNER JOIN sScholarship.tScholarshipReceive RE ON SE.ScholarshipId = RE.ScholarshipId 
		INNER JOIN sScholarship.tScholarshipStudentPaid SP on SE.AcademicId = SP.AcademicId	AND SP.ScholarshipReceiveId = RE.Id	
		INNER JOIN sStudent.tStudentOther SO ON SA1.StudentId = SO.StudentId
		WHERE
		    (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		 	AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		 	AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		 	AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		 	AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = @rOrgGroupBatchId))
		 	AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		 	 AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 	 AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			 AND ((SA1.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=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='') 	
		 	GROUP BY SE.AcademicId,ReferenceRemark
		 ) SS ON p.AcademicId=SS.AcademicId
		LEFT JOIN				
		(SELECT  SE.AcademicId,SUM(SE.EligibleAmount) AS EligibleAmount FROM 
		sScholarship.tScholarshipEligibleStudent SE
		INNER JOIN sStudent.vStudentAcademic SA1  ON SE.AcademicId = SA1.AcademicId		 
		WHERE
		    (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		 	AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		 	AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		 	AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		 	AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = @rOrgGroupBatchId))
		 	AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		 	 AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 	 AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			 AND ((SA1.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=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='') 	  
		 	GROUP BY SE.AcademicId 
		 ) SSE ON p.AcademicId=SSE.AcademicId		 
		 
			GROUP By 
			OrgId,			
			p.AcademicId,
			--SS.AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			OrgName,
			ReferenceRemark,
			SUID,
			ClassOrderIndex,
			DivisionOrderIndex
			ORDER BY AcademicId
END
GO
PRINT N'Altering Procedure [sFee].[pRptFeeReceiptDetailsGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
						
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date='',
			@rClassId int = 0,
			@rOrgIds nvarchar(max) = '',
			@rReceiptPrintGroupId nvarchar(100)='',
			@rDivisionId int = 0,
			@rAdmissionCategoryId int = 0
			

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	Declare @lIDConfigValue nvarchar(50)='',@lOrgGroup_Id int=0
	Select @lOrgGroup_Id = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	 
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @rReceiptId

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

	IF(@rOrgGroupId=0) SET @rOrgGroupId=@lOrgGroupId

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,			
			SA.AcademicId,
			--SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,			
			--changes by Jash on 06/11/2020--%
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),ISNULL(FR.PaymentTransactionId,''))  END AS ChequeNo,
			--CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo
			--	WHEN ISNULL(PT.BankTransactionId,'') = '' THEN  CONVERT(nvarchar(20),FR.PaymentTransactionId)
			--	ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) +' - '+ CONVERT(nvarchar(20),PT.BankTransactionId) END AS ChequeNo,
			--%ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,					
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN '' 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,			
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			(CASE WHEN  ISNULL(FR.PaymentTransactionId,0) > 0 
			  THEN -- Navrachana
				'Online Generated'
				ELSE ISNULL(U.DisplayTitle,'') END) AS UserName,
			--ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0 THEN 
			--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	 			  
			(CASE WHEN  RBM.ReportId = 20576
			      THEN -- HM patel report
				  [sFee].[fReceiptMonthDetailGet](FR.ID,0)
			      WHEN RBM.ReportId = 30457 
			      THEN
				  [sFee].[fReceiptMonthDetailGet](FR.ID,1)		
			      WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
				  [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Head wise Month name in detail
				  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN				
				  [sFee].[fFeeMonthNameGet](FR.ID,FM.Id) -- Fee wise Month name in detail
			ELSE '' END) 
			AS MonthDetail,    			
			(CASE WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
					 Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
					sFee.tReceipt FR1				
					INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
					INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
					INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
					INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
					Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					Order By FS1.StartDate
					FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' )    -- Fee Head wise Fee Duration
				  WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN
					FS.FeeDuration -- Fee wise Fee Duration
				 ELSE '' END) AS FeeDuration,			
			--Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
			--sFee.tReceipt FR1				
			--INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
			--INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
			--INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
			--INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
			--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
			----Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			-- Order By FS.StartDate
			--FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' ) AS FeeDuration,			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN  FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN  FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
			ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue ,
	        SF.FatherName,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,
			(ISNULL((CASE WHEN SC.PresentStreetOne IS NOT NULL AND SC.PresentStreetOne!='' THEN ''+ SC.PresentStreetOne END),'')+
			ISNULL((CASE WHEN SC.PresentStreetTwo IS NOT NULL AND SC.PresentStreetTwo!=''  THEN ', '+ SC.PresentStreetTwo END),'')+
			ISNULL((CASE WHEN SC.PresentStreetThree IS NOT NULL AND SC.PresentStreetThree!=''  THEN ', '+ SC.PresentStreetThree END),'')+
			ISNULL((CASE WHEN SC.PresentCity IS NOT NULL AND SC.PresentCity!=''  THEN ', ' + SC.PresentCity  END),'')+
			ISNULL((CASE WHEN SC.PresentState IS NOT NULL AND SC.PresentState!=''  THEN  ', '+ SC.PresentState END),'')+
			ISNULL((CASE WHEN SC.PresentZipCode IS NOT NULL AND SC.PresentZipCode!=''  THEN  ', '+ SC.PresentZipCode  END),''))
			 AS PresentAdress,
			--ISNULL(SC.PresentStreetOne +','+ SC.PresentStreetTwo +','+ SC.PresentStreetThree +','+ SC.PresentCity +','+ SC.PresentState +'-'+ SC.PresentZipCode ,'') AS PresentAdress,
			SC.ParentContactNo,			
			ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount,
			CASE WHEN @rOrgGroupId = 1134 OR @rOrgGroupId = 1742 THEN
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,RBM.Id),0) END)
			ELSE 
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,0),0) END) END AS PendingFeeAmount,
			SA.FirstName,
			SA.LastName,
			ISNULL([sFee].[fFeeAmountSumGet](FR.SourceId),0) AS FeeAmount,
			ISNULL([sFee].[fFeeReceiptDiscountSumGet](FR.SourceId),0) AS ExemptionAmountSum,
			[sFee].[fTransportBusRouteGet](SA.StudentId,FR.OrgGroupBatchId) AS TransportBusRoute,
			ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
			ISNULL(FHM.Number,0) AS FeeHeadNumber,
			ISNULL(FM.Number,0) AS FeeNumber,
			ISNULL(RBM.DigitalSignature,0x) AS DigitalSignature,
			ISNULL(FR.CancelStatusRemark,'') AS CancelStatusRemark,
			FS.Amount AS FeeSetupAmount,
			FR.CreatedDateTime ,
			ISNULL(FR.PaymentTransactionId,0) As PaymentTransactionId,
			SA.MiddleName,
			CONVERT(char(5),FR.CreatedDateTime,108) AS CreatedTime,
			--by megha - 0026430

			(CASE WHEN ISNULL(FA.VariableAmount,0) > 0 Then FA.VariableAmount 
			      When ISNULL(FS.Amount,0) > 0 Then FS.Amount END) + ISNULL(FA.AdditionalAmount,0) - ISNULL(FA.DiscountAmount,0) - ISNULL(FA.NotApplicableAmount,0) As TotalPayableAmount,
			OGM.Title AS OrgGroupTitle,
			 NID.CollectionGroupName AS NextInstallmentName, --Mantis End- 0031305
			ISNULL(HM.Title,'') AS House,	--add for mantis: 32658
			NID.StartDate AS NextInstallmentStartDate, --Mantis -  Start 32760
			NID.EndDate AS NextInstallmentEndDate,
			NID.PendingAmount AS NextInstallmentAmount,   --Mantis -  End 32760			
			ISNULL([sFee].[fFeeActualAmountSumGet](FR.SourceId),0) AS FeeActualAmount,	-- MantisId : 0032658
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo, -- MantisId : 0032895
			--mantis Start - 0033973
			ISNULL(SC.PermanentStreetOne,'')AS PermanentStreetOne,
			ISNULL(SC.PermanentStreetTwo,'')AS PermanentStreetTwo,
			ISNULL(SC.PermanentStreetThree,'')AS PermanentStreetThree,
			--mantis End - 0033973
			--mantis Start - 0034206
			ISNull(SC.PermanentCountry,'')AS PermanentCountry,
			ISNull(SC.PermanentState,'')AS PermanentState,
			ISNull(SC.PermanentCity,'')AS PermanentCity,
			ISNull(SC.PermanentZipCode,'')AS PermanentZipCode,
			--mantis End - 0034206
			FS.StartDate,          --mantis : 0034274
			FS.EndDate,          --mantis : 0034274
			ISNull(CSM.Title,'') AS CasteCategory,  --mantis : 0034588
			LM.Title AS Medium,   --mantis : 0034588
			CASE WHEN @rOrgGroupId = 1134 OR @rOrgGroupId = 1742 THEN
			ISNULL([sFee].[fPaidFeeAmountReceiptBookwiseGet](FR.SourceId,RBM.Id),0)
			ELSE
			ISNULL([sFee].[fPaidFeeAmountReceiptBookwiseGet](FR.SourceId,0),0)END AS TotalPaidAmount --mantis : 0034862
 	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId  -- Mantis : 0029314
			LEFT JOIN (SELECT * FROM [sFee].[fNextInstallmentDetailsGet](@rReceiptBookId, @rReceiptId)) NID -- Mantis Start - 0031305
			ON NID.SourceId = FR.SourceId AND NID.SourceTypeId = FR.SourcetypeId -- Mantis End - 0031305
			LEFT JOIN sStudent.tStudentOther AS SO ON SO.StudentId = SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId		--add for mantis: 32658
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId --mantis : 0034588
			INNER JOIN sSetup.tLanguageMaster LM ON LM.Id = OM.LanguageId --mantis : 0034588
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
			AND ((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0) )
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
END

--BEGIN
--SELECT
-- CAST(0 AS bigint) AS ReceiptId,
-- 0	AS ReceiptNumber,
-- CAST('' AS date) AS ReceiptDate,
-- CAST(0 AS bigint) AS AcademicId,
-- ''	AS Name,
--''	AS Code,
-- 0	AS RollNo,
--0	AS ClassId,
--0	AS DivisionId,
--''	AS ClassName,
--''	AS DivisionName,
--''	AS ClassDivision,
--0	AS FeeHeadId,
--''	AS FeeHead,
--0	AS FeeId,
--''	AS FeeName,
--CAST(0.0 AS decimal(12,2)) AS PaidAmount,
--CAST(0 AS tinyint) AS PayTypeId,
--''	AS PayType,
--''	AS ChequeNo,	
--''	AS BankName,
--''	AS Address1,
--''	AS Address2,
--''	AS FullTitle,
--CAST(0.0 AS decimal(12,2)) AS TotalReceiptAmount,
--CAST(0.0 AS decimal(12,2)) AS ReceiptAmount,					
--''	AS ReceiptAmountInWords,		
--CAST(0.0 AS decimal(12,2)) AS DiscountAmount,
--''	AS Remark,
--''	AS UserName,		
--0x  AS OrgLogo,
--''	AS Remark1,
--''	AS Remark2,			 
--CAST(0 AS bit) AS IsOnPrePrinted,
--CAST(0 AS bit) AS IsSupressLogo,
--CAST(0 AS bit) AS IsDisplaySchoolName,
--0	AS ReportId,
--''	AS OrganizationName,		  
--''	AS MonthDetail,    			
--''	AS FeeDuration,		
--''	AS DepartmentName,
-- 0	AS FeeOrderIndex,
--CAST(0 AS smallint)	AS FeeHeadOrderIndex,
--CAST(0 AS bit) AS IsCancelReceipt,
--''	AS CurrencyCode,
--''	AS CurrencyTitle,
--''	AS Batch,
--CAST('' AS date) AS ChequeDate,
--CAST(0 AS bit) AS IsMonthDetailOnly,
--CAST(0 AS bit) AS IsFeeInvoiceHeadwise,
--''	AS GroupTitle,
--CAST(0 AS bit) AS IsSuppressFeeDetail,
--''	AS CollectionGroupName,
--0	AS InvoiceNumber,
--''	AS SUID,
--CAST(0 AS tinyint) AS HeaderDisplayId,
--0x  AS ReceiptBookHeader,
--CAST(0.0 AS decimal(6,2)) AS ServiceTaxPercentage,
--CAST(0.0 AS decimal(12,2)) AS AmountAfterDiscount,
--CAST(0.0 AS decimal(5,2)) AS CGSTPercentage,
--CAST(0.0 AS decimal(5,2)) AS SGSTPercentage,
--CAST(0.0 AS decimal(12,2)) AS CGSTAmount,
--CAST(0.0 AS decimal(12,2))	AS SGSTAmount,
--''	AS GSTINNo,
--''	AS HSNSACCode,
--''	AS ItemValue ,
--''	AS FatherName,
--''	AS MotherName,
--CAST(0.0 AS decimal(12,2)) AS ExemptionAmount,
--''	AS ExemptionRemark,
--0x AS EmployeeSign,
--''	AS PresentCity,
--''	AS PresentAdress,
--''	AS ParentContactNo,	
--CAST(0 AS bit) AS IsDisplayPendingFeeAmount,
--CAST(0.0 AS decimal(12,0)) AS PendingFeeAmount,
--''	AS FirstName,
--''	AS LastName,
--CAST(0.0 AS decimal(12,0))	AS FeeAmount,
--CAST(0.0 AS decimal(12,0)) AS ExemptionAmountSum,
--''	AS TransportBusRoute,
--''	AS BankAccountNumber,
--0	AS FeeHeadNumber,
--0	AS FeeNumber,
--0x AS DigitalSignature,
--''	AS CancelStatusRemark,
--CAST(0.0 AS decimal(12,2))	AS FeeSetupAmount,
--CAST('' AS date)	AS CreatedDateTime ,
--CAST(0 AS bigint)	AS PaymentTransactionId,
--''	AS MiddleName,
--'' AS CreatedTime,
-- 0 AS TotalPayableAmount,
-- '' AS OrgGroupTitle,
-- '' AS NextInstallmentName,
-- '' AS House,
-- CAST('' AS date) AS NextInstallmentStartDate,
-- CAST('' AS date) NextInstallmentEndDate,
-- CAST(0.0 AS decimal(12,2)) AS NextInstallmentAmount,
-- CAST(0.0 AS decimal(12,2)) AS FeeActualAmount,
-- '' AS StudentContactNo,
-- '' AS PermanentStreetOne,
-- '' AS PermanentStreetTwo,
-- '' AS PermanentStreetThree,
--'' AS PermanentCountry,
-- '' AS PermanentState,
-- '' AS PermanentCity,
-- '' AS PermanentZipCode,
-- CAST('' AS date) AS StartDate,
-- CAST('' AS date) AS EndDate,  
--   '' AS CasteCategory,  
--	   '' AS Medium,
--CAST(0.0 AS decimal(12,0)) AS TotalPaidAmount
--END
GO
PRINT N'Altering Procedure [sHostel].[pAssignRoomGet]...';

GO

ALTER PROCEDURE [sHostel].[pAssignRoomGet]
          
           @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
           @rHostelId int,
           @rRoomCategoryId int=0,
           @rRoomId int=0,
           @rOrgGroupBatchId int
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			--SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--END


BEGIN

SELECT  
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
       'Employee' AS SourceType,
		95 AS SourceTypeId,
		ISNULL(EM.Id,0) as SourceId,
		EM.Code as SourceCode,
		EM.FirstName+' '+EM.LastName as SourceName,
		ODM.Title as ClassDivisionName,
		RM.StudentsPerRoom,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		RM.Title AS Room,
		OM.DisplayTitle AS OrgDisplayTitle,
		AR.BedNumber AS BedNumber,
		RM.RoomCategoryId,
	    ISNULL(RCM.RoomCharge,0) AS RoomCharge,
	    OM.Id AS OrgId,
	    '' AS SUId,
	    ISNULL(EC.PresentCity,'') AS City, --Added '' AS City--> ISNULL(EC.PresentCity,'') for mantis - 0034976
	    [sHostel].[fAssignRoomEmployeeAssetGet](@rHostelId ,@rRoomId,AR.SourceId ) AS AssetNumber,
	    RM.Id AS RoomId
	   
		
  FROM sHostel.tRoomMaster RM 
	INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.Id=RM.RoomCategoryId AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
	LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=95 AND AR.OrgGroupBatchId=@rOrgGroupBatchId
    LEFT JOIN sHrm.tEmployeeMaster EM ON AR.SourceId=EM.Id
    LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
    LEFT JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
    LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
    LEFT JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
    LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgID
	LEFT JOIN sHrm.tEmployeeCommunications EC ON  EC.EmployeeId = EM.Id --Added by dhananjay for mantis - 0034976

  WHERE 
	--	 CCM.Id = @rId OR @rId = 0
	--AND 
		(RM.HostelId=@rHostelId OR @rHostelId=0)
	AND (RM.Id=@rRoomId OR @rRoomId=0)
	AND ISNULL(EM.Id,0) > 0
	--AND  CCM.IsObsolete = 0
	AND ISNULL(EM.IsOtherUser,0) = 0 
	UNION ALL
	
SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
       'Student' AS SourceType,
		2003 AS SourceTypeId,
	    ISNULL(SA.StudentId,0) as SourceId,
		SA.Code as SourceCode,
		SA.Name AS SourceName,
		sStudent.fStudentCurrentDivisionGet( SA.StudentId) AS ClassDivisionName,
		--'' AS  ClassDivisionName,
		--SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		RM.StudentsPerRoom,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		RM.Title AS Room,
		OM.DisplayTitle AS OrgDisplayTitle,
		AR.BedNumber AS BedNumber,
		RM.RoomCategoryId,
	    ISNULL(RCM.RoomCharge,0) AS RoomCharge,
	    OM.Id AS OrgId,
	    ISNULL(SA.SUId,'') AS SUId,
	    ISNULL(SC.PresentCity,'') AS City,
	    [sHostel].[fAssignRoomAssetGet](@rHostelId ,@rRoomId,SA.StudentId ) AS AssetNumber,
	    RM.Id AS RoomId
	    
  FROM sHostel.tRoomMaster RM 
	INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.Id=RM.RoomCategoryId AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
	LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=2003 AND AR.OrgGroupBatchId=@rOrgGroupBatchId
    LEFT JOIN sStudent.vStudentAcademic SA ON AR.SourceId=SA.StudentId AND SA.OrgGroupBatchId=@rOrgGroupBatchId 
    INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
    INNER JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
    LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgID
    LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=AR.SourceId
  WHERE 
	--	CCM.Id = @rId OR @rId = 0
	--	AND 
		(RM.HostelId=@rHostelId OR @rHostelId=0)
		AND (RM.Id=@rRoomId OR @rRoomId=0)
		AND ISNULL(SA.StudentId,0) > 0
	--  AND  CCM.IsObsolete = 0
	
END
GO
PRINT N'Altering Procedure [sHrm].[pExportLeave]...';


GO
ALTER PROCEDURE [sHrm].[pExportLeave] 
	@rFromBatchId INT
	,@rToBatchId INT
	,@rOrgId INT
	,@rIsDelete BIT
	,@rUserId BIGINT = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		IF (@rIsDelete = 1)
		BEGIN
			DELETE
			FROM sHrm.tLeaveBalance
			WHERE BatchId = @rToBatchId

			SELECT 101 AS RESULT

			RETURN
		END

		IF EXISTS (
				SELECT 1
				FROM sHrm.tLeaveBalance
				WHERE BatchId = @rToBatchId
				)
		BEGIN
			SELECT - 101 AS RESULT

			RETURN
		END

		BEGIN TRANSACTION

		DECLARE @lCount INT

		-- Leave Balance Temp Table
		CREATE TABLE #TempLeaveBalance (
			[AutoId] INT IDENTITY
			,[EmployeeId] BIGINT NOT NULL
			,[LeaveTypeId] INT NOT NULL
			,[BatchId] INT NOT NULL
			,[PendingNoOfLeave] DECIMAL(5, 2) NOT NULL
			,[MaximumCarryForward] INT NOT NULL
			,[OldSettingNoOfLeave] INT NOT NULL
			,[NewSettingNoOfLeave] INT NOT NULL
			,[EmployeeNoOfLeave] DECIMAL(5, 2) NOT NULL
			,[MaxInMonth] DECIMAL(5, 2) NULL
			)

		-- End Create Table
		INSERT INTO #TempLeaveBalance
		SELECT EM.Id
			,
			--EM.Code,
			--EM.FirstName +' '+EM.LastName,
			ISNULL(B.LeaveTypeId, 0)
			,@rToBatchId
			,(
				CASE 
					WHEN (ISNULL(LB.BalanceLeave, 0) - ISNULL(A.NoOfLeave, 0)) > 0
						THEN ISNULL(LB.BalanceLeave, 0) - ISNULL(A.NoOfLeave, 0)
					ELSE 0
					END
				) AS NoOfLeave
			,ISNULL(B.MaximumCarryForward, 0)
			,ISNULL(LB.BalanceLeave, 0)
			,ISNULL(B.NoOfLeave, 0)
			,ISNULL(A.NoOfLeave, 0)
			,ISNULL(LB.MaxInMonth, 0)
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId AND StatusId = 7 AND ISNULL(EM.IsOtherUser, 0) = 0
		-- Changes join sequence for mantis 0035174 by Foram
		LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId = EM.Id 
		LEFT JOIN (
			SELECT L.EmployeeId
				,L.LeaveTypeId
				,SUM(L.NoOfLeave) AS NoOfLeave
				,LTM.MaximumCarryForward
			FROM sHrm.tLeave L
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON L.LeaveTypeId = LTM.Id
				AND IsCarryForward = 1
				AND IsLWP = 0
				AND StatusId = 550
			WHERE L.BatchId = @rFromBatchId
				AND L.OrgId = @rOrgId
				AND LTM.IsCarryForward = 1
			GROUP BY L.EmployeeId
				,L.LeaveTypeId
				,LTM.MaximumCarryForward
		) A ON A.EmployeeId = EM.Id AND LB.LeaveTypeId = A.LeaveTypeId
		LEFT JOIN (
			SELECT LeaveTypeId
				,EmployeeGradeId
				,NoOfLeave
				,LTM.MaximumCarryForward
			FROM sHrm.tLeaveTypeGradeSettings LTGS
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = LTGS.LeaveTypeId
			WHERE LTGS.OrgId = @rOrgId
				AND LTM.IsCarryForward = 1
		) B ON B.EmployeeGradeId = EJD.EmployeeGradeId AND B.LeaveTypeId = LB.LeaveTypeId
		
		WHERE EM.OrgID = @rOrgId
			AND LB.BatchId = @rFromBatchId

		--SELECT * FROM #TempLeaveBalance 
		SELECT @lCount = COUNT(EmployeeId)
		FROM #TempLeaveBalance

		DECLARE @lBatchName NVARCHAR(100)

		SELECT @lBatchName = Title
		FROM sSetup.tBatchMaster
		WHERE Id = @rFromBatchId

		WHILE (@lCount > 0)
		BEGIN
			-- Leave Balance Entry
			INSERT INTO sHrm.tLeaveBalance (
				EmployeeId
				,LeaveTypeId
				,BalanceLeave
				,BatchId
				,LastYearBalanceLeave
				,CurrentBalanceLeave
				)
			SELECT EmployeeId
				,LeaveTypeId
				,(
					CASE 
						WHEN (PendingNoOfLeave >= MaximumCarryForward)
							THEN NewSettingNoOfLeave + MaximumCarryForward
						WHEN (PendingNoOfLeave <= MaximumCarryForward)
							THEN NewSettingNoOfLeave + PendingNoOfLeave
						ELSE NewSettingNoOfLeave
						END
					) AS NoOfLeave
				,BatchId
				,
				--MaxInMonth,
				(
					CASE 
						WHEN (PendingNoOfLeave >= MaximumCarryForward)
							THEN MaximumCarryForward
						ELSE PendingNoOfLeave
						END
					) AS LastYearLeave
				,NewSettingNoOfLeave AS CurrentYearLeave
			FROM #TempLeaveBalance
			WHERE AutoId = @lCount

			-- Add Leave Balance Log
			INSERT INTO sHrm.tLeaveBalanceLog
			SELECT EmployeeId
				,LeaveTypeId
				,NewSettingNoOfLeave
				,1
				,CASE 
					WHEN (PendingNoOfLeave >= MaximumCarryForward)
						THEN MaximumCarryForward
					WHEN (PendingNoOfLeave <= MaximumCarryForward)
						THEN PendingNoOfLeave
					ELSE 0
					END AS TransactionLeave
				,'Carry Forward leave from (' + @lBatchName + ')'
				,BatchId
				,@rUserId
				,sCommon.fGetDate()
			FROM #TempLeaveBalance
			WHERE AutoId = @lCount

			-- END Leave Balance Entry
			SET @lCount = @lCount - 1
		END

		DROP TABLE #TempLeaveBalance

		SELECT 1 AS Result

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		DROP TABLE #TempLeaveBalance

		ROLLBACK TRANSACTION

		SELECT - 1 AS Result
	END CATCH
END
	-- Change History 
	/* 

Change Date : 19/03/2020
Changes by : Jash Gandhi

Change Discription :
	Added 2 fields in INSERT INTO sHrm.tLeaveBalance Query :- 
	Pending Leave from temporary table(#TempLeaveBalance) will go to LastYearBalanceLeave column and NewSettingNoOfLeave will go into CurrentYearBalanceLeave column
*/
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 nvarchar(50)='', --changes bigint to nvarchar for mantis id :0034855
	 @rToBookCode nvarchar(50)='', --changes bigint to nvarchar for mantis id :0034855
	 --End For Mantis: 31829
	 @rAuthor nvarchar(200)=''         --Mantis - 32621  --add ''(2 single quot) for Mantis: 33633
	
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 @rAuthor = sCommon.fSearchStringGet(@rAuthor)
		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,'') = ''))		
		AND ((BM.Code >= @rFromBookCode) OR (@rFromBookCode='')) AND ((BM.Code <= @rToBookCode) OR (@rToBookCode='')) -- Add New Condition For Mantis Id:0034855
		AND ((BM.Author like @rAuthor) OR (@rAuthor=''))            --Mantis - 32621

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


GO
ALTER PROCEDURE [sProcurement].[pRptStockIssueStudent]
 
	@rId int = 0,
	@rStoreLocationId int = 0,
	@rMainGroupId int=0,
	@rSubGroupId int=0,
	@rItemCode nvarchar(50)='',
	@rItemName nvarchar(50)='',
	@rOrgGroupId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int=0,
	@rStockItemCategoryId int=0,
	@rFromDate date='',
	@rTodate date='',
	@rToDepartmentId int =0,
	@rNumber nvarchar(10)='',
	@rAcademicId bigint = 0,
	@rOrgId smallint = 0,
	@rBatchId int = 0,
	@rClassId int=0,
	@rDivisionId int=0
	
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	Declare @lIDConfigValue nvarchar(50)=''
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId

       SELECT  
			@rBuilder1 AS Builder1,
			SIM.Code AS ItemNumber,
			SIM.Title AS ItemName,		
			SI.IssuedByName,	
			SI.Number, 	
			SI.CreatedDateTime AS IssuedDate,
			ID.IssuedQuantity,
			ID.RequestedQuantity,
			SM.FirstName +' '+SM.MiddleName As StudentName,
			Sm.Code AS StudentCode,
			SG.Code AS ItemSubGroup,
			SG.Id AS ItemSubGroupId,
			OM.DisplayTitle,
			BM.Title AS BatchTitle,
			CM.Title +'-'+ DM.TItle As Class,
			(SELECT ISNULL(SUM(AvailableQuantity),0) FROM sProcurement.tStockBatch SB 
		    WHERE SB.StockItemId = SIM.Id 
		    AND ((SB.StorelocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
			) AS Quantity ,
			A.OrgId,
			A.BatchId,
			ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0') AS WeightedAverageCost,
			@lIDConfigValue AS IdNoLabel,
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)) AS Amount,

			(sFinanceCommon.fNumberToWordsWithDecimal(
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)),1,2,SI.OrgGroupId)
			) AS AmountInWords,
			SI.Remark,--Mantis - 0032620
			SI.TransactionDate AS TransactionDate --Mantis : 0034980
		
		FROM  
			sProcurement.tStockIssue SI		
			INNER JOIN sProcurement.tStockIssueDetail ID ON SI.Id = ID.StockIssueId
			INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
			LEFT JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
			INNER JOIN sStudent.tAcademic A on A.Id=IssueToSourceId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentID
			INNER JOIN sIp.tItemSubGroupMaster SG ON SG.Id=SIM.ItemSubGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			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
		WHERE 
			 ((SI.Id = @rId) OR (@rId=0))
			 AND SI.FromStoreLocationId =@rStoreLocationId
			 AND ((SIM.ItemSubGroupId= @rSubGroupId) OR (@rSubGroupId=0))
			 AND ((SIM.Code = @rItemCode) OR (@rItemCode=''))	
			 AND ((SIM.Title = @rItemName) OR (@rItemName=''))
			 AND ((convert(Date,ISNULL(SI.CreatedDateTime,'')) >= @rFromDate) OR (convert(date,ISNULL(@rFromDate,''))=''))
			 AND ((convert(date,ISNULL(SI.CreatedDateTime,'')) <= @rToDate) OR (convert(date,ISNULL(@rToDate,''))=''))
			 AND SI.OrgGroupId = @rOrgGroupId
			 AND ((SI.ToOrganizationDepartmentId=@rToDepartmentId) OR (@rToDepartmentId=0))
			 AND ((SI.Number like @rNumber) OR  (ISNULL(@rNumber,'')= ''))
			 AND ((SI.IssueToSourceId= @rAcademicId) OR (ISNULL(@rAcademicId,0)=0))
			 AND SI.IssueToSourceTypeId = 2001
			 AND ((A.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			 AND ((A.ClassId =  @rClassId) OR (@rClassId=0)) --mantisid : 0034341
			 AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0)) --mantisid : 0034341
			 --AND ((A.BatchId = @rBatchId) OR (ISNULL(@rBatchId,0) = 0))
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockInwardAdd_New]...';


GO
-- drop procedure [sProcurement].[pStockInwardAdd_New]
ALTER PROCEDURE [sProcurement].[pStockInwardAdd_New]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rStockInwardRequestId			Int=0, 
		@rInwardByName					Nvarchar(100) = '',
		--@rToOrganizationDepartmentId	Int,
		@rToStoreLocationId				Int,
		--@rFirstAidId					Int,
		@rRemark						Nvarchar(300)='',
		@rCreatedUserId					BigInt,
		@rDetail						Nvarchar(Max),
		@rLocationId int,
		@rOrgId int,
		@rVendorId int=0,
		@rInwardDate datetime = null,
		@rCreatedOnDate datetime = null,
		@rBillNoRemark						Nvarchar(300)='' --Added by dhananjay for mantis - 0034876
		--@rOrgId int
	)
AS

SET NOCOUNT ON

BEGIN
--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rToStoreLocationId, @rNextNumber  = @rNumber OUTPUT
Declare @loXML XML
SET @loXML = CAST(@rDetail AS XML)
 
	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1005,
	@rStoreLocationId = @rToStoreLocationId, @rNextNumber  = @rNumber OUTPUT
	
	SET @rNumber = ISNULL(@rNumber, '-300')
	IF @rNumber = '-300'
	BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id 
		RETURN
	END

	
 
	DECLARE @tStockInwardDetailBatch TABLE
	(
		Id						Int IDENTITY(1, 1),
		StockInwardRequestDetailId	Int, 
		StockItemId				Int, 
		StockItemName nvarchar(50),
		ItemBatch Nvarchar(300) NULL,
		ItemExpiryDate nvarchar(20) NULL,	
		InwardQuantity			Decimal(12,2),
		RequestedQuantity		Decimal(12,2),  
		InwardValue 			Decimal(12,2) 
		 
	)	
	INSERT INTO @tStockInwardDetailBatch
	Select 
		 T.c.value('@StockInwardRequestDetailId','int') AS StockInwardRequestDetailId,
            T.c.value('@StockItemId','Int') AS StockItemId,
            T.c.value('@StockItemName','nvarchar(50)') AS StockItemName,
            T.c.value('@ItemBatch','Nvarchar(300)') AS ItemBatch,
            T.c.value('@ItemExpiryDate','nvarchar(20)')   AS ItemExpiryDate,
            T.c.value('@InwardQuantity','Decimal(12,2)') AS InwardQuantity,
            T.c.value('@RequestedQuantity','Decimal(12,2)') AS RequestedQuantity,
            T.c.value('@InwardValue','Decimal(12,2)') AS InwardValue 
			 
	
	FROM 
            @loXML.nodes('/Table/StockInward')T(c)
	
	
	
	DECLARE @lNextNumberStockInward INT
 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockInward',@lNextNumber = @lNextNumberStockInward output
	Declare @lNextNumberStockInwardBatch bigint
  
	INSERT INTO sProcurement.tStockInward
		(
			Id,
			Number,
			StockInwardRequestId, 
			InwardByName,		 
			ToStoreLocationId,			 
			Remark,
			TransactionDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			VendorId
		)
	VALUES
		(
			@lNextNumberStockInward,
			@rNumber,
		   (CASE WHEN @rStockInwardRequestId = 0 THEN NULL ELSE @rStockInwardRequestId END),	 
			@rInwardByName,		 
			@rToStoreLocationId,			 
			@rBillNoRemark,				--Added by dhananjay for mantis - 0034876
			@rInwardDate,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rVendorId
		)


	DECLARE @lIntErrorCode INT, @lIntDoc INT
	EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rDetail	
		
	DECLARE @lCount int,@lIsBatchWise bit,@lbatchId int,@lNextNumberStockBatch int,@lExpiryDate date,
			@lItemId int,@lBatch nvarchar(300),@lInwardQty decimal(12,2),@lInwardValue decimal(12,2),
			@lIdCount int,@lNextNumberStockInwardDetail bigint,@lStockItemName nvarchar(50)
	Select @lCount=Count(*) from  @tStockInwardDetailBatch
	
	 
	While(@lCount>0)
	BEGIN
		  
	    Select @lItemId =StockItemId,@lBatch = [ssetup].[fPortalXMLTagsReplaceReverse](ItemBatch),@lInwardQty=InwardQuantity,@lInwardValue=InwardValue
	    ,@lIdCount=Id,@lExpiryDate =ItemExpiryDate
		,@lStockItemname=[ssetup].[fPortalXMLTagsReplaceReverse](StockItemname)
		from  @tStockInwardDetailBatch WHERE Id = @lcount
		Select @lIsBatchWise=IsBatchWiseTracking from sIp.tStockItemMaster    Where Id = @lItemId   
		
		 
		SET @lbatchId = 0
			
	    if (@lIsBatchWise=1)
		BEGIN
			Select @lbatchId= Id from sProcurement.tStockBatch    
			Where  Number =@lBatch   AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId
		END
		else 
		BEGIN
			Select @lbatchId= Id from sProcurement.tStockBatch    
			Where iSNULl( Number,'') =''  AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId
		END	
		 
		if(ISNULL(@lbatchId,0)=0)
	    BEGIN
			
		 	EXECUTE sCommon.pTableRowIdGet @rOrggroupId, 'sProcurement.tStockBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockBatch output
			INSERT INTO sProcurement.tStockBatch (Id,StoreLocationId,StockItemId,Number,ExpiryDate,AvailableQuantity,ItemRate,CreatedUserId
			,CreatedDateTime,OrgGroupId)
			Select @lNextNumberStockBatch,@rToStoreLocationId,@lItemId,@lBatch,@lExpiryDate ,0,0,@rCreatedUserId,getdate(),@rOrgGroupId
			
			SET @lbatchId = @lNextNumberStockBatch
			
	    End
	
		if(isnull(@lbatchId,0)>0)
		BEGIN
			 
			if Exists(Select Id from sProcurement.tStockInwardDetail   
			where  StockInwardId = @lNextNumberStockInward  and  StockItemId = @lItemId  )
			BEGIN
					 
					Select @lNextNumberStockInwardDetail= Id from  sProcurement.tStockInwardDetail
					Where  StockInwardId = @lNextNumberStockInward AND StockIteMid =@lItemId
			END
			ELSE
			BEGIN
			
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardDetail output
				INSERT INTO sProcurement.tStockInwardDetail
				(	
					Id,StockInwardId,StockItemId,RequestedQuantity,InwardQuantity, 
					Remark,StockInwardRequestDetailId,OrgGroupId,InwardValue
				)
				SELECT @lNextNumberStockInwardDetail ,@lNextNumberStockInward,StockItemId,RequestedQuantity,
					    InwardQuantity,@rRemark,StockInwardRequestDetailId,@rOrgGroupId,@lInwardValue
					   from @tStockInwardDetailBatch where Id=@lcount
			END
			
			
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardBatch output
							
							INsert into sProcurement.tStockInwardBatch
							(Id,StockInwardDetailId,Quantity,StockBatchId,OrgGroupId)
							Select @lNextNumberStockInwardBatch,@lNextNumberStockInwardDetail,InwardQuantity,@lbatchId,@rOrgGroupID
							from @tStockInwardDetailBatch where Id=@lcount
							
							
							Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=1010,@rSourceId=@lNextNumberStockInwardBatch,
												@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lInwardQty ,@rValue=@lInwardValue,@rIsReceipt=1,
												@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rToStoreLocationId ,@rLocationId=@rLocationId
												,@rItemBatchId = @lbatchId,@rItemName = @lStockItemname,@rOrgId=@rOrgId


			END
			set @lcount =@lcount-1
	END
	 
	 SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockInward AS Id 
	 
END
GO
PRINT N'Altering Procedure [sSecurity].[pAppPermissionGet]...';


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

	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard 
			20097, -- View Query
			30249, -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786, --Online Learning 
			30787, --Online learning Student View
			30815, --Consolidate - Fee Status
			30813, --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,   -- Consolidate - Admission Inquiry Summary,
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App 
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,   -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,   -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008,  -- Is CS Entry View
			31009,  -- Is Activity Entry View
			20556,  -- Hostel Student Gate Pass
			31005,	-- My Digital Form
			20183, -- View Photo
			30580, -- Employee Attendance Summary
			20056, -- Event Schedule
			31033, --My Proxy
			20687, --  Employee Attendance
			31043 --  Pending Fee
			,30943 -- My Approval Request
			,30739 -- Behaviour Entry User Wise
			,31048 -- Add Gallery
			,31175 -- View Gallery
			,31179 -- Leave Hierarchy Listing
			,30331 -- My Exam Schedule
			,31182 -- My Admit Card
			,30600 -- MIS Consolidate DashBoard
			,31193 -- Consolidate - Admission Inquiry And Admission Form
			,31194 -- Consolidate - Staff Count
			,31195 -- Consolidate - Charge Receipt
			,31244 -- Lesson Plan Complete
			,20776 -- Front office --Student Gate Pass
			,31305 --Consolidate - Staff Biometric Attendance
			,31314 -- Event Attendance Student Wise
			,31323 -- Poll Result
			,31383 -- Consolidate - Student Summary
			,20999 --Attendance Register - mantisid : 34918
			)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard
			20097, -- View Query
			30249,  -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786 , --Online Learning 
			30787,  --Online learning Student View
			30815,  --Consolidate - Fee Status
			30813,  --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,  -- Consolidate - Admission Inquiry Summary
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,    -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance			
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,    -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008,  -- Is CS Entry View
			31009,   -- Is Activity Entry View
			20556,   -- Hostel Student Gate Pass
			31005,	-- My Digital Form
			20183, -- View Photo
			30580, -- Employee Attendance Summary
			20056, -- Event Schedule
			31033, --My Proxy
			20687, --  Employee Attendance
			31043 --  Pending Fee
			,30943 -- My Approval Request
			,30739 -- Behaviour Entry User Wise
			,31048 -- Add Gallery
			,31175 -- View Gallery
			,31179 -- Leave Hierarchy Listing
			,30331 -- My Exam Schedule
			,31182 -- My Admit Card
			,30600 -- MIS Consolidate DashBoard
			,31193 -- Consolidate - Admission Inquiry And Admission Form
			,31194 -- Consolidate - Staff Count
			,31195 -- Consolidate - Charge Receipt
			,31244 -- Lesson Plan Complete
			,20776 -- Front office --Student Gate Pass
			,31305 --Consolidate - Staff Biometric Attendance
			,31314 -- Event Attendance Student Wise
			,31323 -- Poll Result
			,31383 -- Consolidate - Student Summary
			,20999 --Attendance Register - mantisid : 34918
			) 
		) TP 
		GROUP BY TP.TaskId
	END
END
GO
PRINT N'Altering Procedure [sStudent].[pGetDropDownLists]...';


GO
 
ALTER proc [sStudent].[pGetDropDownLists]
@rBatchId int =0,
@rOrgId int =0,
@rUserId bigint,
@rDepartmentId int =0,
@rOrgGroupBatchId int=0,
@rOrgGroupId int=0,
@rSubjectId int=0
as
begin

	DECLARE @lGenderType nvarchar(20) = ''
	SELECT @lGenderType =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 557 AND SourceTypeId = 1016 AND SourceId = @rOrgId

	declare @lStatusRes nvarchar(max)='',@lClassRes Nvarchar(max)='',@lEnrollmentStatusRes nvarchar(max)=''
	declare @lDepartmentRes nvarchar(max)='',@lDivisionRes Nvarchar(max)='',@lAvailableRes nvarchar(max)=''
	declare @lSubjectRes nvarchar(max)=''
	declare @lReportList nvarchar(max)='',@lExamRes nvarchar(max)='',@lGeneralExamRes nvarchar(max)='',@lcastdropdown nvarchar(max)=''
	declare @lExamReportList nvarchar(max)=''
	declare @lclassdropdown nvarchar(max)='',@lStatusdropdown nvarchar(max)='',@lGenderdropdown nvarchar(max)='',@lReligiondropdown nvarchar(max)=''
	declare @lCitydropdown nvarchar(max)='',@lAreadropdown nvarchar(max)='',@lNationalitydropdown nvarchar(max)='',@lTranspotrmodedropdown nvarchar(max)='',@lbusrouedropdown nvarchar(max)=''
	declare @lbusrotedestinationdrop nvarchar(max)='',@lblooddropdown nvarchar(max)='',@lhousedropdown nvarchar(max)='',@lmothertoungedropdown nvarchar(max)='',@lpriviousschooldropdown nvarchar(max)=''
	declare @lfatherqadrop nvarchar(max)='',@lmotherqadropdown nvarchar(max)='',@lfatherocdropdown nvarchar(max)='',@lmotherocdropdown nvarchar(max)='',@lfeescategorydropdown nvarchar(max)=''
	declare @lCustomtagdrop nvarchar(max)='',@lcustomgroupdropdown nvarchar(max)='',@lclubdropdown nvarchar(max)='',@lhosteldropdown nvarchar(max)='',@lstudentgroupdropdown nvarchar(max)=''
	declare @lstudentothergroupdropdown nvarchar(max)='',@lExaminationtypedropdown nvarchar(max)=''
	declare @lSavedReport nvarchar(max)='',@lSavedReport1 nvarchar(max)=''
	declare @lRecordtagdrop nvarchar(max)=''
	declare @lOrgGroupRes nvarchar(max)='',@lOrganizationRes nvarchar(max)='',@lBatchRes nvarchar(max)=''

	
	select @lDivisionRes = @lDivisionRes + '<option value="0"> -- ALL -- </option>'
	
	select @lStatusRes = @lStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lStatusRes = @lStatusRes + '<option value="1">Active</option>'
	select @lStatusRes = @lStatusRes + '<option value="2">InActive</option>'
	select @lStatusRes = @lStatusRes + '<option value="3">Left</option>'
	
	select @lOrgGroupRes = @lOrgGroupRes + '<option value="0"> -- Select -- </option>'
	select @lOrgGroupRes = @lOrgGroupRes + '<option ' + case when Id = @rOrgGroupBatchId then 'selected="selected"' else '' end + ' value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sSetup.tOrgGroupBatchMaster where IsObsolete = 0 AND IsHistory = 0 AND OrgGroupId = @rOrgGroupId
	order by OrderIndex
	
	select @lOrganizationRes = @lOrganizationRes + '<option value="0"> -- ALL -- </option>'
	select @lOrganizationRes = @lOrganizationRes + '<option ' + case when Id = @rOrgId then 'selected="selected"' else '' end + ' value="' + convert(varchar,Id) + '">' + DisplayTitle + '</option>'
	from sSetup.tOrganizationMaster where IsObsolete = 0 AND OrgGroupId = @rOrgGroupId
	order by OrderIndex

	select @lBatchRes = @lBatchRes + '<option value="0"> -- ALL -- </option>'

	select @lClassRes = @lClassRes + '<option value="0"> -- ALL -- </option>'
	select @lClassRes = @lClassRes + '<option value="' + convert(varchar,ClassId) + '">' + ClassName + '</option>'
	from sSetup.vBatchClass where IsObsolete = 0 and BatchId = @rBatchId order by OrderIndex
	
	select @lEnrollmentStatusRes = @lEnrollmentStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lEnrollmentStatusRes = @lEnrollmentStatusRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sStudent.tEnrollmentStatusMaster where IsObsolete = 0 order by Title
	
	select @lDepartmentRes = @lDepartmentRes + '<option value="0"> -- ALL -- </option>'
	select @lDepartmentRes = @lDepartmentRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sSetup.vDepartment where IsObsolete = 0 AND OrgId = @rOrgId and UserId = @rUserId
	and (Id = @rDepartmentId or @rDepartmentId = 0) order by Title

	select @lSubjectRes = @lSubjectRes + '<option value="0"> -- ALL -- </option>'
	select @lSubjectRes = @lSubjectRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sSetup.tSubjectMaster where IsObsolete = 0 AND @rOrgId = OrgId 
	and (Id = @rSubjectId or @rSubjectId = 0) order by Title
	
	select @lAvailableRes = @lAvailableRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sStudent' AND TABLE_NAME='vStudentColumnName' AND COLUMN_NAME <> 'GR No'
	
	
	DECLARE @lAvailableStudentColumns nvarchar(max)=''
	 DECLARE @lAvailableStudentCustomRes nvarchar(max)=''
	 Declare @Title as nvarchar(max)


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

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

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

					select @lGenderdropdown = @lGenderdropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
					from sCommon.tGenderMaster where IsObsolete = 0
																		AND Id = CASE						-- Add Id condition MantisId : 0034447
																		WHEN @lGenderType = 'Male' THEN 1
																		WHEN @lGenderType = 'Female' THEN 2
																		ELSE Id
					END

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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


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

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

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

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

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

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

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

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


GO
ALTER PROCEDURE [sStudent].[pIDNoGenerationGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rRecordStatusId smallint=0,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rFromIdNo nvarchar(50)='',
	 @rToIdNo nvarchar(50)='',
	 @rStatus smallint=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			SO.AcademicId,
			SO.StudentId,
			SO.GenderId,
			SO.ClassId,
			SO.DivisionId,
			SO.RecordStatusId,
			SO.RollNo AS RollNo,
			SO.Code,
			SO.Number,
			SO.FirstName,
			SO.LastName,
			[sStudent].[fStudentNameGet](SO.FirstName , SO.MiddleName, So.LastName,OM.StudentNameFormatId ) AS Name,
			SO.ClassName+'-'+SO.DivisionName AS ClassDivisionName,
			Sm.Title,
			SA.AdmissionDate,
			ISNULL(SS.DateOfBirth,'') AS DateOfBirth --Added by Dhananjay for Mantis - 0034801
			
  FROM 
			[sStudent].[vStudentOther]  SO
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SO.StudentId
			INNER JOIN sSetup.tOrganizationMaster OM
			ON SO.OrgId = OM.Id
			INNER JOIN sCommon.tStatusMaster SM ON Sm.Id=SO.RecordStatusId
			LEFT JOIN sStudent.tStudentOther SS ON SS.StudentId = SO.StudentId --Added by Dhananjay for Mantis - 0034801
		
  WHERE 
			(SO.ClassId=@rClassId OR @rClassId=0)
			AND (SO.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND (SO.RecordStatusId=@rRecordStatusId OR @rRecordStatusId=0)
			AND SO.BatchId=@rBatchId
			AND SO.OrgId=@rOrgId 
			--AND (SO.StudentId >= @rFromIdNo OR @rFromIdNo =0) AND (SO.StudentId <= @rToIdNo OR @rToIdNo =0)
			AND ((SO.Code >= @rFromIdNo) OR (@rFromIdNo='')) AND ((SO.Code <= @rToIdNo) OR (@rToIdNo=''))
			AND((SO.statusId = @rStatus)OR(@rStatus=0))
			order by SO.ClassId,SO.DivisionId,SO.RollNo
			
			
END
GO
PRINT N'Altering Procedure [sStudent].[pRptNewAdmissionStrengthSummaryGet]...';


GO

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

BEGIN 
  DECLARE @lCount Int
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			A.ClassId,
			A.DivisionId,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			DM.OrderIndex AS DivisionOrder,
			Cm.OrderINdex AS ClassOrderIndex  ,
		    ISNUll(AR.SourceId,0) AS HostelStudent,
			ISNUll(RT.SourceId,0) AS TransportStudent,
			A.StudentId,
			ISNULL(SO.GenderId,0) AS GenderId	--Added by dhananjay for mantis id - 0034982

			


			FROM 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			LEFT JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=A.AdmissionCategoryId
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=A.StudentId AND AR.SourceTypeId=2003 
			--AND  ((AR.OrggroupBatchID=@rOrggroupBatchID) OR (@rOrggroupBatchID=0))
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 --AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			) RT
			ON RT.SourceId = A.StudentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
    
	WHERE 
		A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		--AND SM.StatusId = 1
		AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		--AND ((SA.LeftDate > @rAsOnDate) OR (SA.LeftDate Is null AND SM.StatusId = 1))
		AND SA.AdmissionDate BETWEEN @rFromDate AND @rToDate
		
	   END
GO
PRINT N'Altering Procedure [sStudent].[pStudentBulkImagesAdd]...';


GO

ALTER PROCEDURE [sStudent].[pStudentBulkImagesAdd]
	 
	@rNumber bigint,
	@rCode nvarchar(20),
	@rStudentPhoto varbinary(max),
	@rOrgId smallint,
	@rPhotoType nvarchar(50),
	@rOriginalStudentPhoto varbinary(max)
	--@rStudentPhotoSize decimal(12,2)= 0
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DECLARE @lStudentId bigint
	
	SELECT @lStudentId=Id FROM sStudent.tStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId
	
	IF(ISNULL(@lStudentId,'') = '')
	BEGIN
		SELECT 1 AS Result
		RETURN
	END
	
	IF NOT EXISTS(SELECT StudentId FROM sStudent.tStudentImages WHERE StudentId=@lStudentId)
	BEGIN 
	INSERT INTO sStudent.tStudentImages
		(
			StudentId,
			StudentPhoto
		)
	VALUES
		(
			@lStudentId,
			NULL
		)		             
	END	 
	 
	 
	 IF @rPhotoType = 'TempStudentPhotos'
	 BEGIN
	  UPDATE sStudent.tStudentImages  SET StudentPhoto=@rStudentPhoto,OriginalStudentPhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId
	 END 
	 ELSE IF @rPhotoType = 'TempStudentFatherPhotos'
	 BEGIN
	  UPDATE sStudent.tStudentImages  SET FatherPhoto=@rStudentPhoto,OriginalFatherPhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId	 	 
	 END 
	 ELSE IF @rPhotoType = 'TempStudentMotherPhotos' 
	 BEGIN
	  UPDATE sStudent.tStudentImages  SET MotherPhoto=@rStudentPhoto,OriginalMotherPhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId
	 END
	 ELSE IF @rPhotoType = 'TempStudentRelativePhotos' 
	 BEGIN
	 UPDATE sStudent.tStudentImages  SET RelativePhoto=@rStudentPhoto,OriginalRelativePhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId	 
	 END
	 
	 SELECT 1 AS Result
	
	
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentDataModify]...';


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

DECLARE @loDoc INT

--BEGIN TRY
--BEGIN TRANSACTION

        --CategoryId
        --Communication = 1,
        --Other = 2,
        --Admission = 3,
        --Family = 4,
        --Health = 5,
        --AcademicDetail = 6,
        --General = 7
        --CustomDetail = 8
        --Sibling = 9

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup' 
			 OR @rSubCategoryField = 'TransportMode' OR @rSubCategoryField = 'House'
			OR @rSubCategoryField = 'Quota' 
			OR @rSubCategoryField = 'Nationality' OR @rSubCategoryField = 'AdmissionStandard' OR  @rSubCategoryField = 'AdmissionCategory' 
			OR @rSubCategoryField = 'AdmissionQuota'
			OR @rSubCategoryField = 'Tribe')
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	
	IF(	@rSubCategoryField = 'CasteCategory' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast') + 'Id'
	END
	
	IF(	@rSubCategoryField = 'FamilyCaste' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')  
	END
	
	IF(	@rSubCategoryField = 'StudentGroup' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'StudentGroup','StudentGroupId')  
	END
	IF(	@rSubCategoryField = 'StudentOtherGroup' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'StudentOtherGroup','StudentOtherGroupId')  
	END
	
	IF(@rSubCategoryField = 'FeeCategory' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'FeeCategory','AdmissionCategory') + 'Id'
	END

	IF(@rSubCategoryField = 'FatherAnnualIncome' )													-- #Start Mantis Id : 0029214
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'FatherAnnualIncome','FatherIncome')
	END
	IF(@rSubCategoryField = 'MotherAnnualIncome' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'MotherAnnualIncome','MotherIncome')
	END																								
	IF(@rSubCategoryField = 'RelativeAnnualIncome' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'RelativeAnnualIncome','RelativeIncome')
	END																								-- #End Mantis Id : 0029214

	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)  
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication) 
		
		set @sql='INSERT INTO sStudent.tStudentCommunication 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentCommunication set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentCommunication SC 
					INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentOther) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
			set @sql='INSERT INTO sStudent.tStudentOther 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sStudent.tStudentOther SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			set @sql='INSERT INTO sStudent.tStudentOther 
						(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
						SELECT
							LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
						FROM
							ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	    
	Else IF(@rCategoryId= 3)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		set @sql='UPDATE sStudent.tStudentAdmission set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentAdmission SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'AdmissionDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdmission SET '+@rSubCategoryField+' = null WHERE AdmissionDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'PreviousLCDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdmission SET '+@rSubCategoryField+' = null WHERE PreviousLCDate=''1900-01-01'''
			Exec sp_executesql @sql
		END

		IF(@rSubCategoryField = 'InActiveDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdmission SET '+@rSubCategoryField+' = null WHERE InActiveDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
 
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
		set @sql='INSERT INTO sStudent.tStudentFamily 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentFamily set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentFamily SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'FatherDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE FatherDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'MotherDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE MotherDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END

		IF(@rSubCategoryField = 'RelativeDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE RelativeDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END		

		/****Change for mantis 29443*****/
		IF(@rSubCategoryField = 'MarriageAnniversaryDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE MarriageAnniversaryDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		/****Change for mantis 29443*****/		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
    Else IF(@rCategoryId= 5)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentHealth) 
		
		set @sql='INSERT INTO sStudent.tStudentHealth 
					(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentHealth set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentHealth SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END		 
	 
	 Else IF(@rCategoryId= 6)
	    BEGIN
		insert into ListofData
		select E.Id,0,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT AcademicId FROM sStudent.tAcademicDetail) 
		
		set @sql='INSERT INTO sStudent.tAcademicDetail 
					(AcademicId,'+@rSubCategoryField+')
					SELECT
						LD.Id,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tAcademicDetail set '+@rSubCategoryField+' = LD.SubCategory
					from sStudent.tAcademicDetail AD 
					INNER JOIN ListofData LD ON AD.AcademicId=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'BatchAdmissionDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tAcademicDetail SET '+@rSubCategoryField+' = NULL WHERE BatchAdmissionDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	

	Else IF(@rCategoryId= 7)
	     BEGIN
		
	    IF(@rSubCategoryField NOT IN ('AdmissionCategoryId','FeesRemark'))
		BEGIN
			insert into ListofData
			select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
			from
			(
					SELECT StudentId,SubCategory,UpdatedUserId FROM
					OPENXML (@loDoc, '/Students/Students', 2)
					WITH (
							StudentId BIGINT, 
							SubCategory nvarchar(100),
							UpdatedUserId bigint)	
							)E 	
			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
			
			--set @sql='INSERT INTO sStudent.tStudentMaster 
			--			(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
			--			SELECT
			--				LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
			--			FROM
			--				ListofData LD WHERE LD.IsExist=1'				
			--Exec sp_executesql @sql
			
			set @sql='UPDATE sStudent.tStudentMaster set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentMaster SA 
						INNER JOIN ListofData LD ON SA.Id=LD.StudentId AND IsExist=0'
			
			Exec sp_executesql @sql
			Drop Table ListofData
		END
		IF(@rSubCategoryField IN ('AdmissionCategoryId','FeesRemark'))
		BEGIN
			insert into ListofData
			select E.Id,0,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
			from
			(
					SELECT Id,SubCategory,UpdatedUserId FROM
					OPENXML (@loDoc, '/Students/Students', 2)
					WITH (
							Id BIGINT, 
							SubCategory nvarchar(100),
							UpdatedUserId bigint)	
							)E 
							
			set @sql='UPDATE sStudent.tAcademic set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tAcademic A 
						INNER JOIN ListofData LD ON A.Id=LD.Id AND IsExist=0'
		
			Exec sp_executesql @sql

			IF(@rSubCategoryField IN ('AdmissionCategoryId'))
			BEGIN
				set @sql='UPDATE sStudent.tStudentMaster set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentMaster SM
						INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
						INNER JOIN ListofData LD ON A.Id=LD.Id AND IsExist=0'
		
				Exec sp_executesql @sql
			END
			Drop Table ListofData
		
		END
		
			 SELECT 1 AS StatusCode
	    END			 
	 
	 
	 Else IF(@rCategoryId= 8)
	     BEGIN
	     
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 

		set @sql='INSERT INTO sStudent.tStudentAdditional
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentAdditional set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentAdditional SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
					
		Exec sp_executesql @sql
					
		IF(@rSubCategoryField = 'PassportIssueDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdditional SET '+@rSubCategoryField+' = null WHERE PassportIssueDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'PassportExpiryDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdditional SET '+@rSubCategoryField+' = null WHERE PassportExpiryDate=''1900-01-01'''
			Exec sp_executesql @sql
		END						
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	     
	 Else IF(@rCategoryId= 9)
	    BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(200)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
		set @sql='INSERT INTO sStudent.tStudentSibling
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentSibling set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentSibling SS 
					INNER JOIN ListofData LD ON SS.StudentId=LD.StudentId AND IsExist=0'
					
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
GO
PRINT N'Altering Procedure [sStudent].[pUploadStudentPhotoClassWise]...';


GO

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

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
			ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
			ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
			ISNULL(SI.QRCode, CONVERT(VARBINARY(MAX),0)) AS QRCode
			--ISNULL(SI.StudentPhotoSize,0) AS StudentPhotoSize
			
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
ORDER BY CASE WHEN @rOrderByTypeId = 1 then SA.RollNo END,
		 CASE WHEN @rOrderByTypeId = 2 then (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0, 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code END) END,
		 SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
			ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
			ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
			ISNULL(SI.QRCode, CONVERT(VARBINARY(MAX),0)) AS QRCode
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)	
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

ORDER BY CASE WHEN @rOrderByTypeId = 1 then SA.RollNo END,
		 CASE WHEN @rOrderByTypeId = 2 then (CASE ISNUMERIC(SA.Code) WHEN 1 THEN REPLICATE(0, 100 - LEN(SA.Code)) + SA.Code ELSE SA.Code END) END,
		 SA.ClassId,SA.DivisionId,SA.RollNo
END
  
	
END
GO
PRINT N'Altering Procedure [sTally].[pReceiptTallyPostingAdd]...';


GO
ALTER PROCEDURE [sTally].[pReceiptTallyPostingAdd]	 
      @rXmlDoc nvarchar(MAX),     
      @rReceiptId Int,
      @rOrgGroupBatchId Int,
      @rVoucherNumber Int    
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
		
	BEGIN TRY
	 BEGIN TRANSACTION	
		
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	
			
		
	
	UPDATE sTally.tReceiptPosting
	SET
		TransactionDate=A1.ReceiptDate,
		ReceiptBookId=@rReceiptId,
		StudentId=A1.FeeId,
		OrgGroupBatchId=@rOrgGroupBatchId,
		PayTypeId=A1.PayTypeId,		
		Amount = A1.Amount,
		Narration = A1.Narration
	FROM
	(
		SELECT	
			FeeId,
			PayTypeId,
			Amount,
			Narration,
			ReceiptDate			
			FROM OPENXML (@intDoc, '/Table/ReceiptTallyPosting', 1)
			WITH
			(
				FeeId bigint '@FeeId',
				PayTypeId int '@PayTypeId',
				Amount decimal(12,2) '@Amount',
				Narration nvarchar(max) '@Narration',
				ReceiptDate Date '@ReceiptDate'	
			))A1 INNER JOIN sTally.tReceiptPosting RP ON RP.StudentId = A1.FeeId AND RP.OrgGroupBatchId=@rOrgGroupBatchId
			AND RP.ReceiptBookId=@rReceiptId 
			AND RP.TransactionDate= A1.ReceiptDate --AND RP.Narration = A1.Narration
	
	

	INSERT INTO sTally.tReceiptPosting
		(
		TransactionDate,
		ReceiptBookId,
		FeeId,
		StudentId,
		OrgGroupBatchId,
		PayTypeId,		
		VoucherNumber,
		Amount,
		Narration
		)
	SELECT
		A.ReceiptDate,
		@rReceiptId,
		0,
		A.FeeId,
		@rOrgGroupBatchId,
		A.PayTypeId,
		@rVoucherNumber  + ROW_NUMBER() OVER(ORDER BY ReceiptBookId),
		A.Amount,
		A.Narration
		
	FROM OPENXML (@intDoc, '/Table/ReceiptTallyPosting', 1)
	WITH
	(
		FeeId bigint '@FeeId',
		PayTypeId int '@PayTypeId',
		Amount decimal(12,2) '@Amount',
		Narration nvarchar(max) '@Narration',
		ReceiptDate Date '@ReceiptDate'			
	)A LEFT JOIN sTally.tReceiptPosting RP ON RP.StudentId = A.FeeId AND RP.OrgGroupBatchId=@rOrgGroupBatchId
	AND RP.ReceiptBookId=@rReceiptId 
	AND RP.TransactionDate= A.ReceiptDate --AND RP.Narration = A.Narration
	WHERE RP.StudentId IS NULL
	
	SELECT 101 AS RESULT
	
	COMMIT TRANSACTION		
	END TRY

	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sTimetable].[pRptDivisionTimeTableGet]...';


GO

ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

	  --@rBuilder1 nvarchar(max)='',
	  --@rBuilder2 nvarchar(max)='', 
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rEmployeeId bigint,
	  @rTimeTableSchemaId int,
	  @rReportId int=0,
	  @rDate Date='',
	  @rOrgId int=0,
	  @rDisplayWithBreak bit = 1, -- Mantis : 0029066
	  @rDisplayWithTeacher bit = 1 
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

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

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	0 As IsPresent,
	'' As WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	'' as DivisionIncharge,
	IsBreak,
	IsBreakBefore,
	EmployeeSubject,
	 ClassSubject,
	'' AS EmployeeSNSubject,
	ISNULL(Convert(smallint,(select Isnull(max(cast(IsBreak as smallint)),0)*2+ISNULL(max(cast(IsBreakBefore as smallint)),0)*1
			From sTimetable.tTimeTableTime
			where TimeTableSchemaId=@rTimeTableSchemaId AND LectureNumber=A.LactureNumber
			Group by TimeTableSchemaId,LectureNumber)),0) AS HideBreak ,
	'' AS SubjectEmployeeSN,			--add for 27992 mantis
	'' AS SubjectName, --#Start Mantis : 0029066
	Convert(bit,0) AS DisplayWithBreak,
	Convert(bit,0) AS DisplayWithTeacher, --#End Mantis : 0029066
	'' AS SubjectCodeEmployeeSN,           -- add for mantis : 0034746
	'' AS ClassDivisionSubjectTeacher --Added by dhananjay for mantis - 0035030
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--'' AS TimeTableDetail,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,

	--GetBreak
	CASE WHEN 
	(SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1) = 1 
	THEN (SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1)
	ELSE ISNULL(TT.IsBreak,0) END AS IsBreak,

	--GetBreakBefore
	CASE WHEN 
	(SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1) = 1 
	THEN (SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1)
	ELSE ISNULL(TT.IsBreakBefore,0) END AS IsBreakBefore,
	
	STUFF((
			SELECT ', ' +  ISNULL(ISNULL(Em1.FirstName +'  '+Em1.LastName,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '') EmployeeSubject,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +' - '+SM1.Title,'')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject

	FROM 
	sTimetable.tTimeTable TT	
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND TT.EmployeeId <> 0
	  
	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	'' AS TimeTableDetail,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	0 AS IsBreak,
	0 AS IsBreakBefore,
	STUFF((
			SELECT ', ' +  ISNULL(ISNULL(Em1.FirstName +'  '+Em1.LastName,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '') EmployeeSubject ,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +' - '+SM1.Title,'')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject

	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 

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

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

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	ISNULL(A.ClassDivisionName,'')AS ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	A.IsPresent,
	'' As WeekOffs,
	0 As FromTime,
	0 As ToTime,
	'' as DivisionIncharge,
	A.EmployeeSubject,
	'' as ClassSubject,
	'' AS SubjectEmployeeSN,		--add for 27992 mantis
	'' AS SubjectName, --#Start Mantis : 0029066
	Convert(bit,0) AS DisplayWithBreak,
	Convert(bit,0) AS DisplayWithTeacher, --#End Mantis : 0029066
	'' AS SubjectCodeEmployeeSN,           -- add for mantis : 0034746
    '' AS ClassDivisionSubjectTeacher--Added by dhananjay for mantis - 0035030
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EAR.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	'' AS TimeTableDetail,
	ISNULL(EAR.IsPresent,0) AS IsPresent,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' + case when ISNULL(EAR1.IsPresent,0)=0 then   ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)),'') +' <br><b> '+SM1.Title+'</b>','') else '' end
			FROM sTimetable.tTimeTable T1 
			Left join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			left JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR1 ON EAR1.EmployeeId = Em1.Id
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			AND (EAR1.AttendanceDate = @rDate OR @rDate = '')
			AND (T1.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, '')) EmployeeSubject
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	--ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber),'') AS TimeTableDetail
	FROM 
	sTimetable.tTimeTable TT	 
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
	RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

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

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

	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TTD.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(EAR.IsPresent,'') As IsPresent,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT   ',<br>' +case when ISNULL(EAR1.IsPresent,0)=0 then ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)),'') +' <br><b> '+SM1.Title+'</b>','') else '' end
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR1 ON EAR1.EmployeeId = Em1.Id
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			AND (EAR1.AttendanceDate = @rDate OR @rDate = '')
			AND (T1.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, '')) EmployeeSubject
	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = Em.OrgID
	LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

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

	END
ELSE IF(@rReportId = 30925) --TeacherTimeTable_2
   BEGIN
   SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,1) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	DivisionIncharge,
	'' AS EmployeeSubject,
	ClassSubject,
	'' AS SubjectEmployeeSN,		--add for 27992 mantis
	'' AS SubjectName, --#Start Mantis : 0029066
	Convert(bit,0) AS DisplayWithBreak,
	Convert(bit,0) AS DisplayWithTeacher, --#End Mantis : 0029066
	'' AS SubjectCodeEmployeeSN,           -- add for mantis : 0034746
	'' AS ClassDivisionSubjectTeacher --Added by dhananjay for mantis - 0035030
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	[sHrm].[fEmployeeNameGet](ISNULL(EM.FirstName,'') , ISNULL(EM.MiddleName,''), ISNULL(EM.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(EM.LastName+' '+EM.FirstName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,'') As FromTime,
	ISNULL(TTM.ToTime,'') As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	(SELECT ISNULL(EM.FirstName+' '+EM.LastName,'') FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tDivisionMaster DIE ON DIE.InchargeEmployeeId = EM.Id  WHERE DIE.Id = DV.Id) as DivisionIncharge,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName +'<br><b>'+SM1.Title+'</b>','')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, ''))  ClassSubject
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DV.OrgId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	  AND (OM.Id = @rOrgId OR @rOrgId = 0)
	  --AND (Em.OrgId = @rOrgId OR @rOrgId = 0)
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
   END
 ELSE
 BEGIN
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,1) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime,
	DivisionIncharge,
	IsBreak,
	IsBreakBefore,
	EmployeeSubject,
	ClassSubject,
	EmployeeSNSubject,
	ISNULL(Convert(smallint,(select Isnull(max(cast(IsBreak as smallint)),0)*2+ISNULL(max(cast(IsBreakBefore as smallint)),0)*1
			From sTimetable.tTimeTableTime
			where TimeTableSchemaId=@rTimeTableSchemaId AND LectureNumber=A.LactureNumber
			Group by TimeTableSchemaId,LectureNumber)),0) AS HideBreak,
	A.SubjectEmployeeSN,			--add for 27992 mantis
	A.SubjectName, -- #Start Mantis : 0029066
	@rDisplayWithBreak AS DisplayWithBreak,
	@rDisplayWithTeacher AS DisplayWithTeacher, -- #End Mantis : 0029066
	A.SubjectCodeEmployeeSN,   -- add for mantis : 0034746
	ClassDivisionSubjectTeacher ----Added by dhananjay for mantis - 0035030

FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TT.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	[sHrm].[fEmployeeNameGet](ISNULL(Em.FirstName,'') , ISNULL(Em.MiddleName,''), ISNULL(Em.LastName,''),ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
	--ISNULL(EM.LastName+' '+EM.FirstName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,'') As FromTime,
	ISNULL(TTM.ToTime,'') As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime,
	(SELECT ISNULL(EM.FirstName+' '+EM.LastName,'') FROM sHrm.tEmployeeMaster EM INNER JOIN sSetup.tDivisionMaster DIE ON DIE.InchargeEmployeeId = EM.Id  WHERE DIE.Id = DV.Id) as DivisionIncharge,
		
	--GetBreak
	CASE WHEN 
	(SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1) = 1 
	THEN (SELECT ISNULL(IsBreak,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreak = 1)
	ELSE ISNULL(TT.IsBreak,0) END AS IsBreak,

	--GetBreakBefore
	CASE WHEN 
	(SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1) = 1 
	THEN (SELECT ISNULL(IsBreakBefore,0) FROM sTimetable.tTimeTableTime WHERE TimeTableSchemaId = TT.TimeTableSchemaId 
	AND DayId = TT.DayId AND DivisionId = TT.DivisionId AND LectureNumber = TT.LectureNumber AND IsBreakBefore = 1)
	ELSE ISNULL(TT.IsBreakBefore,0) END AS IsBreakBefore,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' +  ISNULL(ISNULL([sHrm].[fEmployeeNameGet](ISNULL(Em1.FirstName,'') , ISNULL(Em1.MiddleName,''), ISNULL(Em1.LastName,''),ISNULL(OM1.EmployeeNameFormatId,1)) ,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, ''))  EmployeeSubject,
	[sCommon].[fXMLTagsReplaceReverse](STUFF((
		SELECT ',<br>' +  ISNULL(VBCD1.ClassDivisionName+'<br><b>' +SM1.Code+'</b>','')
				FROM sTimetable.tTimeTable T1 
				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
					INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId=T1.DivisionId
				where T1.EmployeeId=TT.EmployeeId 
				AND TT.LectureNumber=T1.LectureNumber 
				AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
				--AND timetableid in ()
				FOR XML PATH('')
				), 1, 11, '')) ClassSubject,
	STUFF((
			SELECT ', ' +  ISNULL(ISNULL(Em1.ShortName,'') +' - '+SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '') EmployeeSNSubject,

	[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ', ' +  ISNULL('<b>'+SM1.Title+'</b><br/>'+ISNULL(Em1.ShortName,''),'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '')) SubjectEmployeeSN,			--add for 27992 mantis
			[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ',<br>' +  ISNULL(SM1.Title,'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			LEFT JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = Em1.OrgID
			where T1.DivisionId=TT.DivisionId 
			AND T1.LectureNumber=TT.LectureNumber 
			AND T1.DayId=TT.DayId and T1.TimeTableSchemaId=TT.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 11, ''))  SubjectName, -- #Mantis : 0029066
			[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ', ' +  ISNULL('<b>'+SM1.Code+'</b><br/>'+ISNULL(Em1.ShortName,''),'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '')) SubjectCodeEmployeeSN	, --add for mantis : 0034746
			
			--Added by dhananjay for mantis - 0035030
			[sCommon].[fXMLTagsReplaceReverse](STUFF((
			SELECT ', ' +  ISNULL('<b>'+Em1.ShortName+'</b><br/>'+ISNULL(SM1.Title,''),'')
			FROM sTimetable.tTimeTable T1 
			inner join sHrm.tEmployeeMaster EM1 on EM1.Id=T1.EmployeeId
			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=T1.SubjectId
			where T1.DivisionId=TT.DivisionId 
			AND TT.LectureNumber=T1.LectureNumber 
			AND TT.DayId=T1.DayId and TT.TimeTableSchemaId=T1.TimeTableSchemaId  
			--AND timetableid in ()
			FOR XML PATH('')
			), 1, 1, '')) ClassDivisionSubjectTeacher
			--Added by dhananjay for mantis - 0035030

	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0	
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DV.OrgId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	  AND (OM.Id = @rOrgId OR @rOrgId = 0)
	  AND TT.EmployeeId <> 0
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
		END
END
GO
PRINT N'Altering Procedure [sTransport].[pVTSTrackingDataGet]...';


GO
ALTER PROCEDURE sTransport.pVTSTrackingDataGet
	 
	@rVehicleId int,
	@rBusRouteId int,
	@rIsError smallint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rIsError = 1)
	BEGIN
		IF EXISTS(SELECT 1 FROM sTransport.tVTSTrackingData WHERE VehicleId = @rVehicleId AND BusRouteId = @rBusRouteId)
		BEGIN
			SELECT
				VehicleId,
				BusRouteId,
				Latitude,
				Longitude,
				CreatedDateTime,
				UpdatedDateTime,
				VTSVendorId,
				VTSResponse,
				APICallCount
			FROM
				sTransport.tVTSTrackingData
			WHERE 
				VehicleId = @rVehicleId 
			AND BusRouteId = @rBusRouteId

			--UPDATE sTransport.tVTSTrackingData SET UpdatedDateTime = GETDATE() WHERE VehicleId = @rVehicleId AND BusRouteId = @rBusRouteId
		END
	END
	ELSE
	BEGIN
		DECLARE @lUpdatedDateTime DateTime
		SELECT @lUpdatedDateTime = UpdatedDateTime FROM [sTransport].[tVTSTrackingData] WHERE VehicleId = @rVehicleId AND BusRouteId = @rBusRouteId

		IF EXISTS(SELECT 1 FROM sTransport.tVTSTrackingData WHERE VehicleId = @rVehicleId AND BusRouteId = @rBusRouteId AND DATEDIFF(MINUTE, @lUpdatedDateTime, GETDATE()) < 1)
		BEGIN
			SELECT
				VehicleId,
				BusRouteId,
				Latitude,
				Longitude,
				CreatedDateTime,
				UpdatedDateTime,
				VTSVendorId,
				VTSResponse,
				APICallCount
			FROM
				sTransport.tVTSTrackingData
			WHERE 
				VehicleId = @rVehicleId 
			AND BusRouteId = @rBusRouteId

			--UPDATE sTransport.tVTSTrackingData SET UpdatedDateTime = GETDATE() WHERE VehicleId = @rVehicleId AND BusRouteId = @rBusRouteId 
		END
	END
END
GO
PRINT N'Creating Procedure [sFee].[pRptStudentWiseAllFeeDetailGet]...';


GO

CREATE PROCEDURE [sFee].[pRptStudentWiseAllFeeDetailGet]
	 
		@rReceiptId bigint
		--@lSourceId bigint ,
		--@lSourceTypeId int,
		--@lBatchId int
		--@rStudentId bigint =0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	--if (@rStudentId <> 0)
	--SELECT @lSourceId = Id, @lSourceTypeId = 2001 FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @lBatchId
		DECLARE @lSourceId bigint,@lSourceTypeId int,@lBatchId int

		SELECT @lSourceId = SourceId, @lSourceTypeId = SourceTypeId, @lBatchId = BatchId FROM sFee.tReceipt WHERE Id = @rReceiptId

		DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int
		-- Added
		DECLARE @lExemptionTypeId int = 0
		DECLARE @lExemptionType nvarchar(100) = ''
		
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId, @lExemptionTypeId = ExemptionTypeId FROM sStudent.vStudentAcademic WHERE AcademicId=@lSourceId
		
		-- Added
		SELECT @lExemptionType = Title FROM [sFee].[tExemptionTypeMaster] WHERE Id = @lExemptionTypeId
SELECT 
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,
			ISNULL(FS.Amount,0)AS Amount,
			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
			
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				ISNULL(FS1.FeeDuration,'')  AS FeeDuration
			FROM sFee.tFeeSetup FS1
			   
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = @lBatchId
				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=@lSourceId) AND(FO.SourceTypeId=@lSourceTypeId)
			WHERE
			 FS1.BatchId = @lBatchId
			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=@lSourceId) AND(FA.SourceTypeId=@lSourceTypeId)
		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= @lSourceId
			AND ((R.SourceTypeId = @lSourceTypeId) OR (@lSourceTypeId=0))
			AND R.IsObsolete = 0 
			AND R.BatchId = @lBatchId
			 GROUP BY FeeSetupId
		) R ON R.FeeSetupId = FS.Id	
WHERE 
	FS.BatchId=@lBatchId
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC
END
GO
PRINT N'Creating Procedure [sHrm].[pLeaveHierarchyListingAllGet]...';


GO



CREATE PROCEDURE [sHrm].[pLeaveHierarchyListingAllGet]  
(  
	@rOrgId int,  
	@rLeaveHierarchyLevelId bigint = 0,
    @rEmployeeId  bigint,     
    @rFromDate date,  
    @rLeaveTypeId int,  
    @rTodate date,  
    @rOrgGroupBatchId int,  
    @rEmployeeCode nvarchar(100)='',  
    @rEmployeeName nvarchar(100)='',  
    @rStatusId int = 0,  
    @rDepartmentId int
 )  
AS  
SET NOCOUNT ON  
  
BEGIN  
 
IF OBJECT_ID('tempdb..#EmployeeListTemp') IS NOT NULL
	BEGIN
		DROP TABLE #EmployeeListTemp;
	END     
	CREATE Table #EmployeeListTemp(EmployeeId Bigint, EmployeeName nvarchar(50))

	DECLARE @lHierarchyLevel int
	DECLARE @lOrgId int
	IF (@rOrgId = 0) BEGIN SET @lOrgId = LEFT(@rEmployeeId,4) END ELSE BEGIN SET @lOrgId = @rOrgId END
	SELECT @lHierarchyLevel = ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 485 AND SourceTypeId = 1016 AND SourceId = @lOrgId

	DECLARE @lTempEmployeeIdList NVARCHAR(MAX);
	DECLARE @lTempEmployeeId NVARCHAR(MAX);
	DECLARE @lCount1 int = 1

	SET @lTempEmployeeIdList = CONVERT(nvarchar(Max),@rEmployeeId)

While @lHierarchyLevel > @lCount1
	BEGIN
		INSERT INTO #EmployeeListTemp
			SELECT EJD.EmployeeId,EM.ShortName FROM sHrm.tEmployeeJobDetail EJD INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId Where EmployeeManagerId IN (SELECT cast(item as BigInt) FROM sCommon.fnsplit(@lTempEmployeeIdList,','))

		SET @lTempEmployeeId = STUFF((
		SELECT ',' + CAST(EJD.EmployeeId AS NVARCHAR(MAX))
		FROM sHrm.tEmployeeJobDetail EJD INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId Where EmployeeManagerId IN (SELECT cast(item as BigInt) FROM sCommon.fnsplit(@lTempEmployeeIdList,','))
		FOR XML PATH(''), TYPE
	).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

	SET @lTempEmployeeIdList = @lTempEmployeeId
	SET @lCount1 = @lCount1 + 1

	END


IF OBJECT_ID('tempdb..#EmployeeListLeaveTemp') IS NOT NULL
	BEGIN
		DROP TABLE #EmployeeListLeaveTemp;
	END     
CREATE Table #EmployeeListLeaveTemp(EmployeeId Bigint)

DECLARE @lTempEmployeeIdListLeave NVARCHAR(MAX);
DECLARE @lTempEmployeeIdLeave NVARCHAR(MAX);
DECLARE @lCount2 int = 1

SELECT @lTempEmployeeIdListLeave = STUFF((
    SELECT ',' + CAST(EJD.EmployeeId AS NVARCHAR(MAX))
    FROM sHrm.tEmployeeJobDetail EJD INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId Where EmployeeManagerId = @rEmployeeId
    FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '');


While @lHierarchyLevel > @lCount2

	BEGIN

		INSERT INTO #EmployeeListLeaveTemp
			SELECT EJD.EmployeeId FROM sHrm.tEmployeeJobDetail EJD INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId Where EmployeeManagerId IN (SELECT cast(item as BigInt) FROM sCommon.fnsplit(@lTempEmployeeIdListLeave,','))

	SET @lTempEmployeeIdLeave = STUFF((
		SELECT ',' + CAST(EJD.EmployeeId AS NVARCHAR(MAX))
		FROM sHrm.tEmployeeJobDetail EJD INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId Where EmployeeManagerId IN (SELECT cast(item as BigInt) FROM sCommon.fnsplit(@lTempEmployeeIdListLeave,','))
		FOR XML PATH(''), TYPE
	).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

	SET @lTempEmployeeIdListLeave = @lTempEmployeeIdLeave
	SET @lCount2 = @lCount2 + 1

	END


   SELECT   
      L.[Id] AS LeaveId,  
	  LHL.AutoId AS LeaveHierarchyLevelId,
      L.[EmployeeId],  
      L.[ReportDate],  
      L.[FromDate],  
      L.[ToDate],  
      L.[LeavePeriodId],  
      L.[LeaveTypeId],  
      L.[LeaveReason],  
      LPM.Title AS LeavePeriod,  
      LTM.Title AS LeaveType,   
	  [sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS EmployeeName,
      EM.Code AS EmployeeCode,  
      L.NoOfLeave,  
      ISNULL(LHL.StatusId,0) AS StatusId,  
      ISNULL(SM.Title,'Pending') AS StatusName,  
      ISNULL(L.LeaveRemark,'') AS  LeaveRemark,  
      OM.DisplayTitle AS OrganizationName,    
      OM.Id AS OrgId,  
      L.BatchId AS BatchId,  
      EM.DepartmentId AS DepartmentId,  
      EM.DepartmentName As DepartmentName,
	  ELT.EmployeeName AS ActionByEmployee
  FROM   
	  sHrm.tLeaveHierarchyLevel LHL
	  INNER JOIN sHrm.tLeave L  ON L.Id = LHL.LeaveId
      INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId    
      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
      INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id = L.LeavePeriodId  
      INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId  
      INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId  
      INNER JOIN sCommon.tStatusMaster SM ON SM.Id = LHL.StatusId  
	  INNER JOIN #EmployeeListTemp ELT ON ELT.EmployeeId = LHL.ActionByEmployeeId
  WHERE   
      (LHL.AutoId = @rLeaveHierarchyLevelId OR @rLeaveHierarchyLevelId = 0)     
      AND ((L.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
      AND ((L.FromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
      AND (L.LeaveTypeId = @rLeaveTypeId OR @rLeaveTypeId = 0)        
      AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
      AND ((L.OrgId = @rOrgId) OR (@rOrgId = 0))  
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')  
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')  
      AND (LHL.StatusId = @rStatusId OR @rStatusId = 0) 
      AND ((EM.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
	  AND ISNULL(EM.IsOtherUser,0)=0 
	  AND L.EmployeeId IN (Select EmployeeId From #EmployeeListLeaveTemp)
END
GO
PRINT N'Creating Procedure [sLibrary].[pXMLNewspaperLogAdd]...';


GO


CREATE PROCEDURE [sLibrary].[pXMLNewspaperLogAdd]
	(
		@rXml  nvarchar(MAX),
		@rOrgId int,
		@rCreatedUserId bigint 		
	)
AS

SET NOCOUNT ON

BEGIN

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

	CREATE TABLE #tempTable  
	(
		Id bigint identity,
		NewspaperId smallint,
		NewspaperTitle nvarchar(300),
		NewspaperLanguage nvarchar(100),
		NewsType nvarchar(30),
		NewspaperDate datetime,
		NoOfCopy int,
		NewspaperAmount decimal(12,2)
	)

	INSERT INTO #tempTable
	(
		NewspaperTitle,
		NewspaperLanguage,
		NewsType,
		NewspaperDate,
		NoOfCopy,
		NewspaperAmount
	)
	SELECT	
		A.NewspaperTitle,
		A.NewspaperLanguage,
		A.NewsType,
		CONVERT(datetime, A.NewspaperDate, 103) AS NewspaperDate,
		A.NoOfCopy,
		A.NewspaperAmount
	FROM OPENXML (@intDoc, '/Table/NewspaperLog', 1)
	WITH
	( 
			NewspaperTitle NVARCHAR(300) '@NewspaperTitle',
			NewspaperLanguage NVARCHAR(100) '@NewspaperLanguage',
			NewsType NVARCHAR(30) '@NewsType',
			NewspaperDate datetime '@NewspaperDate',
			NoOfCopy int '@NoOfCopy',
			NewspaperAmount decimal(12,2) '@NewspaperAmount' 
	)A 

	--Select * from #tempTable return
	DECLARE @lCount int,@lId int
	SELECT @lCount = COUNT(Id) FROM #tempTable
	SELECT Top 1 @lId=Id FROM #tempTable
	
	WHILE @lId <= @lCount 
	BEGIN

		DECLARE @lNewspaperId BIGINT, @lNewspaperDate date, @lNoOfCopy Int, @lNewspaperAmount int
	
		SELECT @lNewspaperId = NM.Id from sLibrary.tNewspaperMaster AS NM
		INNER JOIN #tempTable AS TT ON TT.NewspaperTitle = NM.Title 
		where  TT.Id = @lId
		SELECT @lNewspaperDate = NewspaperDate from #tempTable where  Id = @lId
		SELECT @lNoOfCopy = NoOfCopy from #tempTable where  Id = @lId
		SELECT @lNewspaperAmount = NewspaperAmount from #tempTable where  Id = @lId
		
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sLibrary.tNewspaperLog', 0, 1, 1,@outNextNumber = @lNextNumber output

			print @lNextNumber
										
			SET IDENTITY_INSERT sLibrary.tNewspaperLog ON

			INSERT INTO sLibrary.tNewspaperLog
			(		AutoId,
					NewspaperId,
					NewspaperDate,
					NoOfCopy,
					NewspaperAmount,
					CreatedUserId,
					CreatedDateTime 	
			)
			Values
			(	
					@lNextNumber,
					@lNewspaperId,
					@lNewspaperDate,
					@lNoOfCopy,
					@lNewspaperAmount,
					@rCreatedUserId,
					sCommon.fGetDate()   
			)

			SET IDENTITY_INSERT sLibrary.tNewspaperLog OFF
	
		SELECT @lNextNumber = MAX(AutoId) FROM sLibrary.tNewspaperLog
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sLibrary.tNewspaperLog', @rCurrentNumber = @lNextNumber 

		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
	END CATCH
END
GO
PRINT N'Creating Procedure [sStudent].[pValidateImportStudentDetail]...';


GO
CREATE PROCEDURE [sStudent].[pValidateImportStudentDetail] 
	 @rXmlDoc nvarchar(MAX)
	,@rFromBatch int
	,@rOrgId int
AS
BEGIN
	 
	SET NOCOUNT ON;
	SET @rXmlDoc=REPLACE(@rXmlDoc,'&','&amp;')
	DECLARE @lInterrorCode INT, @intDoc INT
	IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL
    DROP TABLE #tempTable
	DECLARE @lCount int = 0

	DECLARE @lFromClass nvarchar(100) = '',
		@lFromDivision nvarchar(100) = '',
		@lToBatch nvarchar(100) = '',
		@lToClass nvarchar(100) = '',
		@lToDivision nvarchar(100) = '',
		@lCode nvarchar(20) = '',
		@lFromClassId int = null,
		@lFromDivisionId int = null,
		@lToClassId int = null,
		@lToBatchId int = null,
		@lToDivisionId int = null,
		@lStudentId bigint=null,
		@lExemptionTypeId int = null,
		@lAdmissionCategoryId int =null,
		@lFeeStructureId int = null,
		@lRollNo int  = null

BEGIN TRY
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

	CREATE TABLE #tempTable  
	(
		Id bigint identity
		,FromClass nvarchar(100)
		,FromDivision nvarchar(100)
		,ToBatch nvarchar(100)
		,ToClass nvarchar(100)
		,ToDivision nvarchar(100)
		,Code nvarchar(20)
		,FromClassId int
		,FromDivisionId int
		,ToBatchId int
		,ToClassId int
		,ToDivisionId int
		,StudentId bigint
		,ExemptionTypeId int 
		,AdmissionCategoryId int
		,FeeStructureId int
		,RollNo int
		,ValidationMsg nvarchar(Max)
	)

	INSERT INTO #tempTable
	(
		 FromClass
		,FromDivision 
		,ToBatch
		,ToClass
		,ToDivision 
		,Code
	)

	SELECT *
			FROM OPENXML (@intDoc, '/Table/ValidateStudentImportDetail', 1)
	WITH
	(						
			FromClass nvarchar(100) '@FromClass',
			FromDivision nvarchar(100) '@FromDivision',
			ToBatch nvarchar(100) '@ToBatch',
			ToClass nvarchar(100) '@ToClass',
			ToDivision nvarchar(100) '@ToDivision',
			Code nvarchar(20) '@Code'
	) A 

	EXEC sp_xml_removedocument @intDoc

	--select * from  #tempTable

	SELECT @lCount = COUNT(Id) FROM #tempTable

	WHILE @lCount > 0
	BEGIN
		DECLARE @lValidationMsg nvarchar(max) = ''
		SELECT  @lFromClass = FromClass, @lFromDivision = FromDivision,
				@lToBatch = ToBatch, @lToClass = ToClass, @lToDivision = ToDivision,
				@lCode = Code FROM #tempTable WHERE Id = @lCount
		
		SELECT @lStudentId = StudentId , @lExemptionTypeId = ExemptionTypeId ,@lAdmissionCategoryId = AdmissionCategoryId
			  ,@lFeeStructureId = FeeStructureId , @lRollNo = RollNo 
		From sStudent.vStudentAcademic where Code = @lCode AND BatchId = @rFromBatch AND OrgId = @rOrgId
		
		SELECT @lToBatchId = Id from sSetup.tBatchMaster where Title = @lToBatch AND OrgId = @rOrgId AND ISObsolete = 0
		SELECT @lFromClassId = Id from sSetup.tClassMaster where DisplayTitle = @lFromClass AND OrgId = @rOrgId AND ISObsolete = 0
		SELECT @lFromDivisionId = Id from sSetup.tDivisionMaster where Title = @lFromDivision AND ClassId = @lFromClassId AND ISObsolete = 0

		SELECT @lToClassId = Id from sSetup.tClassMaster where DisplayTitle = @lToClass AND OrgId = @rOrgId AND ISObsolete = 0
		SELECT @lToDivisionId = Id from sSetup.tDivisionMaster where Title = @lToDivision AND ClassId = @lToClassId AND ISObsolete = 0
		 
		IF(@lStudentId = 0 OR @lStudentId Is NULL)
		BEGIN
			SET @lValidationMsg = 'Invalid Student Code,'
		END

		IF(@lToBatchId = 0 OR @lToBatchId IS NULL)
		BEGIN
			SET @lValidationMsg += 'To Batch Id not Found,'
		END

		IF(@lFromClassId = 0 OR @lFromClassId Is NULL)
		BEGIN
			SET @lValidationMsg += 'From Class Does not Found,'
		END

		IF(@lFromDivisionId = 0 OR @lFromDivisionId Is NULL)
		BEGIN
			SET @lValidationMsg += 'From Division Does not Found,'
		END

		IF(@lToClassId = 0 OR @lToClassId IS NULL)
		BEGIN
			SET @lValidationMsg += 'To Class Does not Found,'
		END
			
		IF(@lToDivisionId = 0 OR @lToDivisionId IS NULL)
		BEGIN
			SET @lValidationMsg += 'To Division Does not Found,'
		END

		Update #tempTable SET FromClassId = @lFromClassId, FromDivisionId = @lFromDivisionId
						,ToBatchId =@lToBatchId, ToClassId= @lToClassId, ToDivisionId = @lToDivisionId 
						,StudentId = @lStudentId, ExemptionTypeId = @lExemptionTypeId, AdmissionCategoryId = @lAdmissionCategoryId
						,FeeStructureId = @lFeeStructureId, RollNo = @lRollNo, ValidationMsg = @lValidationMsg where Id  = @lCount
		
		SET @lCount = @lCount - 1;	
	END

	SELECT * FROM #tempTable
	DROP TABLE #tempTable
    END TRY 

	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating Procedure [sStudent].[pXMLChangeStudentBatchImportAdd]...';


GO
CREATE PROCEDURE [sStudent].[pXMLChangeStudentBatchImportAdd]
	
	@rStudentImpXml [nvarchar](max),
	@rToOrgId int,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStudentImpXml
BEGIN
	DECLARE @lCount int = 0
	IF OBJECT_ID('tempdb..#tempStdTable') IS NOT NULL
    DROP TABLE #tempStdTable

	Declare @rOrgGroupId int,@rOrgGroupBatchId int

	Select @rOrgGroupId=OrgGroupId from [sSetup].[tOrganizationMaster] Where Id=@rToOrgId
		
	Declare @lStudCap int,@lOrgStudentCap int
	Select @lStudCap=ISNULL(NoOfStudent,0)+ISNULL(StudentExtraCap,0) from sSetup.tOrgGroupSetting Where OrgGroupId= @rOrgGroupId
	 
	Declare @lBatchId int 
	Declare @lCode nvarchar(20)

	CREATE TABLE #tempStdTable  
		(
			Id bigint identity
			,Code nvarchar(20)
			,ToBatchId int
			,ToClassId int
			,ToDivisionId int
			,StudentId bigint
			,ExemptionTypeId int 
			,AdmissionCategoryId int
			,FeeStructureId int
			,RollNo int
		)

	BEGIN TRY
	--BEGIN TRANSACTION			
		
		INSERT INTO #tempStdTable
		(
			 Code
			,ToBatchId
			,ToClassId
			,ToDivisionId
			,StudentId
			,ExemptionTypeId
			,AdmissionCategoryId
			,FeeStructureId
			,RollNo
		)
		
		SELECT * FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
		WITH
		(						
				Code nvarchar(20) '@Code',			
				ToBatchId int '@ToBatchId',
				ToClassId  int '@ToClassId',
				ToDivisionId int '@ToDivisionId',
				StudentId bigint '@StudentId',
				ExemptionTypeId int '@ExemptionTypeId',
				AdmissionCategoryId int '@AdmissionCategoryId',
				FeeStructureId int '@FeeStructureId',
				RollNo int '@RollNo'
		) A 

		SELECT @lCount = COUNT(Id) FROM #tempStdTable
		
		WHILE @lCount > 0
		BEGIN
			Select @lBatchId  = ToBatchId From #tempStdTable where Id = @lCount
		
			Select @rOrgGroupBatchId= OrgGroupBatchId from [sSetup].[tBatchMaster] Where Id=@lBatchId
		
			Select @lOrgStudentCap=[sSetup].[fStudentCapGet](@rOrgGroupBatchId)
				
			IF(@lOrgStudentCap > @lStudCap )
			BEGIN
				Select -111 AS Result
				Return			
			END

			Select @lCode = Code From #tempStdTable where Id = @lCount

			IF EXISTS(SELECT Code from sStudent.tStudentMaster SM INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id where SM.Code = @lCode AND A.BatchId = @lBatchId AND SM.OrgId = @rToOrgId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
		
			DECLARE @lNextNumber BIGINT 	
			EXECUTE sCommon.pTableRowIdGet @rToOrgId, 'sStudent.tAcademic', 0, 1, 1,@outNextNumber = @lNextNumber output
		
			INSERT INTO sStudent.tAcademic
			(
				Id,
				StudentId,
				ClassId,
				BatchId,
				DivisionId,
				RollNo,
				OrgId,
				CreatedUserId,
				CreatedDateTime,
				IsCurrent,
				ExemptionTypeId,
				FeeStructureId,
				AdmissionCategoryId,
				ClassStatusId
				)
			SELECT		
				@lNextNumber,
				StudentId,
				ToClassId,
				ToBatchId,
				ToDivisionId,
				ISNULL(RollNo,0),
				@rToOrgId,
				@rCreatedUserId,
				sCommon.fGetDate(),
				1,
				ExemptionTypeId,
				FeeStructureId,
				AdmissionCategoryId,
				1
				From #tempStdTable where Id = @lCount
			
			EXECUTE sCommon.pTableRowIdModify @rToOrgId, @rTableTitle = 'sStudent.tAcademic', @rCurrentNumber = @lNextNumber 
		    
			Set @lCount = @lCount - 1
		END

		SELECT 1 AS Result
		DROP TABLE #tempStdTable
	--COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		--ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating Procedure [sTimetable].[pRptFreeLectureListGet_L]...';


GO
CREATE PROCEDURE [sTimetable].[pRptFreeLectureListGet_L]
    @rBatchId INT,
    @rClassID INT,
    @rDivisionId INT,
    @rEmployeeId BIGINT,
    @rTimeTableSchemaId INT,    
    @rReportId INT,
    @rOrgId INT  
AS
BEGIN   
    CREATE TABLE #Temp (Id INT IDENTITY, LectureNumber INT, TimeTableSchemaId INT);
    
    DECLARE @lMaxLecture INT = (SELECT MAX(NoOfPeriod) FROM sTimeTable.tTimeSetup WHERE TimeTableSchemaId = @rTimeTableSchemaId);
    DECLARE @lCount INT = 1;

    WHILE @lCount <= @lMaxLecture
    BEGIN
        INSERT INTO #Temp (LectureNumber, TimeTableSchemaId) VALUES (@lCount, @rTimeTableSchemaId);
        SET @lCount = @lCount + 1;
    END

	--SELECT * FROM #Temp

    SELECT DISTINCT
        TS.DayId, 
        ISNULL(DM.Title,'') AS DayNames,
        EMP.Code,
        EMP.ID AS EmployeeId,
        [sHrm].[fEmployeeNameGet](ISNULL(EMP.FirstName,''), ISNULL(EMP.MiddleName,''), ISNULL(EMP.LastName,''), ISNULL(OM.EmployeeNameFormatId, 1)) AS EmployeeName,
        EMP.FirstName + ' '  + EMP.LastName AS Employee,
        CASE 
            WHEN ISNULL(TT.LectureNumber, 0) = TEM.LectureNumber AND ISNULL(TT.DayId, 0) = TS.DayId 
            THEN ISNULL(TT.Id, 0) ELSE 0 
        END AS TimeTableId,
        CASE 
            WHEN ISNULL(TT.LectureNumber, 0) = TEM.LectureNumber AND ISNULL(TT.DayId, 0) = TS.DayId 
            THEN ISNULL(TT.LectureNumber, 0) ELSE 0 
        END AS LectureNumber,
        CASE 
            WHEN ISNULL(TT.LectureNumber, 0) = TEM.LectureNumber AND ISNULL(TT.DayId, 0) = TS.DayId 
            THEN ISNULL(TT.DayId, 0) ELSE 0 
        END AS TimeTableDayId,
        TEM.LectureNumber AS Lecture,
        SM.Id AS SubjectId,
        SM.Title AS SubjectName,
        TTT.FromTime + ' - ' + TTT.ToTime AS LectureTime,
        DIM.Id AS DivisionId,
        DIM.Title AS DivisionTitle,
        CM.Id AS ClassId,
        CM.Title AS ClassTitle,
        CM.Title + ' ' + DIM.Title AS ClassDivisionName,
        TTS.IsDisplayPeriodTime,
        OM.Title AS OrganizationName,
        [sCommon].[fXMLTagsReplaceReverse](
            STUFF((
                SELECT ',<br>' + ISNULL(VBCD1.ClassDivisionName + '-' + SM1.Title, '')
                FROM sTimetable.tTimeTable T1 
                INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id = T1.SubjectId
                INNER JOIN sSetup.vClassDivision VBCD1 ON VBCD1.DivisionId = T1.DivisionId
                WHERE T1.EmployeeId = TT.EmployeeId 
                AND TT.LectureNumber = T1.LectureNumber 
                AND TT.DayId = T1.DayId 
                AND TT.TimeTableSchemaId = T1.TimeTableSchemaId  
                FOR XML PATH('')
            ), 1, 11, '')
        ) AS ClassSubject,
		TTS.Id AS TimeTableSchemaId
		  INTO #TempTimeTable
    FROM 
		sTimetable.tTimeSetup TS
		INNER JOIN sTimeTable.tTimeTableSchema TTS ON TTS.Id = TS.TimeTableSchemaId
		INNER JOIN sTimetable.tAssignTeacher ASS ON ASS.TimeTableSchemaId = TS.TimeTableSchemaId
		INNER JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = ASS.EmployeeId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EMP.OrgID
		LEFT JOIN #Temp TEM ON TEM.TimeTableSchemaId = TS.TimeTableSchemaId
		LEFT JOIN sTimetable.tTimeTable TT ON TT.EmployeeId = EMP.Id AND TS.TimeTableSchemaId = TT.TimeTableSchemaId AND TS.DayId = TT.DayId AND TT.LectureNumber = TEM.LectureNumber
		LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId
		LEFT JOIN sSetup.tDivisionMaster DIM ON DIM.Id = TT.DivisionId
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DIM.ClassId
		LEFT JOIN sTimeTable.tTimeTableTime TTT ON TTT.TimeTableSchemaId = TT.TimeTableSchemaId AND TTT.DivisionId = TT.DivisionId AND TTT.DayId = TS.DayId AND TTT.LectureNumber = TEM.LectureNumber
		INNER JOIN sCommon.tDayMaster DM ON DM.Id = TS.DayId AND NoOfPeriod > 0

    WHERE 
		TS.TimeTableSchemaId = @rTimeTableSchemaId
		AND TS.BatchID = @rBatchId 
		AND (EMP.OrgID = @rOrgId OR @rOrgId = 0) 
		AND ISNULL(EMP.IsOtherUser, 0) = 0 
		AND (EMP.Id = @rEmployeeId OR @rEmployeeId = 0);

    SELECT 
        T.DayId, 
        T.DayNames, 
        T.LectureNumber, 
        T.TimeTableDayId, 
        T.Lecture, 
        T.LectureTime, 
        T.OrganizationName,
        EmployeeNames = STUFF((
            SELECT DISTINCT ', ' + EmployeeName
            FROM #TempTimeTable T1
            WHERE T1.DayId = T.DayId 
            AND T1.LectureNumber = T.LectureNumber
			AND T1.Lecture = T.Lecture
			AND T1.TimeTableId = 0 
			AND T1.LectureNumber = 0
            FOR XML PATH('')
        ), 1, 2, '')
    FROM #TempTimeTable T
	INNER JOIN sTimetable.tTimeSetup TS ON TS.TimeTableSchemaId = T.TimeTableSchemaId AND TS.DayId = T.DayId AND T.Lecture <= TS.NoOfPeriod
    GROUP BY T.DayId, T.DayNames, T.LectureNumber, T.TimeTableDayId, T.Lecture, T.LectureTime, T.OrganizationName, T.TimeTableSchemaId
	HAVING T.LectureNumber = 0

	 DROP TABLE #Temp
	 DROP TABLE #TempTimeTable

--	 SELECT 
--		0 AS DayId, 
--		'' AS DayNames,
--		0 AS LectureNumber,
--		0 AS TimeTableDayId,
--		0 AS Lecture,
--		--ISNULL(TT.LectureNumber,0) AS LectureNumber,
--		'' AS LectureTime,
--		'' AS OrganizationName,
--		'' AS EmployeeNames
END;

GO
PRINT N'Update complete.';

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

