

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

GO
PRINT N'Altering Schema [sBooking]...';


GO
ALTER AUTHORIZATION
    ON SCHEMA::[sBooking]
    TO [dbo];


GO
PRINT N'Creating Schema [sPortal]...';


GO
CREATE SCHEMA [sPortal];



GO
PRINT N'Creating Table [sHrm].[tDigitalFormEmployeeStatusOld]...';


GO
CREATE TABLE [sHrm].[tDigitalFormEmployeeStatusOld] (
    [AutoId]         INT      NULL,
    [DigitalFormId]  INT      NULL,
    [EmployeeId]     BIGINT   NULL,
    [StatusId]       SMALLINT NULL,
    [CreatedUserId]  BIGINT   NULL,
    [ActionDateTime] DATETIME NULL,
    [VerifyDateTime] DATETIME NULL
);


GO
PRINT N'Altering Function [sAttendance].[fAbsentDatesGet]...';


GO
ALTER FUNCTION [sAttendance].[fAbsentDatesGet](@rFromDate date,@rToDate date, @rAttendanceTypeId tinyint,@rSubjectId int,@rAcademicId bigint)
RETURNS nvarchar(500) WITH EXECUTE AS CALLER
AS 
BEGIN
    declare @rAbsentDates nvarchar(500)
(Select 
			@rAbsentDates=COALESCE(@rAbsentDates+',','') + CONVERT(VARCHAR(10), SR.attendancedate, 103)
			 FROM 		
		    sAttendance.tStudentRegister SR 
			WHERE SR.AcademicId=@rAcademicId 
			AND SR.IsPresent=0
			AND SR.AttendanceTypeId=@rAttendanceTypeId
			AND (SR.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 		 
			AND ((SR.SubjectId=@rSubjectId) OR (ISNULL(@rSubjectId,0)=0)))
			ORDER BY SR.attendancedate
			
			
    RETURN ISNULL(@rAbsentDates,'') 
END
GO
PRINT N'Creating Function [sCommon].[DateToWord]...';


GO
CREATE FUNCTION [sCommon].[DateToWord](@rDate Date)

  RETURNS NVARCHAR(200)

AS

BEGIN
	DECLARE @lDay INT = DAY(@rDate)
    DECLARE @lMonth INT = MONTH(@rDate)
    DECLARE @lYear INT = YEAR(@rDate)

	DECLARE @Below20 TABLE (ID int identity(0,1), Word varchar(32), RomanWord varchar(32))
	DECLARE @Below100 TABLE (ID int identity(2,1), Word varchar(32))
	DECLARE @lMonthTab TABLE (ID int identity(1,1),Month varchar(32))
	INSERT @Below20 (Word,RomanWord) VALUES

            ('',''),('One','First'),( 'Two','Second' ), ( 'Three','Third'),

            ( 'Four','Fourth' ), ( 'Five', 'Fifth' ), ( 'Six', 'Sixth' ), ( 'Seven','Seventh' ),

            ( 'Eight','Eighth'), ( 'Nine','Ninth'), ( 'Ten','Tenth'), ( 'Eleven','Eleventh' ),

            ( 'Twelve','Twelth' ), ( 'Thirteen','Thirteenth' ), ( 'Fourteen','Fourteenth'),

            ( 'Fifteen','Fifteenth' ), ('Sixteen','Sixteenth' ), ( 'Seventeen','Seventeenth'),

            ('Eighteen','Eighteenth' ), ( 'Nineteen','Nineteenth' )

	INSERT @Below100 VALUES ('Twenty'), ('Thirty'),('Forty'), ('Fifty'),

               ('Sixty'), ('Seventy'), ('Eighty'), ('Ninety')
   
	INSERT @lMonthTab VALUES ('January'),('February'), ('March'), ('April'), ('May'), ('June'),
                
               ('July'), ('August'), ('September'), ('October'), ('November'), ('December')


	DECLARE @lDayInWord NVARCHAR(50) =
	(
		SELECT CASE

		WHEN @lDay BETWEEN 1 AND 19

		THEN (SELECT RomanWord FROM @Below20 WHERE ID=@lDay)

		WHEN @lDay = 20 THEN 'Twentieth'

		WHEN @lDay > 20 AND @lDay <> 30

		THEN (SELECT Word FROM @Below100 WHERE ID=@lDay/10)+ ' ' +

			(SELECT RomanWord FROM @Below20 WHERE ID=@lDay%10)

		WHEN @lDay = 30 THEN 'Thirtieth'
		ELSE '' END
	)

	DECLARE @lMonthInWord NVARCHAR(50) =
	(
	 SELECT Month FROM @lMonthTab WHERE ID = @lMonth
	)

	DECLARE @Thousand nvarchar(20) = CASE WHEN @lYear/1000 > 0 THEN (SELECT Word FROM @Below20 WHERE ID = @lYear/1000)+ ' Thousand ' ELSE '' END
	DECLARE @Hundred nvarchar(20) = CASE WHEN (@lYear%1000)/100>0 THEN (SELECT Word FROM @Below20 WHERE ID = (@lYear%1000)/100)+ ' Hundred ' ELSE '' END
	DECLARE @Ten nvarchar(20) = CASE
					WHEN (@lYear%100) <= 19 THEN (SELECT Word FROM @Below20 WHERE ID=@lYear%100)
					ELSE (SELECT Word FROM @Below100 WHERE ID=(@lYear%100)/10)+ ' ' + (SELECT Word FROM @Below20 WHERE ID=(@lYear%100)%10)
				  END

	DECLARE @lYearInWord NVARCHAR(50) =
	(
	 @Thousand + @Hundred + @Ten
	)

	DECLARE @DOBInWord NVARCHAR(200) = @lDayInWord + ' ' + @lMonthInWord + ' ' + @lYearInWord



	SELECT @DOBInWord = RTRIM(@DOBInWord)


	RETURN (@DOBInWord)

END
GO
PRINT N'Altering Procedure [sAccounting].[pVoucherListGet]...';


GO


ALTER PROCEDURE [sAccounting].[pExpenseOfCandidateAdd]
	 
	 @rOrgId smallint,
	   @rBatchId int,
	 @rId int,
	 @rEmployeeId bigint,
	 @rExpenseDate date,
	 @rExpenseGroupId int,
	 @rAmount decimal(20,5), --Changed for mantis : 32211 by Nilesh
	 @rRemark nvarchar(200),
	 @rCreatedUserId bigint,
	 --@rCreatedDateTime datetime,
	 @rUpdatedUserId bigint,
	 --@rUpdatedDateTime datetime,
	 @rStatusId int,
	 @rExpenseDetailXml nvarchar(max)
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rExpenseDetailXml
BEGIN
	--BEGIN TRY
	
	-- BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

			IF(@rId = 0)	
			BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tExpense', 0, 1, 1,@outNextNumber = @lNextNumber output
			--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO  sAccounting.tExpense
			(
			OrgId,
			 BatchId,
			Id,
			EmployeeId	,
			ExpenseDate	,
			ExpenseGroupId,
			Amount,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			StatusId	
			)
			VALUES
			(
		    @rOrgId ,
		    @rBatchId,
			@lNextNumber ,
			@rEmployeeId ,
			@rExpenseDate ,
			@rExpenseGroupId ,
			@rAmount ,
			@rRemark ,
			@rCreatedUserId ,
			sCommon.fGetDate() ,
			@rUpdatedUserId ,
			sCommon.fGetDate(),	
			@rStatusId 								
			)
		
			INSERT INTO sAccounting.tExpenseDetail
			(ExpenseId,
			ExpenseSubGroupId,
			Amount,Remark)
			SELECT @lNextNumber,ExpenseSubGroupId,Amount,sSetup.fPortalXMLTagsReplaceReverse(Remark)
			FROM OPENXML (@loDoc, '/Table/ExpenseDetail', 1)
			WITH (ExpenseSubGroupId int,Amount decimal(20,5),Remark nvarchar(200)) --Added for mantis : 32211 by Nilesh
		    SELECT @lNextNumber AS Result
			END	 

	ELSE
			BEGIN
			SET @lNextNumber = @rId
			UPDATE  sAccounting.tExpense
		    SET
	    
			ExpenseDate=@rExpenseDate,
			ExpenseGroupId=@rExpenseGroupId,
			Amount=@rAmount,
			Remark=@rRemark,			
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			StatusId=@rStatusId
	    
			WHERE Id = @rId
			DELETE sAccounting.tExpenseDetail WHERE ExpenseId= @rId
			INSERT INTO sAccounting.tExpenseDetail
			(ExpenseId,ExpenseSubGroupId,Amount,Remark)
			SELECT @lNextNumber,ExpenseSubGroupId,Amount,sSetup.fPortalXMLTagsReplaceReverse(Remark)
			FROM OPENXML (@loDoc, '/Table/ExpenseDetail', 1)
			WITH (ExpenseSubGroupId int,Amount decimal(20,5),Remark nvarchar(200)) --Added for mantis : 32211 by Nilesh
	 SELECT @lNextNumber AS Result
	 END  	

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

GO


 
ALTER PROCEDURE [sAccounting].[pExpenseSubGroupMasterAdd]	 	   
        @rOrgId smallint,
        @rId int, 
        @rExpenseGroupId int,
        @rCode nvarchar(100),
        @rTitle nvarchar(100),  
		@rIsObsolete bit,	
		@rCreatedUserId bigint,
		@rUpdatedUserId bigint,
		@rAmountLimit decimal(20,5) --Changed for mantis : 32211 by Nilesh
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
	 
		If Exists(select Id from  sAccounting.tExpenseSubGroupMaster where Code=@rCode AND OrgId=@rOrgId
		AND ExpenseGroupId=@rExpenseGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
			If Exists(select Id from sAccounting.tExpenseSubGroupMaster  where Title=@rTitle AND OrgId=@rOrgId
			AND ExpenseGroupId=@rExpenseGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END
	END
	ELSE
	BEGIN
			If  Exists(select Id from  sAccounting.tExpenseSubGroupMaster where Code=@rCode AND OrgId=@rOrgId 
			AND ExpenseGroupId=@rExpenseGroupId  AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If  Exists(select Id from  sAccounting.tExpenseSubGroupMaster where Title=@rTitle AND OrgId=@rOrgId 
		AND ExpenseGroupId=@rExpenseGroupId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
	

	END
	
	
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAccounting.tExpenseSubGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAccounting.tExpenseSubGroupMaster
		(
			OrgId,			
			Id,
			ExpenseGroupId,
			Code,
			Title, 
			IsObsolete,			
		    CreatedUserId, 
		    CreatedDateTime, 
		    UpdatedUserId, 
            UpdatedDateTime,
            AmountLimit
		)
	VALUES
		(
		    @rOrgId ,
			@lNextNumber , 
			@rExpenseGroupId,
			@rCode ,      
			@rTitle ,	
			@rIsObsolete,				
			@rCreatedUserId ,
			sCommon.fGetDate() ,
			@rUpdatedUserId ,
			sCommon.fGetDate(),
			@rAmountLimit									
		)
		
		   SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAccounting.tExpenseSubGroupMaster
	    SET
			ExpenseGroupId=@rExpenseGroupId,
			Code=@rCode, 
	        Title=@rTitle,
	        IsObsolete=@rIsObsolete,
	        UpdatedUserId=@rCreatedUserId, 
            UpdatedDateTime=sCommon.fGetDate(),
            AmountLimit=@rAmountLimit
	      WHERE Id = @rId
	       SELECT 11 AS Result
	 END  	

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

GO




ALTER PROCEDURE [sAccounting].[pRptExpenseListGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rEmployeeCode nvarchar(100),
    @rEmployeeName nvarchar(100) ,
	@rEmployeeId  bigint=0, 
	@rFromDate date,
    @rTodate date,   
    @rExpenseGroupId int=0,    
    @rStatusId int=0,
    @rOrgId smallint,
    @rIsDetail bit,
      @rBatchId int
	

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	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 = @rOrgId WHERE CM.Id = 548

       SELECT 
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2, 
			 E.Id AS ExpenseId,
			 E.EmployeeId,
			 --E.Amount, 
			 ([sAccounting].[fDecimalValueGet] (E.Amount, @DecimalCount)) AS Amount,	--change by Nilesh
			 E.Remark,
			 E.CreatedUserId,
			 E.CreatedDateTime,			 
			 E.UpdatedUserId,
			 E.UpdatedDateTime,
			 E.ExpenseDate,
			 E.ExpenseGroupId,
			 EGM.Title AS ExpenseGroupName,
			 EM.EmployeeName,
			 EM.Code AS EmployeeCode,
			 E.StatusReason,
			 ISNULL(E.StatusId,0) AS StatusId,
			 ISNULL(SM.Title,'Pending') AS StatusName,
			 --OM.DisplayTitle AS OrganizationName,
			 --ED.Amount AS ExpenseDetailAmount,
			 ([sAccounting].[fDecimalValueGet] (ED.Amount, @DecimalCount)) AS ExpenseDetailAmount,	--change by Nilesh
			 ESGM.Title As ExpenseTitle,
			 ESGM.Id As ExpenseSubGroupId,
			 @rIsDetail AS IsDetail,
			 ED.Remark AS ExpenseSubRemark
			 
        FROM 
				sAccounting.tExpense E
	  INNER JOIN sAccounting.tExpenseGroupMaster EGM ON EGM.Id = E.ExpenseGroupId
	  INNER JOIN sAccounting.tExpenseSubGroupMaster ESGM ON ESGM.ExpenseGroupId= EGM.Id
	  LEFT JOIN sAccounting.tExpenseDetail ED ON E.Id=ED.ExpenseId ANd ED.ExpenseSubGroupId = ESGM.Id
	  INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = E.EmployeeId 
	  INNER JOIN sCommon.tStatusMaster SM ON SM.Id = E.StatusId
	  --INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = E.OrgId
    	WHERE 
    		
    		
    		--(E.Id = @rId OR @rId = 0)
     (E.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND ((E.ExpenseDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
      AND ((E.ExpenseDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
      AND (E.ExpenseGroupId = @rExpenseGroupId OR @rExpenseGroupId = 0)      
       AND ((E.OrgId = @rOrgId) OR (@rOrgId = 0))
           AND (E.BatchId = @rBatchId OR @rBatchId = 0)
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')
      AND (E.StatusId = @rStatusId OR @rStatusId = 0)
      Order By ExpenseDate DESC
    		
END

GO
 
ALTER PROCEDURE [sAccounting].[pVoucherListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rVoucherTypeId int = 0,
	 @rTransactionDate Date,
	 @rTransactionDateTo Date,
	 @rVoucherNumber int,
	 @rVoucherNumberTo int,
	 @rLedgerId int,
	 @rNarration nvarchar(100),
	 @rAmount Decimal(20,5),
	 @rAccountingYearId int = 0,
	 @rIsApproved bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  BEGIN
			SET @rNarration = sCommon.fSearchStringGet(@rNarration)
	  END

	  Declare @DecimalCount INT,@lOrgGroupId Int
	  select @lOrgGroupId = OrgGroupId from sAccounting.tTransaction T where AccountingYearId = @rAccountingYearId

	 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 = @lOrgGroupId WHERE CM.Id = 548
	 
  SELECT   @rBuilder1 AS Builder1
		  ,@rBuilder2 AS Builder2
		  ,T.Id
		  ,VTM.Title AS VoucherType
		  ,T.VoucherNumber AS VoucherNo
		  ,T.TransactionDate AS VoucherDate
		  ,LM.Title AS Ledger
		  --,CASE WHEN ISNULL(TD.Amount,0) < 0 THEN ISNULL(TD.Amount,0) * -1 ELSE 0 END AS Credit --Commented for mantis : 32211 by Nilesh
		  ,([sAccounting].[fDecimalValueGet] ((CASE WHEN ISNULL(TD.Amount,0) < 0 THEN ISNULL(TD.Amount,0) * -1 
			ELSE 0 END), @DecimalCount)) Credit --Commented for mantis : 32211 by Nilesh
		  --,CASE WHEN ISNULL(TD.Amount,0) > 0 THEN ISNULL(TD.Amount,0) ELSE 0 END AS Debit --Commented for mantis : 32211 by Nilesh
		  ,([sAccounting].[fDecimalValueGet] ((CASE WHEN ISNULL(TD.Amount,0) > 0 THEN ISNULL(TD.Amount,0) 
			ELSE 0 END),@DecimalCount)) Debit --Commented for mantis : 32211 by Nilesh
		  ,T.Narration AS Narration
		  ,AM.ReportOrgTitle As OrgTitle
		  ,AM.SmallAddress1 AS SmallAddress1
		  ,AM.SmallAddress2 AS SmallAddress2,
		  T.TransactionApproveId	  	      
  FROM 
          sAccounting.tTransaction T
          INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
          INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id = T.VoucherTypeId
          INNER JOIN sAccounting.tLedgerMaster LM ON LM.Id=TD.LedgerId 
          INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId            
  WHERE 
				(T.VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId = 0) 
			AND ((T.Narration like @rNarration) OR (ISNULL(@rNarration,'') = '')) 		
			AND (T.TransactionDate >= @rTransactionDate OR ISNULL(@rTransactionDate,'') = '') 
			And (T.TransactionDate <= @rTransactionDateTo OR ISNULL(@rTransactionDateTo,'') = '')
			AND (T.VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0) 
			AND (T.VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0)
			AND (TD.LedgerId = @rLedgerId OR @rLedgerId=0)
			AND (TD.Amount = @rAmount OR ISNULL(@rAmount,0) = 0)
			AND LM.AccountingYearId = @rAccountingYearId
			AND T.AccountingYearId = @rAccountingYearId
			AND ((@rIsApproved=1 AND  ISNULL(T.TransactionApproveId,0) !=0) OR (@rIsApproved = 0) )
			
            Order By T.TransactionDate,T.VoucherNumber, LM.Id
END

PRINT N'Altering Procedure [sAccounting].[pTransactionApproveDetailAdd]...';
GO
PRINT N'Altering Procedure [sAlert].[pSubjectwiseAttendanceGet]...';


GO
ALTER PROCEDURE [sAlert].[pSubjectwiseAttendanceGet]	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int=0,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rMailSubject nvarchar(500)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rSubjectId = 0 OR @rSubjectId IS NULL)
	BEGIN 
		select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace(
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[FromDate]',CONVERT(VARCHAR(10), @rFromDate, 103)),
			'[ToDate]',CONVERT(VARCHAR(10), @rToDate, 103)),
			'[TotalCount]',(isnull(TCount,0.00)+isnull(ACount,0.00))),
			'[PresentCount]',convert(decimal(12,2),isnull(TCount,0.00))),
			'[AbsentCount]',convert(decimal(12,2),isnull(ACount,0.00))),
			'[AveragePresence]',case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
								convert(decimal(12,2),(convert(decimal(12,2),isnull(TCount,0.00)*100)/convert(decimal(12,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
								else 0.00 end),
			'[AbsentDates]',[sAttendance].[fAbsentDatesGet](@rFromDate,@rTodate,5,@rSubjectId,SC.AcademicId)),
			'[SubjectName]','All Subject')
			AS MsgText,			 
			@rMailSubject AS Subject,
			2001 AS ReceiverSourceTypeId,
			SC.AcademicId AS ReceiverSourceId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			(isnull(TCount,0.00)+isnull(ACount,0.00)) as TotalCount,
			convert(decimal(12,2),isnull(TCount,0.00)) as PresentCount,
			convert(decimal(12,2),isnull(ACount,0.00)) as AbsentCount,
			case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
							convert(decimal(12,2),(convert(decimal(12,2),isnull(TCount,0.00)*100)/convert(decimal(12,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
							else 0.00 end as AveragePresence,
			[sAttendance].[fAbsentDatesGet](@rFromDate,@rTodate,5,@rSubjectId,SC.AcademicId) AS AbsentDates,
			SC.WhatsAppContactNo
	FROM 
	sStudent.vStudentCommunication SC 
	LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS TCount 
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 		
			SR1.AttendanceTypeId=5
			AND SR1.IsPresent =1 
			AND (SR1.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR1.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) TC ON TC.AcademicId = SC.AcademicId
    LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS ACount  
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 
			SR1.IsPresent = 0		
			AND SR1.AttendanceTypeId=5
			AND (SR1.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR1.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 	 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) AC ON AC.AcademicId = SC.AcademicId
	--INner JOIn sSetup.vClassSubject CS  On  CS.IsObsolete = 0 AND CS.ClassId=@rClassId 
	WHERE
	 SC.BatchId = @rBatchId
	 AND ((SC.ClassId = @rClassId))
	 AND ((SC.DivisionId = @rDivisionId) OR @rDivisionId=0)
	 AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	 Order by SC.AcademicId 
	END
	ELSE
	BEGIN
		select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace(
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[FromDate]',CONVERT(VARCHAR(10), @rFromDate, 103)),
			'[ToDate]',CONVERT(VARCHAR(10), @rToDate, 103)),
			'[TotalCount]',(isnull(TCount,0.00)+isnull(ACount,0.00))),
			'[PresentCount]',convert(decimal(12,2),isnull(TCount,0.00))),
			'[AbsentCount]',convert(decimal(12,2),isnull(ACount,0.00))),
			'[AveragePresence]',case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
								convert(decimal(12,2),(convert(decimal(12,2),isnull(TCount,0.00)*100)/convert(decimal(12,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
								else 0.00 end),
			'[AbsentDates]',[sAttendance].[fAbsentDatesGet](@rFromDate,@rTodate,5,@rSubjectId,SC.AcademicId)),
			'[SubjectName]',CS.SubjectName)
			AS MsgText,			 
			@rMailSubject AS Subject,
			2001 AS ReceiverSourceTypeId,
			SC.AcademicId AS ReceiverSourceId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			(isnull(TCount,0.00)+isnull(ACount,0.00)) as TotalCount,
			convert(decimal(12,2),isnull(TCount,0.00)) as PresentCount,
			convert(decimal(12,2),isnull(ACount,0.00)) as AbsentCount,
			case when (isnull(TCount,0.00)+isnull(ACount,0.00))<>0.00 then
							convert(decimal(12,2),(convert(decimal(12,2),isnull(TCount,0.00)*100)/convert(decimal(12,2),isnull(TCount,0.00)+isnull(ACount,0.00))))
							else 0.00 end as AveragePresence,
			[sAttendance].[fAbsentDatesGet](@rFromDate,@rTodate,5,@rSubjectId,SC.AcademicId) AS AbsentDates,
			SC.WhatsAppContactNo
	 from 
	sStudent.vStudentCommunication SC 
	LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS TCount 
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 		
			SR1.AttendanceTypeId=5
			AND SR1.IsPresent = 1 
			AND (SR1.SubjectId=@rSubjectId OR (ISNULL(@rSubjectId,0)=0))
			AND (SR1.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR1.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) TC ON TC.AcademicId = SC.AcademicId
    LEFT JOIN
	(
		Select A.Id AS AcademicId, COUNT(1) AS ACount  
		   FROM sAttendance.tStudentRegister SR1
		   INNER JOIN sStudent.tAcademic A ON SR1.AcademicId = A.Id 
		   WHERE 
		   SR1.IsPresent = 0		
			AND SR1.AttendanceTypeId=5
			AND (SR1.SubjectId=@rSubjectId OR (ISNULL(@rSubjectId,0)=0)) 
			AND (SR1.AttendanceDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (SR1.AttendanceDate <= @rToDate OR ISNULL(@rToDate,'')='') 	 
			AND (A.BatchId=@rBatchId)			 
			AND (A.ClassId = @rClassId)
			AND (A.DivisionId = @rDivisionId OR @rDivisionId=0)
			GROUP BY A.Id
    ) AC ON AC.AcademicId = SC.AcademicId
	INner JOIn sSetup.vClassSubject CS  On  CS.IsObsolete = 0 AND CS.ClassId=@rClassId 
	WHERE
	 SC.BatchId = @rBatchId
	 AND ((SC.ClassId = @rClassId))
	 AND ((SC.DivisionId = @rDivisionId) OR @rDivisionId=0)
	 AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	 AND (CS.SubjectId=@rSubjectId OR @rSubjectId= 0)
	 Order by SC.AcademicId 
	END
	
End
GO
PRINT N'Altering Procedure [sAttendance].[pYearlyRegisterUpdate]...';


GO
ALTER PROCEDURE [sAttendance].[pYearlyRegisterUpdate]

     @rOrgId int,
	 @rBatchId int,
	 @rAttendanceTypeId tinyint = 1  -- MantisId : 0029240
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @lQuery AS nvarchar(max)
	
	DELETE YR FROM sAttendance.tYearlyRegister  YR INNER JOIN
	sStudent.tAcademic A ON YR.AcademicId = A.Id
	WHERE A.BatchId = @rBatchId AND YR.AttendanceTypeId = @rAttendanceTypeId -- MantisId : 0029240
 
 	INSERT INTO sAttendance.tYearlyRegister(AcademicId,AttendanceTypeId) 
	SELECT Id, @rAttendanceTypeId FROM sStudent.tAcademic WHERE BatchId = @rBatchId
	
	
	CREATE TABLE #tempClass
	(	Id int IDENTITY,
		ClassId int  
	)
	
	INSERT INTO #tempClass (ClassId) 
	SELECT  ID FROM sSetup.tClassMaster  WHERE OrgId = @rOrgId
	
	
	DECLARE @lClassCount int,@lClassId int 
	DECLARE @lClassCounter int 
	SET @lClassCounter = 0
	
	Select @lClassCount = MAX(Id) from #tempClass
	
 	WHILE (@lClassCounter <= @lClassCount)
	BEGIN
	
		SELECT @lClassId = ClassId FROM #tempClass WHERe Id = @lClassCounter	
	
 		CREATE TABLE #tempMonthlySetup
		(	Id int IDENTITY,
			ForMonth int,
			ForYear int,
			ClassId int
		)
	
		INSERT INTO #tempMonthlySetup (ForMonth,ForYear,ClassId) 
		SELECT MS.ForMonth, MS.ForYear,MS.ClassId FROM 
		sSetup.fMonthYearForBatchGET(@rBatchId) AS MY
		LEFT JOIN sAttendance.tMonthlySetup MS ON MS.BatchId=MY.BatchId AND (MS.ClassId=@lClassId) AND MS.ForMonth = MY.MonthNumber AND MS.ForYear = MY.YearNumber WHERE MY.BatchId=@rBatchId
 
	
		DECLARE @lCount int
	
		DECLARE @lCounter int,@lForMonth int,@lForYear int
		Select @lCount = MAX(Id) from #tempMonthlySetup
		
		 SET @lCounter = 1
		 IF (@lCount > 12) 
		 SET @lCount =12
		while (@lCounter <= @lCount)
		BEGIN
	 
			SELECT @lForMonth = ForMonth ,@lForYear = ForYear FROM #tempMonthlySetup WHERe Id = @lCounter

			SET @lQuery = 'UPDATE YR    
			SET Month' +   convert(nvarchar(15),@lCounter)+  ' = MM.Code,
			TotalDays' +   convert(nvarchar(15),@lCounter)+  ' = MR.TotalCount,
			PresentDays' +   convert(nvarchar(15),@lCounter)+  ' = MR.PresentCount 
			from sAttendance.tYearlyRegister YR
			INNER JOIN sAttendance.tMonthlyRegister MR
			ON YR.AcademicId = MR.AcademicId AND YR.AttendanceTypeId = MR.AttendanceTypeId
			AND MR.ForMonth = '  + convert(nvarchar(15),@lForMonth)  + ' AND MR.ForYear = ' + convert(nvarchar(15),@lForYear)  +
			' INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
			INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
			AND A.BatchId = ' +  convert(nvarchar(15),@rBatchId)  + ' AND A.ClassId = ' + convert(nvarchar(15),@lClassId) +
			' WHERE YR.AttendanceTypeId = ' +  convert(nvarchar(5),@rAttendanceTypeId)
    
		print @lQuery
		execute(@lQuery)
	
	--IF 	(@lCounter = 1)
	--BEGIN
 
	--UPDATE YR    
 --   SET Month1  = MM.Title,TotalDays1 = MR.TotalCount,PresentDays1 = MR.PresentCount 
 --   from sAttendance.tYearlyRegister YR
 --   INNER JOIN sAttendance.tMonthlyRegister MR
 --   ON YR.AcademicId = MR.AcademicId
 --   AND MR.ForMonth = @lForMonth AND MR.ForYear = @lForYear
 --   INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
 --   INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
 --   AND A.BatchId = @rBatchId AND A.ClassId = @lClassId
    
	--END
	--ELSE IF (@lCounter = 2)
	--BEGIN

	--UPDATE YR    
 --   SET Month2  = MM.Title,TotalDays2 = MR.TotalCount,PresentDays2 = MR.PresentCount 
 --   from sAttendance.tYearlyRegister YR
 --   INNER JOIN sAttendance.tMonthlyRegister MR
 --   ON YR.AcademicId = MR.AcademicId
 --   AND MR.ForMonth = @lForMonth ANd MR.ForYear = @lForYear
 --   INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
 --   INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
 --   AND A.BatchId = @rBatchId AND A.ClassId = @lClassId
    
	--END
 
		SET @lCounter = @lCounter + 1
	END
	DROP TABLE #tempMonthlySetup
	SET @lClassCounter = @lClassCounter + 1
	END 

    UPDATE YR 
    SET TotalDays = (ISNULL(TotalDays1,0) + ISNULL(TotalDays2,0) + ISNULL(TotalDays3,0) + ISNULL(TotalDays4,0) + ISNULL(TotalDays5,0) + ISNULL(TotalDays6,0)
					+ ISNULL(TotalDays7,0) + ISNULL(TotalDays8,0) + ISNULL(TotalDays9,0) + ISNULL(TotalDays10,0) + ISNULL(TotalDays11,0) + ISNULL(TotalDays12,0)),
		PresentDays = ((ISNULL(PresentDays1,0) + ISNULL(PresentDays2,0) + ISNULL(PresentDays3,0) + ISNULL(PresentDays4,0) + ISNULL(PresentDays5,0) + ISNULL(PresentDays6,0)
					+ ISNULL(PresentDays7,0) + ISNULL(PresentDays8,0) + ISNULL(PresentDays9,0) + ISNULL(PresentDays10,0) + ISNULL(PresentDays11,0) + ISNULL(PresentDays12,0)))		
     FROM sAttendance.tYearlyRegister AS YR
    INNER JOIN sStudent.tAcademic A ON YR.AcademicId = A.Id
    WHERE  A.BatchId = @rBatchId 
	AND YR.AttendanceTypeId = @rAttendanceTypeId -- MantisId : 0029240
 
    UPDATE  YR SET YR.AvergeAttendance = (convert(decimal(5,2),(convert(decimal(5,2),YR.PresentDays)*100)/(convert(decimal(5,2),YR.TotalDays)))) 
    FROM sAttendance.tYearlyRegister AS YR
    INNER JOIN sStudent.tAcademic A ON YR.AcademicId = A.Id	
    WHERE YR.TotalDays <> 0 AND A.BatchId = @rBatchId 
	AND YR.AttendanceTypeId = @rAttendanceTypeId -- MantisId : 0029240
    	 
	DROP TABLE #tempClass
END
GO
PRINT N'Altering Procedure [sCanteen].[pBreakTypeMasterAdd]...';


GO


ALTER PROCEDURE [sCanteen].[pBreakTypeMasterAdd]
	  
		@rOrgGroupId int,
        @rId int,
        @rCanteenId int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rOrderIndex int,
		@rIsObsolete bit,		
		@rCreatedUserId bigint,
		@rUpdatedUserId bigint
								
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		
		   IF EXISTS(SELECT 1 FROM sCanteen.tBreakTypeMaster WHERE Code=@rCode AND CanteenId=@rCanteenId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			IF EXISTS(SELECT 1 FROM sCanteen.tBreakTypeMaster WHERE Title=@rTitle AND CanteenId=@rCanteenId)
			BEGIN
				SELECT -102 AS Result
				RETURN
			END
			--mantis Start - 0033603
			IF EXISTS(SELECT 1 FROM sCanteen.tBreakTypeMaster WHERE OrderIndex=@rOrderIndex AND CanteenId=@rCanteenId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			--mantis End - 0033603
	END
	ELSE
	BEGIN
	        IF EXISTS(SELECT 1 FROM sCanteen.tBreakTypeMaster WHERE Code=@rCode AND CanteenId=@rCanteenId AND Id<>@rId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			IF EXISTS(SELECT 1 FROM sCanteen.tBreakTypeMaster WHERE Title=@rTitle AND CanteenId=@rCanteenId AND Id<>@rId)
			BEGIN
				SELECT -102 AS Result
				RETURN
			END
			--mantis Start - 0033603
			IF EXISTS(SELECT 1 FROM sCanteen.tBreakTypeMaster WHERE OrderIndex=@rOrderIndex AND CanteenId=@rCanteenId AND Id<>@rId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			--mantis End - 0033603

	END
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tBreakTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCanteen.tBreakTypeMaster
		( 
			OrgGroupId,
			Id,	
			CanteenId,			
			Code,
			Title,
			OrderIndex,
			IsObsolete,			
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
			

		)
	VALUES
		(
			@rOrgGroupId,
			@lNextNumber,
		    @rCanteenId,			
			@rCode,
			@rTitle,	
			@rOrderIndex,		
			@rIsObsolete,
			
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rUpdatedUserId,
			sCommon.fGetDate()
			
		)
		
		
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCanteen.tBreakTypeMaster
	    SET
	        CanteenId=@rCanteenId,
			Title=@rTitle,			
			Code=@rCode,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			OrderIndex=@rOrderIndex
			
	      
	      WHERE Id = @rId
	      
	      SELECT @lNextNumber AS Result
	 END  	

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


GO


ALTER PROCEDURE [sCanteen].[pCanteenMasterAdd]
	 
        @rId int,
		@rNumber  int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rIsObsolete bit,
		@rOrgGroupId smallint,
		@rCreatedUserId bigint,
		@rUpdatedUserId bigint,
		@rOrderIndex int,
		@rDepositHeadId bigint,
		@rDepositExpenseTypeId bigint
		
		
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		
		If Exists(select 1 from sCanteen.tCanteenMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId )
		Begin
			select -102 as Result
			RETURN
		End
		If Exists(select 1 from sCanteen.tCanteenMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		--mantis Start - 0033603
		If Exists(select 1 from sCanteen.tCanteenMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -104 as Result
			RETURN
		END 
		If Exists(select 1 from sCanteen.tCanteenMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
			BEGIN
			select -105 as Result
			RETURN
		END 
		--mantis End - 0033603
	END
	ELSE
	BEGIN
	--mantis Start - 0033603
		If Exists(select 1 from sCanteen.tCanteenMaster  where Code=@rCode AND OrgGroupId=@rOrgGroupId )
		Begin
			select -102 as Result
			RETURN
		End
		--mantis End - 0033603
		If  Exists(select Id from sCanteen.tCanteenMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		--mantis Start - 0033603
		If Exists(select 1 from sCanteen.tCanteenMaster where Number=@rNumber AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -104 as Result
			RETURN
		END 
		If Exists(select 1 from sCanteen.tCanteenMaster where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId AND Id<>@rId)
			BEGIN
			select -105 as Result
			RETURN
		END 
		--mantis End - 0033603

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tCanteenMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCanteen.tCanteenMaster
		(
			Id,
			Title,
			Number,
			Code,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgGroupId ,
			OrderIndex,
			DepositHeadId,
			DepositExpenseTypeId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rNumber,
			@rCode,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rUpdatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rOrderIndex,
			@rDepositHeadId,
			@rDepositExpenseTypeId
		)
		
		  INSERT INTO sSecurity.tUserAccess
           (
           SourceTypeId
           ,SourceId
           ,[UserId]
           
           )
		   SELECT 
		   2026
		   ,@lNextNumber
		   ,@rCreatedUserId
		   
		    SELECT @lNextNumber AS Result
		   
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCanteen.tCanteenMaster
	    SET
			Title=@rTitle,
			Number=@rNumber,
			Code=@rCode,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			OrderIndex=@rOrderIndex,
			DepositHeadId=@rDepositHeadId,
			DepositExpenseTypeId=@rDepositExpenseTypeId
			
	      
	      WHERE Id = @rId
	      SELECT @lNextNumber AS Result
	 END  	

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


GO


ALTER PROCEDURE [sCanteen].[pFoodItemMasterAdd]
	  
	  
        @rId int,
        @rCanteenId int,
		@rCode nvarchar(20),
		@rTitle nvarchar(100),
		@rItemPrice decimal(12,2),
		@rIsObsolete bit,
		@rOrgGroupId int,
		@rCreatedUserId bigint,
		@rUpdatedUserId bigint,
		@rOrderIndex int
		
		
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN  
		
		IF EXISTS(SELECT 1 FROM sCanteen.tFoodItemMaster WHERE Code=@rCode AND CanteenId=@rCanteenId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			 --Mantis Start - 0033603
			IF EXISTS(SELECT 1 FROM sCanteen.tFoodItemMaster WHERE OrderIndex=@rOrderIndex AND CanteenId=@rCanteenId)
			BEGIN
				SELECT -102 AS Result
				RETURN
			END
			 --Mantis End - 0033603
	END
	--ELSE
	--BEGIN
	--  If  Exists(select Id from sCanteen.tFoodItemMaster where CanteenId=@rCanteenId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber int

	IF(@rId = 0)	
	BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCanteen.tFoodItemMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCanteen.tFoodItemMaster
		(
			CanteenId,
			Id,	
			Code,
			Title,
			ItemPrice,
			IsObsolete,
			OrderIndex,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
			

		)
	VALUES
		(
		    @rCanteenId,
			@lNextNumber,
			@rCode,
			@rTitle,
			@rItemPrice,
			@rIsObsolete,
			@rOrderIndex,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rUpdatedUserId,
			sCommon.fGetDate()
			
		)
		
		
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId



	 IF EXISTS(SELECT 1 FROM sCanteen.tFoodItemMaster WHERE Code=@rCode AND CanteenId=@rCanteenId AND Id<>@rId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			 --Mantis Start - 0033603
	 IF EXISTS(SELECT 1 FROM sCanteen.tFoodItemMaster WHERE OrderIndex=@rOrderIndex AND CanteenId=@rCanteenId AND Id<>@rId)
			BEGIN
				SELECT -102 AS Result
				RETURN
			END
			 --Mantis End - 0033603


	    UPDATE  sCanteen.tFoodItemMaster
	    SET
	        CanteenId=@rCanteenId,
			Title=@rTitle,
			ItemPrice=@rItemPrice,
			Code=@rCode,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			OrderIndex=@rOrderIndex
			
	      
	      WHERE Id = @rId
	      
	      SELECT @lNextNumber AS Result
	 END  	

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


GO
ALTER PROCEDURE [sCertificate].[pFirstTrialBulkGet]
	 
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rStatusId int=0 --Mantis - 33375
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.Code,			
			SA.Name,
			ISNULL(FT.Id,0) AS Id,
			ISNULL(FT.FirstTrialDate,'') AS FirstTrialDate,
			ISNULL(FT.Trial,'') AS Trial,
			ISNULL(FT.SeatNo,'') AS SeatNo,
			ISNULL(FT.ExamCentre,'') AS ExamCentre,
			ISNULL(FT.Remark,'') AS Remark,
			ISNULL(FT.LastExamName,'') AS LastExamName, -- Mantis : 0027927 #Start
			ISNULL(FT.ObtainedMark,'') AS ObtainedMark,
			ISNULL(FT.AdditionalRemark,'') AS AdditionalRemark -- #End
			
  FROM 
			[sStudent].[vStudentAcademic]  SA 
			LEFT JOIN sCertificate.tFirstTrial FT ON FT.AcademicId=SA.AcademicId
  WHERE 
			(SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SA.BatchId=@rBatchId
			AND SA.OrgID=@rOrgId 
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)   --Mantis - 33375
			order by SA.RollNo
END
GO
PRINT N'Altering Procedure [sCertificate].[pRptFirstTrialCertificateGet]...';


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

DECLARE @lIsDisplayImageHeader bit = 0

DECLARE @lConfigValue nvarchar(50)
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 = 179 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF(@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF(@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	--add for 28093 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 28093 mantis end

	SELECT
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			FT.Id,
			FT.Number,
			FT.AcademicId,
			FT.FirstTrialDate,
			FT.ExamCentre,
			FT.ExamYear,
			FT.SeatNo,
			FT.Trial,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			SM.LastName as Surname,
			SO.GenderId,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SM.StatusId,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			CM.DisplayTitle  AS ClassName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			(CASE WHEN CGM.Title='10' THEN  'SSC'
			WHEN  CGM.Title='12'  THEN 'HSC'  ElSE CGM.Title + ' '+'std'
			 END) AS Exam,
			 FT.Remark AS Remark,
			 ISNULL(SF.FatherName,'') As FatherName,
			 ISNULL(SF.MotherName,'') As MotherName,
			 SA.AdmissionDate,
			 SO.BirthDateInWord ,
			 SO.DateOfBirth,
			 SI.StudentPhoto,
			 @lIDConfigValue AS ItemValue,
			 SM.SUID ,
			 STM.Title as StreamName,
			 ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			 OM.ReportOrgTitle,
			--(CASE WHEN OI.CertificateHeaderA4Portrait IS NULL THEN
			--OI.CertificateHeaderA4
			--ELSE OI.CertificateHeaderA4Portrait END ) AS CertificateHeader
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			BM.Title AS Batch,
			ISNULL(SA.LeftDate,'') AS LeftDate,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(OM.PrincipalSignature,0x) AS PrincipalSignature,
			EI.EmployeeId,
			SC.PresentStreetOne AS PresentStreetOne,		--add for 28093 mantis start
			SC.PresentStreetTwo AS PresentStreetTwo,
			SC.PresentStreetThree AS PresentStreetThree,
			SC.PresentCountry AS PresentCountry,
			SC.PresentState AS PresentState,
			SC.PresentCity AS PresentCity,
			SC.PresentZipCode AS PresentZipCode,
			SC.PresentContactNo AS PresentContactNo,
			@lIsShowPhoto AS IsShowPhoto,
			CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
			ISNULL(SI.QRCode,'') AS QRCode,					--add for 28093 mantis end
			ISNULL(FT.LastExamName,'') AS LastExamName,   -- Mantis : 0027927 #Start
			ISNULL(FT.ObtainedMark,'') AS ObtainedMarkInLastExam,
			ISNULL(FT.AdditionalRemark,'') AS AdditionalRemark,
			DM.DisplayTitle AS DivisionName,
			BM.FromDate AS BatchStartDate,
			BM.ToDate AS BatchEndDate,
			ISNULL(SGM.Title,'') AS StudentGroup,  -- #End
			SA.AdmissionNumber --Add for Mentis : 0033616

	FROM
			sCertificate.tFirstTrial FT
			INNER JOIN sStudent.tAcademic A ON FT.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN  sSetup.tStreamMaster STM ON STM.Id= CM.StreamId
			Left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sSetup.tClassGroupMaster CGM ON CGM.Id = CM.ClassGroupId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id			--add for 28093 mantis
			LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SM.StudentGroupId -- Mantis : 0027927
			
	WHERE
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			AND ((FT.FirstTrialDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((FT.FirstTrialDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((FT.Number=@rNumber) OR (@rNumber=''))
			AND ((FT.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((FT.Number <= @rToNo) OR (@rToNo=''))
			--Group By FT.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,FT.SeatNo,FT.Trial,SM.Code,SM.FirstName,OM.StateName,SO.GenderId,
			--OM.CityName,OM.StateName,FT.FirstTrialDate,FT.ExamCentre,FT.ExamYear,SM.MiddleName,SM.LastName,OM.CityName,SM.StatusId
			--,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering Procedure [sCertificate].[pRptLeavingCertificateGet]...';


GO

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

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

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


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

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


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

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

	WHERE 
				L.OrgId=@rOrgId
				AND	vSA.BatchId = @rBatchId 
				AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
				AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				--AND ((L.LCDate=@rLCDate) OR (ISNULL(@rLCDate,'')=''))
				--AND ((L.LeftDate=@rLeftDate) OR (ISNULL(@rLeftDate,'')=''))
				--AND ((L.LCCopy=@rLCCopy) OR (@rLCCopy=0))
				--AND ((L.LCBookNumber=@rLCBookNumber) OR (@rLCBookNumber=''))
				AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
				AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
				AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
				AND ((DM.ClassId=@rClassId) OR(@rClassId=0))
				--group by MR.PresentCount,MR.TotalCount, SubM.Title, SM.Code,L.AcademicId,SM.FirstName,SM.LastName,SM.MiddleName,SF.FatherName,SF.MotherName,NM.Title,
				--SO.CastCategoryId,RM.Title,so.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,SO.DateOfBirth,SO.BirthDateInWord,SA.PreviousSchool,
				--	SA.AdmissionDate,L.LeftDate,L.LCReason,L.LCProgress,L.LCConduct,L.LCRemark,L.LCDate,SO.GenderId,
				--	OM.CityName,OM.StateName,CM.DisplayTitle,CMS.DisplayTitle,SM.StatusId,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
END
GO
PRINT N'Altering Procedure [sCommon].[pReportHistoryGet]...';


GO

ALTER PROCEDURE [sCommon].[pReportHistoryGet]
	 
	        @rUserId bigint,
	        @rScreenId int
	  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			Id,
			ReportName,
		   (CASE WHEN StatusId = 1 THEN 'Completed' 
				 WHEN StatusId = 2 THEN 'No Record'
				 WHEN StatusId = 3 THEN 'Error'
				 ELSE 'Canceled' END) AS Status,
		   CreatedDateTime,
		   UpdatedDateTime,
		   ISNULL(Guid,'') AS ReportPath,
		   StatusId
	FROM
			 sCommon.tReportHistory
	WHERE 
	ScreenId = @rScreenId
	AND CreatedUserId = @rUserId
	AND CAST(CreatedDateTime AS Date) > CAST(DATEADD(day, -2, GETDATE()) AS DATE)
	Order By CreatedDateTime DESC
   
END
GO
PRINT N'Altering Procedure [sConfig].[pDisplayFieldOrgListGet]...';


GO

ALTER PROCEDURE [sConfig].[pDisplayFieldOrgListGet]
          
           @rOrgId smallint,
           @rFieldSource  nvarchar(100)
 
AS
SET NOCOUNT ON

BEGIN

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) 
ORDER by DM.Id -- Changed for mantis : 33583 by Nilesh
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptAddValidate]...';


GO
ALTER PROCEDURE [sFee].[pReceiptAddValidate] 
	@rAcademicId BIGINT
	,@rFeeSetupIds NVARCHAR(max) = ''
	,@rReceiptDetailXml [nvarchar] (max)
	,@rPayTypeId TINYINT = 0
	,@rPaymentTransactionId BIGINT = 0
	,@rReceiptBookId INT = 0
	,@rIsCreated INT OUTPUT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @loDoc INT

	DECLARE @lWrongFeeSetupOrReceiptBook int = 0, @lAlreadyPaid int = 0, @lDuplicateReceipt int = 0

	EXEC sp_xml_preparedocument @loDoc OUTPUT,@rReceiptDetailXml

	CREATE TABLE #temptable (
		FeeId INT
		,Id INT
		,Amount DECIMAL(12, 2)
		,ReceiptBookId INT
		,AcademicId BIGINT
		)

	INSERT INTO #temptable (
		FeeId
		,Id
		,Amount
		,ReceiptBookId
		,AcademicId
		)
	SELECT FS1.FeeId
		,FS1.Id
		,
		--ISNULL(FS1.IsOptional,0)AS IsOptional,
		--ISNULL(FS1.IsVariable,0)AS IsVariable,
		ISNULL(FS1.Amount, 0) AS Amount
		,
		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--FS1.BatchId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	--FM.Title AS FeeName			 
	FROM sFee.tFeeSetup FS1
	INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId = FS1.ClassId
		AND FS1.BatchId = SA1.BatchId
	INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
	INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
	WHERE (FS1.IsOptional = 0)
		AND SA1.Id = @rAcademicId
		AND (ISNULL(FS1.Id, 0) IN (SELECT cast(item AS INT) FROM sCommon.fnsplit(@rFeeSetupIds, ',')) OR @rFeeSetupIds = '')
	
	UNION ALL
	
	SELECT FS1.FeeId
		,FS1.Id
		,
		--ISNULL(FS1.IsOptional,0)AS IsOptional,
		--ISNULL(FS1.IsVariable,0)AS IsVariable,
		ISNULL(FS1.Amount, 0) AS Amount
		,
		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--FS1.BatchId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	--FM.Title AS FeeName				
	FROM sFee.tFeeSetup FS1
	INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId = FS1.Id
	INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS1.FeeId
	INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id
	INNER JOIN sStudent.tAcademic SA1 ON SA1.Id = FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	WHERE (FS1.IsOptional = 1)
		AND SA1.Id = @rAcademicId
		AND (ISNULL(FS1.Id, 0) IN (SELECT cast(item AS INT) FROM sCommon.fnsplit(@rFeeSetupIds, ',')) OR @rFeeSetupIds = '')

	CREATE TABLE #temptable1 (
		PaidAmount DECIMAL(12, 2)
		,FeeSetupId INT
		,SourceId BIGINT
		)

	INSERT INTO #temptable1 (
		PaidAmount
		,FeeSetupId
		,SourceId
		)
	SELECT ISNULL(SUM(RD.Amount), 0) AS PaidAmount
		,RD.FeeSetupId
		,R.SourceId
	FROM sFee.tReceipt R
	INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id AND R.SourceTypeId = 2001
	INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
	INNER JOIN sStudent.tAcademic SA1 ON SA1.Id = R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId
	WHERE (R.SourceTypeId = 2001)
		AND R.SourceId = @rAcademicId
		AND (R.IsObsolete = 0)
		AND (ISNULL(FS.Id, 0) IN (SELECT cast(item AS INT) FROM sCommon.fnsplit(@rFeeSetupIds, ',')) OR @rFeeSetupIds = '')
	GROUP BY FeeSetupId,R.SourceId

	-- For Mantis 0032370 by Foram Start
	IF (@rAcademicId > 0)
	BEGIN
		IF NOT EXISTS (
				SELECT 1
				FROM #temptable FS
				INNER JOIN (
					SELECT FeeSetupId
						,Amount
						,@rReceiptBookId AS ReceiptBookId
					FROM OPENXML(@loDoc, '/Table/ReceiptDetail', 1) WITH (
							FeeSetupId INT
							,Amount DECIMAL(12, 2)
							)
					) AS RD ON RD.FeeSetupId = FS.Id AND RD.ReceiptBookId = FS.ReceiptBookId
				)
		BEGIN
			SELECT @lWrongFeeSetupOrReceiptBook = 1
		END
	END -- For Mantis 0032370 by Foram End
	
	
	IF EXISTS (
			SELECT 1
			FROM sStudent.tAcademic SA
			INNER JOIN #temptable
				--(
				--SELECT 
				--		FS1.FeeId,
				--		FS1.Id,
				--		--ISNULL(FS1.IsOptional,0)AS IsOptional,
				--		--ISNULL(FS1.IsVariable,0)AS IsVariable,
				--		ISNULL(FS1.Amount,0) AS Amount,
				--		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				--		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				--		--FS1.BatchId,
				--		--ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				--		SA1.Id AS AcademicId
				--		--FM.Title AS FeeName			 
				--	FROM sFee.tFeeSetup FS1
				--	INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				--	--INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
				--	AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
				--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				--	--INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
				--	WHERE 
				--	    (FS1.IsOptional=0)
				--	    AND SA1.Id = @rAcademicId				
				--		AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				--		UNION ALL
				--	SELECT 
				--		FS1.FeeId,
				--		FS1.Id,
				--		--ISNULL(FS1.IsOptional,0)AS IsOptional,
				--		--ISNULL(FS1.IsVariable,0)AS IsVariable,
				--		ISNULL(FS1.Amount,0)AS Amount,
				--		--ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				--		--ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				--		--FS1.BatchId,
				--		--ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				--		SA1.Id AS AcademicId
				--		--FM.Title AS FeeName				
				--	FROM sFee.tFeeSetup FS1
				--		INNER JOIN sFee.tFeeOptional FO	ON FO.FeeSetupId=FS1.Id
				--		--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				--   					--INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
				--		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId 
				--		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				--WHERE
				--		  (FS1.IsOptional=1)
				--		   AND SA1.Id = @rAcademicId	
				--		AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='') 
				--)
				FS ON FS.AcademicId = SA.Id
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId = FS.Id AND FA.SourceId = SA.Id
			LEFT JOIN #temptable1
				--(
				--	SELECT 
				--			ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				--    FROM
				--		sFee.tReceipt R 
				--		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id AND R.SourceTypeId = 2001
				--		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				--		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId	 
				--	WHERE	
				--	(R.SourceTypeId = 2001)
				--		 AND R.SourceId = @rAcademicId				
				--		AND (R.IsObsolete = 0) 
				--		AND (ISNULL(FS.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				--		GROUP BY FeeSetupId,R.SourceId	
				--)
				R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
			LEFT JOIN (
				SELECT FeeSetupId
					,Amount
				FROM OPENXML(@loDoc, '/Table/ReceiptDetail', 1) WITH (
						FeeSetupId INT
						,Amount DECIMAL(12, 2)
						)
				) AS RD ON RD.FeeSetupId = FS.Id
			WHERE SA.Id = @rAcademicId
				AND (ISNULL(FS.Amount, 0.00) + ISNULL(FA.VariableAmount, 0.00) + ISNULL(FA.AdditionalAmount, 0.00) - ISNULL(FA.DiscountAmount, 0.00) - ISNULL(FA.NotApplicableAmount, 0.00) - ISNULL(R.PaidAmount, 0.00) - RD.Amount < 0)
			)
	BEGIN
		SELECT @lAlreadyPaid = 1
	END
	
	--Start for mantis 0031290 By Foram
	IF (@rPayTypeId = 8)
	BEGIN
		IF EXISTS (
				SELECT 1
				FROM sFee.tReceipt R
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id
					AND R.SourceTypeId = 2001
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id = R.SourceId
					AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId
				WHERE (R.SourceTypeId = 2001)
					AND R.SourceId = @rAcademicId
					AND (R.IsObsolete = 0)
					AND (
						ISNULL(FS.Id, 0) IN (
							SELECT cast(item AS INT)
							FROM sCommon.fnsplit(@rFeeSetupIds, ',')
							)
						OR @rFeeSetupIds = ''
						)
					AND R.PaymentTransactionId = @rPaymentTransactionId
					AND R.PayTypeId = 8
				)
		BEGIN
			SELECT @lDuplicateReceipt = 1
		END
	END
			--end for mantis 0031290 By Foram
	
	--@lWrongFeeSetupOrReceiptBook			-1
	--@lAlreadyPaid,@lDuplicateReceipt		1

	IF(@lWrongFeeSetupOrReceiptBook = 1)
	BEGIN
		SELECT @rIsCreated = -1
	END
	ELSE IF(@lAlreadyPaid = 1 OR @lDuplicateReceipt = 1)
	BEGIN
		SELECT @rIsCreated = 1
	END
	ELSE
	BEGIN
		SELECT @rIsCreated = 0	
	END

	EXEC sp_xml_removedocument @loDoc
END
GO
PRINT N'Altering Procedure [sHostel].[pHostelStudentGatePassNewGet]...';


GO

ALTER PROCEDURE [sHostel].[pHostelStudentGatePassNewGet]
          
           @rId int,
           @rOrgId int=0,
           @rHostelGatePassReasonId int=0,
           @rFromGatePassDate datetime='',
           @rToGatePassDate datetime='',
           @rEntryModeStatusId smallint=0,
           @rCode nvarchar(20)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0,
           @rOrgGroupBatchId int=0,
           @rRoomId int =0,
           @rHostelId int =0
AS
SET NOCOUNT ON
DECLARE @lIsOnPrePrinted bit = 0
DECLARE @lConfigValue nvarchar(50)
DECLARE @lIsDisplayImageHeader bit = 0
BEGIN

--Select @rHostelId
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 232 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
		IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
			BEGIN
			SET @lIsOnPrePrinted = 0
			SET @lIsDisplayImageHeader = 0
			END
		ELSE IF (@lConfigValue = 'Image')
			BEGIN
			SET @lIsOnPrePrinted = 0
			SET @lIsDisplayImageHeader = 1
			END
		ELSE IF (@lConfigValue = 'Blank')
			BEGIN
			SET @lIsOnPrePrinted = 1
			END
	

			SELECT
				HSGP.Id, 
				HSGP.Id AS HostelStudentGatePassId,
				vSA.Code,
				--vSA.FirstName+' '+vSA.LastName AS Name,
				VSA.Name,
				VSA.ClassName+' - '+VSA.DivisionName AS Class,
				HSGP.StudentId,
				HSGP.RelationshipId,		
				RM.Title AS Relationship,
				HSGP.Relation,
				HSGP.VisitorName,
				HSGP.VisitorMobile,
				HSGP.HostelGatePassReasonId,
				HGRM.Title AS HostelGetPassReason,
				HSGP.Remark,
				--HSGP.VisitorPhoto	,


				--CASE  WHEN @rIsPrintView=1 THEN HSGP.VisitorPhoto		
				--ELSE ISNULL(HSGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END AS VisitorPhoto,
				--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
				HSGP.GatePassDate,
				HSGP.GatePassInDate,
				(CASE  WHEN @rIsPrintView=1 THEN 
				ISNULL(HSGP.VisitorPhoto,0x)
				ELSE ISNULL(HSGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0x)) END) AS VisitorPhoto,
				CONVERT(varchar(15),CAST(HSGP.GatePassTime AS TIME),100) As GatePassTime,
				ISNULL(CONVERT(varchar(15),CAST(HSGP.GatePassInTime AS TIME),100), '12:00AM') As GatePassInTime,

				--ISNULL(HSGP.GatePassTime,'') As GatePassTime,
				HSGP.EntryModeStatusId,
				HSGP.HostelId,
				SM.Title AS EntryModeStatus,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				(CASE  WHEN @rIsPrintView=1 THEN 
				ISNULL(SI.StudentPhoto,0x)		
				ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0x)) END) AS StudentPhoto,
				--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				ISNULL(U.DisplayTitle,'') AS UserName,
				HSGP.OrgGroupBatchId,
				vSA.SUId,
				HM.Title As HostelName,
				HM.ReportOrgTitle AS ReportOrgTitle,
				HM.SmallAddress1 AS SmallAddress1,
				HM.SmallAddress2 AS SmallAddress2,
				@lIsOnPrePrinted AS IsOnPrePrinted,			
				ISNULL(HRM.Id,0) AS RoomId,
				ISNULL(HRM.Title,'') AS RoomTitle,
				@lIsDisplayImageHeader AS IsDisplayImageHeader,
				(CASE @lIsDisplayImageHeader WHEN 1 THEN
				OI.CertificateHeaderA4
				ELSE NULL END ) AS CertificateHeaderA4

		FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sHostel.tHostelStudentGatePass HSGP ON HSGP.StudentId = vSA.StudentId
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
				LEFT JOIN sHostel.tHostelGatePassReasonMaster HGRM ON HGRM.Id=HSGP.HostelGatePassReasonId
				LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=HSGP.RelationshipId
				LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=HSGP.EntryModeStatusId
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
				LEFT JOIN sSecurity.tUser U	ON U.Id=HSGP.CreatedUserId
				LEFT JOIN  sHostel.tAssignRoom AR ON AR.SourceId=HSGP.StudentId AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  AND (AR.SourceTypeId=2003)--Added  (AR.SourceTypeId=2003) for mantis - 0033745 
				LEFT JOIN sHostel.tRoomMaster HRM ON HRM.Id = AR.RoomId
				INNER JOIN sHostel.tHostelMaster HM ON HM.Id = HSGP.HostelId
				LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = vSA.OrgId		--  MantisId : 0033298
			
		WHERE 
				OM.OrgGroupId=@rOrgGroupId
				AND HSGP.HostelId = @rHostelId
				AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId) 
				--if student remove from Assign room then it is not display in HostelStudentGatePass
				--AND (AR.SourceId=HSGP.StudentId) 
				AND (HSGP.OrgGroupBatchId=@rOrgGroupBatchId) 
				AND ((HSGP.Id=@rId) OR (@rId=0))
				AND ((vSA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((HSGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
				AND ((HSGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
				AND ((HSGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
				AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
				AND ((HSGP.HostelGatePassReasonId=@rHostelGatePassReasonId) OR (@rHostelGatePassReasonId=0))
				AND ((HRM.Id = @rRoomId) OR (@rRoomId = 0))
				
				ORDER BY HSGP.GatePassDate,HSGP.GatePassTime DESC
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeAttendanceRegisterGet]...';


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


GO


ALTER PROCEDURE [sLibrary].[pRptAccessionRegisterGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rAccessionNo nvarchar(50)='',
	 @rClassificationNo nvarchar(50)='',
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 @rBookSubjectDrop nvarchar(200)='',
	 @rBookSubjectText nvarchar(200)='',
	 @rFromPurchaseDate date='',
	 @rToPurchaseDate date='',
	 @rBookDepartment nvarchar(150)--mantis - 0033576
           
AS
SET NOCOUNT ON
BEGIN
	BEGIN	  
		SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
		SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
		SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
		SET @rAccessionNo = sCommon.fSearchStringGet(@rAccessionNo)
		SET @rClassificationNo = sCommon.fSearchStringGet(@rClassificationNo)
		SET @rBookSubjectText = sCommon.fSearchStringGet(@rBookSubjectText)
		SET @rBookDepartment = sCommon.fSearchStringGet(@rBookDepartment)
	END
	SELECT   
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Id AS BookId,
		BM.Code AS BookCode,
		BM.Title AS BookName,
		BM.Author,
		BM.Publisher,
		BM.ClassificationNo,
		BM.BookSubject,
		BM.AccessionNo,
		BM.Edition,
		BM.NoOfPages,
		BM.BookLanguage,
		BM.Supplier,
		BM.PurchaseDate,
		BM.Price,
		BM.ISBNNumber,
		BM.Location,
		BM.BookRemark,
		LM.ReportOrgTitle,
		LM.SmallAddress1,
		LM.SmallAddress2,
		BM.BookDepartment--mantis - 0033576
	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.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.AccessionNo like @rAccessionNo) OR (@rAccessionNo=''))
		AND ((BM.ClassificationNo like @rClassificationNo) OR (@rClassificationNo=''))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((BM.BookSubject = @rBookSubjectDrop) OR (@rBookSubjectDrop=''))
		AND ((BM.BookSubject like @rBookSubjectText) OR (@rBookSubjectText=''))
		AND ((BM.PurchaseDate >= @rFromPurchaseDate) OR (ISNULL(@rFromPurchaseDate,'') = ''))
		AND ((BM.PurchaseDate <= @rToPurchaseDate) OR (ISNULL(@rToPurchaseDate,'') =''))
		AND ((BM.BookDepartment like @rBookDepartment) OR (ISNULL(@rBookDepartment,'') =''))--mantis - 0033576
END
GO
PRINT N'Altering Procedure [sLibrary].[pRptBookListCirculationGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptBookListCirculationGet]

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

BEGIN 
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)

		SELECT 
				Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount ,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2
	        
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND SA.BatchId = BL.BatchId
	WHERE 
			(BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))    --Mantis - 32621
			AND ((BM.Author like @rAuthor) OR (@rAuthor=''))            --Mantis - 32621
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			
	UNION

	SELECT 
				Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount ,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95

	WHERE 
			(BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			AND  ISNULL(EM.IsOtherUser,0) = 0
			AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))     --Mantis - 32621
			AND ((BM.Author like @rAuthor) OR (@rAuthor=''))                  --Mantis - 32621
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			
			
	UNION 

	SELECT 
	Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
	WHERE (BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND (ISNULL(BL.ReaderSourceTypeId,0)=0 AND 0=0)
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))           --Mantis - 32621
			AND ((BM.Author like @rAuthor) OR (@rAuthor=''))           --Mantis - 32621
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			ORDER BY COUNT(BL.Id) desc


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

END
GO
PRINT N'Altering Procedure [sLibrary].[pRptBookListGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptBookListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),      
	 @rBookSubjectText nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150)='',
	 @rIsDetail bit=0,
	 @rFromPurchaseDate date='',
	 @rToPurchaseDate date='',
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 --@rOrgGroupId int,
	 @rFromCode nvarchar(25) ='',
	 @rToCode nvarchar(25) ='',
	 @rSpecificCode nvarchar(max) ='',
	 @rBookSubjectDrop nvarchar(500)='',
	 @rFromDate date ='',
	 @rToDate date ='',
	 --Start For Mantis: 31829
	 @rFromBookCode bigint=0,
	 @rToBookCode bigint=0,
	 --End For Mantis: 31829
	 @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,'') = ''))
		--Start For Mantis: 31829
		AND (ISNUMERIC(BM.Code) = 1 AND (CAST(BM.Code AS bigint) >= @rFromBookCode OR Convert(bigint, ISNULL(@rFromBookCode, '0')) = 0) OR (ISNUMERIC(BM.Code) = 0 AND Convert(bigint, ISNULL(@rFromBookCode, '0')) = 0))
		AND (ISNUMERIC(BM.Code) = 1 AND (CAST(BM.Code AS bigint) <= @rToBookCode OR Convert(bigint, ISNULL(@rToBookCode, '0')) = 0) OR (ISNUMERIC(BM.Code) = 0 AND Convert(bigint, ISNULL(@rToBookCode, '0')) = 0))
		--End For Mantis: 31829
		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 [sLibrary].[pRptBookListNotReturnGet]...';


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

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



	
END
GO
PRINT N'Altering Procedure [sLibrary].[pRptBookLogRegisterGet]...';


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

		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.EmployeeName
			WHEN BL.ReaderSourceTypeId = 2003 THEN vSF.Name
			ELSE
			''
			END) AS Name,
			
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.DepartmentName
			WHEN BL.ReaderSourceTypeId = 2003 THEN (vSF.ClassName + ' - '+ vSF.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
		 
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	Emp.Code
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	vSF.Code
			 ELSE '' END) AS Code, 	
	   BL.ReaderSourceTypeId,
	   BL.ReaderSourceId,
	   BL.LogDate,
	   BL.DueDate,
	   BL.ReturnDate,
	   BM.Code AS BookCode,
	   BM.Title AS BookName,
	   OM.DisplayTitle AS OrganizationName,
	    LM.ReportOrgTitle,
	    LM.SmallAddress1,
	    LM.SmallAddress2
	   
  FROM  
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
		LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 95 
		LEFT JOIN sStudent.vStudentLastAcademic vSF
			ON vSF.StudentId = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 2003 
			--AND (SELECT IsActive FROM sSetup.tBatchMaster WHERE Id=vSF.BatchId AND IsActive = 1) = 1	 edited by Jash for Issue no :- 0018773
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId			
 
  WHERE 
    BL.StatusId = 523 
	AND BL.LibraryId=@rLibraryId
	AND (BL.LogDate>=@rFromLogDate OR ISNULL(@rFromLogDate,'')='')
	AND (BL.LogDate<=@rToLogDate OR ISNULL(@rToLogDate,'')='')
	AND ((BL.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,'') = ''))
	AND ((BL.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,'') = ''))
	AND ((BL.ReaderSourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0)) 
	AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))   --Mantis - 32621
	AND ((BM.Author like @rAuthor) OR (@rAuthor=''))         --Mantis - 32621


END
GO
PRINT N'Altering Procedure [sLibrary].[pRptReaderBookListGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptReaderBookListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rReaderSourceTypeId smallint,
	 --@rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromLogDate date,
	 @rToLogDate date,
	 @rLibraryId int,
	 @rCode nvarchar(20) = '',  --added
	 @rBookPublisher nvarchar(200)='' ,      --Mantis - 32621
	 @rAuthor nvarchar(200)='' 	 --Mantis - 32621
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	If(@rReaderSourceTypeId=2003)
	BEGIN
		SELECT

				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,
				BL.Id AS BookLogId,
				BM.Code AS ResourceCode,
				BM.Title AS ResourceName,
				BL.LogDate,
				BL.DueDate,
				IS1.NoOfBookIssuable,
				BL.StatusId ,
				SM.Title AS Status,
				SA.Name,
				SA.RollNo,
				SA.Code,
				SA.ClassName,
				SA.DivisionName,
				LM.ReportOrgTitle,
				LM.SmallAddress1,
				LM.SmallAddress2

		FROM
				sLibrary.tBookLog BL
				INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
				INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
				INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005
				INNER JOIN sSetup.tBatchMaster B ON SA.BatchId = B.Id --AND B.IsActive = 1
				LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
		WHERE
				((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
			--AND (BL.ReaderSourceId=@rReaderSourceId OR @rReaderSourceId=0)
			AND (SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.StatusId=523)
			AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (BL.LibraryId=@rLibraryId)
			AND (SA.Code=@rCode OR @rCode='') --added
			AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))    --Mantis - 32621
		AND ((BM.Author like @rAuthor) OR (@rAuthor=''))            --Mantis - 32621
	END
	ELSE If(@rReaderSourceTypeId=95)
	BEGIN
			SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
			SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
		SELECT

				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,
				BL.Id AS BookLogId,
				BM.Code AS ResourceCode,
				BM.Title AS ResourceName,
				BM.BookSubject,
				BL.LogDate,
				BL.DueDate,
				IS1.NoOfBookIssuable,
				BL.StatusId,
				SM.Title AS Status,
				BL.IsCurrentStatus,
				EM.FirstName+' '+EM.LastName AS Name,
				EM.Code,
				ODM.Title AS EmpDept,
				LM.ReportOrgTitle,
				LM.SmallAddress1,
				LM.SmallAddress2
		FROM
				sLibrary.tBookLog BL
				LEFT JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
				INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
				INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004
				LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
		WHERE
				((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
			--AND (BL.ReaderSourceId=@rReaderSourceId OR @rReaderSourceId=0)
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.StatusId=523)
			AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (BL.LibraryId=@rLibraryId)
			AND  ISNULL(EM.IsOtherUser,0) = 0
			AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))    --Mantis - 32621
			AND ((BM.Author like @rAuthor) OR (@rAuthor=''))		   --Mantis - 32621
	END
END
GO
PRINT N'Altering Procedure [sSecurity].[pMenu_Migration]...';


GO
ALTER PROCEDURE [sSecurity].[pMenu_Migration]    
 @rUserId [bigint],    
 @rMenuId int = 0,    
 @rResourceTypeId int= 0,    
 @rIsCoreMenu bit = 0,
 @rEnvironmentName nvarchar(max)  
      
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
    
BEGIN    
 IF(@rIsCoreMenu=0)    
 BEGIN    
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)    
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
    PageURL  AS PagePath,    
    IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermissionUser P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
       WHERE    
        T.IsObsolete = 0 AND P.UserId = @rUserId    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 ELSE     
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
     PageURL  AS PagePath,    
     IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermission P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
        INNER JOIN    
        (    
        SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0    
        ) B ON B.RoleId = P.RoleId    
       WHERE    
        T.IsObsolete = 0    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 END    
 ELSE    
 BEGIN     
  SELECT    
   MenuID,    
   ModuleId,    
   ParentMenuID,    
   MenuTitle,      
   ScreenTitle,       
   PageURL,    
   ScreenId,    
   Permission,    
   OrderNumber,      
   TaskId,      
   PageURL AS PagePath,    
   MenuIsObsolete,    
   Icon      
  FROM    
  (    
	SELECT    
   ISNULL(Menu.Id,0) AS MenuID,     
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
   ISNULL(Menu.Title,'') AS MenuTitle,       
   ISNULL(Screen.Title, '') AS ScreenTitle,        
   ISNULL(Screen.Page, '') AS PageURL,    
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Menu.ScreenId, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen.IconPath,'') AS Icon    
  FROM     
  sSecurity.tMenu Menu     
  LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
  LEFT OUTER JOIN     
  (    
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId  AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId      
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id        
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId     
  GROUP BY P.TaskId    
  ) TBL2 ON Screen.TaskId = TBL2.TaskId     
  LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
  WHERE (Menu.IsObsolete = 0)    
  AND ISNULL(Screen.IsObsolete, 0) = 0    
  AND (
		(@rEnvironmentName = 'Local' AND Menu.Id in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622)) -- updated by parth for showing more menu inside the communication 07-02-2023 
	OR (@rEnvironmentName = 'QA' AND Menu.Id in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622))
	OR (@rEnvironmentName = 'LiveEnvironment' AND Menu.Id in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622))
	)
	
  --AND Menu.Id  in (24,2711,2411)  -- Issue: For Only Student Center, My Communication Menu , Developer: Foram, Date: 15-07-2022
  --AND (Menu.Id  in (24,2711)   
  --Or ParentMenuID  in (24,2711))     
  --AND (Menu.Id IN (15, 32, 55,24, 19181042, 36, 3606,2714)  
  --OR ParentMenuID IN (15, 32, 55, 19181042, 36, 24, 18))  
  UNION    
       
  SELECT     
  
   ISNULL(Menu.Id, 0) AS MenuID,     
   ISNULL(Menu.Id, 0) AS ParentMenuID,     
   ISNULL(Screen1.Title,'') AS MenuTitle,       
   ISNULL(Screen1.Title, '') AS ScreenTitle,        
   ISNULL(Screen1.Page, '')  AS PageURL,    
   ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Menu.ScreenId, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen1.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen1.IconPath,'') AS Icon    
  FROM     
   sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
   LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId     
   LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId    
   LEFT OUTER JOIN (     
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId   AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId        
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id       
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId    
            
  GROUP BY P.TaskId    
  ) TBL2 ON Screen1.TaskId = TBL2.TaskId    
  WHERE (Menu.IsObsolete = 0) 
  AND ISNULL(Screen1.IsObsolete, 0) = 0   
  --AND (Menu.ParentMenuID  in (24,2711)   
  --or Menu.Id  in (24,2711))   
  AND Screen1.Id IN (10187,30363,30342,20241,30282,20565,20563,30377,20915,30331,20564,20180,20617,30364,20130,30818,30828,20191,30787,20996,20193,20717  -- Issue: For Only Student Center Menu , Developer: Foram, Date: 15-07-2022  
		,9137,20054,20085,20088,20093,20099,20104,20107,20172,20198,20204,20209,20222,20566,20577,20692,20723,20724,30228,30242,30254,30365,30556,30559,30585,30794,30858,30943,31175,30921,20103,20102,20223,30561, -- Issue: For Only My Communication Menu , Developer: Foram, Date: 20-07-2022  
		30857,30696,30739,30284,20171,20105,31048,9136,30678,20179,30793,20720,20115,20693,20086,20819,20126,20950,20094,30856,30855,30795,30789,20697,20758,20083,30245,30246,20125,30874,30274,30817,30251,30252,30253,30247,30395, -- this line for communication screen changes by parth
		20983,30071,30103,30859,30935,30602,30848,30362,20181,20246,20576,20916,20979,30020,30093,30106,30115,30124,30134,30139,30149,30257,30327,30788,30455,30344,31005, -- this line for employee center screen changes by parth
		20108,30298,30552,20025,20026,20068,20336,20551,20719,20866,20894,20899,20900,3009530203,30296,30701,30816,30962, -- this line for fees screen changes by parth
		20396,20630,30138,30548,31012,20075,20161,20163,20167,20654,20985,30974,30994,20388,20073,20074,20165, -- this line for atte screen changes by parth
		20766,20927,20555,30366,20622,30651,30515,20554,20561,20159, 30664, -- this line is use for academic module
		30236,30500,30600,30604,31188,31182,30797,30471,30456,30803,30411,30412,30409,30410,30447,30449,20949,20197,20056,20952,20059,20150,20153) --17/05/2023
  --AND Screen1.Id IN (9147, 30300, 30301, 30330, 30341, 30782, 30783, 30784, 30785, 30786, 30787, 30788, 30790, 30791, 30792, 30499,20246,
  --30914,30913,30912,30911
  --)  
  ) MenuTable      
  WHERE     
  --(MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2)  
  --AND   
  ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
  AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
  AND MenuIsObsolete = 0    
  --AND MenuTable.MenuId IN (15,32,36,55,24,1515,3606,19184009,19181042,2714,19184020) 
  AND (
		(@rEnvironmentName = 'Local' AND MenuTable.MenuId in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622)) -- updated by parth for showing more menu inside the communication 07-02-2023 
	OR (@rEnvironmentName = 'QA' AND MenuTable.MenuId in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622))
	OR (@rEnvironmentName = 'LiveEnvironment' AND MenuTable.MenuId in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622))
	)
  --AND MenuTable.MenuId  in (24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622)  -- updated by parth for showing more menu inside the communication 07-02-2023
  --AND MenuTable.MenuId  in (24,2711,2411)  -- Issue: For Only Student Center, My Communication Menu , Developer: Foram, Date: 15-07-2022  
  ORDER BY ParentMenuID    
 END    
END
GO
PRINT N'Altering Procedure [sSecurity].[pMobValidateUser]...';


GO
ALTER PROCEDURE [sSecurity].[pMobValidateUser]

    @rOrgId int = 0,
    @rUserTitle nvarchar(100)='',
    @rUserMobileNumber nvarchar(50)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		DECLARE @rUserSourceId bigint=0
		DECLARE @rUserId bigint=0
		DECLARE @rUserSourceTypeId smallint=0
		DECLARE @newpwd VARCHAR(100)
		SELECT @rUserId=Id,@rUserSourceId = SourceId,@rUserSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND OrgId = @rOrgId
		IF(@rUserId = 0 AND @rUserSourceTypeId=0)
		BEGIN
			SELECT -11 AS Result, 'User does not exist' AS [Message], '' AS OTP
			Return
		END
		IF(@rUserSourceTypeId = 95)
		BEGIN
			IF EXISTS (SELECT 1 FROM sHrm.tEmployeeCommunications WHERE MobileNumber = @rUserMobileNumber and EmployeeId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				--Changes for Mantis Id : 33613 4 digit OTP
					EXEC [sSecurity].[pNumericOTPGenerate] @len=4, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId

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


GO
ALTER proc [sStudent].[pImportStudentValidateFordynamic]
@rXml varchar(max),
@rOrgId Int = 0,		-- MantisId : 0033278
@rBatchId Int = 0		-- MantisId : 0033278
as
begin

DECLARE @loXML XML
SET @loXML = CAST(@rXml AS XML)
	DECLARE @tblStudent table(tid int identity(1,1),ecode varchar(200),LeftStandard varchar(100))
	INSERT INTO @tblStudent(ecode,LeftStandard)
	SELECT 
	T.c.value('@Code','varchar(200)') AS StudentCode,
	T.c.value('@LeftStandard','varchar(200)') AS LeftStandard	-- MantisId : 0033278
	FROM 
	@loXML.nodes('/Table/ImportStudent')T(c)
	
	--select * from @tblStudent

	DECLARE @validate varchar(max)='',@orgid int,@cnt int,@i int
    SELECT @cnt = count(*),@i = 1 FROM @tblStudent
	WHILE @i <= @cnt
	BEGIN
		DECLARE @Code varchar(200)
		DECLARE @LeftStandard varchar(100)
		DECLARE @LeftStandardId int
		DECLARE @ClassStatusId SmallInt
		SELECT @Code = ecode FROM @tblStudent WHERE tid = @i
		SELECT @LeftStandard = LeftStandard FROM @tblStudent WHERE tid = @i
		IF not exists (SELECT 1 FROM sStudent.tStudentMaster WHERE Code = @Code AND OrgId = @rOrgId)
		BEGIN
			SELECT @validate = @validate + 'Student code Like : '+@Code+' Not Found ,<br/>' 
		END

		-- #Start MantisId : 0033278
		IF exists (SELECT 1 FROM sStudent.tStudentMaster WHERE Code = @Code AND OrgId = @rOrgId)
		BEGIN
			IF (@LeftStandard <> '')
				BEGIN
					SELECT @LeftStandardId = isnull(Id,0) FROM sSetup.tClassMaster WHERE Title = @LeftStandard and OrgId = @rOrgId
					DECLARE @CurrentStandardId Int
					SELECT @CurrentStandardId = A.ClassId, @ClassStatusId = A.ClassStatusId From sStudent.tAcademic A
					INNER JOIN sStudent.tStudentmaster SM ON A.StudentId = SM.Id 
					WHERE SM.Code = @Code AND A.BatchId = @rBatchId 
							
					if(@LeftStandardId <> @CurrentStandardId AND @ClassStatusId = 3)
						BEGIN
							SELECT @validate = @validate + 'Class and Left Standard must be same for Code : '+@Code
						END
				END
		END
		-- #End MantisId : 0033278
		SELECT @i = @i + 1;
	END
	
	SELECT isnull(@validate,'') as valid
END
GO
PRINT N'Altering Procedure [sStudent].[ppImportStudent_Update_Dynamicly]...';


GO

ALTER proc [sStudent].[ppImportStudent_Update_Dynamicly]
@rOrgId int,
@rCreatedUserId bigint,
@rCode nvarchar(20) = '', 
@rFirstName nvarchar(100) = '',
@rMiddleName nvarchar(100) = '',
@rLastName nvarchar(100) = '',
@rGender nvarchar(20) = '',
@rAdmissionStandard nvarchar(100) = '',
@rAdmissionCategory nvarchar(100) = '',
@rAdmissionYear nvarchar(10) = '',
@rAdmissionDate datetime = '',
@rLeftStandard nvarchar(100) = '',
@rLeftDate datetime = '',
@rLeftYear nvarchar(10) = '',
@rLeftReason nvarchar(200) = '',
@rPreviousSchool nvarchar(200) = '',
@rDateOfBirth datetime = '',
@rBirthPlace nvarchar(150) = '',
@rBloodGroup nvarchar(20) = '',
@rBirthTaluka nvarchar(150) = '',
@rBirthDistrict nvarchar(150) = '',
@rFamilySubCast nvarchar(100) = '',
@rFamilyCast nvarchar(100) = '',
@rCastCatagory nvarchar(50) = '',
@rMotherTongue nvarchar(100) = '',
@rNationality nvarchar(50) = '',
@rReligion nvarchar(50) = '',
@rHobby nvarchar(50) = '',
@rFatherName nvarchar(100)='',
@rFatherContactNo nvarchar(50)='',
@rFatherDateOfBirth datetime = '',
@rFatherOccupation nvarchar(50)='',
@rFatherQualification nvarchar(50)='',
@rFatherMail nvarchar(50)='',
@rFatherOfficeAddress nvarchar(500)='',
@rFatherIncome int=0,
@rMotherDateOfBirth datetime = '',
@rMothername nvarchar(100)='',
@rMotherContactNo nvarchar(50)='',
@rMotherOccupation nvarchar(50)='',
@rMotherQualification nvarchar(50)='',
@rMotherMail nvarchar(50)='',
@rMotherOfficeAddress nvarchar(100)='',
@rMotherIncome int=0,
@rRelationshipName nvarchar(100)='',
@rRelativeName nvarchar(100)='',
@rRelativeDateOfBirth datetime='',
@rRelativeOccupation nvarchar(50)='',
@rRelativeQualification	nvarchar(50)='',
@rRelativeContactNo	nvarchar(50)='',
@rRelativeMail nvarchar(50)='',
@rRelativeOfficeAddress nvarchar(500)='',
@rRelativeIncome int=0,
@rPresentStreetOne nvarchar(150)='',
@rPresentStreetTwo nvarchar(150)='',
@rPresentStreetThree nvarchar(150)='',
@rPresentCity nvarchar(50)='',
@rPresentZipCode nvarchar(20)='',
@rPresentState nvarchar(50)='',
@rPresentCountry nvarchar(50)='',
@rPresentContactNo nvarchar(20)='', 
@rParentEmail nvarchar(50)='',
@rStudentContactNo  nvarchar(50)='',
@rStudentEmail nvarchar(50)='', 
@rAccountNumber nvarchar(20)='',
@rBankName nvarchar(100)=0,
@rBranch nvarchar(100)='', 
@rBankIFSCCode  nvarchar(20)='',
@rAdhaarNumber nvarchar(20)='',
@rValidate varchar(250)='' ,
@rOrgGroupId int,
@rBirthState  nvarchar(150)='',
@rUIDNumber nvarchar(50)='', 
@rBirthCountry nvarchar(150)='',
@rFatherOfficeContactNo nvarchar(50)='',
@rMotherOfficeContactNo varchar(50)='',
@rWhatsAppContactNo nvarchar(20)='',
@rPreviousLeftDate datetime = '',
@rMarriageAnniversaryDate datetime = '', -- Added parameter of @rMarriageAnniversaryDate for mantis 29443
@rPENNumber bigint = 0, --Mantis - 0031338
@rStatusId tinyint = 0	-- MantisId : 0033278

as
begin	
	IF(@rAdmissionDate='') 
	SET @rAdmissionDate = NULL
	IF(@rDateOfBirth='') 
	SET @rDateOfBirth = NULL
	IF(@rFatherDateOfBirth='') 
	SET @rFatherDateOfBirth = NULL
	IF(@rMotherDateOfBirth='') 
	SET @rMotherDateOfBirth = NULL
	IF(@rRelativeDateOfBirth='') 
	SET @rRelativeDateOfBirth = NULL
	IF(@rPreviousLeftDate='') 
	SET @rPreviousLeftDate = NULL
	/**Changes done for mantis 29443**/
	IF(@rMarriageAnniversaryDate='') 
	SET @rMarriageAnniversaryDate = NULL
	
	declare @StudentId bigint = 0
	select @StudentId = Id from sStudent.tStudentMaster where Code = @rCode and OrgID = @rOrgId
	select @StudentId = isnull(@StudentId,0)
	
	declare @genderid int,@AdmissionStandardid int,@LeftStandardid int,@nationalityid int,@religionid int, 
	 @castcategoryid int,@admissioncategoryid int,@bloodgroupid int 
	
	select @rGender = case when upper(@rGender) = 'M' then 'Male'
	when  upper(@rGender) = 'MALE' then 'Male'
	when upper(@rGender) ='FEMALE' then 'Female'
	when upper(@rGender) = 'F' then 'Female' when upper(@rGender) = 'N' then 'Not Known' else 'Not Known' end
	 
	select @genderid = isnull(Id,0) from sCommon.tGenderMaster where Title = @rGender
	
	select @AdmissionStandardid = isnull(Id,0) from sSetup.tClassMaster where Title = @rAdmissionStandard and OrgId = @rOrgId
 
	select @LeftStandardid = isnull(Id,0) from sSetup.tClassMaster where Title = @rLeftStandard and OrgId = @rOrgId
	
	select @nationalityid = isnull(Id,0) from sCommon.tCountryMaster where Nationality = @rNationality and OrgGroupId = @rOrgGroupId
	 
	 select @religionid = isnull(Id,0) from sCommon.tReligionMaster where Title = @rReligion  and OrgGroupId = @rOrgGroupId
	 
	  select @castcategoryid = isnull(Id,0) from sCommon.tCastCategoryMaster where Title = @rcastcatagory and OrgGroupId = @rOrgGroupId
	  
	  select @admissioncategoryid = isnull(Id,0) from sStudent.tAdmissionCategoryMaster where Title = @radmissioncategory and OrgGroupId = @rOrgGroupId
	 
	 select @bloodgroupid = isnull(Id,0) from sCommon.tBloodGroupMaster  where Title = @rBloodGroup  
	  
	select @genderid = isnull(@genderid,0),@AdmissionStandardid = isnull(@AdmissionStandardid,0),@LeftStandardid = isnull(@LeftStandardid,0),
	@nationalityid = isnull(@nationalityid,0),@religionid = isnull(@religionid,0),@castcategoryid = isnull(@castcategoryid,0),
	@admissioncategoryid = isnull(@admissioncategoryid,0),@bloodgroupid = isnull(@bloodgroupid,0) 
	
	declare @lNextNumber bigint,@Title varchar(100)=''
	
	 
	 
	if @rFirstName <> ''
	select @rFirstName = [sSetup].[fPortalXMLTagsReplaceReverse](@rFirstName)
	if @rMiddleName <> ''
	select @rMiddleName = [sSetup].[fPortalXMLTagsReplaceReverse](@rMiddleName)
	if @rLastName <> ''
	select @rLastName = [sSetup].[fPortalXMLTagsReplaceReverse](@rLastName)
	 if @rAdmissionDate <> ''
	select @rAdmissionDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdmissionDate)
	 if @rAdmissionYear <> ''
	select @rAdmissionYear = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdmissionYear)
	 if @rLeftDate <> ''
	select @rLeftDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rLeftDate)
	if @rLeftYear <> ''
	select @rLeftYear= [sSetup].[fPortalXMLTagsReplaceReverse](@rLeftYear)
	if @rLeftReason <> ''
	select @rLeftReason= [sSetup].[fPortalXMLTagsReplaceReverse](@rLeftReason)
	if @rPreviousSchool <> ''
	select @rPreviousSchool= [sSetup].[fPortalXMLTagsReplaceReverse](@rPreviousSchool)
	if @rDateOfBirth <> ''
	select @rDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rDateOfBirth)
	if @rBirthPlace <> ''
	select @rBirthPlace= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthPlace)
	if @rBirthTaluka<> ''
	select @rBirthTaluka= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthTaluka)
	if @rBirthDistrict <> ''
	select @rBirthDistrict= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthDistrict)
	if @rFamilyCast <> ''
	select @rFamilyCast= [sSetup].[fPortalXMLTagsReplaceReverse](@rFamilyCast)
	if @rFamilySubCast <> ''
	select @rFamilySubCast= [sSetup].[fPortalXMLTagsReplaceReverse](@rFamilySubCast)
	if @rMotherTongue <> ''
	select @rMotherTongue= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherTongue)
	if @rHobby <> ''
	select @rHobby= [sSetup].[fPortalXMLTagsReplaceReverse](@rHobby)
	if @rFatherName<> ''
	select @rFatherName= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherName)
	if @rFatherContactNo<> ''
	select @rFatherContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherContactNo)
	if @rFatherDateOfBirth<> ''
	select @rFatherDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherDateOfBirth)
	if @rFatherOccupation<> ''
	select @rFatherOccupation= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherOccupation)
	if @rFatherQualification<> ''
	select @rFatherQualification= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherQualification)
	if @rFatherMail<> ''
	select @rFatherMail= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherMail)
	if @rFatherOfficeAddress<> ''
	select @rFatherOfficeAddress= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherOfficeAddress)
	if @rFatherIncome<> ''
	select @rFatherIncome= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherIncome)
	if @rMothername<> ''
	select @rMothername= [sSetup].[fPortalXMLTagsReplaceReverse](@rMothername)
	if @rMotherContactNo<> ''
	select @rMotherContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherContactNo)
	if @rMotherDateOfBirth<> ''
	select @rMotherDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherDateOfBirth)
	if @rMotherOccupation<> ''
	select @rMotherOccupation= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherOccupation)
	if @rMotherQualification <> ''
	select @rMotherQualification= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherQualification)
	if @rMotherMail<> ''
	select @rMotherMail= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherMail)
	if @rMotherOfficeAddress<> ''
	select @rMotherOfficeAddress= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherOfficeAddress)
	if @rMotherIncome<> ''
	select @rMotherIncome= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherIncome)
	if @rRelationshipName <> ''
	select @rRelationshipName= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelationshipName)
	if @rRelativeName <> ''
	select @rRelativeName= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeName)
	if @rRelativeDateOfBirth <> ''
	select @rRelativeDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeDateOfBirth)
	if @rRelativeOccupation <> ''
	select @rRelativeOccupation= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeOccupation)
	if @rRelativeQualification <> ''
	select @rRelativeQualification= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeQualification)
	if @rRelativeContactNo<> ''
	select @rRelativeContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeContactNo)
	if @rRelativeMail<> ''
	select @rRelativeMail= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeMail)
	if @rRelativeOfficeAddress <> ''
	select @rRelativeOfficeAddress= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeOfficeAddress)
	if @rRelativeIncome <> ''
	select @rRelativeIncome= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeIncome)
	 
	if @rPresentStreetOne <> ''
	select @rPresentStreetOne = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetOne)
	if @rPresentStreetTwo <> ''
	select @rPresentStreetTwo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetTwo)
	if @rPresentStreetThree <> ''
	select @rPresentStreetThree = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetThree)
	 
	if @rPresentZipCode <> ''
	select @rPresentZipCode = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentZipCode)
	if @rPresentState <> ''
	select @rPresentState = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentState)
	if @rPresentCountry <> ''
	select @rPresentCountry = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCountry)
	if @rPresentCity <> ''
	select @rPresentCity = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCity)
	if @rPresentContactNo <> ''
	select @rPresentContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentContactNo)
	if @rPresentState <> ''
	select @rPresentState = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentState)
	if @rAccountNumber <> ''
	select @rAccountNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAccountNumber)
	if @rBankName <> ''
	select @rBankName = [sSetup].[fPortalXMLTagsReplaceReverse](@rBankName)
	if @rBranch <> ''
	select @rBranch = [sSetup].[fPortalXMLTagsReplaceReverse](@rBranch)
	if @rParentEmail<> ''
	select @rParentEmail = [sSetup].[fPortalXMLTagsReplaceReverse](@rParentEmail)
	if @rUIDNumber <> ''
	select @rUIDNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rUIDNumber)
	if @rAdhaarNumber <> ''
	select @rAdhaarNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdhaarNumber)
	  if @rStudentContactNo <> ''
	select @rStudentContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rStudentContactNo)
	if @rStudentEmail <> ''
	select @rStudentEmail= [sSetup].[fPortalXMLTagsReplaceReverse](@rStudentEmail)
	if @rBankIFSCCode <> ''
	select @rBankIFSCCode = [sSetup].[fPortalXMLTagsReplaceReverse](@rBankIFSCCode)
	if @rBirthState<> ''
	select @rBirthState= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthState)
	if @rBirthCountry<> ''
	select @rBirthCountry= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthCountry)
	if @rFatherOfficeContactNo<> ''
	select @rFatherOfficeContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherOfficeContactNo)
	if @rMotherOfficeContactNo<> ''
	select @rMotherOfficeContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherOfficeContactNo)
	if @rWhatsAppContactNo<> ''
	select @rWhatsAppContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rWhatsAppContactNo)

	 if @rPreviousLeftDate <> ''
	select @rPreviousLeftDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rPreviousLeftDate)

	/***Changes done for mantis 29443***/
	if @rMarriageAnniversaryDate <> ''
	select @rMarriageAnniversaryDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rMarriageAnniversaryDate)


	--Mantis Start- 0031338	
	DECLARE @lPENNumberActive nvarchar(50)=''
	SELECT @lPENNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 544 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	--Mantis END- 0031338	
	begin

		UPDATE sStudent.tStudentMaster
		SET 
		FirstName = case when isnull(@rFirstName,'') <> '' then @rFirstName else FirstName end
		,MiddleName   = case when isnull(@rMiddleName,'') <> '' then @rMiddleName else MiddleName end
		,LastName     = case when isnull(@rLastName,'') <> '' then @rLastName else LastName end
		--,StatusId     = case when isnull(@statusid,0) <> 0 then @statusid else StatusId end
		 ,UpdatedUserId = @rCreatedUserId
		,UpdatedDateTime = sCommon.fGetDate()
		,StatusId = case when isnull(@rStatusId,0) <> 0 then @rStatusId else StatusId end		-- MantisId : 0033278
		WHERE Id = @StudentId and OrgId = @rOrgId
		--Mantis Start- 0031338	
		
		IF (@lPENNumberActive = 'True')
		Begin
			UPDATE sStudent.tStudentMaster
			SET 
			PENNumber =case when isnull(@rPENNumber,0) <> 0 then  @rPENNumber else PENNumber END--Mantis - 0031338
			WHERE Id = @StudentId and OrgId = @rOrgId
		END
--Mantis End- 0031338	

		IF NOT EXISTS(Select * from sStudent.tStudentAdmission where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentAdmission(StudentId,CreatedUserId,CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

		SELECT @rLeftDate,@LeftStandardid			
		UPDATE sStudent.tStudentAdmission
		SET 
			AdmissionStandardId = case when isnull(@AdmissionStandardid,0) <> 0 then @AdmissionStandardid else AdmissionStandardId end,	 
			AdmissionYear = case when isnull(@rAdmissionYear,0) <> 0 then @rAdmissionYear else AdmissionYear end,			
			AdmissionDate = case when isnull(@rAdmissionDate,'') <> '' then @rAdmissionDate else AdmissionDate end,
			LeftStandardId =	case when isnull(@LeftStandardid,'') <> '' then @LeftStandardid else LeftStandardId end,
			LeftDate = case when isnull(@rLeftDate,'') <> '' then @rLeftDate else LeftDate end,	 
			LeftYear = case when isnull(@rLeftYear,0) <> 0 then @rLeftYear else LeftYear end,
			LeftReason = case when isnull(@rLeftReason,'') <> '' then @rLeftReason else LeftReason end,
			PreviousSchool = case when isnull(@rPreviousSchool,'') <> '' then @rPreviousSchool else PreviousSchool end,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			PreviousLeftDate = case when isnull(@rPreviousLeftDate,'') <> '' then @rPreviousLeftDate else PreviousLeftDate end
		WHERE StudentId = @StudentId 
	 

		IF NOT EXISTS(Select * from sStudent.tStudentOther where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentOther (StudentId, CreatedUserId, CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

		Update sStudent.tStudentOther
		set  
		GenderId = case when isnull(@genderid,0) <> 0 then @genderid else GenderId  end,
		ReligionId =  case when isnull(@religionId,0) <> 0 then @religionId else ReligionId  end,
		 BloodGroupId =  case when isnull(@bloodgroupid,0) <> 0 then @bloodgroupid else BloodGroupId  end,
		DateOfBirth =  case when isnull(@rDateOfBirth,'') <> '' then @rDateOfBirth else DateOfBirth  end,
		BirthPlace = case when isnull(@rBirthPlace,'') <> '' then @rBirthPlace else BirthPlace  end,
		BirthTaluka = case when isnull(@rBirthTaluka,'') <> '' then @rBirthTaluka else BirthTaluka  end,
			BirthDistrict = case when isnull(@rBirthDistrict,'') <> '' then @rBirthDistrict else BirthDistrict  end,
		 UIDNumber =  case when isnull(@rUIDNumber,'') <> '' then @rUIDNumber else UIDNumber  end,
		UpdatedUserId = @rCreatedUserId,
		UpdatedDateTime = sCommon.fGetDate(),
		FamilyCast =case when isnull(@rFamilyCast,'') <> '' then @rFamilyCast else FamilyCast  end,
		AdhaarNumber =case when isnull(@rAdhaarNumber,'') <> '' then @rAdhaarNumber else AdhaarNumber  end,
		FamilySubCast = case when isnull(@rFamilySubCast,'') <> '' then @rFamilySubCast else FamilySubCast  end,
		MotherTongue = case when isnull(@rMotherTongue,'') <>'' then @rMotherTongue else MotherTongue  end,
		NationalityId = case when isnull(@NationalityId,0) <> 0 then @NationalityId else NationalityId  end,
		 Hobby = case when isnull(@rHobby,'') <> '' then @rHobby else Hobby  end,
		CastCategoryId =case when isnull(@castcategoryid,0) <> 0 then @castcategoryid else CastCategoryId  end,
			BirthState = case when isnull(@rBirthState,'') <> '' then @rBirthState else BirthState  end,
				BirthCountry = case when isnull(@rBirthCountry,'') <> '' then @rBirthCountry else BirthCountry  end
		where StudentId = @StudentId 
		
	
		IF NOT EXISTS(Select * from sStudent.tStudentFamily where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentFamily (StudentId, CreatedUserId, CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

  		UPDATE sStudent.tStudentFamily
		SET 
	      
		   FatherName = case when isnull(@rFatherName,'') <> '' then @rFatherName else FatherName end 
		  ,FatherDateOfBirth =  case when isnull(@rFatherDateOfBirth,'') <> '' then @rFatherDateOfBirth else FatherDateOfBirth end 
		  ,FatherOccupation = case when isnull(@rFatherOccupation,'') <> '' then @rFatherOccupation else FatherOccupation end 
		  ,FatherQualification = case when isnull(@rFatherQualification,'') <> '' then @rFatherQualification else FatherQualification end 
		  ,FatherContactNo =  case when isnull(@rFatherContactNo,'') <> '' then @rFatherContactNo else FatherContactNo end 
		  ,FatherMail =  case when isnull(@rFatherMail,'') <> '' then @rFatherMail else FatherMail end 
		  ,FatherOfficeAddress = case when isnull(@rFatherOfficeAddress,'') <> '' then @rFatherOfficeAddress else FatherOfficeAddress end 
		  ,FatherIncome = case when isnull(@rFatherIncome,'') <> '' then @rFatherIncome else FatherIncome end 
		  ,MotherName = case when isnull(@rMotherName,'') <> '' then @rMotherName else MotherName end  
		  ,MotherDateOfBirth =  case when isnull(@rMotherDateOfBirth,'') <> '' then @rMotherDateOfBirth else MotherDateOfBirth  end   
		  ,MotherOccupation =  case when isnull(@rMotherOccupation,'') <> '' then @rMotherOccupation else MotherOccupation  end   
		  ,MotherQualification =  case when isnull(@rMotherQualification,'') <> '' then @rMotherQualification else MotherQualification  end      
		   ,MotherContactNo = case when isnull(@rMotherContactNo,'') <> '' then @rMotherContactNo else MotherContactNo end
		   ,MotherMail = case when isnull(@rMotherMail,'') <> '' then @rMotherMail else MotherMail end
		   ,MotherOfficeAddress = case when isnull(@rMotherOfficeAddress,'') <> '' then @rMotherOfficeAddress else MotherOfficeAddress end
		   ,MotherIncome = case when isnull(@rMotherIncome,'') <> '' then @rMotherIncome else MotherIncome end
		   ,RelationshipName = case when isnull(@rRelationshipName,'') <> '' then @rRelationshipName else RelationshipName end
		   ,RelativeName = case when isnull(@rRelativeName,'') <> '' then @rRelativeName else RelativeName end
			,RelativeDateOfBirth = case when isnull(@rRelativeDateOfBirth,'') <> '' then @rRelativeDateOfBirth else RelativeDateOfBirth end 
			,RelativeOccupation = case when isnull(@rRelativeOccupation,'') <> '' then @rRelativeOccupation else RelativeOccupation end 
			,RelativeQualification = case when isnull(@rRelativeQualification,'') <> '' then @rRelativeQualification else RelativeQualification end 
			,RelativeContactNo = case when isnull(@rRelativeContactNo,'') <> '' then @rRelativeContactNo else RelativeContactNo end 
			,RelativeMail = case when isnull(@rRelativeMail,'') <> '' then @rRelativeMail else RelativeMail end 
			,RelativeOfficeAddress = case when isnull(@rRelativeOfficeAddress,'') <> '' then @rRelativeOfficeAddress else RelativeOfficeAddress end 
			,RelativeIncome = case when isnull(@rRelativeIncome,'') <> '' then @rRelativeIncome else RelativeIncome end 
			,FatherOfficeContactNo = case when isnull(@rFatherOfficeContactNo,'') <> '' then @rFatherOfficeContactNo else FatherOfficeContactNo end 
			,MotherOfficeContactNo = case when isnull(@rMotherOfficeContactNo,'') <> '' then @rMotherOfficeContactNo else MotherOfficeContactNo end 
			,MarriageAnniversaryDate = case when isnull(@rMarriageAnniversaryDate,'') <> '' then @rMarriageAnniversaryDate else MarriageAnniversaryDate end -- Added new field of MarriageAnniversaryDate for mantis : 29443
		  ,[UpdatedUserId] = @rCreatedUserId
		  ,[UpdatedDateTime] =  sCommon.fGetDate() 
		WHERE StudentId = @StudentId
			

		IF NOT EXISTS(Select * from sStudent.tStudentCommunication where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentCommunication (StudentId, CreatedUserId, CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

  		UPDATE sStudent.tStudentCommunication
		SET 
	      
		   [PresentStreetOne] = case when isnull(@rPresentStreetOne,'') <> '' then @rPresentStreetOne else [PresentStreetOne] end 
		  ,[PresentStreetTwo] =  case when isnull(@rPresentStreetTwo,'') <> '' then @rPresentStreetTwo else [PresentStreetTwo] end 
		  ,[PresentStreetThree] = case when isnull(@rPresentStreetThree,'') <> '' then @rPresentStreetThree else [PresentStreetThree] end 
		  ,[PresentCountry] = case when isnull(@rPresentCountry,'') <> '' then @rPresentCountry else [PresentCountry] end 
		  ,[PresentState] =  case when isnull(@rPresentState,'') <> '' then @rPresentState else [PresentState] end 
		  ,[PresentCity] =  case when isnull(@rPresentCity,'') <> '' then @rPresentCity else [PresentCity] end 
		  ,PresentZipCode = case when isnull(@rPresentZipCode,'') <> '' then @rPresentZipCode else PresentZipCode end 
		  ,PresentContactNo = case when isnull(@rPresentContactNo,'') <> '' then @rPresentContactNo else PresentContactNo end 
		  ,ParentEmail = case when isnull(@rParentEmail,'') <> '' then @rParentEmail else ParentEmail end  
		  ,StudentContactNo =  case when isnull(@rStudentContactNo,'') <> '' then @rStudentContactNo else StudentContactNo  end   
		  ,StudentEmail =  case when isnull(@rStudentEmail,'') <> '' then @rStudentEmail else StudentEmail  end   
		   ,[UpdatedUserId] = @rCreatedUserId
		  ,[UpdatedDateTime] =  sCommon.fGetDate() 
		  ,WhatsAppContactNo =  case when isnull(@rWhatsAppContactNo,'') <> '' then @rWhatsAppContactNo else WhatsAppContactNo  end   
		WHERE StudentId = @StudentId
		

		IF NOT EXISTS(Select * from sStudent.tStudentAdditional where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentAdditional (StudentId) Values (@StudentId)
		END

		UPDATE sStudent.tStudentAdditional
		SET
			BankBranch = case when isnull(@rBranch,'') <> '' then @rBranch else BankBranch end 
		  ,BankAccountNumber = case when isnull(@rAccountNumber,'') <> '' then @rAccountNumber else BankAccountNumber end 
		  ,BankName = case when isnull(@rBankName,'') <> '' then @rBankName else BankName end 
		  ,BankIFSCCode = case when isnull(@rBankIFSCCode,'') <> '' then @rBankIFSCCode else BankIFSCCode end 
		  
		where StudentId=@StudentId
		
	end	
end
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentIcardGet]...';


GO

ALTER PROCEDURE [sStudent].[pRptStudentIcardGet]  
  @rBuilder1 nvarchar(max)='',  
  @rBuilder2 nvarchar(max)='',   
  @rOrgId smallint,  
  @rBatchId int,  
  @rStrCode nvarchar(max),  
  @rClassId int,  
  @rDivisionId int,  
  @rStudentId bigint,  
  @rFromRollNo Int,  
  @rToRollNo Int,  
  @rStatusId int,  
  @rDateOfBirth int,  
  @rDepartmentId int,  
  @rHouseGroupId int=0,  
  @rIsShowBarcode bit=0,  
  @rOrgGroupBatchId int,
  @rHouseId int=0  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
  
BEGIN   
  
DECLARE @lIcardBorder nvarchar(10)  
DECLARE @lSUIdBarcode nvarchar(50)  
--DECLARE @lIsBarcodeBasedOnSUId bit = 0  
DECLARE @lOrgGroupId int = 0  
Declare @lIDConfigValue nvarchar(50)=''  
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId  
  
SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup  
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId  
  
SELECT @lIcardBorder = ItemValue FROM sConfig.tConfigurationSetup WHERE configurationId = 130 AND SourceTypeId = 1016 AND SourceId = @rOrgId --ItemKey = 'sConfig.tConfigurationSetup'   
SELECT @lSUIdBarcode = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 168 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
   
 --IF (@lSUIdBarcode IS NULL) OR (@lSUIdBarcode = 'False')  
 --SET @lIsBarcodeBasedOnSUId = 0  
 --ELSE  
 --SET @lIsBarcodeBasedOnSUId = 1   
   
 SELECT      
   SD.AcademicId,  
   SD.StudentId,   
   SD.ClassId,  
   SD.DivisionId,  
   SD.ClassName,  
   SD.DivisionName,  
   SD.ClassDivision,  
   SD.Batch,  
   SD.Code,  
   SD.Number AS StudentNumber,  
   SD.RegistrationNumber,   
   SD.RollNo,      
   SD.FirstName,  
   SD.MiddleName,     
   SD.LastName,  
   SF.FatherName,
   [sStudent].[fStudentNameGet](SD.FirstName , SD.MiddleName, SD.LastName,OM.StudentNameFormatId ) AS Name,   
   --SD.FirstName + ' ' + SD.MiddleName + ' ' + SD.LastName As Name,     
   SD.StatusId,  
   SD.DateOfBirth,    
   SD.BloodGroup,  
   ISNULL(SD.PresentStreetone,'') AS PresentStreetone,  
   ISNULL(SD.PresentStreetTwo,'') AS PresentStreetTwo,  
   ISNULL(SD.PresentStreetThree,'') AS PresentStreetThree,  
      ISNULL(SD.PresentCity,'') AS PresentCity, 
	  ISNULL(SD.PresentState,'') AS PresentState, 
      ISNULL(SD.PresentZipCode,'') AS PresentZipCode,  
   SD.PresentContactNo,         
   SD.ParentContactNo AS ParentContactNo,  
   SD.StudentContactNo,     
   SD.StudentPhoto,  
   SD.AdmissionCategory,   
   SD.DivisionOrder,    
   ISNULL(SD.FamilyCast,'')AS FamilyCast, 
   ISNull(SD.AdhaarNumber,'')As AdhaarNumber,
   OM.Title AS OrgName,   
   ISNULL(HM.Title,'') AS HouseName,   
   OM.PrincipalSignature,  
   ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,  
   ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,  
   ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,  
   ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,     
   OM.OrgLogo AS ICardLogo,  
     
   --ISNULL(ICO.ICardBackground,0) AS ICardBackground,   
   --ISNULL(ICO.ICardBackBackground,0) AS ICardBackBackground,   
     
    ICO.ICardBackground  AS ICardBackground,   
    ICO.ICardBackBackground  AS ICardBackBackground,        
       
   ISNULL(ICO.LabelColor,'Black') AS LabelColor,  
   ISNULL(ICO.DetailColor,'Black') AS DetailColor,  
   ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,  
   ISNULL(SF.FatherName,'') AS FatherName,  
   ISNULL(SF.FatherContactNo,'') AS FatherContactNo,  
   ISNULL(SF.MotherName,'') AS MotherName,  
   ISNULL(SF.MotherContactNo,'') AS MotherContactNo,  
   ISNULL(RT.RouteName,'') AS RouteName,  
   ISNULL(RT.PickupPoint,'') AS PickupPoint,  
   ISNULL(RT.DropPoint,'') AS DropPoint,  
     
   @lIcardBorder AS IcardBorder,  
   HM.ColorCode,  
   OM.OrgLogo,  
   OM.SmallAddress1,  
   --@lSUIdBarcode AS IsBarcodeBasedOnSUId,  
   CASE WHEN @lSUIdBarcode = 'True' THEN SD.SUId  ELSE SD.Code END AS BarcodeNumber,  
    ISNULL(SD.EmergencyStreetOne,'') AS EmergencyStreetOne,  
          ISNULL(SD.EmergencyStreetTwo,'') AS EmergencyStreetTwo,  
         ISNULL(SD.EmergencyStreetThree,'') AS EmergencyStreetThree,  
         ISNULL(SD.EmergencyCountry,'') AS EmergencyCountry,  
         ISNULL(SD.EmergencyState,'') As EmergencyState,  
         ISNULL(SD.EmergencyCity,'') AS EmergencyCity,  
         ISNULL(SD.EmergencyZipCode,'') as EmergencyZipCode,  
         SD.EmergencyContactNo AS EmergencyContactNo,  
   ISNULL(SD.SUId,'') As SUId,  
   ISNULL(RT.RouteNumber,0) AS RouteNumber,  
   @rIsShowBarcode As IsShowBarcode,  
   SD.Name,  
   SM.Title AS Stream,  
   SD.AdmissionDate,  
   ISNULL(DM.Title,'') AS DepartmentName,  
   SD.FatherPhoto,  
   SD.MotherPhoto,  
   SD.RelativePhoto,  
   RT.Transport AS TransPortMode,  
   @lIDConfigValue AS ItemValue,  
   RT.RouteCode,
   ISNULL(LM.Title,'') AS Medium ,
   ISNULL(HA.Hosteld,'') AS HostelId,
   SD.Gender,
   SI.QRCode
   ,  (Select ToDate from sSetup.tBatchMaster where Id = @rBatchId) as LastBatchDate,

   --STUFF(SELECT  ', ' + Title FROM sActivity.tClubMaster CM INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId=SD.AcademicId FOR XML PATH ('') ),0,0,',') AS Club

    STUFF(
         (SELECT DISTINCT  ', ' + Title 
          FROM sActivity.tClubMaster CM INNER JOIN sActivity.tAssignClub AC ON SD.AcademicId  = AC.AcademicId AND CM.OrgGroupId = LEFT(SD.OrgGroupBatchId,4)
		  
          FOR XML PATH (''))
          , 1, 1, '')  AS Club,

	ISNULL(TM.Title,'') AS StudentTransportMode,
	ISNULL(RT.VehicleName,'') AS VehicleName,
	ISNULL(SO.BirthPlace,'') AS BirthPlace,
   --CM.Title as Club 
   ISNULL(SD.WhatsAppContactNo,'') AS WhatsAppContactNo-- mantis - 0033621

 FROM   
   sStudent.vStudentAllDetail SD  
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId  
   --INNER JOIN sStudent.tStudentOther SO ON SD.StudentId = So.StudentId      
   LEFT JOIN sActivity.tHouseMaster HM ON SD.HouseId = HM.Id   
   LEFT JOIN sActivity.tHouseGroupMaster HGM ON HGM.Id=HM.HouseGroupId  
   LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SD.StudentId 
   LEFT JOIN sHostel.tHostelAdmission HA ON HA.SourceId= SD.StudentId 
   LEFT JOIN  sStudent.tStudentImages SI ON SD.StudentId = SI.StudentId
   LEFT JOIN  
   (SELECT TM.Title AS Transport,  AT.SourceId,ISNULL(BRM.RouteCode,0) AS RouteCode,BRM.Title As RouteName,BRDM.Title As PickupPoint,ISNULL(BRM.RouteNumber,0) AS RouteNumber,
		ISNULL(BRDM1.Title,'')As DropPoint, VM.Title AS VehicleName
    FROM 
		sTransport.tAssignRoute AT   
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND  AT.SourceTypeId=2003 AND ((BRM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		INNER JOIN sTransport.tTransportMaster TM ON TM.Id=BRM.TransportId
		LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AT.DropDestinationId AND BRM.Id=BRDM1.BusRouteId
		LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id = BRM.VehicleId
   ) RT  
   ON RT.SourceId = SD.StudentId AND ((SD.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
   --LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId =SD.StudentId   
   --LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id =AR.PickupDestinationId   
   --LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id =BRDM.BusRouteId  AND(( BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
   LEFT JOIN sStudent.tICardOrg ICO ON SD.OrgId = ICO.OrgId  
   LEFT JOIN sSetup.tStreamMaster SM ON SM.Id=SD.StreamId  
   LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id=SD.DepartmentId  
   LEFT JOIN sStudent.tStudentOther SO ON SD.StudentId = SO.StudentId  
   LEFT JOIN sCommon.tTransportModeMaster TM ON so.TransportModeId = TM.Id  
   LEFT JOIN sSetup.tLanguageMaster LM ON OM.LanguageId = LM.Id

   
   
   --LEFT JOIN sSetup.tOrganizationConfiguration OC ON OM.Id = OC.OrgId   
     
 WHERE   
  SD.OrgId=@rOrgId  
  AND SD.BatchId = @rBatchId   
  AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')   
  AND ((SD.ClassId=@rClassId) OR (@rClassId=0))  
  AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
  AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))  
  AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
  AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
  AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))  
  AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
  AND ((HGM.Id=@rHouseGroupId)OR(@rHouseGroupId=0)) 
  AND ((HM.Id=@rHouseId) OR (Isnull(@rHouseId,0)=0)) 
  AND ((SD.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
END
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentRegisterDetailsGet]...';


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

BEGIN 

	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--SM.Id AS StudentId,
			A.Id AS AcademicId,
			SM.Code,
			SA.AdmissionDate,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			AdmissionStandard=(SELECT Title FROM SSetup.tClassMaster WHERE Id=SA.AdmissionStandardId),
			SF.MotherName,
			SF.MotherOccupation,
			SF.FatherName,
			SF.FatherOccupation,
			ISNULL(SC.PresentStreetone,'') AS PresentStreetone,
			ISNULL(SC.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(SC.PresentStreetThree,'') AS PresentStreetThree,
			ISNULL(SC.PresentCity,'-') AS PresentCity,
			ISNULL(SC.PresentState,'-') As PresentState,
			ISNULL(SC.PresentZipCode,'-') as PresentZipCode,
			ISNULL(SC.PresentCountry,'-') AS PresentCountry,	
			SF.RelativeName,
			SF.RelativeOfficeAddress,
			SF.RelativeOccupation,	
			SO.FamilyCast,
			SO.FamilySubCast,
			ISNULL(SO.DateOfBirth,'0001/01/01') AS DateOfBirth,
			SO.BirthDateInWord,
			SA.PreviousSchool,
			SA.PreviousStandard,
			SA.LCDate,
			SA.AdmissionNumber,
			ISNULL(SC.PermanentStreetOne,'') AS  PermanentStreetOne ,
			ISNULL(SC.PermanentStreetTwo,'')  AS  PermanentStreetTwo,
			ISNULL(SC.PermanentStreetThree,'') AS PermanentStreetThree,
			ISNULL(SC.PermanentState,'') AS PermanentState,
			ISNULL(SC.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SC.PermanentZipCode,'') AS PermanentZipCode,
			BM.Title AS Batch,
			CT.Title AS Category  --Mantis - 33516
				
	FROM 
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			INNER JOIN sStudent.tStatusMaster STM ON STM.Id=SM.StatusId   
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tDepartmentMaster DEM on DEM.Id=CM.DepartmentId
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId   --Mantis - 33516
			
	WHERE 
		SM.OrgId=@rOrgId
		AND (ISNULL(SM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((CM.Id=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((A.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND ((MONTH(SO.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=0))
	    AND ((DEM.Id=@rDepartmentId) OR (@rDepartmentId=0))
	    AND((SM.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	    AND((SM.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))
		AND((SM.Number>=@rFromNumber) OR (ISNULL(@rFromNumber,0)=0))
	    AND((SM.Number<=@rToNumber) OR (ISNULL(@rToNumber,0)=0))
	   
	 Order by
	 BM.Title, A.RollNo
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentAdmissionAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentAdmissionAdd] @rStudentId BIGINT
	,@rPreviousSchool NVARCHAR(200)
	,@rPreviousSchoolTypeId INT
	,@rPreviousStudentId BIGINT
	,@rAdmissionFormId BIGINT
	,@rAdmissionFormNumber NVARCHAR(20)
	,@rAdmissionStandardId INT
	,@rAdmissionDate DATE
	,@rAdmissionYear NVARCHAR(10)
	,@rLeftStandardId INT
	,@rLeftDate DATE
	,@rLeftYear NVARCHAR(10)
	,@rInactiveDate DATE
	,@rInActiveReason NVARCHAR(200)
	,@rLeftReason NVARCHAR(200)
	,@rLCProgress NVARCHAR(200)
	,@rLCConduct NVARCHAR(200)
	,@rLCBook NVARCHAR(20)
	,@rLCNumber NVARCHAR(20)
	,@rLCDate DATE
	,@rLCRemark NVARCHAR(200)
	,@rLCCopy TINYINT
	,@rLcId BIGINT
	,@rBatchId INT
	,@rCreatedUserId BIGINT
	,@rUpdatedUserId BIGINT
	,@rIsGeneral BIT
	,@rAdmissionNumber NVARCHAR(50) = ''
	,@rIsTransfer BIT = 0
	,@rTransferFrom NVARCHAR(150) = ''
	,@rPassingYear NVARCHAR(20) = ''
	,@rIsTFWS BIT = 0
	,@rIsCertificateHolder BIT = 0
	,@rCertificateName NVARCHAR(100) = ''
	,@rAdmissionQuotaId INT = 0
	,@rPreviousStandard NVARCHAR(50) = ''
	,@rAcademicId BIGINT = 0
	,@rPreviousLCDate DATE = NULL
	,@rPreviousLCNumber NVARCHAR(100) = ''
	,@rPreviousLCResult NVARCHAR(100) = ''
	,@rProofOfDOB NVARCHAR(200) = ''
	,@rPreviousLeftDate DATE = NULL --add for 27789 mantis
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRANSACTION

		IF (@rIsGeneral = 1)
		BEGIN
			IF NOT EXISTS (
					SELECT *
					FROM sStudent.tStudentAdmission
					WHERE StudentId = @rStudentId
					)
			BEGIN
				INSERT INTO sStudent.tStudentAdmission (
					StudentId
					,PreviousSchool
					,AdmissionStandardId
					,AdmissionDate
					,LeftStandardId
					,LeftDate
					,InactiveDate
					,BatchId
					,CreatedUserId
					,CreatedDateTime
					,AdmissionQuotaId	--mantis: 33647
					,PreviousStandard
					,PreviousLCNumber
					,PreviousLCDate
					,PreviousLCResult
					,ProofOfDOB
					,PreviousLeftDate
					)
				VALUES (
					@rStudentId
					,@rPreviousSchool
					,@rAdmissionStandardId
					,@rAdmissionDate
					,@rLeftStandardId
					,@rLeftDate
					,@rInactiveDate
					,@rBatchId
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rAdmissionQuotaId	--mantis: 33647
					,@rPreviousStandard
					,@rPreviousLCNumber
					,@rPreviousLCDate
					,@rPreviousLCResult
					,@rProofOfDOB
					,@rPreviousLeftDate
					)

				SELECT 1 AS Result
			END
			ELSE
			BEGIN
				UPDATE sStudent.tStudentAdmission
				SET AdmissionStandardId = @rAdmissionStandardId
					,AdmissionDate = @rAdmissionDate
					,LeftStandardId = @rLeftStandardId
					,LeftDate = @rLeftDate
					,InactiveDate = @rInactiveDate
					,PreviousLeftDate = @rPreviousLeftDate
					,UpdatedUserId = @rUpdatedUserId
					,UpdatedDateTime = sCommon.fGetDate()
				WHERE StudentId = @rStudentId
			END

			SELECT 11 AS Result
		END
		ELSE
		BEGIN
			IF (@rIsGeneral = 0)
				IF NOT EXISTS (
						SELECT *
						FROM sStudent.tStudentAdmission
						WHERE StudentId = @rStudentId
						)
				BEGIN
					INSERT INTO sStudent.tStudentAdmission (
						StudentId
						,PreviousSchool
						,PreviousSchoolTypeId
						,PreviousStudentId
						,AdmissionFormId
						,AdmissionFormNumber
						,AdmissionStandardId
						,AdmissionDate
						,AdmissionYear
						,LeftStandardId
						,LeftDate
						,LeftYear
						,InactiveDate
						,InActiveReason
						,LeftReason
						,LCProgress
						,LCConduct
						,LCBook
						,LCNumber
						,LCDate
						,LCRemark
						,LCCopy
						,LcId
						,BatchId
						,CreatedUserId
						,CreatedDateTime
						,AdmissionNumber
						,IsTransfer
						,TransferFrom
						,PassingYear
						,IsTFWS
						,IsCertificateHolder
						,CertificateName
						,AdmissionQuotaId
						,PreviousStandard
						,PreviousLCNumber
						,PreviousLCDate
						,PreviousLCResult
						,ProofOfDOB
						,PreviousLeftDate --add for 27789 mantis
						)
					VALUES (
						@rStudentId
						,@rPreviousSchool
						,@rPreviousSchoolTypeId
						,@rPreviousStudentId
						,@rAdmissionFormId
						,@rAdmissionFormNumber
						,@rAdmissionStandardId
						,@rAdmissionDate
						,@rAdmissionYear
						,@rLeftStandardId
						,@rLeftDate
						,@rLeftYear
						,@rInactiveDate
						,@rInActiveReason
						,@rLeftReason
						,@rLCProgress
						,@rLCConduct
						,@rLCBook
						,@rLCNumber
						,@rLCDate
						,@rLCRemark
						,@rLCCopy
						,@rLcId
						,@rBatchId
						,@rCreatedUserId
						,sCommon.fGetDate()
						,@rAdmissionNumber
						,@rIsTransfer
						,@rTransferFrom
						,@rPassingYear
						,@rIsTFWS
						,@rIsCertificateHolder
						,@rCertificateName
						,@rAdmissionQuotaId
						,@rPreviousStandard
						,@rPreviousLCNumber
						,@rPreviousLCDate
						,@rPreviousLCResult
						,@rProofOfDOB
						,@rPreviousLeftDate --add for 27789 mantis
						)

					SELECT 1 AS Result
				END
				ELSE
				BEGIN
					UPDATE sStudent.tStudentAdmission
					SET PreviousSchool = @rPreviousSchool
						,PreviousSchoolTypeId = @rPreviousSchoolTypeId
						,PreviousStudentId = @rPreviousStudentId
						,AdmissionFormId = @rAdmissionFormId
						,AdmissionFormNumber = @rAdmissionFormNumber
						,AdmissionStandardId = @rAdmissionStandardId
						,AdmissionDate = @rAdmissionDate
						,AdmissionYear = @rAdmissionYear
						,LeftStandardId = @rLeftStandardId
						,LeftDate = @rLeftDate
						,LeftYear = @rLeftYear
						,InactiveDate = @rInactiveDate
						,InActiveReason = @rInActiveReason
						,LeftReason = @rLeftReason
						,LCProgress = @rLCProgress
						,LCConduct = @rLCConduct
						,LCBook = @rLCBook
						,LCNumber = @rLCNumber
						,LCDate = @rLCDate
						,LCRemark = @rLCRemark
						,LCCopy = @rLCCopy
						,LcId = @rLcId
						,UpdatedUserId = @rUpdatedUserId
						,UpdatedDateTime = sCommon.fGetDate()
						,AdmissionNumber = @rAdmissionNumber
						,IsTransfer = @rIsTransfer
						,TransferFrom = @rTransferFrom
						,PassingYear = @rPassingYear
						,IsTFWS = @rIsTFWS
						,IsCertificateHolder = @rIsCertificateHolder
						,CertificateName = @rCertificateName
						,AdmissionQuotaId = @rAdmissionQuotaId
						,PreviousStandard = @rPreviousStandard
						,PreviousLCNumber = @rPreviousLCNumber
						,PreviousLCDate = @rPreviousLCDate
						,PreviousLCResult = @rPreviousLCResult
						,ProofOfDOB = @rProofOfDOB
						,PreviousLeftDate = @rPreviousLeftDate --add for 27789 mantis
					WHERE StudentId = @rStudentId
				END

			SELECT 11 AS Result
		END

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

		COMMIT TRANSACTION
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT - 1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentDetailUpdate]...';


GO
 
 
ALTER PROCEDURE [sStudent].[pStudentDetailUpdate]
	 
	@rStudentId Bigint=0,
	@rCategory int,
	@rSubCategory nvarchar(20),
	@rStrXml nvarchar(max)=''
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
		 if @rCategory=1
		 BEGIN
			IF @rSubCategory='Present Address'
			BEGIN
				Update sStudent.tStudentCommunication
				Set
					PresentStreetOne=A.PresentStreetOne,
					PresentStreetTwo=A.PresentStreetTwo,
					PresentStreetThree=A.PresentStreetThree,
					PresentCountry=A.PresentCountry,
					PresentState=A.PresentState,
					PresentCity=A.PresentCity,
					PresentZipCode=A.PresentZipCode,
					PresentContactNo=A.PresentContactNo
				From
				(
					Select StudentId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,
					       PresentState,PresentCity,PresentZipCode,PresentContactNo
					from openxml (@loDoc,'/Table/Student',1)
					with
					(
						StudentId bigint,
						PresentStreetOne nvarchar(100),
						PresentStreetTwo nvarchar(100),
						PresentStreetThree nvarchar(100),
						PresentCountry nvarchar(50),
						PresentState nvarchar(50),
						PresentCity nvarchar(50),
						PresentZipCode nvarchar(50),
						PresentContactNo nvarchar(50)
					)	   
				)A Where sStudent.tStudentCommunication.StudentId=A.StudentId
			END
			IF @rSubCategory='Permanent Address'
			BEGIN
				Update sStudent.tStudentCommunication
				Set
					PermanentStreetOne=A.PresentStreetOne,
					PermanentStreetTwo=A.PresentStreetTwo,
					PermanentStreetThree=A.PresentStreetThree,
					PermanentCountry=A.PresentCountry,
					PermanentState=A.PresentState,
					PermanentCity=A.PresentCity,
					PermanentZipCode=A.PresentZipCode,
					PermanentContactNo=A.PresentContactNo
				from
				(
					Select StudentId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,
						    PresentState,PresentCity,PresentZipCode,PresentContactNo
					From openXml(@loDoc,'/Table/Student',1)
					With
					(
						StudentId bigint,
						PresentStreetOne nvarchar(150),
						PresentStreetTwo nvarchar(150),
						PresentStreetThree nvarchar(150),
						PresentCountry nvarchar(50),
						PresentState nvarchar(50),
						PresentCity nvarchar(50),
						PresentZipCode nvarchar(20),
						PresentContactNo nvarchar(20)
					)	
				)A Where sStudent.tStudentCommunication.StudentId=A.StudentId
			END
			IF @rSubCategory='Emergency Address'
			BEGIN
				Update sStudent.tStudentCommunication
				Set
					EmergencyStreetOne=A.PresentStreetOne,
					EmergencyStreetTwo=A.PresentStreetTwo,
					EmergencyStreetThree=A.PresentStreetThree,
					EmergencyCountry=A.PresentCountry,
					EmergencyState=A.PresentState,
					EmergencyCity=A.PresentCity,
					EmergencyZipCode=A.PresentZipCode,
					EmergencyContactNo=A.PresentContactNo
				From
				(
					Select StudentId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,
						    PresentState,PresentCity,PresentZipCode,PresentContactNo
					From Openxml(@loDoc,'Table/Student',1)
					With
					(
						StudentId Bigint,
						PresentStreetOne nvarchar(150),
						PresentStreetTwo nvarchar(150),
						PresentStreetThree nvarchar(150),
						PresentCountry nvarchar(20),
						PresentState nvarchar(20),
						PresentCity nvarchar(20),
						PresentZipCode nvarchar(20),
						PresentContactNo nvarchar(20) 
					)
				) A Where sStudent.tStudentCommunication.StudentId=A.StudentId
			END
		END
		If @rCategory=2
		BEGIN
			If @rSubCategory='Father'
			BEGIN
				Update sStudent.tStudentFamily
				Set
					FatherName=A.Name,
					FatherDateOfBirth=A.DateOfBirth,
					FatherOccupation=A.Occupation,
					FatherQualification=A.Qualification,
					FatherContactNo=A.ContactNo,
					FatherMail=A.Mail,
					FatherOfficeAddress=A.OfficeAddress,
					FatherIncome=A.Income,
					FatherOfficeContactNo = A.OfficeContactNo
				From
				(
					Select StudentId,Name,DateOfBirth,Occupation,
							Qualification,ContactNo,Mail,OfficeAddress,Income,OfficeContactNo
					from openxml(@loDoc,'Table/Student',1)
					with
					(
						StudentId bigint,
						Name nvarchar(100),
						DateOfBirth date,
						Occupation nvarchar(50),
						Qualification nvarchar(50),
						ContactNo nvarchar(50),
						Mail nvarchar(50),
						OfficeAddress nvarchar(50),
						Income int,
						OfficeContactNo nvarchar(50)
					)
				)A Where sStudent.tStudentFamily.StudentId=A.StudentId
			END
			IF @rSubCategory='Mother'
			BEGIN
				update sStudent.tStudentFamily 
				Set
					MotherName=A.Name,
					MotherDateOfBirth=A.DateOfBirth,
					MotherOccupation=A.Occupation,
					MotherQualification=A.Qualification,
					MotherContactNo=A.ContactNo,
					MotherMail=A.Mail,
					MotherOfficeAddress=A.OfficeAddress,
					MotherIncome=A.Income,
					MotherOfficeContactNo = A.OfficeContactNo
				from
				(
					Select StudentId,Name,DateOfBirth,Occupation,
							Qualification,ContactNo,Mail,OfficeAddress,Income,OfficeContactNo
					
					from openxml(@loDoc,'Table/Student',1)
					With
					(
						StudentId bigint,
						Name nvarchar(100),
						DateOfBirth date,
						Occupation nvarchar(50),
						Qualification nvarchar(50),
						ContactNo nvarchar(20),
						Mail nvarchar(50),
						OfficeAddress nvarchar(50),
						Income int,
						OfficeContactNo nvarchar(50)
					)
				)A Where sStudent.tStudentFamily.StudentId=A.StudentId
			END
			IF @rSubCategory ='Relative'
			BEGIN
				Update sStudent.tStudentFamily 
				Set 
					RelationshipName =A.RelationshipName,
					RelativeName=A.Name,
					RelativeDateOfBirth=A.DateOfBirth,
					RelativeOccupation=A.Occupation,
					RelativeQualification=A.Qualification,
					RelativeContactNo=A.ContactNo,
					RelativeMail=A.Mail,
					RelativeOfficeAddress=A.OfficeAddress,
					RelativeIncome=A.Income
				From
				(
					Select StudentId,RelationshipName,Name,DateOfBirth,Occupation,
							Qualification,ContactNo,Mail,OfficeAddress,Income
					From Openxml(@loDoc,'Table/Student',1)
						With
						(
							StudentId bigint,
							RelationshipName nvarchar(100),
							Name nvarchar(100),
							DateOfBirth date,
							Occupation nvarchar(50),
							Qualification nvarchar(50),
							ContactNo nvarchar(20),
							Mail nvarchar(50),
							OfficeAddress nvarchar(50),
							Income int
						)
				)A Where sStudent.tStudentFamily.StudentId=A.StudentId
			END
		END
		If @rCategory=3
		BEGIN
			DECLARE @Str varchar(500)=''
			IF @rSubCategory ='Academic'
			BEGIN
				Create Table #table1
				(
					FirstName nvarchar(100),
					MiddleName nvarchar(100),
					LastName nvarchar(100),
					StudentId bigint,
					AdmissionStandardId int,
					AdmissionDate date,
					GenderId int,
					DateOfBirth date,
					BirthdateInWord nvarchar(150)-- mantisid - 0033546
				)
				Insert into #table1
				Select FirstName,MiddleName,LastName,StudentId, AdmissionStandardId,AdmissionDate,GenderId,DateOfBirth,BirthdateInWord
					From Openxml(@loDoc,'Table/Student',1)
						With
						( 
							FirstName nvarchar(100),
							MiddleName nvarchar(100),
							LastName nvarchar(100),
							StudentId bigint,
							AdmissionStandardId int,
							AdmissionDate date,
							GenderId int,
							DateOfBirth Date,
							BirthdateInWord nvarchar(150)
						) 
			 IF Exists (SELECT 1 FROM #table1 WHERE AdmissionDate <= DateOfBirth)
			BEGIN
					--Set @Str=''
					--SELECT @Str=COALESCE(@Str,'')+CAST(FirstName As nvarchar(50))+ ',' FROM #table1 WHERE AdmissionDate >= DateOfBirth
					select -109,@Str AS Result
			RETURN		
			END 
			-- --Select * from #table1
				Update  Stu
				Set
					FirstName =T.FirstName,
					MiddleName=T.MiddleName,
					LastName=T.LastName 
					
				From sStudent.tStudentMaster Stu
				INNER JOIN #table1 T ON T.StudentId =Stu.Id
				Where Stu.Id =T.StudentId
					
				Update A
				Set 
						AdmissionDate=T.AdmissionDate,
						AdmissionStandardId =T.AdmissionStandardId
				from sStudent.tStudentAdmission A 
				INNER JOIN #table1 T ON T.StudentId =A.StudentId
				
				 
				
				Update SO 
				Set
					GenderId =T1.GenderId,
					
					DateOfBirth=T1.DateOfBirth,
					BirthDateInWord = T1.BirthDateInWord
				From sStudent.tStudentOther SO 
				INNER JOIN #table1 T1 ON T1.StudentId=So.StudentId
				
				
				
				
				--Update sStudent.tStudentMaster
				--Set
				--	FirstName =SM.FirstName,
				--	MiddleName=SM.MiddleName,
				--	LastName=SM.LastName
					
				--From
				--(
				--	Select StudentId,FirstName,MiddleName,LastName
				--	From Openxml(@loDoc,'Table/Student',1)
				--		With
				--		(
				--			StudentId bigint,
				--			FirstName nvarchar(100),
				--			MiddleName nvarchar(100),
				--			LastName nvarchar(100)
				--		) 
				--)SM 
				--Where sStudent.tStudentMaster.Id=SM.StudentId
				
				 
				--Update sStudent.tAcademic
				--Set
				--	ClassID=AC.CLassId,
				--	DivisionId=AC.DivisionID
				--From
				--(
				--	Select StudentID,ClassID,DivisionId
				--	from OpenXml(@loDoc,'Table/Student',1)
				--	With
				--	(
				--		StudentID bigint,
				--		ClassID int,
				--		DivisionID int
				--	)
				--)AC Where sStudent.tAcademic.StudentId=AC.StudentID
				 
				--Update sStudent.tStudentAdmission
				--Set
				--	AdmissionStandardId =A.AdmissionStandardId,
				--	AdmissionDate =A.AdmissionDate
				--From
				--(
				--	Select StudentID,AdmissionStandardId,AdmissionDate
				--	from Openxml(@loDoc,'Table/Student',1)
				--	With
				--	(
				--		StudentID Bigint,
				--		AdmissionStandardId int,
				--		AdmissionDate date
				--	)
				--)A Where sStudent.tStudentAdmission.StudentId=A.StudentID
			 END
			 
			 
			 
			 
			IF @rSubCategory ='Main Group'
			BEGIN
				 Update sStudent.tStudentMaster Set StudentGroupId=A.StudentGroupId
				 
				 From
				(
					Select StudentId,StudentGroupId
					From Openxml(@loDoc,'Table/Student',1)
						With
						(
							StudentId bigint,
							StudentGroupId int
						)
				)A Where sStudent.tStudentMaster.Id=A.StudentId
			 END
			 
			 IF @rSubCategory ='Other Group'
			BEGIN
				 Update sStudent.tStudentMaster Set StudentOtherGroupId=A.StudentGroupId
				 
				 From
				(
					Select StudentId,StudentGroupId
					From Openxml(@loDoc,'Table/Student',1)
						With
						(
							StudentId bigint,
							StudentGroupId int
						)
				)A Where sStudent.tStudentMaster.Id=A.StudentId
			 END
			 
			  IF @rSubCategory ='Demographic'
			BEGIN
				 Update sStudent.tStudentOther Set ReligionId=A.ReligionId,FamilyCast=A.Familycast,FamilySubCast=A.Subcast,CastCategoryId=A.CastCategoryId,NationalityId=A.NationalityId
				 
				 From
				(
					Select StudentId,ReligionId,Familycast,Subcast,CastCategoryId,NationalityId 
					From Openxml(@loDoc,'Table/Student',1)
						With
						(
							ReligionId int,
							Familycast nvarchar(100),
							Subcast nvarchar(100),
							CastCategoryId int,
							NationalityId int,
							StudentId bigint
						)
				)A Where sStudent.tStudentOther.StudentId=A.StudentId
			 END
		END
		 	Select 1 As Result
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentGenerateReport]...';


GO


ALTER PROCEDURE [sStudent].[pStudentGenerateReport]
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9999-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9999-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@rIsCommon bit,
	@rIsCommonForOrg bit,
	@rCreatedUserId bigint,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rSpecificCode nvarchar(max),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount smallint=0,
	@rStudentStatusId smallint=0,
	@rHostelId nvarchar(max) = '',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption nvarchar(max)='',
	@rRecordTagId nvarchar(max) = '',
	@rContactNo nvarchar(50) = '',
	@rBirthDay int =0,
	@rDateOfMonth int =0,
	@rStopApplicationAccess int = 0,
	@rCurrentOrgId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		IF(@rHostelId IS NULL)
			SET @rHostelId = ''
		IF(@rStudentGroupId IS NULL)
			SET @rStudentGroupId = ''
		IF(@rStudentOtherGroupId IS NULL)
			SET @rStudentOtherGroupId = ''	
		IF(@rOrgGroupBatchId IS NULL)
			SET @rOrgGroupBatchId = 0
		IF(@rGenderId IS NULL)
			SET @rGenderId = ''
		IF(@rBusRouteId IS NULL)
			SET @rBusRouteId = ''	
		IF(@rDOBFromDate IS NULL)
			SET @rDOBFromDate='0001-01-01'
		IF(@rDOBToDate IS NULL)
			SET @rDOBToDate='9999-12-31'
		IF(@rDOAFromDate IS NULL)
			SET @rDOAFromDate='0001-01-01'
		IF(@rDOAToDate IS NULL)
			SET @rDOAToDate='9999-12-31'
		IF(@rDOLFromDate IS NULL)
			SET @rDOLFromDate='0001-01-01'
		IF(@rDOLToDate IS NULL)
			SET @rDOLToDate='9999-12-31'
		
		IF(@rTitle != '' AND @rId = 0)
		BEGIN
			DECLARE @lNextNumber BIGINT

			-- when OrgId 0 then issue in @lNextNumber thats why add new parameter @rCurrentOrgId and generate Id according current session -- mantisid - 0033556
			IF(@rOrgId = 0)
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rCurrentOrgId, 'sStudent.tStudentCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

				INSERT INTO sStudent.tStudentCustomSearch
				(
					Id,Title,ColumnName,OrderBy,OrgId,Code,FirstName,LastName,Country,State,City,Area,DivisionId,
					StatusId,TransportModeId,BusRouteDestinationId,BloodGroupId,GenderId,ReligionId,CastCategoryId,
					HouseId,MotherTongueId,NationalityId,Hobby,FatherQualification,MotherQualification,FatherOccupation,
					MotherOccupation,PreviousSchool,AdmissionCategoryId,DOBFromDate,DOBToDate,DOAFromDate,DOAToDate,
					DOLFromDate,DOLToDate,IsPysicalDeformity,IsMajorIllness,IsCommon,IsCommonForOrg, CreatedUserId,CreatedDateTime,
					IsBlackList,FromCode,ToCode,CustomTag,CustomGroup,Club,RepeatCount,StudentStatusId,Hostel,StudentGroup,
					StudentOtherGroup,FeeExemption,RecordTag,ContactNo,BirthDay,DateOfMonth,IsStopApplicationAccess
				)
				VALUES
				(
					@lNextNumber,@rTitle,@rColumnName,@rOrderBy,@rCurrentOrgId,@rSpecificCode,@rFirstName,@rLastName,@rCountry,@rState,
					@rCity,@rArea,@rDivisionId,@rStatusId,@rTransportModeId,@rBusRouteDestinationId,@rBloodGroupId,@rGenderId,
					@rReligionId,@rCastCategoryId,@rHouseId,@rMotherTongueId,@rNationalityId,@rHobby,@rFatherQualification,
					@rMotherQualification,@rFatherOccupation,@rMotherOccupation,@rPreviousSchool,@rAdmissionCategoryId,
					@rDOBFromDate,@rDOBToDate,@rDOAFromDate,@rDOAToDate,@rDOLFromDate,@rDOLToDate,@rIsPysicalDeformity,
					@rIsMajorIllness,@rIsCommon,@rIsCommonForOrg,@rCreatedUserId,sCommon.fGetDate(),@rIsBlackList,@rFromCode,@rToCode,
					@rCustomTagId,@rCustomGroupId,@rClubId,@rRepeatCount,@rStudentStatusId,@rHostelId,@rStudentGroupId,
					@rStudentOtherGroupId,@rFeeExemption,@rRecordTagId,@rContactNo,@rBirthDay,@rDateOfMonth,@rStopApplicationAccess
				)
			END
			ELSE
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

				INSERT INTO sStudent.tStudentCustomSearch
				(
					Id,Title,ColumnName,OrderBy,OrgId,Code,FirstName,LastName,Country,State,City,Area,DivisionId,
					StatusId,TransportModeId,BusRouteDestinationId,BloodGroupId,GenderId,ReligionId,CastCategoryId,
					HouseId,MotherTongueId,NationalityId,Hobby,FatherQualification,MotherQualification,FatherOccupation,
					MotherOccupation,PreviousSchool,AdmissionCategoryId,DOBFromDate,DOBToDate,DOAFromDate,DOAToDate,
					DOLFromDate,DOLToDate,IsPysicalDeformity,IsMajorIllness,IsCommon,IsCommonForOrg, CreatedUserId,CreatedDateTime,
					IsBlackList,FromCode,ToCode,CustomTag,CustomGroup,Club,RepeatCount,StudentStatusId,Hostel,StudentGroup,
					StudentOtherGroup,FeeExemption,RecordTag,ContactNo,BirthDay,DateOfMonth,IsStopApplicationAccess
				)
				VALUES
				(
					@lNextNumber,@rTitle,@rColumnName,@rOrderBy,@rOrgId,@rSpecificCode,@rFirstName,@rLastName,@rCountry,@rState,
					@rCity,@rArea,@rDivisionId,@rStatusId,@rTransportModeId,@rBusRouteDestinationId,@rBloodGroupId,@rGenderId,
					@rReligionId,@rCastCategoryId,@rHouseId,@rMotherTongueId,@rNationalityId,@rHobby,@rFatherQualification,
					@rMotherQualification,@rFatherOccupation,@rMotherOccupation,@rPreviousSchool,@rAdmissionCategoryId,
					@rDOBFromDate,@rDOBToDate,@rDOAFromDate,@rDOAToDate,@rDOLFromDate,@rDOLToDate,@rIsPysicalDeformity,
					@rIsMajorIllness,@rIsCommon,@rIsCommonForOrg,@rCreatedUserId,sCommon.fGetDate(),@rIsBlackList,@rFromCode,@rToCode,
					@rCustomTagId,@rCustomGroupId,@rClubId,@rRepeatCount,@rStudentStatusId,@rHostelId,@rStudentGroupId,
					@rStudentOtherGroupId,@rFeeExemption,@rRecordTagId,@rContactNo,@rBirthDay,@rDateOfMonth,@rStopApplicationAccess
				)
			END

		END
		
		
		IF(@rId > 0)
		BEGIN
			Select @rColumnName=ColumnName,@rOrderBy=OrderBy,@rOrgId=OrgId,@rSpecificCode=Code,@rFirstName=FirstName,
			@rLastName=LastName,@rCountry=Country,@rState=State,@rCity=City,@rArea=Area,@rDivisionId=DivisionId,
			@rStatusId=StatusId,@rTransportModeId=TransportModeId,@rBusRouteDestinationId=BusRouteDestinationId,
			@rBloodGroupId=BloodGroupId,@rGenderId=GenderId,@rReligionId=ReligionId,@rCastCategoryId=CastCategoryId,
			@rHouseId=HouseId,@rMotherTongueId=MotherTongueId,@rNationalityId=NationalityId,@rHobby=Hobby,
			@rFatherQualification=FatherQualification,@rMotherQualification=MotherQualification,
			@rFatherOccupation=FatherOccupation,@rMotherOccupation=MotherOccupation,
			@rPreviousSchool=PreviousSchool,@rAdmissionCategoryId=AdmissionCategoryId,
			@rDOBFromDate=DOBFromDate,@rDOBToDate=DOBToDate,@rDOAFromDate=DOAFromDate,
			@rDOAToDate=DOAToDate,@rDOLFromDate=DOLFromDate,@rDOLToDate=DOLToDate,
			@rIsPysicalDeformity=IsPysicalDeformity,@rIsMajorIllness=IsMajorIllness,
			@rIsBlackList=IsBlackList,@rFromCode=FromCode,@rToCode=ToCode,
			@rCustomTagId=CustomTag,@rCustomGroupId = CustomGroup,@rClubId = Club,
			@rRepeatCount = RepeatCount,@rStudentStatusId =StudentStatusId,
			@rHostelId = Hostel,@rStudentGroupId = StudentGroup,
			@rStudentOtherGroupId = StudentOtherGroup,@rFeeExemption =FeeExemption,
			@rRecordTagId=RecordTag,@rContactNo=ContactNo,@rStopApplicationAccess=IsStopApplicationAccess
			FROM sStudent.tStudentCustomSearch WHERE Id=@rId
		END
		
		DECLARE @ListofCodes TABLE(Code nvarchar(25), ID INT IDENTITY(1,1));
			INSERT INTO @ListofCodes
	     
		SELECT q2.value from
			(SELECT cast('<x>'+replace(@rSpecificCode,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
			(SELECT x.value('.','nvarchar(max)') as value FROM thexml.nodes('x') as f(x))q2
		
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		SET @rColumnName=Replace(@rColumnName,'PhysicalDeformityRemark','PysicalDeformityRemark')
		SET @rColumnName=Replace(@rColumnName,'IsPhysicalDeformity','IsPysicalDeformity')
		SET @rOrderBy=Replace(@rOrderBy,'PhysicalDeformityRemark','PysicalDeformityRemark')
		SET @rOrderBy=Replace(@rOrderBy,'IsPhysicalDeformity','IsPysicalDeformity')
		
		DECLARE @Sql nvarchar(MAX)= ''
		
		SET @rSpecificCode = sCommon.fSearchStringGet(@rSpecificCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rCountry = sCommon.fSearchStringGet(@rCountry)
		SET @rState = sCommon.fSearchStringGet(@rState)
		
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent1')
		 BEGIN
			DROP Table sStudent.tTempStudent1
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent2')
		 BEGIN		
			DROP Table sStudent.tTempStudent2
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent3')
		 BEGIN
			DROP Table sStudent.tTempStudent3
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent4')
		 BEGIN
			DROP Table sStudent.tTempStudent4
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent5')
		 BEGIN
			DROP Table sStudent.tTempStudent5  
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent6')
		 BEGIN
			DROP Table sStudent.tTempStudent6
		 END
		 
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent7')
		 BEGIN
			DROP Table sStudent.tTempStudent7
		 END
		 
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent8')
		 BEGIN
			DROP Table sStudent.tTempStudent8
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent9')
		 BEGIN
			DROP Table sStudent.tTempStudent9
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent10')
		 BEGIN
			DROP Table sStudent.tTempStudent10
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent11')
		 BEGIN
			DROP Table sStudent.tTempStudent11
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent12')
		 BEGIN
			DROP Table sStudent.tTempStudent12
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent13')
		 BEGIN
			DROP Table sStudent.tTempStudent13
		 END
		  IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent14')
		 BEGIN
			DROP Table sStudent.tTempStudent14
		 END
		
		SELECT  DISTINCT SM.Id AS StudentId6,
		CASE WHEN SF.IsFatherExStudent = 0 THEN 'No' WHEN SF.IsFatherExStudent = 1 THEN 'Yes' ELSE '' END AS IsFatherExStudent,
		CASE WHEN SF.IsMotherExStudent = 0 THEN 'No' WHEN SF.IsMotherExStudent = 1 THEN 'Yes' ELSE '' END AS IsMotherExStudent,
		SF.FatherOrganization, SF.FatherDesignation, SF.MotherOrganization, SF.MotherDesignation, SF.RelativeOrganization, SF.RelativeDesignation
		INTO sStudent.tTempStudent11
		FROM sStudent.tStudentMaster SM
			 INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND ((SM.OrgId = @rOrgId) OR (@rOrgId=0)) AND ((A.BatchId=@BatchId) OR (@BatchId = 0))
			 INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
	
		-- For Left Detail
		SELECT DISTINCT  SA.StudentId AS StudentId12,InactiveDate,InActiveReason,LCBook,--LeftStandardId,
		CM.Title AS LeftStandard,
		CONVERT(VARCHAR(10),LCDate,111) AS LCDate,LCCopy,LeftReason,LCProgress,
		LCConduct,LCRemark 
		INTO sStudent.tTempStudent12
		FROM sStudent.tStudentAdmission SA
		     INNER JOIN sStudent.tAcademic A ON A.StudentId = SA.StudentId AND ((A.OrgId = @rOrgId) OR (@rOrgId = 0)) AND ((A.BatchId=@BatchId) OR (@BatchId=0))
		     LEFT JOIN sSetup.tClassMaster CM ON CM.Id = SA.LeftStandardId
		
		-- For Custom Tag
		IF (@rCustomTagId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId1
			INTO sStudent.tTempStudent5
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId1
			INTO sStudent.tTempStudent5
		END
		
		-- For Custom Group
		IF (@rCustomGroupId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId2
			INTO sStudent.tTempStudent6
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId2
			INTO sStudent.tTempStudent6
		END
		
		-- For Club Group
		IF (@rClubId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId3
			INTO sStudent.tTempStudent7
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId3
			INTO sStudent.tTempStudent7
		END
		
		-- For Hostel
		IF (@rHostelId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId4
			INTO sStudent.tTempStudent9
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
			AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
			WHERE((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId4
			INTO sStudent.tTempStudent9
		END
		
		--Transport
		IF (@rBusRouteId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId5
			INTO sStudent.tTempStudent10
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
			AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0)) 
			AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId5
			INTO sStudent.tTempStudent10
			
			
		END
		-- For Record Tag
		IF (@rRecordTagId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId14		
			--INTO sStudent.tTempStudent14
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(SM.RecordStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rRecordTagId,','))OR @rRecordTagId='')
		END
		ELSE
		BEGIN
		
			SELECT DISTINCT NULL AS StudentId14
			INTO sStudent.tTempStudent14
		END
		
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		--if @rColumnName <> ''
		--begin
		--	select @rColumnName = left(@rColumnName,len(@rColumnName)-1)
		--end
		--print 'asdasda'
		    DECLARE @lAvailableStudentColumns nvarchar(max)=''
			DECLARE @lAvailableStudentCustomRes nvarchar(max)=''
			Declare @Title as nvarchar(max)
			DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
		
		
          --BEGIN  
		   
		   --drop table sStudent.tTempStudent13

             
			--print @BatchId
			--print @rOrgId
            DECLARE @rOrgGroupId smallint

			--mantisid -- 0033556
			IF(@rOrgId = 0)
			BEGIN
				SET @rOrgGroupId = (Select orggroupid from sSetup.tOrganizationMaster where Id=@rCurrentOrgId)
			END
			ELSE
			BEGIN
				SET @rOrgGroupId = (Select orggroupid from sSetup.tOrganizationMaster where Id=@rOrgId)
			END

                        
             
			SET @lAvailableStudentColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
								from sStudent.tStudentCustomFieldMaster PP  WHERE PP.OrgGroupId = @rOrgGroupId  
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
					--Print @lAvailableStudentColumns
	        IF(@lAvailableStudentColumns IS NOT NULL)
	        BEGIN
				set @query = 'SELECT  StudentId AS StudentId13 ,' + @lAvailableStudentColumns + ' into sStudent.tTempStudent13 from 
					 (
						select PPE.FieldTitle,PP.StudentId,FieldData 
						FROM
						sStudent.tStudentCustomFieldData PP 
							INNER JOIN sStudent.tStudentCustomFieldMaster PPE ON PPE.Id = PP.StudentCustomFieldId AND PPE.IsObsolete=0
							INNER JOIN sStudent.tStudentMaster SM ON SM.Id = PP.StudentId						
							INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND A.BatchId='+convert(varchar(20),@BatchId)+' 
							WHERE ((SM.OrgId='+convert(varchar(20),@rOrgId) +') OR ('+ convert(varchar(20),@rOrgId) +' = 0))
					) x 
					pivot 
					(
						Max(FieldData)
						for FieldTitle in (' +@lAvailableStudentColumns  + ')
					) p'
					
				 --print @query
                execute(@query)
		   
		   
		
		Select * into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
		LEFT JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6
		LEFT JOIN  sStudent.tTempStudent12 T12 ON SCS.StudentId= T12.StudentId12 
		LEFT JOIN  sStudent.tTempStudent13 T13 ON SCS.StudentId= T13.StudentId13 
		INNER JOIN sStudent.tTempStudent14 T14 ON SCS.StudentId = T14.StudentId14 OR @rRecordTagId = ''
		WHERE ((SCS.OrgId = @rOrgId) OR (@rOrgId = 0)) 
		AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0))
		--AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
		AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
		AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%') OR(@rCountry = ''))
		AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
		AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
		AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
		AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
		AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
		AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR (@rGenderId=''))
		AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
		AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
		AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
		AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
		AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
		AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		--AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) >= (REPLICATE(0, 50 - LEN(@rFromCode)) + @rFromCode) OR (@rFromCode='') OR (@rFromCode=0))	-- Add @rFromCode=0 for MantisId : 0029214
		--AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) <= (REPLICATE(0, 50 - LEN(@rToCode)) + @rToCode) OR (@rToCode='') OR (@rToCode=0))			-- Add @rToCode=0 for MantisId : 0029214
		AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) >= (REPLICATE(0, 50 - LEN(@rFromCode)) + @rFromCode) OR (@rFromCode=''))			-- MantisId : 0032524
		AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) <= (REPLICATE(0, 50 - LEN(@rToCode)) + @rToCode) OR (@rToCode=''))				-- MantisId : 0032524
		AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
		AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		AND ((SCS.PresentContactNo=@rContactNo) OR (SCS.PermanentContactNo=@rContactNo) OR (SCS.EmergencyContactNo=@rContactNo) OR (SCS.ParentContactno=@rContactNo) OR (SCS.StudentContactNo=@rContactNo) OR (SCS.FatherContactNo=@rContactNo) OR (SCS.MotherContactNo=@rContactNo) OR (@rContactNo=''))
		AND (( DAY(CONVERT(date,SCS.DateOfBirth)) = @rBirthDay) OR (@rBirthDay = 0))
	    AND (( MONTH(CONVERT(date,SCS.DateOfBirth)) = @rDateOfMonth) OR (@rDateOfMonth = 0))
		--AND (ISNULL(SCS.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--Select * from sStudent.tTempStudent return	
		AND ((SCS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		AND ((SCS.IsStopApplicationAccess = @rStopApplicationAccess) OR (@rStopApplicationAccess = -1))
				
		set @sql = 'SELECT '+ @rColumnName+' FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		
		exec(@Sql)
			
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
		DROP Table sStudent.tTempStudent12
		DROP Table sStudent.tTempStudent13
		DROP Table sStudent.tTempStudent14
 
	END 
	 
	ELSE
	BEGIN
	    Select * into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
		LEFT JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6
		LEFT JOIN  sStudent.tTempStudent12 T12 ON SCS.StudentId= T12.StudentId12 
		INNER JOIN sStudent.tTempStudent14 T14 ON SCS.StudentId = T14.StudentId14 OR @rRecordTagId = ''
		
		WHERE ((SCS.OrgId = @rOrgId) OR (@rOrgId = 0)) 
		AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0)) 
		--AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
		AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
		AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%') OR(@rCountry = ''))
		AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
		AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
		AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
		AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
		AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
		AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR (@rGenderId=''))
		AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
		AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
		AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
		AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
		AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
		AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		--AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) >= (REPLICATE(0, 50 - LEN(@rFromCode)) + @rFromCode) OR (@rFromCode='') OR (@rFromCode=0))	-- Add @rFromCode=0 for MantisId : 0029214
		--AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) <= (REPLICATE(0, 50 - LEN(@rToCode)) + @rToCode) OR (@rToCode='') OR (@rToCode=0))			-- Add @rToCode=0 for MantisId : 0029214
		AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) >= (REPLICATE(0, 50 - LEN(@rFromCode)) + @rFromCode) OR (@rFromCode=''))			-- MantisId : 0032524
		AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) <= (REPLICATE(0, 50 - LEN(@rToCode)) + @rToCode) OR (@rToCode=''))				-- MantisId : 0032524
		AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
		AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		AND ((SCS.PresentContactNo=@rContactNo) OR (SCS.PermanentContactNo=@rContactNo) OR (SCS.EmergencyContactNo=@rContactNo) OR (SCS.ParentContactno=@rContactNo) OR (SCS.StudentContactNo=@rContactNo) OR (SCS.FatherContactNo=@rContactNo) OR (SCS.MotherContactNo=@rContactNo) OR (@rContactNo=''))
		--AND (ISNULL(SCS.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--Select * from sStudent.tTempStudent return	
		AND ((SCS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		AND (( DAY(CONVERT(date,SCS.DateOfBirth)) = @rBirthDay) OR (@rBirthDay = 0))
	    AND (( MONTH(CONVERT(date,SCS.DateOfBirth)) = @rDateOfMonth) OR (@rDateOfMonth = 0))
		AND ((SCS.IsStopApplicationAccess = @rStopApplicationAccess) OR (@rStopApplicationAccess = -1))		
				--Select * From sStudent.tTempStudent
		set @sql = 'SELECT '+ @rColumnName+' FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		
		
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		
		exec(@Sql)
			
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
		DROP Table sStudent.tTempStudent12
		
	    
	    
	END 
	 
	 
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentLeaveListingGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentLeaveListingGet]
(  
	@rOrgId int,  
    --@rId bigint = 0, 
	@rAcademicId bigint=0,
    @rStudentId  bigint=0,     
    @rFromDate date='',   
    @rTodate date='',  
    @rOrgGroupBatchId int=0,  
    @rStudentCode nvarchar(100)='',  
    @rStudentName nvarchar(100)='',  
    @rStatusId int = 0,  
	@rClassId int =0,
    @rOrgGroupId int=0,  
    --@rIsSearchLeaveHierarchyWise int = 0,  
    --@rDepartmentId int,	
	@rDivisionId bigint=0,
	@rUserId bigint = 0,
	@rBatchId int = 0

 )  
AS  
SET NOCOUNT ON  

DECLARE @lItemValue nvarchar(20) = '' , @lUserSourceId bigint , @lUserSourceTypeId int
	
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 = 186

SELECT @lUserSourceId = SourceId , @lUserSourceTypeId = ISNULL(SourceTypeId,0) from sSecurity.tUser WHERE Id = @rUserId

IF(@lUserSourceTypeId = 95)
BEGIN
	IF(@lItemValue = 'Class Teacher')
	BEGIN
		IF(@rUserId=0)
		BEGIN
		 SELECT DISTINCT --Add Distict for Mantis Id:0033687
			  --ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
			  L.AcademicId AS AcademicId,  
			  SA.[StudentId],  
			  L.CreatedDateTime AS ReportDate,  
			  L.[LeaveFromDate] AS FromDate,  
			  L.[LeaveToDate] AS ToDate,  
			  ISNULL(L.LeaveReason,'') as LeaveReason,  
			  --EM.EmployeeName,  
			  SA.Name AS StudentName,
			  SA.Code AS StudentCode,  
			  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
			  ISNULL(L.StatusId,0) AS StatusId,  
			  ISNULL(SM.Title,'Pending') AS StatusName,  
			  ISNULL(L.StatusReason,'') AS  StatusReason,  
			  OM.DisplayTitle AS OrganizationName,  
			  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
			  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
			  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
			  OM.Id AS OrgId,  
			  SA.BatchId AS BatchId, 
			  SA.DivisionId,
			  SA.DivisionName,
			  SA.ClassId,
			  SA.ClassName, 
			  SA.DepartmentId AS DepartmentId,  
			  SA.DepartmentName As DepartmentName
			  --US.Id As UserId
		  FROM   
			  sAttendance.tStudentLeaveRequest L   
			  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
			  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
			  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
			  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
			 --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
			  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
			 -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017     

		  WHERE   
			  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
			  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
			  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			  AND (SA.ClassId=@rClassId OR @rClassId=0)
			  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
			  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
			  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
			  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
			  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
			  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
			  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
			  AND ISNULL(EMP.IsOtherUser,0)=0 
			  AND SA.InchargeEmployeeId = @lUserSourceId
			 -- AND U.UserId = @rUserId     
		  ORDER BY   
			  L.CreatedDateTime DESC  
		END
		ELSE
		BEGIN 
		--Select 111      
		  SELECT DISTINCT  --Add Distict for Mantis Id:0033687
		      --ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
			  L.AcademicId AS AcademicId,  
			  SA.[StudentId],  
			  L.CreatedDateTime AS ReportDate,  
			  L.[LeaveFromDate] AS FromDate,  
			  L.[LeaveToDate] AS ToDate,  
			  ISNULL(L.LeaveReason,'') as LeaveReason,  
			  --EM.EmployeeName,  
			  SA.Name AS StudentName,
			  SA.Code AS StudentCode,  
			  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
			  ISNULL(L.StatusId,0) AS StatusId,  
			  ISNULL(SM.Title,'Pending') AS StatusName,  
			  ISNULL(L.StatusReason,'') AS  StatusReason,  
			  OM.DisplayTitle AS OrganizationName,  
			  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
			  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
			  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
			  OM.Id AS OrgId,  
			  SA.BatchId AS BatchId, 
			  SA.DivisionId,
			  SA.DivisionName,
			  SA.ClassId,
			  SA.ClassName, 
			  SA.DepartmentId AS DepartmentId,  
			  SA.DepartmentName As DepartmentName
			  --US.Id As UserId
		  FROM   
			  sAttendance.tStudentLeaveRequest L   
			  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
			  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
			  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
			  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
			  --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
			  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
			  -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017   
			  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id  

		  WHERE   
			  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
			  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
			  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			  AND (SA.ClassId=@rClassId OR @rClassId=0)
			  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
			  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
			  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
			  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
			  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
			  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
			  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
			  AND ISNULL(EMP.IsOtherUser,0)=0 
			  AND UO.UserId = @rUserId 
			  AND SA.InchargeEmployeeId = @lUserSourceId
			 -- AND U.UserId = @rUserId     
		  ORDER BY   
			  L.CreatedDateTime DESC        
		END
	END

	IF(@lItemValue = 'Class Teacher Batch')
	BEGIN
		IF(@rUserId=0)
		BEGIN
		   SELECT DISTINCT   
			  --ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
			  L.AcademicId AS AcademicId,  
			  SA.[StudentId],  
			  L.CreatedDateTime AS ReportDate,  
			  L.[LeaveFromDate] AS FromDate,  
			  L.[LeaveToDate] AS ToDate,  
			  ISNULL(L.LeaveReason,'') as LeaveReason,  
			  --EM.EmployeeName,  
			  SA.Name AS StudentName,
			  SA.Code AS StudentCode,  
			  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
			  ISNULL(L.StatusId,0) AS StatusId,  
			  ISNULL(SM.Title,'Pending') AS StatusName,  
			  ISNULL(L.StatusReason,'') AS  StatusReason,  
			  OM.DisplayTitle AS OrganizationName,  
			  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
			  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
			  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
			  OM.Id AS OrgId,  
			  SA.BatchId AS BatchId, 
			  SA.DivisionId,
			  SA.DivisionName,
			  SA.ClassId,
			  SA.ClassName, 
			  SA.DepartmentId AS DepartmentId,  
			  SA.DepartmentName As DepartmentName
			  --US.Id As UserId
		  FROM   
			  sAttendance.tStudentLeaveRequest L   
			  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
			  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
			  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
			  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
			 --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
			  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
			 -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017     
			 INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = SA.DivisionId
		  WHERE   
			  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
			  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
			  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			  AND (SA.ClassId=@rClassId OR @rClassId=0)
			  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
			  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
			  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
			  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
			  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
			  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
			  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
			  AND ISNULL(EMP.IsOtherUser,0)=0 
			  AND DIE.EmployeeId = @lUserSourceId
			  AND DIE.BatchId = @rBatchId
			 --BatchId required only for Class Teacher Batch
			 -- AND U.UserId = @rUserId     
			ORDER BY   
			  L.CreatedDateTime DESC  
		END
	    ELSE
	    BEGIN 		   SELECT  DISTINCT 
				--ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
				L.AcademicId AS AcademicId,  
				SA.[StudentId],  
				L.CreatedDateTime AS ReportDate,  
				L.[LeaveFromDate] AS FromDate,  
				L.[LeaveToDate] AS ToDate,  
				ISNULL(L.LeaveReason,'') as LeaveReason,  
				--EM.EmployeeName,  
				SA.Name AS StudentName,
				SA.Code AS StudentCode,  
				DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
				ISNULL(L.StatusId,0) AS StatusId,  
				ISNULL(SM.Title,'Pending') AS StatusName,  
				ISNULL(L.StatusReason,'') AS  StatusReason,  
				OM.DisplayTitle AS OrganizationName,  
				ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
				CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
				ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
				OM.Id AS OrgId,  
				SA.BatchId AS BatchId, 
				SA.DivisionId,
				SA.DivisionName,
				SA.ClassId,
				SA.ClassName, 
				SA.DepartmentId AS DepartmentId,  
				SA.DepartmentName As DepartmentName
				--US.Id As UserId
			FROM   
				sAttendance.tStudentLeaveRequest L   
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
				LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
				--LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
				LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
				-- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017   
				INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id  
				INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = SA.DivisionId
			WHERE   
				((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
				AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
				AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
				AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
				AND (SA.ClassId=@rClassId OR @rClassId=0)
				AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
				And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
				AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
				AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
				AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
				AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
				--AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
				AND ISNULL(EMP.IsOtherUser,0)=0 
				AND UO.UserId = @rUserId 
				AND DIE.EmployeeId = @lUserSourceId
				AND DIE.BatchId = @rBatchId
				--BatchId required only for Class Teacher Batch
				-- AND U.UserId = @rUserId     
			ORDER BY   
				L.CreatedDateTime DESC        
	    END
	END

	IF(@lItemValue = 'Academic Setup')
	BEGIN
		IF(@rUserId=0)
		BEGIN
			SELECT DISTINCT
				 --ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
				  L.AcademicId AS AcademicId,  
				  SA.[StudentId],  
				  L.CreatedDateTime AS ReportDate,  
				  L.[LeaveFromDate] AS FromDate,  
				  L.[LeaveToDate] AS ToDate,  
				  ISNULL(L.LeaveReason,'') as LeaveReason,  
				  --EM.EmployeeName,  
				  SA.Name AS StudentName,
				  SA.Code AS StudentCode,  
				  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
				  ISNULL(L.StatusId,0) AS StatusId,  
				  ISNULL(SM.Title,'Pending') AS StatusName,  
				  ISNULL(L.StatusReason,'') AS  StatusReason,  
				  OM.DisplayTitle AS OrganizationName,  
				  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
				  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
				  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
				  OM.Id AS OrgId,  
				  SA.BatchId AS BatchId, 
				  SA.DivisionId,
				  SA.DivisionName,
				  SA.ClassId,
				  SA.ClassName, 
				  SA.DepartmentId AS DepartmentId,  
				  SA.DepartmentName As DepartmentName
				  --US.Id As UserId
			  FROM   
				  sAttendance.tStudentLeaveRequest L   
				  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
				  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
				  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
				  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
				 --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
				  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
				 -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017     
				 --INNER JOIN sAcademic.vTeacherSubjectDivision TSD ON SA.ClassId = TSD.ClassId AND SA.DivisionId = TSD.DivisionId

			  WHERE   
				  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
				  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
				  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
				  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
				  AND (SA.ClassId=@rClassId OR @rClassId=0)
				  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
				  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
				  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
				  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
				  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
				  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
				  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
				  AND ISNULL(EMP.IsOtherUser,0)=0 
				  --AND TSD.EmployeeId = @lUserSourceId
				  AND @lUserSourceId IN (Select EmployeeId From sAcademic.vTeacherSubjectDivision WHERE ClassId = SA.ClassId AND DivisionId = SA.DivisionId AND OrgId = SA.OrgId)
				 -- AND U.UserId = @rUserId     
			  ORDER BY   
				  L.CreatedDateTime DESC  
		END
		ELSE
		BEGIN
			SELECT  DISTINCT
			  --ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
			  L.AcademicId AS AcademicId,  
			  SA.[StudentId],  
			  L.CreatedDateTime AS ReportDate,  
			  L.[LeaveFromDate] AS FromDate,  
			  L.[LeaveToDate] AS ToDate,  
			 ISNULL(L.LeaveReason,'') as LeaveReason,  
			  --EM.EmployeeName,  
			  SA.Name AS StudentName,
			  SA.Code AS StudentCode,  
			  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
			  ISNULL(L.StatusId,0) AS StatusId,  
			  ISNULL(SM.Title,'Pending') AS StatusName,  
			  ISNULL(L.StatusReason,'') AS  StatusReason,  
			  OM.DisplayTitle AS OrganizationName,  
			  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
			  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
			  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
			  OM.Id AS OrgId,  
			  SA.BatchId AS BatchId, 
			  SA.DivisionId,
			  SA.DivisionName,
			  SA.ClassId,
			  SA.ClassName, 
			  SA.DepartmentId AS DepartmentId,  
			  SA.DepartmentName As DepartmentName
			  --US.Id As UserId
		  FROM   
			  sAttendance.tStudentLeaveRequest L   
			  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
			  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
			  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
			  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
			  --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
			  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
			  -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017   
			  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id
			  --INNER JOIN sAcademic.vTeacherSubjectDivision TSD ON SA.ClassId = TSD.ClassId AND SA.DivisionId = TSD.DivisionId AND TSD.OrgId = SA.OrgId 

		  WHERE   
			  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
			  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
			  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			  AND (SA.ClassId=@rClassId OR @rClassId=0)
			  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
			  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
			  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
			  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
			  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
			  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
			  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
			  AND ISNULL(EMP.IsOtherUser,0)=0 
			  AND UO.UserId = @rUserId 
			  --AND TSD.EmployeeId = @lUserSourceId
			  AND @lUserSourceId IN (Select EmployeeId From sAcademic.vTeacherSubjectDivision WHERE ClassId = SA.ClassId AND DivisionId = SA.DivisionId AND OrgId = SA.OrgId)
			 -- AND U.UserId = @rUserId     
		  ORDER BY   
			  L.CreatedDateTime DESC        
		END
	END

	IF(@lItemValue = 'User Access')
	BEGIN
		IF(@rUserId=0)
		BEGIN
		 	SELECT  DISTINCT
			  --ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
			  L.AcademicId AS AcademicId,  
			  SA.[StudentId],  
			  L.CreatedDateTime AS ReportDate,  
			  L.[LeaveFromDate] AS FromDate,  
			  L.[LeaveToDate] AS ToDate,  
			  ISNULL(L.LeaveReason,'') as LeaveReason,  
			  --EM.EmployeeName,  
			  SA.Name AS StudentName,
			  SA.Code AS StudentCode,  
			  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
			  ISNULL(L.StatusId,0) AS StatusId,  
			  ISNULL(SM.Title,'Pending') AS StatusName,  
			  ISNULL(L.StatusReason,'') AS  StatusReason,  
			  OM.DisplayTitle AS OrganizationName,  
			  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
			  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
			  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
			  OM.Id AS OrgId,  
			  SA.BatchId AS BatchId, 
			  SA.DivisionId,
			  SA.DivisionName,
			  SA.ClassId,
			  SA.ClassName, 
			  SA.DepartmentId AS DepartmentId,  
			  SA.DepartmentName As DepartmentName
			  --US.Id As UserId
		  FROM   
			  sAttendance.tStudentLeaveRequest L   
			  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
			  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
			  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
			  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
			 --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
			  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
			  INNER JOIN sSecurity.tUserAccess UA ON 
			  (UA.SourceId = CASE WHEN UA.SourceTypeId = 2021 THEN (Select OrgId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2017 THEN (Select DepartmentId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2016 THEN (Select ClassId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2005 THEN (Select DivisionId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2003 THEN (Select StudentId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								END) AND UA.UserId = @rUserId


		  WHERE   
			  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
			  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
			  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			  AND (SA.ClassId=@rClassId OR @rClassId=0)
			  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
			  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
			  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
			  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
			  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
			  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
			  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
			  AND ISNULL(EMP.IsOtherUser,0)=0 
	  
			 -- AND U.UserId = @rUserId     
	  ORDER BY   
		  L.CreatedDateTime DESC  
		END
	ELSE
	BEGIN  
	--CREATE TABLE #tmp
	--(
	--	SourceTypeId int,
	--	SourceId int,
	--	UserId bigint
	--)
	--INSERT INTO #tmp
	--SELECT 
	--SourceTypeId ,SourceId ,UserId 
	--FROM 
	--sSecurity.tUserAccess WHERE UserId = @rUserId

	--Select * from #tmp
	  SELECT  DISTINCT 
	     -- ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
		  L.AcademicId AS AcademicId,  
		  SA.[StudentId],  
		  L.CreatedDateTime AS ReportDate,  
		  L.[LeaveFromDate] AS FromDate,  
		  L.[LeaveToDate] AS ToDate,  
		 ISNULL(L.LeaveReason,'') as LeaveReason,  
		  --EM.EmployeeName,  
		  SA.Name AS StudentName,
		  SA.Code AS StudentCode,  
		  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
		  ISNULL(L.StatusId,0) AS StatusId,  
		  ISNULL(SM.Title,'Pending') AS StatusName,  
		  ISNULL(L.StatusReason,'') AS  StatusReason,  
		  OM.DisplayTitle AS OrganizationName,  
		  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
		  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
		  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
		  OM.Id AS OrgId,  
		  SA.BatchId AS BatchId, 
		  SA.DivisionId,
		  SA.DivisionName,
		  SA.ClassId,
		  SA.ClassName, 
		  SA.DepartmentId AS DepartmentId,  
		  SA.DepartmentName As DepartmentName
	  FROM   
		  sAttendance.tStudentLeaveRequest L   
		  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
		  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
		  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
		  --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
		  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
		  -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017   
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id  
		  --INNER JOIN #tmp tmp ON 
		  --(tmp.SourceId = CASE WHEN tmp.SourceTypeId = 2021 THEN SA.OrgId
				--		       WHEN tmp.SourceTypeId = 2017 THEN SA.DepartmentId
				--			   WHEN tmp.SourceTypeId = 2016 THEN SA.ClassId
				--			   WHEN tmp.SourceTypeId = 2005 THEN SA.DivisionId
				--			   WHEN tmp.SourceTypeId = 2003 THEN SA.StudentId
				--			   END
		  --)AND tmp.UserId = @rUserId

		  INNER JOIN sSecurity.tUserAccess UA ON 
			(UA.SourceId = CASE WHEN UA.SourceTypeId = 2021 THEN (Select OrgId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2017 THEN (Select DepartmentId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2016 THEN (Select ClassId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2005 THEN (Select DivisionId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								WHEN UA.SourceTypeId = 2003 THEN (Select StudentId from sStudent.vStudentAcademic SA1 WHERE SA1.AcademicId = SA.AcademicId)
								END) AND UA.UserId = @rUserId

	  WHERE   
		  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
		  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
		  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		  AND (SA.ClassId=@rClassId OR @rClassId=0)
		  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
		  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
		  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
		  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
		  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
		  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
		  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
		  AND ISNULL(EMP.IsOtherUser,0)=0 
		  AND UO.UserId = @rUserId 
	  
		 -- AND U.UserId = @rUserId     
	  ORDER BY   
		  L.CreatedDateTime DESC    
		  
	 --DROP TABLE #tmp    
	END
	END
END

--old Code
ELSE
BEGIN
	IF(@rUserId=0)
	BEGIN
	 SELECT  DISTINCT
		--ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
		  L.AcademicId AS AcademicId,  
		  SA.[StudentId],  
		  L.CreatedDateTime AS ReportDate,  
		  L.[LeaveFromDate] AS FromDate,  
		  L.[LeaveToDate] AS ToDate,  
		  ISNULL(L.LeaveReason,'') as LeaveReason,  
		  --EM.EmployeeName,  
		  SA.Name AS StudentName,
		  SA.Code AS StudentCode,  
		  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
		  ISNULL(L.StatusId,0) AS StatusId,  
		  ISNULL(SM.Title,'Pending') AS StatusName,  
		  ISNULL(L.StatusReason,'') AS  StatusReason,  
		  OM.DisplayTitle AS OrganizationName,  
		  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
		  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
		  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
		  OM.Id AS OrgId,  
		  SA.BatchId AS BatchId, 
		  SA.DivisionId,
		  SA.DivisionName,
		  SA.ClassId,
		  SA.ClassName, 
		  SA.DepartmentId AS DepartmentId,  
		  SA.DepartmentName As DepartmentName
		  --US.Id As UserId
	  FROM   
		  sAttendance.tStudentLeaveRequest L   
		  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
		  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
		  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
		 --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
		  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
		 -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017     

	  WHERE   
		  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
		  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
		  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		  AND (SA.ClassId=@rClassId OR @rClassId=0)
		  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
		  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
		  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
		  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
		  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
		  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
		  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
		  AND ISNULL(EMP.IsOtherUser,0)=0 	  
		 -- AND U.UserId = @rUserId     
	  ORDER BY   
		  L.CreatedDateTime DESC  
	END
	ELSE
	BEGIN       
	  SELECT  DISTINCT
	  --ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
			L.AcademicId AS AcademicId,  
		  SA.[StudentId],  
		  L.CreatedDateTime AS ReportDate,  
		  L.[LeaveFromDate] AS FromDate,  
		  L.[LeaveToDate] AS ToDate,  
		 ISNULL(L.LeaveReason,'') as LeaveReason,  
		  --EM.EmployeeName,  
		  SA.Name AS StudentName,
		  SA.Code AS StudentCode,  
		  DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
		  ISNULL(L.StatusId,0) AS StatusId,  
		  ISNULL(SM.Title,'Pending') AS StatusName,  
		  ISNULL(L.StatusReason,'') AS  StatusReason,  
		  OM.DisplayTitle AS OrganizationName,  
		  ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
		  CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
		  ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
		  OM.Id AS OrgId,  
		  SA.BatchId AS BatchId, 
		  SA.DivisionId,
		  SA.DivisionName,
		  SA.ClassId,
		  SA.ClassName, 
		  SA.DepartmentId AS DepartmentId,  
		  SA.DepartmentName As DepartmentName
		  --US.Id As UserId
	  FROM   
		  sAttendance.tStudentLeaveRequest L   
		  INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
		  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
		  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
		  --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
		  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
		  -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017   
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id  

	  WHERE   
		  ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		  AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
		  AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
		  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		  AND (SA.ClassId=@rClassId OR @rClassId=0)
		  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
		  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
		  AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
		  AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
		  AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
		  AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
		  --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
		  AND ISNULL(EMP.IsOtherUser,0)=0 
		  AND UO.UserId = @rUserId 
	  
		 -- AND U.UserId = @rUserId     
	  ORDER BY   
		  L.CreatedDateTime DESC        
	END

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


GO

ALTER  PROCEDURE [sStudent].[pStudentSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rBatchId int=0,
	@rUserId bigint =0,
	@rCount int =0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'StudentList')
		BEGIN
			SELECT 
			(SELECT COUNT(*) FROM sStudent.tStudentMaster SM INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId WHERE((SM.OrgId = @rOrgId)OR(@rOrgId=0)) AND ((BM.Id = @rBatchId)OR(@rBatchId=0))) AS TotalStudent,
			(SELECT COUNT(*) FROM sStudent.tStudentMaster SM INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId WHERE((SM.OrgId = @rOrgId)OR(@rOrgId=0)) AND ((BM.Id = @rBatchId)OR(@rBatchId=0)) AND SM.StatusId=1)AS ActiveStudent,
			(SELECT COUNT(*) FROM sStudent.tStudentMaster SM INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId WHERE((SM.OrgId = @rOrgId)OR(@rOrgId=0)) AND ((BM.Id = @rBatchId)OR(@rBatchId=0)) AND SM.StatusId=2)AS InActiveStudent,
			(SELECT COUNT(*) FROM sStudent.tStudentMaster SM INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  WHERE((SM.OrgId = @rOrgId)OR(@rOrgId=0)) AND ((BM.Id = @rBatchId)OR(@rBatchId=0)) AND SM.StatusId=3 ) AS LeftStudent,
			(SELECT COUNT(*) FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId WHERE ((A.BatchId=@rBatchId)OR(@rBatchId=0)) AND ((SM.OrgId = @rOrgId)OR(@rOrgId=0)) AND (ISNULL(SA.AdmissionDate,'') >= BM.FromDate) AND (ISNULL(SA.AdmissionDate,'') <= BM.ToDate) )AS CurrentBatchNewAdmission, 
			(SELECT COUNT(*) FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId WHERE ((A.BatchId=@rBatchId)OR(@rBatchId=0)) AND ((SM.OrgId = @rOrgId)OR(@rOrgId=0)) AND (ISNULL(SA.LeftDate,'') >= BM.FromDate)  AND (ISNULL(SA.LeftDate,'') <= BM.ToDate) AND SM.StatusId=3  )AS CurrentBatchLeftStudent
		END
	ELSE IF(@rType = 'StudentGraph')
		BEGIN
		
			Declare @lOrderIndex smallint=0
			Declare @lBatchId int=0
			Select @lOrderIndex  = OrderIndex from sSetup.tBatchMaster Where Id = @rBatchId AND OrgId = @rOrgId
			Select @lBatchId=Id from sSetup.tBatchMAster Where OrderIndex = @lOrderIndex - 1 AND OrgId = @rOrgId
			
			DECLARE @cols NVARCHAR(MAX),@query  NVARCHAR(MAX),@cols1 NVARCHAR(MAX);
			SET @cols = STUFF((SELECT ',ISNULL([' +  (Title) + '],0)as [' +  (Title)+ ']'
			FROM sSetup.tClassMaster
			WHERE OrgId = @rOrgId ORDER BY OrderIndex 
			FOR XML PATH(''), TYPE
			).value('.', 'NVARCHAR(MAX)') 
			,1,1,'')

			SET @cols1 = STUFF((SELECT ',' +  QUOTENAME(Title)
			FROM sSetup.tClassMaster
			WHERE OrgId = @rOrgId ORDER BY OrderIndex 
			FOR XML PATH(''), TYPE
			).value('.', 'NVARCHAR(MAX)') 
			,1,1,'')
			--print @col1s
			--return
			set @query = 'SELECT BatchName, ' + @cols + ' from 
			(
			SELECT BM.Title AS BatchName,COUNT(*) AS totalCount,T.Class AS Class FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			LEFT JOIN 
			(
			SELECT Id AS ClassId,Title AS Class FROM sSetup.tClassMaster 
			WHERE ((OrgId='+CONVERT(nvarchar(20),@rOrgId)+') OR ('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			)T ON T.ClassId = A.ClassId	
			WHERE((BM.OrgId='+CONVERT(nvarchar(20),@rOrgId)+') OR ('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			AND (BM.Id in ('+CONVERT(nvarchar(20),@rBatchId)+','+CONVERT(nvarchar(20),@lBatchId)+'))
			AND BM.IsObsolete = 0 AND BM.IsHistory = 0 AND SM.StatusId = 1 
			GROUP BY BM.Title,T.Class
			) x
			pivot 
			(
			SUM(totalCount)
			for Class in (' + @cols1 + ')
			) p '
			--print ( @query)			-- Add where condition AND SM.StatusId = 1 for MantisId : 0033474 in @query
			EXECUTE (@query)
		END
	ELSE IF(@rType =  'AllGraph')
		BEGIN
			IF(@rCount = 1)
				BEGIN
					SELECT CASE WHEN SO.GenderId = 1 THEN  'Boy' WHEN SO.GenderId = 2  THEN  'Girl'  ELSE  'Other' END AS Gender,
					COUNT(*) AS GenderCount FROM sStudent.vStudentAcademic SA
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
					WHERE((SA.OrgId = @rOrgId)OR(@rOrgId=0)) AND((SA.BatchId = @rBatchId)OR(@rBatchId=0))
					GROUP BY SO.GenderId 
				END
			ELSE IF(@rCount = 2)
				BEGIN
					SELECT ISNULL(CCM.Title,'NA') AS CastCategory, COUNT(*)  AS GenderCount FROM sStudent.vStudentAcademic SA
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
					LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
					WHERE((SA.OrgId = @rOrgId)OR(@rOrgId=0)) AND((SA.BatchId = @rBatchId)OR(@rBatchId=0))
					GROUP BY CCM.Title
				END
			ELSE IF(@rCount = 3)
				BEGIN
					SELECT ISNULL(HM.Title,'NA') AS CastCategory, COUNT(*)  AS GenderCount FROM sStudent.vStudentAcademic SA
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
					LEFT JOIN sActivity.tHouseMaster HM ON HM.Id = SO.HouseId
					WHERE((SA.OrgId = @rOrgId)OR(@rOrgId=0)) AND((SA.BatchId = @rBatchId)OR(@rBatchId=0))
					GROUP BY HM.Title
				END
			ELSE IF(@rCount = 4)
				BEGIN
					SELECT ISNULL(RM.Title,'NA') AS CastCategory, COUNT(*)  AS GenderCount FROM sStudent.vStudentAcademic SA
					INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
					LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = SO.ReligionId
					WHERE((SA.OrgId = @rOrgId)OR(@rOrgId=0)) AND((SA.BatchId = @rBatchId)OR(@rBatchId=0))
					GROUP BY RM.Title
				END
		END 

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


GO

 
 
ALTER PROCEDURE [sStudent].[pStudentVerificationUpdate]
	 
	@rAdmissionDate date='',
	@rPreviousSchool nvarchar(50)='',
	@rStudentId bigint,
	@rDateOfBirth date,
	@rBirthPlace nvarchar(150),
	@rFamilyCast nvarchar(100),
	@rMotherTongue nvarchar(100),
	@rUIDNumber nvarchar(50),
	@rAdhaarNumber nvarchar(20),
	@rFatherContactNo nvarchar(10),
	@rMotherName nvarchar(50),
	@rMotherContactNo nvarchar(10),
	@rStudentContactNo nvarchar(10),
	@rBankBranch nvarchar(100),
	@rBankAccountNumber nvarchar(20),
	@rBankName nvarchar(100),
	@rBankIFSCCode nvarchar(20),
	@rGenderId int,
	@rClassId int=0,
	@rCastCategoryId int,
	@rNationalityId int,
	@rPresentStreetOne nvarchar(300),
	@rPresentStreetTwo nvarchar(300),
	@rPresentStreetThree nvarchar(300),
	@rReligionId int,
	@rFirstName nvarchar(50),
	@rMiddleName nvarchar(50),
	@rLastName nvarchar(50),
	@rStudentEmail nvarchar(50),
	@rAdmissionStandardId int,
	@rFatherName nvarchar(50),
	@rBirthState nvarchar(100),
	@rBirthCountry nvarchar(100),
	@rBirthTaluka nvarchar(100),
	@rBirthDistrict nvarchar(100),
	@rBankAccountHolderName nvarchar (200) = '',
	@rMarriageAnniversaryDate date,
	@rBirthdateInWord nvarchar(150) = '' --mantisid - 0033546
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 

		IF NOT EXISTS (Select 1 From sStudent.tStudentAdmission Where StudentId=@rStudentId)
		BEGIN
			INSERT INTO sStudent.tStudentAdmission(StudentId) VALUES(@rStudentId)
		END
		
		IF NOT EXISTS (Select 1 From sStudent.tStudentOther Where StudentId=@rStudentId)
		BEGIN
			INSERT INTO sStudent.tStudentOther(StudentId) VALUES(@rStudentId)
		END
		
		IF NOT EXISTS (Select 1 From sStudent.tStudentFamily Where StudentId=@rStudentId)
		BEGIN
			INSERT INTO sStudent.tStudentFamily(StudentId,CreatedUserId,CreatedDateTime) VALUES(@rStudentId,0,sCommon.fGetDate())
		END
		
		IF NOT EXISTS (Select 1 From sStudent.tStudentCommunication Where StudentId=@rStudentId)
		BEGIN
			INSERT INTO sStudent.tStudentCommunication(StudentId,CreatedUserId,CreatedDateTime) VALUES(@rStudentId,0,sCommon.fGetDate())
		END
		
		IF NOT EXISTS (Select 1 From sStudent.tStudentAdditional Where StudentId=@rStudentId)
		BEGIN
			INSERT INTO sStudent.tStudentAdditional(StudentId) VALUES(@rStudentId)
		END
		

	    IF (@rFirstName IS NOT NULL AND @rFirstName != '')
	    BEGIN
		update sStudent.tStudentMaster Set FirstName=@rFirstName Where Id=@rStudentId
		END
		
		IF @rMiddleName IS NOT NULL AND @rMiddleName != ''
		BEGIN
		update sStudent.tStudentMaster Set MiddleName=@rMiddleName Where Id=@rStudentId
		END
		
		IF @rLastName IS NOT NULL AND @rLastName != ''
		BEGIN
		update sStudent.tStudentMaster Set LastName=@rLastName Where Id=@rStudentId
		END
		
		IF @rAdmissionDate IS NOT NULL AND @rAdmissionDate != ''
		BEGIN
		Update sStudent.tStudentAdmission Set AdmissionDate=@rAdmissionDate  Where StudentId =@rStudentId
		END
		
		IF @rPreviousSchool IS NOT NULL AND @rPreviousSchool != ''
		BEGIN
		Update sStudent.tStudentAdmission Set PreviousSchool=@rPreviousSchool  Where StudentId =@rStudentId
		END
		
		IF @rAdmissionStandardId IS NOT NULL AND @rAdmissionStandardId != ''
		BEGIN
		Update sStudent.tStudentAdmission Set AdmissionStandardId=@rAdmissionStandardId Where StudentId =@rStudentId
		END
		
		IF @rDateOfBirth IS NOT NULL AND @rDateOfBirth != ''
		BEGIN
		Update sStudent.tStudentOther Set DateOfBirth=@rDateOfBirth,BirthDateInWord = @rBirthdateInWord Where StudentId=@rStudentId
		END
		--ADD BirthDateInWord in Update due to matisid - 0033546
		IF @rBirthPlace IS NOT NULL AND @rBirthPlace != ''
		BEGIN
		Update sStudent.tStudentOther Set BirthPlace=@rBirthPlace Where StudentId=@rStudentId
		END
		
		IF @rBirthTaluka IS NOT NULL AND @rBirthTaluka != ''
		BEGIN
		Update sStudent.tStudentOther Set BirthTaluka=@rBirthTaluka Where StudentId=@rStudentId
		END
		
		IF @rBirthDistrict IS NOT NULL AND @rBirthDistrict != ''
		BEGIN
		Update sStudent.tStudentOther Set BirthDistrict=@rBirthDistrict Where StudentId=@rStudentId
		END
		
		IF @rFamilyCast IS NOT NULL AND @rFamilyCast != ''
		BEGIN
		Update sStudent.tStudentOther Set FamilyCast=@rFamilyCast Where StudentId=@rStudentId
		END
		 
		IF @rMotherTongue IS NOT NULL AND @rMotherTongue != ''
		BEGIN
		Update sStudent.tStudentOther Set MotherTongue=@rMotherTongue Where StudentId=@rStudentId
		END
		
		IF @rUIDNumber IS NOT NULL AND @rUIDNumber != ''
		BEGIN
		Update sStudent.tStudentOther Set UIDNumber=@rUIDNumber Where StudentId=@rStudentId
		END
		
		IF @rAdhaarNumber IS NOT NULL AND @rAdhaarNumber != ''
		BEGIN
		Update sStudent.tStudentOther Set AdhaarNumber=@rAdhaarNumber Where StudentId=@rStudentId
		END
		
		IF @rGenderId IS NOT NULL AND @rGenderId != ''
		BEGIN
		Update sStudent.tStudentOther Set GenderId=@rGenderId Where StudentId=@rStudentId
		END
		
		IF @rCastCategoryId IS NOT NULL AND @rCastCategoryId != ''
		BEGIN
		Update sStudent.tStudentOther Set CastCategoryId =@rCastCategoryId Where StudentId=@rStudentId
		END
		
		IF @rNationalityId IS NOT NULL AND @rNationalityId != ''
		BEGIN
		Update sStudent.tStudentOther Set NationalityId=@rNationalityId Where StudentId=@rStudentId
		END
		
		IF @rReligionId IS NOT NULL AND @rReligionId != ''
		BEGIN
		Update sStudent.tStudentOther Set ReligionId=@rReligionId Where StudentId=@rStudentId
		END
		
		IF @rBirthState IS NOT NULL AND @rBirthState != ''
		BEGIN
		Update sStudent.tStudentOther Set BirthState = @rBirthState Where StudentId=@rStudentId
		END
		
		IF @rBirthCountry IS NOT NULL AND @rBirthCountry != ''
		BEGIN
		Update sStudent.tStudentOther Set BirthCountry =@rBirthCountry Where StudentId=@rStudentId
		END
		
		IF @rFatherContactNo IS NOT NULL AND @rFatherContactNo != ''
		BEGIN
		Update sStudent.tStudentFamily Set FatherContactNo =@rFatherContactNo Where StudentId=@rStudentId
		END
		
		IF @rMotherName IS NOT NULL AND @rMotherName != ''
		BEGIN
		Update sStudent.tStudentFamily Set MotherName =@rMotherName Where StudentId=@rStudentId
		END
		
		IF @rMotherContactNo IS NOT NULL AND @rMotherContactNo != ''
		BEGIN
		Update sStudent.tStudentFamily Set MotherContactNo =@rMotherContactNo Where StudentId=@rStudentId
		END
		
		IF @rFatherName IS NOT NULL AND @rFatherName != ''
		BEGIN
		Update sStudent.tStudentFamily Set FatherName =@rFatherName Where StudentId=@rStudentId
		END
		
		IF @rStudentContactNo IS NOT NULL AND @rStudentContactNo != ''
		BEGIN
		Update sStudent.tStudentCommunication Set StudentContactNo =@rStudentContactNo Where StudentId=@rStudentId
		END
		
		IF @rPresentStreetOne IS NOT NULL AND @rPresentStreetOne != ''
		BEGIN
		Update sStudent.tStudentCommunication Set PresentStreetOne =@rPresentStreetOne Where StudentId=@rStudentId
		END
		
		IF @rPresentStreetTwo IS NOT NULL AND @rPresentStreetTwo != ''
		BEGIN
		Update sStudent.tStudentCommunication Set PresentStreetTwo =@rPresentStreetTwo Where StudentId=@rStudentId
		END
		
		IF @rPresentStreetThree IS NOT NULL AND @rPresentStreetThree != ''
		BEGIN
		Update sStudent.tStudentCommunication Set PresentStreetThree =@rPresentStreetThree Where StudentId=@rStudentId
		END
		
		IF @rStudentEmail IS NOT NULL AND @rStudentEmail != ''
		BEGIN
		Update sStudent.tStudentCommunication Set StudentEmail =@rStudentEmail Where StudentId=@rStudentId
		END
		
		IF @rBankBranch IS NOT NULL AND @rBankBranch != ''
		BEGIN
		Update sStudent.tStudentAdditional Set BankBranch =@rBankBranch Where StudentId=@rStudentId
		END
		
		IF (@rBankAccountNumber IS NOT NULL AND @rBankAccountNumber != '')
		BEGIN
		Update sStudent.tStudentAdditional Set BankAccountNumber =@rBankAccountNumber Where StudentId=@rStudentId
		END
		
		IF (@rBankName IS NOT NULL AND @rBankName != '')
		BEGIN
		Update sStudent.tStudentAdditional Set BankName =@rBankName Where StudentId=@rStudentId
		END
		
		IF (@rBankIFSCCode IS NOT NULL AND @rBankIFSCCode != '')
		BEGIN
		Update sStudent.tStudentAdditional Set BankIFSCCode =@rBankIFSCCode Where StudentId=@rStudentId
		END

		IF (@rBankAccountHolderName IS NOT NULL AND @rBankAccountHolderName != '')
		BEGIN
		Update sStudent.tStudentAdditional Set BankAccountHolderName =@rBankAccountHolderName Where StudentId=@rStudentId
		END

		/************Change for mantis : 29443************/
		IF (@rMarriageAnniversaryDate IS NOT NULL AND @rMarriageAnniversaryDate != '')
		BEGIN
		Update sStudent.tstudentfamily Set MarriageAnniversaryDate =@rMarriageAnniversaryDate Where StudentId=@rStudentId
		END
		
END
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
			
			
  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 [sTimetable].[pWebGetTimeTableBySchemaId]...';


GO
ALTER PROCEDURE [sTimetable].[pWebGetTimeTableBySchemaId] --991100006,0,0,0,0,0,1
    @rSchemaId bigint,
	@rDivisionId BIGINT,
	@rDayId int,
    @rOrgId bigint ,
    @rClassId bigint,
    @rFromFilter int ,
    @rToFilter int 
AS
BEGIN
    SET NOCOUNT ON;
    sELECT OM.ID AS OrganizationId,
        OM.Title AS OrganizationTitle,
        CM.ID AS ClassId,
        Cm.Title AS ClassTitle,
        TST.DivisionId,
        TST.EmployeeId,
        TST.SubjectId,
        TST.DayId,
        TST.LectureNumber,
        --TE.Title AS TeacherTitle,
        --SU.Title AS SubjectTitle,
        TST.Id 
FROM STIMETABLE.tTempSTimeTable TST
INNER JOIN sSetup.tDivisionMaster DM on TST.DivisionId=DM.Id
Inner Join sSetup.tClassMaster CM ON DM.ClassId=CM.Id
Inner Join sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId
Inner Join sTimetable.tTimeTableSchema TSC ON TSC.Id=tst.TimeTableSchemaId
iNNER Join sTimetable.tAssignOrg AO ON AO.TimeTableSchemaId=TSC.Id
where TSC.Id=@rSchemaId
AND (OM.Id = @rOrgId OR (@rOrgId = 0 or isnull(@rOrgId,0) = 0))
AND (DM.ClassId = @rClassId OR (@rClassId = 0 or isnull(@rClassId,0) = 0))
AND (DM.Id = @rDivisionId OR (@rDivisionId = 0 or isnull(@rDivisionId,0) = 0))
AND (TST.DayId = @rDayId OR (@rDayId = 0 or isnull(@rDayId,0) = 0))
AND (TST.LectureNumber >=@rFromFilter OR (@rFromFilter = 0 or isnull(@rFromFilter,0) = 0))
AND (TST.LectureNumber <=@rToFilter OR (@rToFilter = 0 or isnull(@rToFilter,0) = 0))
GROUP BY 
OM.ID, OM.Title, CM.ID, Cm.Title, TST.DivisionId, TST.EmployeeId, TST.SubjectId, 
TST.DayId, TST.LectureNumber, TST.Id
ORDER BY 
Om.Id,TST.DayId
END
GO
PRINT N'Creating Procedure [sPortal].[pQueryAdd]...';


GO
CREATE PROCEDURE [sPortal].[pQueryAdd]
	 
	@rOrgGroupId smallint,
	@rOrgGroupBatchId int,
	@rQueryCategoryId int,
	@rId AS bigint,
	@rTitle nvarchar(100),
	@rRemark nvarchar(1000),
	@rIsUserView bit,
	@rIsAssigneeView bit,
	@rStatusId smallint,
	@rCreatedUserId bigint,
	@rCreatedDateTime datetime,
	@rSubjectId int=0,
	@rAssignedToEmployeeId bigint=0,
	@rAssignedToRemark nvarchar(500)='',
	@rIsOfflineEntry bit=0,
	@rFromSourceTypeId smallInt=0,
	@rFromSourceId bigint=0,
	@rTargetResolutionDate datetime=null    
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		IF(@rId = 0)
BEGIN
DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tQuery', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	DECLARE @lNumber int=0
	SELECT @lNumber=ISNULL(MAX(Number),0)+1 FROM sCommunication.tQuery WHERE OrgGroupBatchId = @rOrgGroupBatchId
	
	
	INSERT INTO sCommunication.tQuery
		(
			OrgGroupId,
			OrgGroupBatchId,
			QueryCategoryId,
			Id,
			Title,
			Number,
			Remark,
			IsUserView,
			IsAssigneeView,
			StatusId,
			CreatedUserId,
			CreatedDateTime,
			SubjectId,
			AssignedToEmployeeId,
			AssignedToRemark,
			IsOfflineEntry,
			FromSourceTypeId,
			FromSourceId,
			TargetResolutionDate
		)
	VALUES
		(
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rQueryCategoryId,
			@lNextNumber,
			@rTitle,
			@lNumber,
			@rRemark,
			@rIsUserView,
			@rIsAssigneeView,
			@rStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSubjectId,
			@rAssignedToEmployeeId,
			@rAssignedToRemark,
			@rIsOfflineEntry,
			@rFromSourceTypeId,
			@rFromSourceId,
			@rTargetResolutionDate
		)
		--select @lNextNumber,1 as result
		select @lNextNumber,@lNextNumber as result
END
ELSE
BEGIN
		UPDATE sCommunication.tQuery 
		SET IsUserView = @rIsUserView,
		IsAssigneeView=@rIsAssigneeView,
		AssignedToEmployeeId=@rAssignedToEmployeeId,
		AssignedToRemark=@rAssignedToRemark,
		IsOfflineEntry=@rIsOfflineEntry,
		FromSourceTypeId=@rFromSourceTypeId,
		FromSourceId=@rFromSourceId,
		TargetResolutionDate=@rTargetResolutionDate,
		Remark=@rRemark
		
		 WHERE Id = @rId
		select 0,11 as result
END
	
	COMMIT TRANSACTION
	
END TRY

	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
END
GO
PRINT N'Creating Procedure [sPortal].[pClassDropdownList]...';


GO

CREATE PROCEDURE [sPortal].[pClassDropdownList]
	 @rBatchId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT ClassId , ClassName , OrderIndex FROM  
( SELECT CAST(sSetup.vBatchClass.ClassId AS NVARCHAR(25)) AS ClassId , 
CAST(sSetup.vBatchClass.ClassName AS NVARCHAR(300)) AS ClassName , 
CAST(sSetup.vBatchClass.OrderIndex AS NVARCHAR(300)) AS OrderIndex 
FROM sSetup.vBatchClass WHERE ClassId = 0  UNION SELECT DISTINCT 
CAST(sSetup.vBatchClass.ClassId AS NVARCHAR(25)) AS ClassId , 
CAST(sSetup.vBatchClass.ClassName AS NVARCHAR(300)) AS ClassName , 
CAST(sSetup.vBatchClass.OrderIndex AS NVARCHAR(300)) AS OrderIndex 
FROM sSetup.vBatchClass WHERE 1 = 1  AND  IsObsolete = 0  AND BatchId=@rBatchId )  AS NewTable  ORDER BY CAST(OrderIndex AS INT ) ASC 
 
END
GO
PRINT N'Creating Procedure [sPortal].[pDepositHeadMasterDropDownLists]...';


GO

CREATE PROC [sPortal].[pDepositHeadMasterDropDownLists]
@rOrgGroupId smallint


AS
BEGIN
	SELECT Id, Title FROM sFee.tDepositHeadMaster WHERE IsObsolete = 0 AND OrgGroupId =9911
   
END
GO
PRINT N'Creating Procedure [sPortal].[pFeeBatchDropDownLists]...';


GO


CREATE PROC [sPortal].[pFeeBatchDropDownLists]
@rId int

AS
BEGIN
	select Id , Title 
	from sSetup.tBatchMaster where IsObsolete = 0 
	AND IsHistory= 0
   and OrgId =@rId
END
GO
PRINT N'Creating Procedure [sPortal].[pGetLessonPlan]...';


GO

CREATE PROCEDURE [sPortal].[pGetLessonPlan]

	  @rStudentId BIGINT
	 ,@rBatchId INT
	 ,@rOrgId INT
	 ,@rFromDate DATETIME = ''
	 ,@rToDate DATETIME = ''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	DECLARE @lTopicId NVARCHAR(MAX)
	
		SELECT  @lTopicId = STUFF((SELECT DISTINCT ',' + CONVERT(NVARCHAR(MAX), ISNULL( TL.TopicId,0))
	           FROM sAcademic.tLessonPlan TL
			   INNER JOIN sStudent.tAcademic TA ON TA.BatchId = TL.BatchId AND TA.DivisionId = TL.DivisionId 
		WHERE TL.BatchId = @rBatchId AND TA.StudentId = @rStudentId  
	           FOR XML PATH('')), 1, 1, '')
		FROM sAcademic.tLessonPlan TL1
		ORDER BY TL1.TopicId


	SELECT DISTINCT 
			 TM.SubjectId
			,SM.Title AS SubjectName
		FROM  sAcademic.tLessonPlan LP 
		INNER JOIN sAcademic.tTopicMaster TM ON TM.Id = LP.TopicId  
		INNER JOIN  sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId  
		WHERE  LP.TopicId IN (SELECT item FROM sCommon.fnSplit(@lTopicId,','))
		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,'')=''))
END
GO
PRINT N'Creating Procedure [sPortal].[pStaffDropdownList]...';


GO

CREATE PROCEDURE [sPortal].[pStaffDropdownList]
	 
	 @rOrgId int
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
SELECT Id, Title FROM sSetup.tDepartmentMaster WHERE IsObsolete = 0 AND OrgId =  @rOrgId

SELECT Id, Title FROM sHrm.tEmployeeGroupMaster WHERE IsObsolete = 0  

 
 END
GO
PRINT N'Creating Procedure [sPortal].[pBookDropdownListet]...';


GO

CREATE PROCEDURE [sPortal].[pBookDropdownListet]
	 
	 @rOrgGroupId int,
	 @rOrgId smallint
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
 SELECT Id,Title 
 FROM sLibrary.tResourceTypeMaster ORDER BY Title


 SELECT Id,Title 
 FROM sLibrary.tLibraryMaster LM 
 INNER JOIN sLibrary.tAssignOrganization AO ON AO.LibraryId=LM.Id 
  WHERE LM.IsObsolete = 0 AND OrgGroupId=@rOrgGroupId AND AO.OrgId = @rOrgId ORDER BY Title

 
 END
GO
PRINT N'Creating Procedure [sCommunication].[pQueryListGetNew]...';


GO
CREATE PROCEDURE [sCommunication].[pQueryListGetNew]
	 @rQueryCategoryId int = 0,
	 @rOrgGroupBatchId int,
	 @rOrgGroupId int=0,
	 @rId bigint,
	 @rCreatedUserId bigint=0,
	 @rSyncedQueryId bigint = 0,
	 @rStatusId int = 0,
	 @rCreatedFromDate date=NULL,
	 @rCreatedToDate date=NULL, 
	 @rFromResolutionDate date=NULL,
	 @rToResolutionDate date=NULL,
	 @rFromSourceTypeId smallint=0,  
	 @rTitle nvarchar(100)='',  
	 @rNumber smallint=0,
	 @rQueryStatus varchar(25)=NULL ,
	 @rAssignedToEmployeeId bigint=0,
	 @rSourceId bigint=0,
	 @FromPage varchar(50)='',
	 @rAssignedToId smallint = 0,
	 @rUserSourceTypeId int= 0 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	  BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  END

	  DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint

	  IF @rUserSourceTypeId   = 95 -- For Employee Login
	  BEGIN
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
				 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rSourceId


		SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(U.SourceTypeId,0) AS FromSourceTypeId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId 
			   AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT DM.Title  FROM [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId)
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT DM.Title FROM sHrm.tEmployeeJobDetail EJD
											  INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
											  WHERE EmployeeId=QM.FromSourceId)
				ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT U.DisplayTitle )
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT U.DisplayTitle)
			   ELSE U.DisplayTitle
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate  ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
		INNER JOIN 
				(SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
				 WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
				(QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
				(QCS.SourceTypeId = 95 AND QCS.SourceId =@lEmployeeId )) AND ((QCS.AssigneeToId=3) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0)))
				 ) D
				ON D.QueryCategoryId= QCM.Id
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)<=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)<=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		--AND ((ISNULL(VQCM.AssignedToId,1) <> @rAssignedToId) OR (@rAssignedToId = 0))
		AND QCM.AssignedToId IN (1,3) 
        ORDER BY QM.CreatedDateTime DESC

	  END

	  ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
	  BEGIN
		
		SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId
		FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM	ON A.BatchId = BM.Id 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		WHERE StudentId = @rSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId

		SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			--VQCM.OrgId As OrgId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(U.SourceTypeId,0) AS FromSourceTypeId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=U.SourceId)
			   WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=U.SourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT DM.Title FROM [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=U.SourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId)
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT DM.Title FROM sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=U.SourceId)	
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT U.DisplayTitle)
               WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT U.DisplayTitle)
			   ELSE '' END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate  ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
		FROM sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
		INNER JOIN (SELECT QCS.QueryCategoryId FROM sCommunication.tQueryCategoryScope QCS
            WHERE (((QCS.SourceTypeId = 2021 AND QCS.SourceId =@lOrgId) OR
            (QCS.SourceTypeId = 2017 AND QCS.SourceId =@lDepartmentId) OR
            (QCS.SourceTypeId = 2016 AND QCS.SourceId =@lClassId) OR
            (QCS.SourceTypeId = 2005 AND QCS.SourceId =@lDivisionId) OR
            (QCS.SourceTypeId = 2003 AND QCS.SourceId =@lStudentId) OR
            (QCS.SourceTypeId = 2001 AND QCS.SourceId =@lAcademicId) )
            )AND ((QCS.AssigneeToId=2) OR (QCS.AssigneeToId IS NULL) OR (ISNULL(QCS.AssigneeToId,0)=0))) D
			ON	D.QueryCategoryId= QCM.Id
	
	WHERE ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)<=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)<=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		AND QCM.AssignedToId IN (1,2) 
        ORDER BY QM.CreatedDateTime DESC

	  END

	  ELSE --For Other Login
	  BEGIN
		SELECT 
		QM.Id AS QueryId,
		QCM.Id AS QueryCategoryId,
		ISNULL(QCM.Title,'') AS QueryCategoryMaster,
		QM.Title,
		QM.Remark,
		QM.CreatedDateTime,
		QM.StatusId,
		ISNULL(sm.Title,'') AS StatusMaster,
		QM.IsAssigneeView,
		QM.IsUserView,
		QM.CreatedUserId AS QueryCreatedUserId,
		ISNULL(QM.SubjectId,0) AS SubjectId,
		ISNULL(SubM.Title,'') AS SubjectName,
		ISNULL(QM.Number,0) AS Number,
		ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
		ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
		ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
		ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
		CASE 
			WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			ELSE ''
		END AS FromSourceId,
		CASE 
			WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT  DM.Title FROM [sStudent].[vStudentAcademic] A 
			                                                INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId)
            WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT DM.Title FROM  sHrm.tEmployeeJobDetail EJD
														INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                            WHERE EmployeeId=QM.FromSourceId)
			ELSE ''
		END AS Code,
		CASE 
			WHEN ISNULL(U.SourceTypeId,0) = 2003 THEN (SELECT U.DisplayTitle)
            WHEN ISNULL(U.SourceTypeId,0) = 95 THEN (SELECT U.DisplayTitle)
			ELSE U.DisplayTitle
		END AS Name,
		ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate  ,
		(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName			  
			
	FROM sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
	
	WHERE ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)<=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)<=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((QCM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
        ORDER BY QM.CreatedDateTime DESC
	END        
END
GO
PRINT N'Creating Procedure [sFee].[pDeletedRecieptFeeProcessGenerate]...';


GO
CREATE PROCEDURE [sFee].[pDeletedRecieptFeeProcessGenerate]
		@rOrgId int,
		@rBatchId int,
	    @rAcademicId bigint,
		@rReceiptId bigint,
		@rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		  SELECT ROW_NUMBER() OVER (ORDER BY FS.Id) as RowNumberFeeSetup,FS.Id AS FeeSetupId,PaidAmount AS PaidAmount,ToPayAmount AS PendingAmount 
		  INTO  #temptFeeSetup 
		  FROM [sFee].[tFeeAllocationStudent] FAS
		  INNER JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId 
		  INNER JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId 
		  AND FS.ClassId = A.ClassId
		  WHERE FAS.AcademicId = @rAcademicId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId

		  DECLARE @rowcountFeesetup BIGINT=0
		  SELECT @rowcountFeesetup = COUNT(RowNumberFeeSetup) FROM #temptFeeSetup

		  WHILE (@rowcountFeesetup!=0)
		  BEGIN	
				DECLARE @FeeSetupId BIGINT=0
				DECLARE @PaidAmount DECIMAL(12,2) = 0.00
				DECLARE @PendingAmount DECIMAL(12,2) = 0.00
				DECLARE @ReceiptPaidAmount DECIMAL(12,2) = 0.00

				SELECT @FeeSetupId=FeeSetupId,@PaidAmount=PaidAmount,@PendingAmount=PendingAmount FROM #temptFeeSetup WHERE RowNumberFeeSetup=@rowcountFeesetup

				SELECT @ReceiptPaidAmount = Amount FROM sFee.tReceiptDetail RD INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId WHERE ReceiptId = @rReceiptId AND FeeSetupId = @FeeSetupId AND R.SourceId = @rAcademicId

				SET @PaidAmount = @PaidAmount - @ReceiptPaidAmount
				SET @PendingAmount = @PendingAmount + @ReceiptPaidAmount

				UPDATE [sFee].[tFeeAllocationStudent] 
				SET 
					ToPayAmount = @PendingAmount,
					PaidAmount = @PaidAmount,
					UpdatedUserId = @rCreatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				WHERE 
					AcademicId = @rAcademicId
					AND FeeSetupId = @FeeSetupId

				SET @rowcountFeesetup=@rowcountFeesetup-1
		  END

		  DROP TABLE #temptFeeSetup
	
END
GO
PRINT N'Creating Procedure [sFee].[pRptMultiFeeReceiptDetailsGet]...';


GO

CREATE PROCEDURE [sFee].[pRptMultiFeeReceiptDetailsGet]
						
			@rReportId int=0,
			@rReceiptIds nvarchar(max) = '',
			@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 @lReceiptId bigint
CREATE TABLE #tmp
(
	Id int IDENTITY,
	ReceiptId bigint
)

INSERT INTO #tmp
SELECT cast(item as nvarchar(500)) FROM  sCommon.fnsplit(@rReceiptIds,',')
	
DECLARE @lCountReceiptId int,@lId int

SELECT @lCountReceiptId=COUNT(Id) FROM #tmp
SELECT Top 1 @lId=Id FROM #tmp
	
	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


	CREATE TABLE #ReceiptDetail
	(
	  	ReceiptId bigint,
		ReceiptNumber int,
		ReceiptDate date,			
		AcademicId bigint,
		Name nvarchar(500),
		Code nvarchar(500),
		RollNo int,
		ClassId int,
		DivisionId int,
		ClassName nvarchar(500),
		DivisionName nvarchar(500),
		ClassDivision nvarchar(500),
		FeeHeadId int,
		FeeHead nvarchar(400),
		FeeId int,
		FeeName nvarchar(300),
		PaidAmount decimal(12,2),
		PayTypeId int,
		PayType nvarchar(500),			
		ChequeNo nvarchar(500),
		BankName nvarchar(500),
		Address1 nvarchar(max),
		Address2 nvarchar(max),
		FullTitle nvarchar(500),
		TotalReceiptAmount decimal(12,2),
		ReceiptAmount decimal(12,2),					
		ReceiptAmountInWords nvarchar(1000),			
		DiscountAmount decimal(12,2),
		Remark nvarchar(max),
		UserName nvarchar(500),
		OrgLogo varbinary(max),
		Remark1 nvarchar(max),
		Remark2 nvarchar(max),			 
		IsOnPrePrinted bit,
		IsSupressLogo bit,
		IsDisplaySchoolName bit,
		ReportId int,
		OrganizationName nvarchar(500),
		MonthDetail nvarchar(200),    		 	
		FeeDuration nvarchar(500),			
		DepartmentName nvarchar(500),
		FeeOrderIndex int,
		FeeHeadOrderIndex int,
		IsCancelReceipt bit,
		CurrencyCode nvarchar(200),
		CurrencyTitle nvarchar(200),
		Batch nvarchar(200),
		ChequeDate Date,
		IsMonthDetailOnly bit,
	    IsFeeInvoiceHeadwise bit,
	    GroupTitle nvarchar(200),
	    IsSuppressFeeDetail bit,
	    CollectionGroupName nvarchar(500),
	    InvoiceNumber int,
	    SUID nvarchar(400),
	    HeaderDisplayId int,
	    ReceiptBookHeader varbinary(max),
	    ServiceTaxPercentage decimal(6,2),
	    AmountAfterDiscount decimal(12,2),
	    CGSTPercentage decimal(5,2),
	    SGSTPercentage decimal(5,2),
	    CGSTAmount decimal(12,2),
	    SGSTAmount decimal(12,2),
		GSTINNo nvarchar(50),
	    HSNSACCode nvarchar(15),
	    ItemValue nvarchar(200),
	    FatherName nvarchar(200),
	    MotherName nvarchar(200),
	    ExemptionAmount decimal(12,2),
		ExemptionRemark nvarchar(max),
		EmployeeSign varbinary(max),
		PresentCity nvarchar(50),
		PresentAdress nvarchar(2000),
		ParentContactNo nvarchar(50),			
		IsDisplayPendingFeeAmount bit,
		PendingFeeAmount decimal(12,2),
		FirstName nvarchar(200),
		LastName nvarchar(200),
		FeeAmount decimal(12,2),
		ExemptionAmountSum decimal(12,0),
		TransportBusRoute nvarchar(max),
		BankAccountNumber nvarchar(50),
		FeeHeadNumber int,
		FeeNumber int,
		DigitalSignature varbinary(max),
		CancelStatusRemark nvarchar(max),
		FeeSetupAmount decimal(12,2),
		CreatedDateTime datetime,
		PaymentTransactionId bigint,
		MiddleName nvarchar(200),
		CreatedTime datetime,
		TotalPayableAmount decimal(12,2),
		OrgGroupTitle nvarchar(400),
		NextInstallmentName nvarchar(200), 
		House nvarchar(200),	
		NextInstallmentStartDate date, 
		NextInstallmentEndDate date,
		NextInstallmentAmount decimal(12,2),  
		FeeActualAmount decimal(12,2),	
		StudentContactNo nvarchar(100)
	)

WHILE @lId <= @lCountReceiptId
	BEGIN

	SELECT @lReceiptId = ReceiptId FROM #tmp WHERE Id = @lId
	
	
	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 = @lReceiptId

		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

	INSERT INTO #ReceiptDetail
	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,
			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 = @lReceiptId
					--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,			
			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
 	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, @lReceiptId)) 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
	WHERE 
			((FR.Id=@lReceiptId) OR (@lReceiptId = 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 
	

	SET @lId=@lId+1
	END


	Select * from #ReceiptDetail
	DROP TABLE #tmp
	DROP TABLE #ReceiptDetail
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,
--''	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

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


GO
ALTER PROCEDURE [sFee].[pFeeReceiptImportValidate]
	
	@rReceiptNumber int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rReceiptBookId int,
	@rSourceId bigint,
	@rReceiptDetailXml [nvarchar](max),
	@rChequeNoValidate nvarchar(40) = ''  --Mantis - 0030695

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN

	DECLARE @lValidatioCode TABLE(Id int identity, Result nvarchar(10))

	SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId
	
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
		BEGIN
			INSERT @lValidatioCode SELECT ('-101')
		END
	END
	--Mantis Start - 0030695
	 DECLARE @lConfigValue1 nvarchar(50)=''
	 SELECT @lConfigValue1 = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 543 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	If(@rChequeNoValidate <> '' AND @lConfigValue1 = 'True')
	BEGIN
		IF EXISTS(SELECT 1 FROM SFee.tReceipt where ChequeNo = @rChequeNoValidate  AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
		BEGIN
			 INSERT @lValidatioCode SELECT ('-103')
		END
	END
	--Mantis End - 0030695
	EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml, 0, 0, @rReceiptBookId, @rIsCreated = @lIsCreated OUTPUT
 	IF(@lIsCreated = 1)
	BEGIN
		INSERT @lValidatioCode SELECT ('-102')
	END
	IF(@lIsCreated = -1) -- For Mantis 0032370 by Foram
 	BEGIN
		INSERT @lValidatioCode SELECT ('-502')
	END
	
	EXEC sp_xml_removedocument @loDoc
	
	SELECT * FROM @lValidatioCode 
END
GO
PRINT N'Altering Procedure [sFee].[pFeeReceiptRemove]...';


GO
ALTER PROCEDURE [sFee].[pFeeReceiptRemove]
	 @rReceiptId bigint,
	 @rIsDelete bit,
	 @rCancelRemark nvarchar(300)='',
	 @rUserId bigint=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY
	
BEGIN TRANSACTION	

IF EXISTS (SELECT 1 FROM sFee.tReceipt WHERE Id = @rReceiptId AND IsObsolete = 0)
BEGIN
		DECLARE  @lFeeSetupId int,@rCharge decimal(12,2)=0,
		@lSourceId bigint,@lSourceTypeId int 
		
		SELECT  @lFeeSetupId = FS.ID,@rCharge = RD.Amount,
		@lSourceId = R.SourceId ,@lSourceTypeId =SourceTypeId 
		FROM sFee.tReceiptDetail RD 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id 
		INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId
		WHERE RD.ReceiptId = @rReceiptId AND FH.Number = 100 AND FS.IsVariable = 1
		
		
		 IF @lFeeSetupId IS NOT NULL
		 BEGIN
		 UPDATE sFee.tFeeAllocation SET VariableAmount = VariableAmount - @rCharge WHERE FeeSetupId = @lFeeSetupId
		 AND SourceTypeId = @lSourceTypeId AND SourceId = @lSourceId
		 
		 DELETE FROM sFee.tFeeAllocation WHERE FeeSetupId = @lFeeSetupId
		 AND SourceTypeId = @lSourceTypeId AND SourceId = @lSourceId
		 AND (VariableAmount - DiscountAmount-NotApplicableAmount+AdditionalAmount <= 0)
		 
		 END
END
	 
	 DECLARE @lBatchId int, @lOrgId int
	 SELECT @lSourceId = SourceId, @lBatchId = BatchId from sFee.tReceipt where Id=@rReceiptId 
	 Select @lOrgId = OrgId from sSetup.tBatchMaster where Id = @lBatchId
	

	 IF(@rIsDelete=1)
	 BEGIN
		 
		Insert into sFee.tReceiptDeleted Select 
		Id,SourceTypeId,SourceId,ReceiptNumber,ReceiptDate,ReceiptAmount,PayTypeId,ChequeNo,BankName,
		ReceiptBookId,Remark,IsObsolete,BatchId,OrgGroupBatchId,CreatedUserId,
		CreatedDateTime,TotalReceiptAmount,DiscountAmount,
		IsChequeCleared,ChequeClearDate,ChequeDate,FeeInvoiceId,CollectionGroupId,
		AmountAfterDiscount,CGSTPercentage,SGSTPercentage,CGSTAmount,SGSTAmount,
		DepositedLedgerId,PaymentTransactionId,@rUserId,sCommon.fGetDate()
		From sFee.tReceipt where Id=@rReceiptId 
		
		Insert INTO sFee.tReceiptDetailDeleted Select
		ReceiptId,FeeSetupId,Amount
		From sFee.tReceiptDetail Where ReceiptId=@rReceiptId 

		
		EXEC [sFee].[pDeletedRecieptFeeProcessGenerate] @lOrgId,@lBatchId,@lSourceId,@rReceiptId,@rUserId
		
	    Delete From sFee.tReceiptDetail where ReceiptId=@rReceiptId 
		Delete From sFee.tReceipt where Id=@rReceiptId 
		
		
		SELECT 1 AS Result
	 END
	 ELSE
	 BEGIN 

		UPDATE  sFee.tReceipt
	    SET
			IsObsolete=1,
			CancelStatusRemark = @rCancelRemark
		WHERE Id=@rReceiptId
		
		
	SELECT 1 AS Result
	 END
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

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


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

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

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

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

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

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

	EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rPayTypeId,@rPaymentTransactionId,@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, StatusId = 752 
		WHERE BatchId = @lBatchId AND OrgGroupBatchId = @lOrgGroupBatchId 
			AND SourceTypeId = @lSourceTypeId1 AND SourceId = @lSourceId AND ReceiptBookId = @lReceiptBookId 
			AND PayTypeId = @lPayTypeId AND ChequeNo = @lChequeNo AND BankName = @lBankName AND Amount = @lTotalReceiptAmount
	END
	ELSE
	BEGIN
		UPDATE sFee.tPostDatePayment SET ReceiptId = 0, StatusId = 751 WHERE ReceiptId = @rId
	END
	-- For Mantis 0023321 By Foram on 14/03/2024 END

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


GO
ALTER PROCEDURE [sStudent].[pImportStudent] @rOrgGroupId SMALLINT
	,@rOrgId SMALLINT
	,@rXmldoc [nvarchar] (max)
	,@rUserId BIGINT
	,@rBatchId INT
	,@rOrgGroupBatchId INT
	,@rOperation INT = 0 --1 For Insert,2 For Update
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		DECLARE @lCount INT
		DECLARE @lInterrorCode INT
			,@intDoc INT
			,@lCode NVARCHAR(20)
			,@lNumber BIGINT
			,@lRegistrationNumber NVARCHAR(20)
			,@lFirstName NVARCHAR(100)
			,@lMiddleName NVARCHAR(100)
			,@lLastName NVARCHAR(100)
			,@lClassId INT
			,@lClass NVARCHAR(100)
			,@lDivisionId INT
			,@lDivision NVARCHAR(100)
			,@lRollNo INT
			,@lAdmissionStandardId INT
			,@lAdmissionStandard NVARCHAR(100)
			,@lAdmissionDate DATE
			,@lPreviousSchool NVARCHAR(200)
			,@lDOB DATE
			,@lGenderId INT = 0
			,@lGender NVARCHAR(10)
			,@lBloodGroupId INT = 0
			,@lBloodGroup NVARCHAR(10)
			,@lAdmissionCategoryId INT
			,--@lAdmissionCategory nvarchar(100),
			@lReligionId INT
			,@lReligion NVARCHAR(100)
			,@lFamilyCast NVARCHAR(100)
			,@lFamilySubCast NVARCHAR(100)
			,@lCastCategoryId INT = 0
			,@lCastCategory NVARCHAR(100)
			,@lParentContactNo NVARCHAR(20)
			,@lParentEmail NVARCHAR(50)
			,@lStudentContactNo NVARCHAR(20)
			,@lStudentEmail NVARCHAR(50)
			,@lPresentStreetOne NVARCHAR(150)
			,@lPresentStreetTwo NVARCHAR(150)
			,@lPresentStreetThree NVARCHAR(150)
			,@lPresentCity NVARCHAR(50)
			,@lPresentZipCode NVARCHAR(20)
			,@lPresentState NVARCHAR(50)
			,@lPresentCountry NVARCHAR(50)
			,@lPresentContactNo NVARCHAR(20)
			,
			--@lEmergencyStreetOne nvarchar(50),
			--@lEmergencyStreetTwo nvarchar(50),
			--@lEmergencyStreetThree nvarchar(50),
			--@lEmergencyCountry nvarchar(50),
			--@lEmergencyState nvarchar(50),
			--@lEmergencyCity nvarchar(50),
			--@lEmergencyZipCode nvarchar(20),
			@lEmergencyContactNo NVARCHAR(20)
			,@lBirthPlace NVARCHAR(150)
			,@lBirthTaluka NVARCHAR(150)
			,@lBirthDistrict NVARCHAR(150)
			,@lBirthDateInWord NVARCHAR(150)
			,@lHouseId INT
			,@lHouse NVARCHAR(100)
			,
			--@lMotherTongueId int,
			@lMotherTongue NVARCHAR(100)
			,@lAdhaarNumber NVARCHAR(20)
			,@lUIDNumber NVARCHAR(50)
			,@lQuotaId INT
			,@lQuota NVARCHAR(100)
			,
			-- New Add
			@lSUId NVARCHAR(50)
			,@lLeftStandardId INT
			,@lLeftStandard NVARCHAR(100)
			,@lLeftDate DATE
			,@lLCNumber NVARCHAR(20)
			,@lLCDate DATE
			,@lLCReason NVARCHAR(200)
			,@lLCProgress NVARCHAR(200)
			,@lLCConduct NVARCHAR(200)
			,@lLCRemark NVARCHAR(200)
			,@lStatusId SMALLINT
			,@lBirthState NVARCHAR(100)
			,@lBirthCountry NVARCHAR(100)
			,@lAcademicId BIGINT
			,@lPreviousStandard NVARCHAR(100)
			,@lWhatsAppContactNo NVARCHAR(20)
			,@lTribeId INT = 0
			,@lTribe NVARCHAR(100)
			,@lPreviousLeftDate DATE
			,@lPENNumber BIGINT --Mantis - 0031338
		DECLARE @EmployeeId BIGINT
		--DECLARE @OutClassId int
		--DECLARE @OutDivisionId int
		DECLARE @OutStudentId BIGINT

		--DECLARE @OutAdmissionStandardId int
		--DECLARE @OutReligionId int
		--DECLARE @OutAdmissionCategoryId int		
		SET @lAdmissionCategoryId = sCommon.fGetIntIdForOrg(1, @rOrgGroupId)

		DECLARE @1StudentId BIGINT = 0

		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT
			,@rXmlDoc

		CREATE TABLE #tTable (
			Id BIGINT identity
			,Code NVARCHAR(20)
			,Number BIGINT
			,RegistrationNumber NVARCHAR(20)
			,FirstName NVARCHAR(100)
			,MiddleName NVARCHAR(100)
			,LastName NVARCHAR(100)
			,ClassId INT NULL
			,Class NVARCHAR(100)
			,DivisionId INT NULL
			,Division NVARCHAR(100)
			,RollNo INT
			,AdmissionStandardId INT
			,AdmissionStandard NVARCHAR(100)
			,AdmissionDate DATE
			,PreviousSchool NVARCHAR(200)
			,DOB DATE
			,GenderId INT NULL
			,Gender NVARCHAR(10)
			,BloodGroupId INT NULL
			,BloodGroup NVARCHAR(10)
			,ReligionId INT
			,Religion NVARCHAR(100)
			,
			--AdmissionCategoryId int,
			--AdmissionCategory nvarchar(100),
			FamilyCast NVARCHAR(100)
			,FamilySubCast NVARCHAR(100)
			,CastCategoryId INT
			,CastCategory NVARCHAR(100)
			,ParentContactNo NVARCHAR(20)
			,ParentEmail NVARCHAR(50)
			,StudentContactNo NVARCHAR(20)
			,StudentEmail NVARCHAR(50)
			,PresentStreetOne NVARCHAR(150)
			,PresentStreetTwo NVARCHAR(150)
			,PresentStreetThree NVARCHAR(150)
			,PresentCity NVARCHAR(50)
			,PresentZipCode NVARCHAR(20)
			,PresentState NVARCHAR(50)
			,PresentCountry NVARCHAR(50)
			,PresentContactNo NVARCHAR(20)
			,
			--EmergencyStreetOne nvarchar(50),
			--EmergencyStreetTwo nvarchar(50),
			--EmergencyStreetThree nvarchar(50),
			--EmergencyCountry nvarchar(50),
			--EmergencyState nvarchar(50),
			--EmergencyCity nvarchar(50),
			--EmergencyZipCode nvarchar(20),
			EmergencyContactNo NVARCHAR(20)
			,BirthPlace NVARCHAR(150)
			,BirthTaluka NVARCHAR(150)
			,BirthDistrict NVARCHAR(150)
			,BirthDateInWord NVARCHAR(150)
			,CreatedUserId BIGINT
			,HouseId INT
			,House NVARCHAR(100)
			,MotherTongueId INT
			,MotherTongue NVARCHAR(100)
			,AdhaarNumber NVARCHAR(20)
			,UIDNumber NVARCHAR(50)
			,QuotaId INT
			,Quota NVARCHAR(100)
			,SUId NVARCHAR(50)
			,LeftStandardId INT
			,LeftStandard NVARCHAR(100)
			,LeftDate DATE
			,LCNumber NVARCHAR(20)
			,LCDate DATE
			,LCReason NVARCHAR(200)
			,LCProgress NVARCHAR(200)
			,LCConduct NVARCHAR(200)
			,LCRemark NVARCHAR(200)
			,StatusId SMALLINT
			,BirthState NVARCHAR(100)
			,BirthCountry NVARCHAR(100)
			,PreviousStandard NVARCHAR(100)
			,WhatsAppContactNo NVARCHAR(20)
			,TribeId INT NULL
			,Tribe NVARCHAR(100)
			,PreviousLeftDate DATE
			,PENNumber BIGINT --Mantis - 0031338
			)

		INSERT INTO #tTable (
			Code
			,Number
			,RegistrationNumber
			,FirstName
			,MiddleName
			,LastName
			,ClassId
			,Class
			,DivisionId
			,Division
			,RollNo
			,AdmissionStandardId
			,AdmissionStandard
			,AdmissionDate
			,PreviousSchool
			,DOB
			,GenderId
			,Gender
			,BloodGroupId
			,BloodGroup
			,ReligionId
			,Religion
			,
			--AdmissionCategoryId,
			--AdmissionCategory,
			FamilyCast
			,FamilySubCast
			,CastCategoryId
			,CastCategory
			,ParentContactNo
			,ParentEmail
			,StudentContactNo
			,StudentEmail
			,PresentStreetOne
			,PresentStreetTwo
			,PresentStreetThree
			,PresentCity
			,PresentZipCode
			,PresentState
			,PresentCountry
			,PresentContactNo
			,
			--EmergencyStreetOne,
			--EmergencyStreetTwo,
			--EmergencyStreetThree,
			--EmergencyCountry,
			--EmergencyState,
			--EmergencyCity,
			--EmergencyZipCode,
			EmergencyContactNo
			,BirthPlace
			,BirthTaluka
			,BirthDistrict
			,BirthDateInWord
			,CreatedUserId
			,HouseId
			,House
			,MotherTongueId
			,MotherTongue
			,AdhaarNumber
			,UIDNumber
			,QuotaId
			,Quota
			,SUId
			,LeftStandardId
			,LeftStandard
			,LeftDate
			,LCNumber
			,LCDate
			,LCReason
			,LCProgress
			,LCConduct
			,LCRemark
			,StatusId
			,BirthState
			,BirthCountry
			,PreviousStandard
			,WhatsAppContactNo
			,TribeId
			,Tribe
			,PreviousLeftDate
			,PENNumber
			)
		SELECT Code
			,Number
			,RegistrationNumber
			,sSetup.fPortalXMLTagsReplaceReverse(FirstName) AS FirstName
			,sSetup.fPortalXMLTagsReplaceReverse(MiddleName) AS MiddleName
			,sSetup.fPortalXMLTagsReplaceReverse(LastName) AS LastName
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Class) AS Class
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Division) AS Division
			,RollNo
			,0
			,AdmissionStandard
			,AdmissionDate
			,sSetup.fPortalXMLTagsReplaceReverse(PreviousSchool) AS PreviousSchool
			,DOB
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Gender) AS Gender
			,0
			,BloodGroup
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(Religion) AS Religion
			,
			--0,
			--AdmissionCategory,
			sSetup.fPortalXMLTagsReplaceReverse(FamilyCast) AS FamilyCast
			,sSetup.fPortalXMLTagsReplaceReverse(FamilySubCast) AS FamilySubCast
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(CastCategory) AS CastCategory
			,ParentContactNo
			,ParentEmail
			,StudentContactNo
			,StudentEmail
			,sSetup.fPortalXMLTagsReplaceReverse(PresentStreetOne) AS PresentStreetOne
			,sSetup.fPortalXMLTagsReplaceReverse(PresentStreetTwo) AS PresentStreetTwo
			,sSetup.fPortalXMLTagsReplaceReverse(PresentStreetThree) AS PresentStreetThree
			,sSetup.fPortalXMLTagsReplaceReverse(PresentCity) AS PresentCity
			,PresentZipCode
			,sSetup.fPortalXMLTagsReplaceReverse(PresentState) AS PresentState
			,sSetup.fPortalXMLTagsReplaceReverse(PresentCountry) AS PresentCountry
			,PresentContactNo
			,
			--EmergencyStreetOne,
			--EmergencyStreetTwo,
			--EmergencyStreetThree,
			--EmergencyCountry,
			--EmergencyState,
			--EmergencyCity,
			--EmergencyZipCode,
			EmergencyContactNo
			,sSetup.fPortalXMLTagsReplaceReverse(BirthPlace) AS BirthPlace
			,sSetup.fPortalXMLTagsReplaceReverse(BirthTaluka) AS BirthTaluka
			,sSetup.fPortalXMLTagsReplaceReverse(BirthDistrict) AS BirthDistrict
			,sSetup.fPortalXMLTagsReplaceReverse(BirthDateInWord) AS BirthDateInWord
			,CreatedUserId
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(House) AS House
			,0
			,sSetup.fPortalXMLTagsReplaceReverse(MotherTongue) AS MotherTongue
			,sSetup.fPortalXMLTagsReplaceReverse(AdhaarNumber) AS AdhaarNumber
			,UIDNumber
			,0
			,Quota
			,SUId
			,0
			,LeftStandard
			,LeftDate
			,LCNumber
			,LCDate
			,sSetup.fPortalXMLTagsReplaceReverse(LCReason) AS LCReason
			,LCProgress
			,LCConduct
			,sSetup.fPortalXMLTagsReplaceReverse(LCRemark) AS LCRemark
			,StatusId
			,sSetup.fPortalXMLTagsReplaceReverse(BirthState) AS BirthState
			,sSetup.fPortalXMLTagsReplaceReverse(BIrthCountry) AS BIrthCountry
			,PreviousStandard
			,WhatsAppContactNo
			,0
			,Tribe
			,PreviousLeftDate
			,PENNumber --Mantis - 0031338
		FROM OPENXML(@intDoc, '/Table/ImportStudent', 1) WITH (
				Code NVARCHAR(20) '@Code'
				,Number BIGINT '@Number'
				,RegistrationNumber NVARCHAR(20) '@RegistrationNumber'
				,FirstName NVARCHAR(100) '@FirstName'
				,MiddleName NVARCHAR(100) '@MiddleName'
				,LastName NVARCHAR(100) '@LastName'
				,Class NVARCHAR(100) '@Class'
				,Division NVARCHAR(100) '@Division'
				,RollNo INT '@RollNo'
				,AdmissionStandard NVARCHAR(100) '@AdmissionStandard'
				,AdmissionDate DATE '@AdmissionDate'
				,PreviousSchool NVARCHAR(200) '@PreviousSchool'
				,DOB DATE '@DOB'
				,Gender NVARCHAR(10) '@Gender'
				,BloodGroup NVARCHAR(10) '@BloodGroup'
				,Religion NVARCHAR(100) '@Religion'
				,
				--AdmissionCategory nvarchar(100) '@AdmissionCategory',
				FamilyCast NVARCHAR(100) '@FamilyCast'
				,FamilySubCast NVARCHAR(100) '@FamilySubCast'
				,CastCategory NVARCHAR(100) '@CastCategory'
				,ParentContactNo NVARCHAR(20) '@ParentContactNo'
				,ParentEmail NVARCHAR(50) '@ParentEmail'
				,StudentContactNo NVARCHAR(20) '@StudentContactNo'
				,StudentEmail NVARCHAR(50) '@StudentEmail'
				,PresentStreetOne NVARCHAR(150) '@PresentStreetOne'
				,PresentStreetTwo NVARCHAR(150) '@PresentStreetTwo'
				,PresentStreetThree NVARCHAR(150) '@PresentStreetThree'
				,PresentCity NVARCHAR(50) '@PresentCity'
				,PresentZipCode NVARCHAR(20) '@PresentZipCode'
				,PresentState NVARCHAR(50) '@PresentState'
				,PresentCountry NVARCHAR(50) '@PresentCountry'
				,PresentContactNo NVARCHAR(20) '@PresentContactNo'
				,
				--EmergencyStreetOne nvarchar(50) '@EmergencyStreetOne',
				--EmergencyStreetTwo nvarchar(50) '@EmergencyStreetTwo',
				--EmergencyStreetThree nvarchar(50) '@EmergencyStreetThree',
				--EmergencyCountry nvarchar(50) '@EmergencyCountry',
				--EmergencyState nvarchar(50) '@EmergencyState',
				--EmergencyCity nvarchar(50) '@EmergencyCity',
				--EmergencyZipCode nvarchar(20) '@EmergencyZipCode',
				EmergencyContactNo NVARCHAR(20) '@EmergencyContactNo'
				,BirthPlace NVARCHAR(150) '@BirthPlace'
				,BirthTaluka NVARCHAR(150) '@BirthTaluka'
				,BirthDistrict NVARCHAR(150) '@BirthDistrict'
				,BirthDateInWord NVARCHAR(150) '@BirthDateInWord'
				,CreatedUserId BIGINT '@CreatedUserId'
				,House NVARCHAR(100) '@House'
				,MotherTongue NVARCHAR(100) '@MotherTongue'
				,AdhaarNumber NVARCHAR(20) '@AdhaarNumber'
				,UIDNumber NVARCHAR(50) '@UIDNumber'
				,Quota NVARCHAR(20) '@Quota'
				,SUId NVARCHAR(50) '@SUId'
				,LeftStandard NVARCHAR(100) '@LeftStandard'
				,LeftDate DATE '@LeftDate'
				,LCNumber NVARCHAR(20) '@LCNumber'
				,LCDate DATE '@LCDate'
				,LCReason NVARCHAR(200) '@LCReason'
				,LCProgress NVARCHAR(200) '@LCProgress'
				,LCConduct NVARCHAR(200) '@LCConduct'
				,LCRemark NVARCHAR(200) '@LCRemark'
				,StatusId SMALLINT '@StatusId'
				,BirthState NVARCHAR(100) '@BirthState'
				,BirthCountry NVARCHAR(100) '@BirthCountry'
				,PreviousStandard NVARCHAR(100) '@PreviousStandard'
				,WhatsAppContactNo NVARCHAR(20) '@WhatsAppContactNo'
				,Tribe NVARCHAR(100) '@Tribe'
				,PreviousLeftDate DATE '@PreviousLeftDate'
				,PENNumber BIGINT '@PENNumber'--Mantis - 0031338
				)

		EXEC sp_xml_removedocument @intDoc

		SELECT @lCount = COUNT(Id)
		FROM #tTable

		WHILE @lCount > 0
		BEGIN
			SET @lCode = ''
			SET @lNumber = NULL
			SET @lRegistrationNumber = NULL
			SET @lFirstName = ''
			SET @lMiddleName = ''
			SET @lLastName = ''
			SET @lClassId = NULL
			SET @lClass = ''
			SET @lDivisionId = NULL
			SET @lDivision = ''
			SET @lRollNo = NULL
			SET @lAdmissionStandardId = NULL
			SET @lAdmissionStandard = ''
			SET @lAdmissionDate = ''
			SET @lPreviousSchool = ''
			SET @lDOB = ''
			SET @lGenderId = NULL
			SET @lGender = ''
			SET @lBloodGroupId = NULL
			SET @lBloodGroup = ''
			SET @lReligionId = NULL
			SET @lReligion = ''
			--SET @lAdmissionCategoryId  = null
			--SET @lAdmissionCategory = ''
			SET @lFamilyCast = ''
			SET @lFamilySubCast = ''
			SET @lCastCategoryId = NULL
			SET @lCastCategory = ''
			SET @lParentContactNo = ''
			SET @lParentEmail = ''
			SET @lStudentContactNo = ''
			SET @lStudentEmail = ''
			SET @lPresentStreetOne = ''
			SET @lPresentStreetTwo = ''
			SET @lPresentStreetThree = ''
			SET @lPresentCity = ''
			SET @lPresentZipCode = ''
			SET @lPresentState = ''
			SET @lPresentCountry = ''
			SET @lPresentContactNo = ''
			--SET @lEmergencyStreetOne = ''
			--SET @lEmergencyStreetTwo = ''
			--SET @lEmergencyStreetThree = ''
			--SET @lEmergencyCountry = ''
			--SET @lEmergencyState = ''
			--SET @lEmergencyCity = ''
			--SET @lEmergencyZipCode = ''
			SET @lEmergencyContactNo = ''
			SET @lBirthPlace = ''
			SET @lBirthTaluka = ''
			SET @lBirthDistrict = ''
			SET @lBirthDateInWord = ''
			--SET @OutClassId = null
			--SET @OutDivisionId = null
			SET @OutStudentId = NULL
			--SET @OutAdmissionStandardId = null
			--SET @OutReligionId = null,
			SET @lHouseId = NULL
			SET @lHouse = ''
			--SET @lMotherTongueId=NULL
			SET @lMotherTongue = ''
			SET @lAdhaarNumber = ''
			SET @lUIDNumber = ''
			SET @lQuotaId = NULL
			SET @lQuota = ''
			SET @lSUId = ''
			SET @lLeftStandardId = NULL
			SET @lLeftStandard = ''
			SET @lLeftDate = ''
			SET @lLCNumber = ''
			SET @lLCDate = ''
			SET @lLCReason = ''
			SET @lLCProgress = ''
			SET @lLCConduct = ''
			SET @lLCRemark = ''
			SET @lStatusId = NULL
			SET @lBirthState = ''
			SET @lBirthCountry = ''
			SET @lPreviousStandard = ''
			SET @lWhatsAppContactNo = ''
			SET @lTribeId = NULL
			SET @lTribe = ''
			SET @lPreviousLeftDate = ''
			SET @lPENNumber = NULL --Mantis - 0031338

			SELECT @lCode = Code
				,@lNumber = Number
				,@lRegistrationNumber = RegistrationNumber
				,@lFirstName = FirstName
				,@lMiddleName = MiddleName
				,@lLastName = LastName
				,@lClass = Class
				,@lDivision = Division
				,@lRollNo = RollNo
				,@lAdmissionStandard = AdmissionStandard
				,@lAdmissionDate = CASE 
					WHEN AdmissionDate = ''
						THEN NULL
					ELSE AdmissionDate
					END
				,@lPreviousSchool = PreviousSchool
				,@lReligion = Religion
				,
				--@lAdmissionCategory = AdmissionCategory,
				@lFamilyCast = FamilyCast
				,@lFamilySubCast = FamilySubCast
				,@lCastCategory = CastCategory
				,@lDOB = CASE 
					WHEN DOB = ''
						THEN NULL
					ELSE DOB
					END
				,@lGender = Gender
				,@lBloodGroup = BloodGroup
				,@lParentContactNo = ParentContactNo
				,@lParentEmail = ParentEmail
				,@lStudentContactNo = StudentContactNo
				,@lStudentEmail = StudentEmail
				,@lPresentStreetOne = PresentStreetOne
				,@lPresentStreetTwo = PresentStreetTwo
				,@lPresentStreetThree = PresentStreetThree
				,@lPresentCountry = PresentCountry
				,@lPresentState = PresentState
				,@lPresentCity = PresentCity
				,@lPresentZipCode = PresentZipCode
				,@lPresentContactNo = PresentContactNo
				,
				--@lEmergencyStreetOne = EmergencyStreetOne,
				--@lEmergencyStreetTwo = EmergencyStreetTwo,
				--@lEmergencyStreetThree = EmergencyStreetThree,
				--@lEmergencyCountry = EmergencyCountry,
				--@lEmergencyState = EmergencyState,
				--@lEmergencyCity = EmergencyCity,
				--@lEmergencyZipCode = EmergencyZipCode,
				@lEmergencyContactNo = EmergencyContactNo
				,@lBirthPlace = BirthPlace
				,@lBirthTaluka = BirthTaluka
				,@lBirthDistrict = BirthDistrict
				,@lBirthDateInWord = BirthDateInWord
				,@lHouse = House
				,@lMotherTongue = MotherTongue
				,@lAdhaarNumber = AdhaarNumber
				,@lUIDNumber = UIDNumber
				,@lQuota = Quota	--mantis: 33647
				,@lSUId = SUId
				,@lLeftStandard = LeftStandard
				,@lLeftDate = CASE 
					WHEN LeftDate = ''
						THEN NULL
					ELSE LeftDate
					END
				,@lLCNumber = LCNumber
				,@lLCDate = CASE 
					WHEN LCDate = ''
						THEN NULL
					ELSE LCDate
					END
				,@lLCReason = LCReason
				,@lLCProgress = LCProgress
				,@lLCConduct = LCConduct
				,@lLCRemark = LCRemark
				,@lStatusId = StatusId
				,@lBirthState = BirthState
				,@lBirthCountry = BirthCountry
				,@lPreviousStandard = PreviousStandard
				,@lWhatsAppContactNo = WhatsAppContactNo
				,@lTribe = Tribe
				,@lPreviousLeftDate = CASE 
					WHEN PreviousLeftDate = ''
						THEN NULL
					ELSE PreviousLeftDate
					END
				,@lPENNumber = PENNumber --Mantis - 0031338
			FROM #tTable
			WHERE Id = @lCount

			SELECT @lGenderId = ID
			FROM sCommon.tGenderMaster
			WHERE Title = @lGender

			SELECT @lLeftStandardId = ID
			FROM sSetup.tClassMaster
			WHERE Title = @lLeftStandard
				AND OrgId = @rOrgId

			SELECT @lClassId = ID
			FROM sSetup.tClassMaster
			WHERE Title = @lClass
				AND OrgId = @rOrgId

			SELECT @lDivisionId = ID
			FROM sSetup.tDivisionMaster
			WHERE Title = @lDivision
				AND ClassId = @lClassId
				AND OrgId = @rOrgId

			SELECT @lBloodGroupId = ID
			FROM sCommon.tBloodGroupMaster
			WHERE Title = @lBloodGroup

			SELECT @lAdmissionStandardId = ID
			FROM sSetup.tClassMaster
			WHERE Title = @lAdmissionStandard
				AND OrgId = @rOrgId

			SELECT @lReligionId = ID
			FROM sCommon.tReligionMaster
			WHERE Title = @lReligion
				AND OrgGroupId = @rOrgGroupId

			--SELECT	@lAdmissionCategoryId  = ID FROM tAdmissionCategoryMaster WHERE Title = @lAdmissionCategory AND OrgGroupId = @rOrgGroupId
			SELECT @lCastCategoryId = ID
			FROM sCommon.tCastCategoryMaster
			WHERE Title = @lCastCategory
				AND OrgGroupId = @rOrgGroupId

			SELECT @lHouseId = ID
			FROM sActivity.tHouseMaster
			WHERE Title = @lHouse
				AND OrgId = @rOrgId

			--mantis: 33647, comment the below query and add another query under that commented query
			--SELECT @lQuotaId = ID
			--FROM sCommon.tQuotaMaster
			--WHERE Title = @lQuota
			--	AND OrgGroupId = @rOrgGroupId
			SELECT @lQuotaId = ID
			FROM sCommon.tAdmissionQuotaMaster
			WHERE Title = @lQuota
				AND OrgGroupId = @rOrgGroupId

			--SELECT	@lMotherTongueId  = ID FROM sCommon.tMotherTongueMaster WHERE Title = @lMotherTongue
			SELECT @lTribeId = ID
			FROM sCommon.tTribeMaster
			WHERE Title = @lTribe

			PRINT (@lTribeId)

			IF (@lGenderId IS NULL)
				SET @lGenderId = 0

			IF (@lBloodGroupId IS NULL)
				SET @lBloodGroupId = 0

			IF (@lCastCategoryId IS NULL)
				SET @lCastCategoryId = 0

			IF (@lHouseId IS NULL)
				SET @lHouseId = 0

			IF (@lQuotaId IS NULL)
				SET @lQuotaId = 0

			IF (@lTribeId IS NULL)
				SET @lTribeId = 0

			--IF(@lMotherTongueId IS NULL)
			--	SET	@lMotherTongueId = 0		
			--IF 	@lClassId IS NULL  AND @lClass != ''
			--BEGIN
			--	EXEC [sSetup].[pClassMasterAdd] 0,@lClass,@lClass,@lClass,@lClass,1,0,0,0,@rUserId,@rUserId,@rOrgId,@OutClassId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutClassId = @lClassId
			--END
			--IF 	@lAdmissionStandardId IS NULL  AND @lAdmissionStandard != ''
			--BEGIN
			--	EXEC [sSetup].[pClassMasterAdd] 0,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,1,0,0,0,@rUserId,@rUserId,@rOrgId,0,@OutAdmissionStandardId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutAdmissionStandardId = @lAdmissionStandardId
			--END
			--IF 	@lDivisionId IS NULL  AND @lDivision != ''
			--BEGIN
			--	SET @EmployeeId = sCommon.fGetBigIntIdForOrg(1,@rOrgId)
			--	EXEC [sSetup].[pDivisionMasterAdd] 0,@lDivision,@lDivision,@lDivision,@lClassId,@EmployeeId,NULL,0,@rUserId,@rUserId,0,@rOrgId,@OutDivisionId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutDivisionId = @lDivisionId
			--END
			--IF 	@lReligionId IS NULL  AND @lReligion != ''
			--BEGIN
			--	EXEC [sCommon].[pReligionMasterAdd] 0,@lReligion,@lReligion,0,@rUserId,@rOrgId,@OutReligionId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutReligionId = @lReligionId
			--END
			--IF 	@lAdmissionCategoryId IS NULL  AND @lAdmissionCategory != ''
			--BEGIN
			--	EXEC [sStudent].[pAdmissionCategoryMasterAdd] 0,@lAdmissionCategory,@lAdmissionCategory,0,@rUserId,@rOrgId,@OutAdmissionCategoryId OUTPUT
			-- END
			--ELSE
			--BEGIN
			--SET @OutAdmissionCategoryId = @lAdmissionCategoryId
			--END
			BEGIN TRANSACTION

			DECLARE @lStudCap INT
				,@lOrgStudentCap INT

			SELECT @lStudCap = ISNULL(NoOfStudent, 0) + ISNULL(StudentExtraCap, 0)
			FROM sSetup.tOrgGroupSetting
			WHERE OrgGroupId = @rOrgGroupId

			SELECT @lOrgStudentCap = [sSetup].[fStudentCapGet](@rOrgGroupBatchId)

			IF (@lOrgStudentCap >= @lStudCap)
			BEGIN
				SELECT - 111 AS RESULT

				COMMIT TRANSACTION

				RETURN
			END

			IF (
					@rOperation = 1
					OR @rOperation = 0
					)
			BEGIN
				IF (@lStatusId = 1)
					EXEC sStudent.pStudentMasterAdd 0
						,@lCode
						,@lRegistrationNumber
						,@lNumber
						,@lFirstName
						,@lMiddleName
						,@lLastName
						,@rOrgId
						,@lAdmissionCategoryId
						,1
						,502
						,@rUserId
						,@rUserId
						,@rOrgGroupBatchId
						,@OutStudentId OUTPUT
						,@lSUId
						,@lPENNumber --Mantis - 0031338
				ELSE
					EXEC sStudent.pStudentMasterAdd 0
						,@lCode
						,@lRegistrationNumber
						,@lNumber
						,@lFirstName
						,@lMiddleName
						,@lLastName
						,@rOrgId
						,@lAdmissionCategoryId
						,3
						,502
						,@rUserId
						,@rUserId
						,@rOrgGroupBatchId
						,@OutStudentId OUTPUT
						,@lSUId
						,@lPENNumber --Mantis - 0031338

				EXEC sStudent.pAcademicAdd 0
					,@OutStudentId
					,@lClassId
					,@lDivisionId
					,@lRollNo
					,@rOrgId
					,@rBatchId
					,@rUserId
					,@rUserId
					,@lAdmissionCategoryId
					,1

				EXEC sStudent.pStudentCommunicationAdd @OutStudentId
					,@lPresentStreetOne
					,@lPresentStreetTwo
					,@lPresentStreetThree
					,@lPresentCountry
					,@lPresentState
					,@lPresentCity
					,@lPresentZipCode
					,@lPresentContactNo
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,@lEmergencyContactNo
					,@lParentContactNo
					,@lParentEmail
					,@lStudentContactNo
					,@lStudentEmail
					,@rUserId
					,@rUserId
					,NULL
					,NULL
					,NULL
					,NULL
					,NULL
					,@lWhatsAppContactNo

				EXEC sStudent.pStudentOtherAdd @OutStudentId
					,@lUIDNumber
					,@lDOB
					,@lGenderId
					,@lReligionId
					,@lBloodGroupId
					,@lBirthPlace
					,@lBirthTaluka
					,@lBirthDistrict
					,@lBirthDateInWord
					,@lFamilyCast
					,@lFamilySubCast
					,@lCastCategoryId
					,NULL
					,@lHouseId
					,NULL
					,NULL
					,''
					,@rUserId
					,@rUserId
					,''
					,@lAdhaarNumber
					,@lMotherTongue
					,@lQuotaId
					,@lBirthState
					,@lBirthCountry
					,@rBatchId
					,@lTribeId

				IF (@lStatusId = 1)
					EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId
						,@lPreviousSchool
						,NULL
						,NULL
						,NULL
						,NULL
						,@lAdmissionStandardId
						,@lAdmissionDate
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@rBatchId
						,@rUserId
						,@rUserId
						,1
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lQuotaId	--mantis: 33647
						,@lPreviousStandard
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lPreviousLeftDate
				ELSE
					EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId
						,@lPreviousSchool
						,NULL
						,NULL
						,NULL
						,NULL
						,@lAdmissionStandardId
						,@lAdmissionDate
						,NULL
						,@lLeftStandardId
						,@lLeftDate
						,NULL
						,NULL
						,NULL
						,@lLCReason
						,@lLCProgress
						,@lLCConduct
						,NULL
						,@lLCNumber
						,@lLCDate
						,@lLCRemark
						,NULL
						,NULL
						,@rBatchId
						,@rUserId
						,@rUserId
						,0
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lQuotaId	--mantis: 33647
						,@lPreviousStandard
						,NULL
						,NULL
						,NULL
						,NULL
						,NULL
						,@lPreviousLeftDate
			END
			ELSE
			BEGIN
				SET @1StudentId = (
						SELECT Id
						FROM sStudent.tStudentMaster
						WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT
							AND OrgId = @rOrgId
						)
	--Mantis Start- 0031338	
	DECLARE @lPENNumberActive nvarchar(50)=''
	SELECT @lPENNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 544 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	--Mantis END- 0031338	

				UPDATE sStudent.tStudentMaster
				SET RegistrationNumber = @lRegistrationNumber
					,FirstName = @lFirstName
					,MiddleName = @lMiddleName
					,LastName = @lLastName
					,SUId = @lSUId
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
				WHERE Id = @1StudentId

--Mantis Start- 0031338		
		IF (@lPENNumberActive = 'True')
		Begin
			UPDATE sStudent.tStudentMaster
			SET 
			PENNumber =case when isnull(@lPENNumber,0) <> 0 then  @lPENNumber else PENNumber END--Mantis - 0031338
			WHERE Id = @1StudentId and OrgId = @rOrgId
		END
--Mantis End- 0031338	

				UPDATE sStudent.tStudentAdmission
				SET AdmissionStandardId = @lAdmissionStandardId
					,AdmissionDate = @lAdmissionDate
					,PreviousSchool = @lPreviousSchool
					,LeftStandardId = @lLeftStandardId
					,LeftDate = @lLeftDate
					,LCNumber = @lLCNumber
					,LCDate = @lLCDate
					,LCRemark = @lLCRemark
					,LCConduct = @lLCConduct
					,LCProgress = @lLCProgress
					,LeftReason = @lLCReason
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
					,PreviousStandard = @lPreviousStandard
					,PreviousLeftDate = @lPreviousLeftDate
					,AdmissionQuotaId = @lQuotaId	--mantis: 33647
				WHERE StudentId = @1StudentId

				UPDATE sStudent.tStudentOther
				SET DateOfBirth = @lDOB
					,GenderId = @lGenderId
					,BloodGroupId = @lBloodGroupId
					,ReligionId = @lReligionId
					,FamilyCast = @lFamilyCast
					,FamilySubCast = @lFamilySubCast
					,CastCategoryId = @lCastCategoryId
					,BirthPlace = @lBirthPlace
					,BirthTaluka = @lBirthTaluka
					,BirthDistrict = @lBirthDistrict
					,BirthState = @lBirthState
					,BirthCountry = @lBirthCountry
					,AdhaarNumber = @lAdhaarNumber
					,MotherTongue = @lMotherTongue
					,QuotaId = @lQuotaId
					,UIDNumber = @lUIDNumber
					,HouseId = @lHouseId
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
					,TribeId = @lTribeId
				WHERE StudentId = @1StudentId

				IF (@lDivisionId IS NOT NULL)
				BEGIN
					UPDATE sStudent.tAcademic
					SET DivisionId = @lDivisionId
						,RollNo = @lRollNo
						,UpdatedUserId = @rUserId
						,UpdatedDateTime = getdate()
					WHERE StudentId = @1StudentId
						AND BatchId = @rBatchId
						AND OrgId = @rOrgId
				END

				UPDATE sStudent.tStudentCommunication
				SET PresentStreetOne = @lPresentStreetOne
					,PresentStreetTwo = @lPresentStreetTwo
					,PresentStreetThree = @lPresentStreetThree
					,PresentCountry = @lPresentCountry
					,PresentState = @lPresentState
					,PresentCity = @lPresentCity
					,PresentZipCode = @lPresentZipCode
					,PresentContactNo = @lPresentContactNo
					,EmergencyContactNo = @lEmergencyContactNo
					,ParentContactNo = @lParentContactNo
					,ParentEmail = @lParentEmail
					,StudentContactNo = @lStudentContactNo
					,StudentEmail = @lStudentEmail
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
				WHERE StudentId = @1StudentId
			END

			SET @lCount = @lCount - 1

			COMMIT TRANSACTION
		END

		SELECT 1
	END TRY

	BEGIN CATCH
		ROLLBACK TRANSACTION

		SELECT ERROR_MESSAGE()
			,ERROR_LINE()
	END CATCH
END
GO

PRINT N'Update complete.';


GO


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

