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


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


GO
DROP TABLE [sStudent].[tTempStudent11];


GO
PRINT N'Dropping Table [sStudent].[tTempStudentId]...';


GO
DROP TABLE [sStudent].[tTempStudentId];


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


GO
ALTER TABLE [sAssessment].[tStudentRemark]
    ADD [CGPA] DECIMAL (6, 2) NULL,
        [SGPA] DECIMAL (6, 2) NULL;


GO
PRINT N'Creating Table [sStudent].[tTempStudent5]...';


GO
CREATE TABLE [sStudent].[tTempStudent5] (
    [StudentId1] INT NULL
);


GO
PRINT N'Creating Table [sStudent].[tTempStudent6]...';


GO
CREATE TABLE [sStudent].[tTempStudent6] (
    [StudentId2] INT NULL
);


GO
PRINT N'Creating Table [sStudent].[tTempStudent7]...';


GO
CREATE TABLE [sStudent].[tTempStudent7] (
    [StudentId3] INT NULL
);


GO

PRINT N'Altering View [sCertificate].[vPrintTemplateStudentBasicDetails]...';


GO


ALTER VIEW [sCertificate].[vPrintTemplateStudentBasicDetails]
AS
	SELECT
		[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS StudentName,
		SM.Code,
		DM.Code AS ClassDivision,
		A.RollNo,
		BM.Title AS BatchName,
		SO.DateOfBirth AS DateOfBirth,
		GetDate() AS PrintDate, 	-- Change for Mantis id 29447 and also added in below row "[PrintDate]"
		'[BatchName],[ClassDivision],[Code],[DateOfBirth],[RollNo],[FirstName],[MiddleName],
		[LastName],[PreviousSchool],[Gender],[Caste],[SubCaste],[BirthPlace],[DOBInWords],[PreviousSchoolYear],
		[OldGRNo],[PreviousLCDate],[PreviousLCResult],[PreviousLCNumber],[PreviousStandard],
		[BirthTaluka],[BirthState],[BirthCountry],[BirthDistrict],[Address],[ContactNo],[Email],[Religion],[FamilyCaste],[CasteCategory],[Nationality],[MotherTongue],[BloodGroup],[AadhaarNumber],[PhysicalCategory],
		[FatherName],[FatherQualification],[FatherOccupation],[FatherContactNo],[FatherOfficeAddress],[FatherEmail],[FatherExStudent],[FatherPassingYear],[FatherIncome],
		[MotherName],[MotherQualification],[MotherOccupation],[MotherContactNo],[MotherOfficeAddress],[MotherEmail],[MotherExStudent],[MotherPassingYear],[MotherIncome],
		[AdmissionDate],[AdmissionStandard],[ClassName],[UIDNumber],[BankHolderName],[BankName],[BankBranch],[BankIFSCcode],[BankAccountNo],[StudentPhoto],[WhatsAppContactNo],[PrintDate],[SUIDNumber],[LocalName],[PENNo]' As ColumnList
		--Manits: 31034, add SUIDNumber in ColumnList
		--Mantis: 32199, add LocalName in ColumnList
		--[PENNo] For Mantis Id : 0035456
	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.tClassMaster CM
			ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM
			ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		INNER JOIN sStudent.tStatusMaster STM
			ON STM.Id=SM.StatusId
		INNER JOIN sSetup.tDepartmentMaster DeptM
			ON DeptM.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM
			ON A.OrgId = OM.Id
		INNER JOIN [sStudent].[tStudentOther] SO
			ON SO.StudentId=SM.Id
GO
PRINT N'Altering View [sCertificate].[vPrintTemplateStudentDetail]...';


GO


ALTER VIEW [sCertificate].[vPrintTemplateStudentDetail] 
AS
	SELECT
		A.Id AS AcademicId,
		DivM.Id AS DivisionId,
		DivM.DisplayTitle AS DivisionName,
		CM.Id AS ClassId,
		CM.DisplayTitle AS ClassName,
		CM.DisplayTitle+'-'+DivM.DisplayTitle AS ClassDivision,
		DM.Id AS DepartmentId,
		DM.DisplayTitle AS DepartmentName,
		SM.FirstName AS FirstName,
		SM.MiddleName AS MiddleName,
		SM.LastName AS LastName,
		SM.Code,
		A.RollNo,
		A.BatchId,
		BM.Title AS BatchName,
		CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
		SA.PreviousSchool,
		ISNULL(GM.Title,'') AS Gender,
		SO.FamilyCast AS Caste,
		SO.FamilySubCast AS SubCaste,
		SO.BirthPlace,
		SO.BirthDateInWord AS DOBInWords,
		SA.PreviousLCDate AS PreviousLCDate,
		SA.PreviousLCResult AS PreviousLCResult,
		SA.PreviousLCNumber AS PreviousLCNumber,
		SA.AdmissionNumber AS OldGRNo,
		SA.PassingYear AS PreviousSchoolYear,
		SA.PreviousStandard AS PreviousStandard,
		SO.BirthTaluka AS BirthTaluka,
		SO.BirthState AS BirthState,
		SO.BirthCountry AS BirthCountry,
		SO.BirthDistrict AS BirthDistrict,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS Address,
		SC.ParentContactNo AS ContactNo,
		SC.ParentEmail AS Email,
		ISNULL(RM.Title,'') AS Religion,
		SO.FamilyCast AS FamilyCaste,
		ISNULL(CCM.Title,'') AS CasteCategory,
		ISNULL(NM.Title,'') AS Nationality,
		ISNULL(SO.MotherTongue,'') AS MotherTongue,
		ISNULL(BGM.Title,'') As BloodGroup,
		ISNULL(SO.AdhaarNumber,'') AS AadhaarNumber,
		ISNULL(PDCM.Title,'') AS PhysicalCategory,
		SF.FatherName AS FatherName,
		SF.FatherQualification AS FatherQualification,
		SF.FatherOccupation AS FatherOccupation,
		SF.FatherContactNo AS FatherContactNo,
		SF.FatherOfficeAddress AS FatherOfficeAddress,
		SF.FatherMail AS FatherEmail,
		SF.IsFatherExStudent AS FatherExStudent,
		SF.FatherPassOutYear AS FatherPassingYear,
		SF.FatherIncome AS FatherIncome,
		SF.MotherName AS MotherName,
		SF.MotherQualification AS MotherQualification,
		SF.MotherOccupation AS MotherOccupation,
		SF.MotherContactNo AS MotherContactNo,
		SF.MotherOfficeAddress AS MotherOfficeAddress,
		SF.MotherMail AS MotherEmail,
		SF.IsMotherExStudent AS MotherExStudent,
		SF.MotherPassOutYear AS MotherPassingYear,
		SF.MotherIncome AS MotherIncome,
		SA.AdmissionDate AS AdmissionDate,
		CM1.Title AS AdmissionStandard,
		SO.UIDNumber AS UIDNumber,
		ISNULL(StuA.BankAccountHolderName,'') AS BankHolderName,
		ISNULL(StuA.BankName,'') AS BankName,
		ISNULL(StuA.BankBranch,'') AS BankBranch,
		ISNULL(StuA.BankIFSCcode,'') AS BankIFSCcode,
		ISNULL(StuA.BankAccountNumber,'') AS BankAccountNo,
		ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
		ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
		GetDate() AS PrintDate, -- Change for Mantis id 29447 added "[PrintDate]"
		SM.SUId AS SUIDNumber,	--Add for Manits: 31034
		ISNULL(SM.LocalName,'') AS LocalName,	--Add for Mantis: 32199
		ISNULL(PENNumber,0) AS PENNo			-- Mantis Id : 0035456
	FROM
		sStudent.tAcademic A
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DivM ON DivM.Id=A.DivisionId
		INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = A.StudentId
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
		LEFT JOIN sCommon.tCastCategoryMaster CCM  ON CCM.Id=SO.CastCategoryId
		LEFT JoIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
		LEFT JOIN sCommon.tMotherTongueMaster MT ON MT.Id = SO.MotherTongueId
		LEFT JOIN sCommon.tCountryMaster NM ON NM.Id = SO.NationalityId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId
		LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId = A.StudentId
		LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id=SA.AdmissionStandardId
		LEFT JOIN sStudent.tStudentAdditional StuA ON StuA.StudentId = SM.Id
		LEFT JOIN sStudent.tStudentImages SI ON SM.Id = SI.StudentId
GO
PRINT N'Altering View [sHrm].[vEmployeeCommonDetail]...';


GO
 

/******************************************************************************
	Purpose          : External view to get data from sHrm.tEmployeeMaster table
	Created date     : 03 Sep 2010
	Author           : Rajendra Patel
	Copyright©       : Copyright © Sapphire Software
	
	Last Change Desc : Added for jobtitle
*******************************************************************************/

ALTER VIEW [sHrm].[vEmployeeCommonDetail]

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

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


GO
ALTER VIEW [sStudent].[vStudentAllDetail]  
  
AS  
  
SELECT 
	  A.Id AS AcademicId,	  
	  A.ClassId,
	  A.DivisionId,
	  A.RollNo,
	  A.OrgId,
	  A.BatchId,
	  SM.Id AS StudentId,
	  SM.Code,
	  SM.Number,
	  SM.FirstName,
	  SM.MiddleName,
	  SM.LastName,
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	  CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,
	  SA.LCProgress,
	  SA.LCConduct,
	  SA.LeftDate,
	  SA.PreviousSchool,
	  SA.LeftReason,
	  SA.InactiveDate,
	  SA.AdmissionDate,
	  AdmissionStandard=(SELECT Title FROM SSetup.tClassMaster WHERE Id=SA.AdmissionStandardId),
	  LeftStandard=(SELECT Title FROM SSetup.tClassMaster WHERE Id=SA.LeftStandardId),
	  SA.LCNumber,
	  SA.LCDate,
	  RM.Title AS Religion,
	  SO.FamilyCast,
	  SO.FamilySubCast,
	  SO.BirthPlace,
	  SO.BirthTaluka,
	  SO.BirthDistrict,
	  ISNULL(SO.DateOfBirth,'0001/01/01') AS DateOfBirth,
	  SO.BirthDateInWord,
	  (SI.StudentPhoto) AS StudentPhoto,
	  (SI.FatherPhoto) AS FatherPhoto,
	  (SI.MotherPhoto) AS MotherPhoto,
	  (SI.RelativePhoto) AS RelativePhoto,
	  BGM.Title AS BloodGroup,
	  ISNULL(SC.PermanentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS PresentAddress,
	  GM.Id AS GenderId,
	  ISNULL(GM.Title,'') AS Gender,
	  ISNULL(SC.StudentContactNo,'') AS ContactNo,
	  BM.Title AS Batch,
	  ISNULL(ACM.Title,'') AS AdmissionCategory,
	  SO.HouseId,
	  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,
	  ISNULL(SC.PresentContactNo,'-') as PresentContactNo,
	  ISNULL(SC.ParentEmail,'-') AS ParentEmail,
	  ISNULL(SC.ParentContactNo,'-') AS ParentContactNo,
	  ISNULL(SC.StudentContactNo,'-') AS StudentContactNo,
	  DM.OrderIndex AS DivisionOrder,
	  SM.RegistrationNumber,
	  BM.IsActive AS IsActiveBatch,
	  CM.DepartmentId,
	  DEM.Title as DepartmentName,
	  BM.OrgGroupBatchId ,
	  ISNULL(SO.UIDNumber,'' ) AS UIDNumber,
	  ISNULL(SO.AdhaarNumber,'') AS AdhaarNumber,
	  ISNULL(SM.SUId,'') AS SUId,
	  ISNUll(SA.IsTransfer,0)AS IsTransfer,
	  ISNULL(SA.TransferFrom,'') AS TransferFrom,
	  ISNULL(SA.CertificateName,'') AS CertificateName,
	  ISNUll(SA.IsTFWS,0)AS IsTFWS,
	  ISNUll(SA.IsCertificateHolder,0)AS IsCertificateHolder,
	  ISNULL(SC.EmergencyStreetOne,'') AS EmergencyStreetOne,
	  ISNULL(SC.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
	  ISNULL(SC.EmergencyStreetThree,'') AS EmergencyStreetThree,
	  ISNULL(SC.EmergencyCountry,'') AS EmergencyCountry,
	  ISNULL(SC.EmergencyState,'') As EmergencyState,
	  ISNULL(SC.EmergencyCity,'') AS EmergencyCity,
	  ISNULL(SC.EmergencyZipCode,'') as EmergencyZipCode,
	  ISNULL(SC.EmergencyContactNo,'') AS EmergencyContactNo,
	  ISNULL(CM.StreamId,0) AS StreamId,
	  Isnull(SO.CastCategoryId,0) AS CastCategoryId,
	  Isnull(SO.NationalityId,0) AS NationalityId,
	  ISNULL(SO.MotherTongue,'') As MotherTongue,
	  Isnull(SO.BirthState,'') AS BirthState,
	  ISNULL(SO.BirthCountry,'') As BirthCountry,
	  ISNULL(SC.PermanentStreetOne,'') AS  PermanentStreetOne ,
	  ISNULL(SC.PermanentStreetTwo,'')  AS  PermanentStreetTwo,
	  ISNULL(SC.PermanentStreetThree,'') AS PermanentStreetThree,
	  ISNULL(SC.PermanentCity,'') AS PermanentCity,
	  ISNULL(SC.PermanentState,'') AS PermanentState,
	  ISNULL(SC.PermanentCountry,'') AS PermanentCountry,
	  ISNULL(SC.PermanentZipCode,'') AS PermanentZipCode,
	  ISNULL(SC.PermanentContactNo,'') AS PermanentContactNo,
	  ISNULL(Sc.StudentEmail,'') AS StudentEmail,
	  ISNULL(SC.PresentDistanceFromSchool,0) AS PresentDistanceFromSchool,
	  ISNULL(NM.Nationality,'') AS Nationality,
	  ISNULL(SA.PreviousStandard,'')AS PreviousStandard,
	  A.ClassStatusId,
	  STM1.Title AS ClassStatusName,
	  ISNULL(WhatsAppContactNo, '-') AS WhatsAppContactNo,
	  SO.ReferenceRemark,
	  ISNULL(SM.StudentGroupId,0) AS StudentGroupId  -- Add for mantis : 0035772

  FROM 
  
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDepartmentMaster DEM on DEM.Id=CM.DepartmentId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sStudent.tStatusMaster STM ON STM.Id=SM.StatusId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
	LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON ACM.Id=A.AdmissionCategoryId
	INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
	LEFT JOIN sCommon.tCountryMaster NM ON Nm.Id=SO.NationalityId
	INNER JOIN sStudent.tStatusMaster STM1 ON STM1.Id=A.ClassStatusId
GO
PRINT N'Creating Function [sFee].[fnGetStockDepositeAdd]...';


GO
CREATE FUNCTION [sFee].[fnGetStockDepositeAdd](@StockIssueReturnId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	

	DECLARE @lResult  VARCHAR(MAX)=''

	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ ISNULL(SIM.Title,'') + '(' + CONVERT(VARCHAR(10), CAST(ISNULL(SIRB.ReturnQuantity, 0) AS INT))
				 + ')' 
			    + ' , '
 
	FROM 
	sProcurement.tStockIssueReturn SIR
	INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIR.Id = SIRB.StockIssueReturnId
	INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id = SIRB.StockIssueBatchId
	INNER JOIN sProcurement.tStockIssueDetail SID ON SID.Id = SIB.StockIssueDetailId
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SID.StockItemId
	WHERE 
	SIR.Id = @StockIssueReturnId
	)

	IF(@lResult = '')
	BEGIN
		SET @lResult = ''
	END
	ELSE
	BEGIN
		SET @lResult = ISNULL(LEFT(@lResult, LEN(@lResult) - 1),'')
	END
 
	RETURN @lResult

END
GO
PRINT N'Creating Function [sFee].[fnGetStockDepositeAdjustment]...';


GO
CREATE FUNCTION [sFee].[fnGetStockDepositeAdjustment](@StockIssueId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	

DECLARE @lResult  VARCHAR(MAX)=''
 
(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ ISNULL(SIM.Title,'') + '(' + CONVERT(VARCHAR(10), CAST(ISNULL(SID.IssuedQuantity, 0) AS INT))
				 + ')' 
			    + ' , '
 
	FROM sProcurement.tStockIssue SI 
	INNER JOIN sProcurement.tStockIssueDetail SID ON SID.StockIssueId = SI.Id
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SID.StockItemId
	WHERE SI.Id = @StockIssueId
	)
 
 IF(@lResult = '')
 BEGIN
	SET @lResult = ''
 END
 ELSE
 BEGIN
	SET @lResult = ISNULL(LEFT(@lResult, LEN(@lResult) - 1),'')
 END
   
RETURN @lResult

END
GO
PRINT N'Creating Function [sProcurement].[fnGetStockDepositeAdd]...';


GO
CREATE FUNCTION [sProcurement].[fnGetStockDepositeAdd](@StockIssueReturnId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	

	DECLARE @lResult  VARCHAR(MAX)=''

	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ ISNULL(SIM.Title,'') + '(' + CONVERT(VARCHAR(10), CAST(ISNULL(SIRB.ReturnQuantity, 0) AS INT))
				 + ')' 
			    + ' , '
 
	FROM 
	sProcurement.tStockIssueReturn SIR
	INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIR.Id = SIRB.StockIssueReturnId
	INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id = SIRB.StockIssueBatchId
	INNER JOIN sProcurement.tStockIssueDetail SID ON SID.Id = SIB.StockIssueDetailId
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SID.StockItemId
	WHERE 
	SIR.Id = @StockIssueReturnId
	)

	SET @lResult = ISNULL(LEFT(@lResult, LEN(@lResult) - 1),'')
 
	RETURN @lResult

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


GO

ALTER PROCEDURE [sAssessment].[pRptSubjectActivityMaxMarkGradeTwoColumnGet]
	 
		@rOrgId int=0,
		@rExamId int=0,
		@rClass int=0,
		@rDivisionId int=0,
		@rBatchId int=0,
		@rBuilder1 nvarchar(max)='',
		@rAcademicId bigint=0,
		@rCode nvarchar(20)='',
		@rFromRollNo int=0,
		@rToRollNo int=0,
		@rMultiCode nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 

Declare @GradeSetId int,@GradeString nvarchar(1000),@GradeStringRemark nvarchar(1000)
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

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

	SELECT 			 
			Convert(nvarchar(20),SA.Id) AS AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
			@rBuilder1 AS Builder1,
			SA.Id AS AcademicId,
			SA.RollNo,
			StuM.Number,
			AIS.Grade,
			SAM.Title AS SubjectActivityTitle,
			SSA.Title AS SubjectSubActivityTitle,
			SAM.Id AS ActivityId,
			SSA.Id AS SubjectSubActivityId,
			SAM.OrderIndex AS ActivityOrderIndex,
			SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade, 
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
			EM.IsDisplayGradeString,
			EM.IsDisplayParentName,
			[sStudent].[fStudentNameGet](StuM.FirstName , ISNULL(StuM.MiddleName,'') , StuM.LastName,OM.StudentNameFormatId ) AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			StuM.code,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto, 
			ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
			CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			CS.OrderIndex,
			EM.SubjectGroupPerPage,
			AIS.GradeIndicator,
			EM.IsCoScholasticGradeIndicator,
			CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EI.EmployeeSign ELSE NULL END AS EmployeeSign,
			Em.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsCoScholasticGradeDesIndicator,
			EM.IsCoScholasticGrade,
			Em.IsDisplayParentName,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			OI.MarksheetHeaderA4 
			ELSE 
			NULL END) AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
			--@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			TeacherSignCaption,
			EM.PrincipalSignCaption,
			ParentSignCaption,
			--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
			--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
			SR.ResultRemark1,
			SR.ResultRemark2,	
			SR.ResultRemark3,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			ISNULL(SR.PresentDays,0)AS PresentDays,			
			ISNULL(SR.TotalDays,0)AS TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			
			ISNULL(SR.MyGoal,'') AS MyGoal,
			ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
			ISNULL(SR.Responsibility,'') AS Responsibility,
			ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
			ISNULL(SR.MyStrength,'') AS MyStrength,
			ISNULL(SR.Achievements,'') AS Achievements,
			ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
			ISNULL(SR.VisionLeft,'') AS VisionLeft,
			ISNULL(SR.VisionRight,'') AS VisionRight,
			ISNULL(SR.ImprovementArea,'') As ImprovementArea,
			ISNULL(SR.ProgressArea,'') AS ProgressArea,
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			ISNULL(SR.MyActivity,'') AS MyActivity,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			DivisionId,
			SM.ID,
			( EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			CONVERT(bit,@DecimalConfid) AS IsDecimal,
			AIS.Marks,
			SR.ExamSeatNo AS ExamSeatNo,					--add for 27710 mantis
			[sAssessment].[fSubjectWiseGradeGet](SA.Id,@rExamId,SAM.Id,SAM.ClassSubjectId,@rBatchId,@rClass) AS SubjectGrade,
			ED.Maximum AS SubjectMaximum,
			ED.IsShowSubjectMark --Added by dhananjay for mantis id : 0035701

	 FROM 
			sAssessment.tCCESubjectSubActivityExamScore AIS 
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id 
			INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId		
			INNER JOIN sStudent.tAcademic SA ON SA.Id = AIS.AcademicId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = CS.Id 		 			 
			INNER JOIN sAssessment.tResult AR ON AR.ExamId = AIS.ExamId AND AIS.AcademicId = AR.AcademicId
			INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id AND ARD.ExamDetailId = ED.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId	
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=DM.ClassId 
			LEFT JOIN sHrm.tEmployeeMaster EmpM 
				ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.IsObsolete = 0
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.Id = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.Id AND EM.ID=RD.ExamId AND CS.Id=RD.ClassSubjectID 
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =StuM.ID
	    --LEFT JOIN @lAcademicId A ON A.AcademicId = SA.AcademicId AND A.ClassSubjectId = ED.ClassSubjectId
			----------------------------------------------------------------------------
			--sAssessment.tCCESubjectActivityMaster SAM 	
			--INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId 
			--INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			--INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			--INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CS.ClassId 
			--INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId			 
			--LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id 	
			--LEFT JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			--LEFT JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId	AND ED.ClassSubjectId = CS.ClassSubjectId 		 
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			--LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
			--INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId
			--LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			--LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			--LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId	AND EM.Id = SR.ExamId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			--LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.AcademicId AND EM.ID=RD.ExamId AND CS.ClassSubjectId=RD.ClassSubjectID 
		WHERE
			((SA.Id=@rAcademicId) OR(@rAcademicId=0))
			AND ((CS.ClassId=@rClass) OR (@rClass=0))
			And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
			And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
			and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			And AIS.ExamId=@rExamId
			AND ((STum.Code = @rCode) OR(@rCode=''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND StuM.StatusId = 1
			AND (ISNULL(STum.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
			AND SAM.IsObsolete = 0
		ORDER BY 
			SA.RollNo ASC,
			SAM.OrderIndex ASC,
			SSA.OrderIndex ASC;
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetStandardGet]...';


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

BEGIN 

DECLARE @GradeString nvarchar(1000),  @GradeStringRemark nvarchar(500),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

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

--add for 28663 mantis start
DECLARE @lAbsentRemarkConfig nvarchar(20) = ''
SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId
--add for 28663 mantis end
 
	SELECT 
	R.examId,
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		ESGM.Title AS Exam,
		StuM.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		R.AcademicId,			
		R.ResultStatus,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,
		R.Percentile,			
		RD.Id AS ResultDetailId,		
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		RD.Obtain AS SubjectObtain,
		ED.Minimum AS SubjectMinimum,
		ED.Maximum AS SubjectMaximum,
		RD.SubjectGrade,
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		R.Id AS ResultId,
		CS.Id AS SubjectId,			 	
		EM.IsMarksInDecimal,
		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsMarksInDecimal,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		--ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END) AS StudentPhoto,
		RD.IsPresent,
		CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,			
		OM.SmallAddress1,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
		
		EM.IsDisplayTeacherSign,
		Em.IsDisplayPrincipalSign,
		(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
		ELSE NULL END)AS EmployeeSign,
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		--(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		--	OI.CertificateHeaderA4 
		--ELSE 
		--	NULL END) AS MarksheetHeaderA4,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		
		SR.StudentHeight,
		SR.StudentWeight,		
		SR.PresentDays,			
		SR.TotalDays,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.Resultremark3,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		BM.Title AS BatchName,
		Em.DecimalFormat,
		RD.GraceMark,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(BGM.Title,'') AS BloodGroup,
		GS.GradeTitle,
		GS.GradePoint,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		RD.KrupaMark,
		RD.Remark AS OtherDetailRemark,
		ISNULL(SO.AdhaarNumber,'') AS AdharNumber,
		ISNULL(SO.UIDNumber,'') AS UIDNumber,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		(CASE  When EM.IsDisplayAbsentCount=1 then ([sAssessment].[fGetAbsentCount](@rExamId,R.AcademicId, CS.Id)) ELSE 0 END) AS AbsentCount,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = 20438 AND OrgId=A.OrgId),0) AS ReportTemplate,
		StuM.SUId As SUID,
		ISNULL(SO.MotherTongue,'') as MotherTongue,
		CONVERT(bit,@DecimalConfigid) AS IsDecimal,
		ISNULL(Stum.RegistrationNumber,'') as RegistrationNumber,
		EM.IsDisplayHighestDivisionMark,
		EM.ResultSheetAdditionalTitle,
		SR.ExamSeatNo,
		ISNULL(R.ResultIndicator,'') AS ResultIndicator,
		CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,	--add for 28663 mantis
		ISNULL(RD.AbsentRemark,'') AS AbsentRemark,				--add for 28663 mantis
		ISNUll(SF.FatherContactNo,'') AS FatherContactNo,		--Mantis - 0033000
		ISNUll(SF.MotherContactNo,'') AS MotherContactNo,		--Mantis - 0033000
		ISNUll(ED.ExamTopic,'') AS ExamTopic        --Mantis : 0035823

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


GO

ALTER PROCEDURE [sAssessment].[pRptProgressCardGet]	 	 
	 @rClassId int,
	 @rBatchId int,
	 @rDivisionId int,	 
	 @rClassSubjectIdStr nvarchar(max),
	 @rExamGroupIdStr nvarchar(max),
	 @rFromDate Date='',
	 @rToDate Date='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rAcadedmidId bigint=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

-- Select * from dbo.TempTableForProgress
	--SELECT 
	--	Convert(BigInt,0) AS AcademicId,
	--	Convert(date,'') AS ExamDate,
	--	Convert(Decimal,0) AS Maximum,
	--	Convert(Decimal,0) AS Obtain,
	--	Convert(Decimal,0) AS Percentage,
	--	'' AS ExamTopic,
	--	'' AS SubjectName,
	--	'' AS ExamGroup,
	--	Convert(varbinary,0) AS StudentPhoto,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	'' AS StudentName,
	--	0 AS RollNo,
	--    Convert(bit,0) AS IsMarksInDecimal,
	--	'' AS Year,
	--	'' AS MonthFrom,
	--	'' AS MonthTo,
	--	'' AS Code,
	--	'' AS EXAMNAME,
	--	'' AS ResultStatus,
	--	Convert(bit,0) As IsPresent,
	--  Convert(decimal,0) AS TotalObtainSubWise,
	--  Convert(decimal,0) AS TotalMarkSubWise,
	--  Convert(decimal,0) AS PercentageSubWise,
	--	Convert(bit,0) IsIncludeInTotal, --mantis - 35312
	--	'' As DecimalFormat, --mantis - 35312
	--	'' AS ExamSeatNo, --mantis - 35312
	--  0 AS ExamSubGroupOrderIndex, --Added by dhananjay for mantis Start -35688
	--  '' As DepartmentName, --Added by dhananjay for mantis End -35688
	-- '' ExamNameTitle
		

	CREATE TABLE #tempProgressCard
	(
		Id int Identity,
		AcademicId Bigint,
		ClassSubjectId bigint,
		ExamDate Date,
		Obtain Decimal(6,2),
		Maximum Decimal(6,2),
		Percentage Decimal(6,2),
		ExamId int,
		IsPresent bit
		
	)
 
 DECLARE @query  AS NVARCHAR(MAX)
 set @query = 'INSERT INTO #tempProgressCard 
 SELECT	R.AcademicId,ED.ClassSubjectId,ED.ExamDate ,SUM(RD.Obtain) AS Obtain,SUM(ED.Maximum) AS Maximum,
 (SUM(RD.Obtain)/SUM(ED.Maximum))*100 AS PERCENTAGE,ED.ExamId,RD.IsPresent
FROM sAssessment.tExamMaster EM INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id
INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id AND ED.Id = RD.ExamDetailId
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = ESGM.ExamGroupId
INNER JOIN sStudent.tAcademic AM ON AM.Id = R.AcademicId
WHERE EM.ClassId =' + CONVERT(NVARCHAR,@rClassId) + '
 

AND AM.DivisionId = ' + CONVERT(NVARCHAR(500),@rDivisionId) + '
AND EGM.Id IN (' + CONVERT(NVARCHAR(500),@rExamGroupIdStr) + ')
AND ED.ClassSubjectId IN (' + CONVERT(NVARCHAR(500),@rClassSubjectIdStr) + ')
AND ED.EXAMDATE >= ''' + CONVERT(NVARCHAR,@rFromDate) +
''' AND ED.EXAMDATE <= ''' + CONVERT(NVARCHAR,@rToDate) +
''' AND ((AM.RollNo >= '''+ CONVERT(NVARCHAR(10),@rFromRollNo)+''') OR (' + CONVERT(NVARCHAR(10),@rFromRollNo)+'='''+ CONVERT(NVARCHAR(10),0) + ''')) 
AND ((AM.RollNo <= '''+ CONVERT(NVARCHAR(10),@rToRollNo) + ''' ) OR (' + CONVERT(NVARCHAR(10),@rToRollNo)+'='''+ CONVERT(NVARCHAR(10),0) + ''')) 
AND ((AM.Id = '''+ CONVERT(NVARCHAR(20),@rAcadedmidId) + ''' ) OR (' + CONVERT(NVARCHAR(20),@rAcadedmidId)+'='''+ CONVERT(NVARCHAR(20),0) + ''')) 
GROUP BY R.AcademicId,ED.ClassSubjectId,ED.ExamDate,ED.ExamId,RD.IsPresent'
-- Remove RD.IsPresent = 1 Condition from @query (As requirement Absent and present students data should be visibled) Mantis :0027445
 --print @query
execute(@query)

-- To maintain Group Footer length add in report row	
--select 1, '.' + replicate('`', 600)  + '.'   font size 1

SELECT
T.AcademicId,
T.ExamDate,
T.Maximum,T.Obtain,T.Percentage,
CASE WHEN ED.ExamTopic = '0' THEN '' ELSE ED.ExamTopic  END AS ExamTopic,
CS.SubjectName AS SubjectName,
EGM.Title AS ExamGroup,
SF.StudentPhoto as StudentPhoto , 
SF.ClassName,
SF.DivisionName,
SF.Name AS StudentName,SF.RollNo, 
EM.IsMarksInDecimal,
SF.Code,
sCommon.fGetMonthName(DatePart(MM,@rFromDate)) AS MonthFrom,
sCommon.fGetMonthName(DatePart(MM,@rToDate)) AS MonthTo,
BM.Title AS Year,
ISNULL(ESGM.Title,'') AS EXAMNAME ,
(Select ResultStatus FROM sAssessment.tResult Where AcademicId = T.AcademicId AND  ExamId = EM.Id)AS ResultStatus,
T.IsPresent,
-- Mantis Start - 35312
(SELECT SUM(T2.Obtain)
     FROM #tempProgressCard T2
     WHERE T2.AcademicId = T.AcademicId
       AND T2.ClassSubjectId = T.ClassSubjectId
 ) AS TotalObtainSubWise,
 (SELECT SUM(T2.Maximum)
     FROM #tempProgressCard T2
     WHERE T2.AcademicId = T.AcademicId
       AND T2.ClassSubjectId = T.ClassSubjectId
 ) AS TotalMarkSubWise,
 (SELECT (SUM(T2.Obtain) * 100) / SUM(T2.Maximum)
     FROM #tempProgressCard T2
     WHERE T2.AcademicId = T.AcademicId
       AND T2.ClassSubjectId = T.ClassSubjectId
 ) AS PercentageSubWise,
 ISNULL(ED.IsIncludeInTotal,0) AS IsIncludeInTotal, 
ISNULL(Em.DecimalFormat,'') AS DecimalFormat,
ISNULL(AD.ExamSeatNo,'') AS ExamSeatNo, 
	--Mantis End - 35312
	--Added by dhananjay for mantis Start -35688
	ESGM.OrderIndex AS ExamSubGroupOrderIndex,
	DM.Title As DepartmentName,
	--Added by dhananjay for mantis End -35688
	ISNULL(EM.DisplayTitle,'') AS ExamNameTitle



FROM #tempProgressCard T 
INNER JOIN sAssessment.tExamMaster EM on EM.Id=T.ExamId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = T.ExamId AND EM.Id=ED.ExamId AND T.ExamDate = ED.ExamDate
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = ESGM.ExamGroupId
--INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id
INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = ED.ClassSubjectId AND CS.ClassSubjectId=T.ClassSubjectId 
INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId	= T.AcademicId AND SF.StatusId=1
INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SF.BatchId
LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId=EM.Id AND SR.AcademicId=T.AcademicId

INNER JOIN sSetup.tDepartmentMaster DM ON  DM.id = SF.DepartmentId   --Added by dhananjay for mantis - 35688
LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = T.AcademicId
Order By SF.RollNo,CS.OrderIndex,T.ExamDate Desc



DROP TABLE #tempProgressCard

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


GO
ALTER PROCEDURE [sAccounting].[pAccountingYearMasterAdd] 
	@rId INT
	,@rCode NVARCHAR(20)
	,@rTitle NVARCHAR(100)
	,@rFromDate DATE
	,@rToDate DATE
	,@rCreatedUserId BIGINT
	,@rUpdatedUserId BIGINT
	,@rOrgGroupId INT
	,@rAccountId INT
	,@rIsLocked BIT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		IF EXISTS (
				SELECT Id
				FROM sAccounting.tAccountingYearMaster
				WHERE (Title = @rTitle AND AccountId = @rAccountId)
					OR (Code = @rCode AND AccountId = @rAccountId)
				)
		BEGIN
			SELECT - 103 AS Result
			RETURN
		END

		BEGIN TRANSACTION

		DECLARE @lCount INT
		DECLARE @lNextNumber INT
		DECLARE @1CurruntAccountingYearId INT
		DECLARE @1MaxLedgerGroupId INT
		DECLARE @1MaxLedgerId INT
		DECLARE @1Count INT
		DECLARE @1LedgerGroupId INT
		DECLARE @1LedgerGroupName NVARCHAR(200)
		DECLARE @1LedgerId INT

		SELECT @lCount = ISNULL(COUNT(Id), 0)
		FROM sAccounting.tAccountingYearMaster
		WHERE AccountId = @rAccountId

		CREATE TABLE #TempLedgerGroupMaster (
			Id BIGINT identity
			,LedgerGroupName NVARCHAR(100)
			,LedgerId INT
			,LedgerGroupId INT
			)

		IF @lCount >= 1 --- If any year created get old ledger and Ledger group accordingly
		BEGIN
			SELECT @1CurruntAccountingYearId = MAX(Id)
			FROM sAccounting.tAccountingYearMaster
			WHERE OrgGroupId = @rOrgGroupId
				AND AccountId = @rAccountId

			SET @1CurruntAccountingYearId = ISNULL(@1CurruntAccountingYearId, 1)

			IF (@rId = 0)
			BEGIN
				--SELECT @1MaxLedgerGroupId =  sCommon.fGetIntIdForOrg(101,@rOrgGroupId)
				--SELECT @1MaxLedgerId = sCommon.fGetIntIdForOrg(101,@rOrgGroupId) 
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId
					,'sAccounting.tAccountingYearMaster'
					,0
					,1
					,1
					,@outNextNumber = @lNextNumber OUTPUT

				--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tAccountingYearMaster',@lNextNumber = @lNextNumber output
				INSERT INTO sAccounting.tAccountingYearMaster (
					Id
					,Code
					,Title
					,FromDate
					,ToDate
					,CreatedUserId
					,CreatedDateTime
					,AccountId
					,OrgGroupId
					,IsLocked
					)
				VALUES (
					@lNextNumber
					,@rCode
					,@rTitle
					,@rFromDate
					,@rToDate
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rAccountId
					,@rOrgGroupId
					,@rIsLocked
					)

				--END 
				INSERT INTO sAccounting.tLedgerGroupMaster
				SELECT CASE 
						WHEN @1CurruntAccountingYearId = 1
							THEN sCommon.fGetIntIdForOrg(Id, @rOrgGroupId)
						ELSE Id
						END
					,Code
					,Title
					,IsObsolete
					,LedgerMainGroupId
					,@lNextNumber
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rAccountId
					,@rOrgGroupId
				FROM sAccounting.tLedgerGroupMaster
				WHERE AccountingYearId = @1CurruntAccountingYearId

				--SELECT @1MaxLedgerGroupId = MAX(Id)  from sAccounting.tLedgerGroupMaster Where AccountingYearId = @lNextNumber
				INSERT INTO #TempLedgerGroupMaster
				SELECT LGM.Title
					,l.Id
					,LedgerGroupId AS LedgerGroup
				FROM sAccounting.tLedgerMaster l
				INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = l.LedgerGroupId
					AND lgm.AccountingYearId = @1CurruntAccountingYearId
				WHERE l.AccountingYearId = @1CurruntAccountingYearId
				ORDER BY l.Id DESC

				SELECT @1Count = COUNT(*)
				FROM #TempLedgerGroupMaster

				WHILE (@1Count > 0)
				BEGIN
					SELECT @1LedgerGroupName = LedgerGroupName
						,@1LedgerId = LedgerId
					FROM #TempLedgerGroupMaster
					WHERE Id = @1Count

					SELECT @1LedgerGroupId = Id
					FROM sAccounting.tLedgerGroupMaster
					WHERE Title = @1LedgerGroupName
						AND AccountingYearId = @lNextNumber

					INSERT INTO sAccounting.tLedgerMaster
					SELECT CASE 
							WHEN @1CurruntAccountingYearId = 1
								THEN sCommon.fGetIntIdForOrg(Id, @rOrgGroupId)
							ELSE Id
							END
						--@1MaxLedgerId + ROW_NUMBER() over(Order by Id asc)
						,Code
						,Title
						,IsObsolete
						,@1LedgerGroupId
						,0.00
						,LedgerTypeId
						,@lNextNumber
						,@rCreatedUserId
						,sCommon.fGetDate()
						,@rCreatedUserId
						,sCommon.fGetDate()
						,@rOrgGroupId
						,1 -- Added 1 for mantis 0035985 by Foram
					FROM sAccounting.tLedgerMaster
					WHERE AccountingYearId = @1CurruntAccountingYearId
						AND Id = @1LedgerId

					SET @1Count = @1Count - 1;
				END

				SELECT 1 AS RESULT
			END
			ELSE
			BEGIN
				SET @lNextNumber = @rId

				UPDATE sAccounting.tAccountingYearMaster
				SET Code = @rCode
					,Title = @rTitle
					,FromDate = @rFromDate
					,AccountId = @rAccountId
					,ToDate = @rToDate
					,UpdatedUserId = @rUpdatedUserId
					,UpdatedDateTime = sCommon.fGetDate()
					,IsLocked = @rIsLocked
				WHERE Id = @rId
			END

			SELECT @lNextNumber AS Result
		END
		ELSE --- If any year not created get old ledger and Ledger group from default
		BEGIN
			IF (@rId = 0)
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId
					,'sAccounting.tAccountingYearMaster'
					,0
					,1
					,1
					,@outNextNumber = @lNextNumber OUTPUT

				--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tAccountingYearMaster',@lNextNumber = @lNextNumber output
				INSERT INTO sAccounting.tAccountingYearMaster (
					Id
					,Code
					,Title
					,FromDate
					,ToDate
					,CreatedUserId
					,CreatedDateTime
					,AccountId
					,OrgGroupId
					,IsLocked
					)
				VALUES (
					@lNextNumber
					,@rCode
					,@rTitle
					,@rFromDate
					,@rToDate
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rAccountId
					,@rOrgGroupId
					,@rIsLocked
					)

				INSERT INTO sAccounting.tLedgerGroupMaster
				SELECT sCommon.fGetIntIdForOrg(Id, @rOrgGroupId)
					,Code
					,Title
					,IsObsolete
					,LedgerMainGroupId
					,@lNextNumber
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rAccountId
					,@rOrgGroupId
				FROM sAccounting.tLedgerGroupMaster
				WHERE OrgGroupId = 1
					AND AccountId = 1
					AND AccountingYearId = 1

				INSERT INTO sAccounting.tLedgerMaster
				SELECT sCommon.fGetIntIdForOrg(Id, @rOrgGroupId)
					,Code
					,Title
					,IsObsolete
					,sCommon.fGetIntIdForOrg(Id, @rOrgGroupId)
					,0.00
					,LedgerTypeId
					,@lNextNumber
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rCreatedUserId
					,sCommon.fGetDate()
					,@rOrgGroupId
					,1 -- Added 1 for mantis 0035985 by Foram
				FROM sAccounting.tLedgerMaster
				WHERE AccountingYearId = 1
					AND OrgGroupId = 1

				SELECT 1 AS RESULT
			END
			ELSE
			BEGIN
				SET @lNextNumber = @rId

				UPDATE sAccounting.tAccountingYearMaster
				SET Code = @rCode
					,Title = @rTitle
					,FromDate = @rFromDate
					,AccountId = @rAccountId
					,ToDate = @rToDate
					,UpdatedUserId = @rUpdatedUserId
					,UpdatedDateTime = sCommon.fGetDate()
					,IsLocked = @rIsLocked
				WHERE Id = @rId
			END

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


GO


ALTER PROCEDURE [sActivity].[pEventAssignGet]
	 @rEventScheduleId int,
	 @rOrgId smallint,
	 @rBatchId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
		
	SELECT 
			DM.Id  as SourceId,
			CM.Title+'-'+DM.Title as DivDept,
			2005 as SourceTypeId,
			CASE WHEN EA.SourceId IS NULL OR EA.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END AS IsObsolete,
			CM.OrderIndex AS OrderIndex,
			DM.OrderIndex AS DivisionOrderIndex --Added for mantis : 35121 by Nilesh
  FROM 
			sSetup.tDivisionMaster DM
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId --Commented for mantis : 35121 by Nilesh
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND DM.IsObsolete = 0 --Added for mantis : 35121 by Nilesh
			INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId AND BC.BatchId=@rBatchId
			LEFT JOIN sActivity.tEventAssign EA ON EA.SourceId=DM.Id AND EA.SourceTypeId=2005 AND EA.EventScheduleId=@rEventScheduleId
	 WHERE
		DM.OrgId=@rOrgId
		UNION
	SELECT 
			ODM.Id  as SourceId,
			ODM.Title as DivDept,
			2004 as SourceTypeId,
			CASE WHEN EA.SourceId IS NULL OR EA.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END AS IsObsolete,
			0 AS OrderIndex,
			0 AS DivisionOrderIndex --Added for mantis : 35121 by Nilesh
  FROM 
			sSetup.tDepartmentMaster ODM
			LEFT JOIN sActivity.tEventAssign EA ON EA.SourceId=ODM.Id AND EA.SourceTypeId=2004 AND EA.EventScheduleId=@rEventScheduleId
	WHERE
		ODM.OrgId=@rOrgId
		UNION 
	SELECT 
			EC.EmployeeId  as SourceId,
			EC.EmployeeName as DivDept,
			95 as SourceTypeId,
			CASE WHEN EA.SourceId IS NULL OR EA.EventScheduleId!=@rEventScheduleId THEN 0 ELSE 1 END AS IsObsolete,
			0 AS OrderIndex,
			0 AS DivisionOrderIndex --Added for mantis : 35121 by Nilesh
  FROM 
			sHrm.vEmployeeCommunication EC
			LEFT JOIN sActivity.tEventAssign EA ON EA.SourceId=EC.Id AND EA.SourceTypeId=95 AND EA.EventScheduleId=@rEventScheduleId
	WHERE
		EC.OrgId=@rOrgId 
		Order By OrderIndex,DivisionOrderIndex --Added for mantis : 35121 by Nilesh
END
GO
PRINT N'Altering Procedure [sAdmission].[pRptAdmissionReceiptGet]...';


GO


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


GO


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

Select 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			A.Id AS AcademicId,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
			A.RollNo,
			SF.FatherContactNo AS MobileNo,			 
			'Father' AS CategoryName,
			SF.FatherName AS PersonName,
			SF.FatherDateOfBirth AS DateOfBirth,
			MONTH(SF.FatherDateOfBirth),
			SI.FatherPhoto AS Photo,
			 CM.DisplayTitle+' '+DM.DisplayTitle AS ClassName
	From 
			--sStudent.vStudentAllDetail SC
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sStudent.tStudentFamily SF ON SC.StudentId = SF.StudentId
	WHERE
			((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (A.OrgId=@rOrgId)
			AND (A.BatchId=@rBatchId)
			--AND (DAY(SF.FatherDateOfBirth) = DAY(@rDateOfBirth))
			AND  (@rDayOfBirth = 0)
			AND ((MONTH(SF.FatherDateOfBirth) = @rDateOfBirth) OR (@rDateOfBirth=0))
			AND ((SM.StatusId= @rStatusId) OR(@rStatusId = 0))--Changed For mantis : 35958 by Nilesh		
			AND(@rFather=1)
			AND SF.FatherDateOfBirth != ''
			AND (A.ClassStatusId=@rClassStatusId OR  ISNULL(A.ClassStatusId,0)=0 OR @rClassStatusId=0)
			/****Added for mantis : 35770 by Nilesh****/
			AND((SF.FatherDateOfBirth>=@rFromBirthDayDate) OR (ISNULL(@rFromBirthDayDate,'')=''))		
			AND((SF.FatherDateOfBirth<=@rToBirthDayDate) OR (ISNULL(@rToBirthDayDate,'')=''))
			--Added For mantis : 35958 by Nilesh
			AND((SM.Code = @rStrCode)OR(ISNULL(@rStrCode,'')=''))  
			AND((A.RollNo>=@rFromRollNo) OR (ISNULL(@rFromRollNo,'')=''))		
			AND((A.RollNo<=@rToRollNo) OR (ISNULL(@rToRollNo,'')=''))
			AND ((A.StudentId= @rStudentId) OR(@rStudentId = 0))
	
	UNION ALL

	Select 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,			
			A.Id AS AcademicId,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
			A.RollNo,
			SF.MotherContactNo AS MobileNo,			 
			'Mother' AS CategoryName,
			SF.MotherName AS PersonName,
			SF.MotherDateOfBirth AS DateOfBirth,
			MONTH(SF.MotherDateOfBirth),
			ISNULL(SI.MotherPhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassName
	From 
			--sStudent.vStudentAllDetail SC
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sStudent.tStudentFamily SF ON SC.StudentId = SF.StudentId
	WHERE
			((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (A.OrgId=@rOrgId)
			AND (A.BatchId=@rBatchId)
			--AND (DAY(SF.MotherDateOfBirth) = DAY(@rDateOfBirth))
			AND  (@rDayOfBirth = 0)
			AND  ((MONTH(SF.MotherDateOfBirth) = @rDateOfBirth) OR (@rDateOfBirth=0))
			AND ((SM.StatusId= @rStatusId) OR(@rStatusId = 0))--Changed For mantis : 35958 by Nilesh	
			AND(@rMother=1)
			AND SF.MotherDateOfBirth != ''	
			AND (A.ClassStatusId=@rClassStatusId OR  ISNULL(A.ClassStatusId,0)=0 OR @rClassStatusId=0)
			/****Added for mantis : 35770 by Nilesh****/
			AND((SF.MotherDateOfBirth>=@rFromBirthDayDate) OR (ISNULL(@rFromBirthDayDate,'')=''))		
			AND((SF.MotherDateOfBirth<=@rToBirthDayDate) OR (ISNULL(@rToBirthDayDate,'')=''))
			 --Added For mantis : 35958 by Nilesh
			AND((A.RollNo>=@rFromRollNo) OR (ISNULL(@rFromRollNo,'')=''))		
			AND((A.RollNo<=@rToRollNo) OR (ISNULL(@rToRollNo,'')=''))
			AND ((A.StudentId= @rStudentId) OR(@rStudentId = 0))
			AND((SM.Code = @rStrCode)OR(ISNULL(@rStrCode,'')=''))
	UNION ALL

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

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


GO
 

ALTER PROCEDURE [sAlert].[pResultWithDetailsGet]
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rExamId int,
	 	 @rSubjectId int=0,
		 @rIsSubjectInNewLine bit = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	Declare @lSubjectCode nvarchar(20)
	IF(@rSubjectId > 0)
		BEGIN
		Select @lSubjectCode = Code from sSetup.tSubjectMaster Where Id = @rSubjectId
		END
	ELSE
		BEGIN
		SET @lSubjectCode = 'All'
		END

	IF(@rIsSubjectInNewLine = 0)
	BEGIN
		Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ExamName]',ES.Title),
			'[SubjectMark]', CHAR(13) + ISNULL([sAlert].[fResultGet](R.Id,@rSubjectId,1),'')),
			'[SubjectMarkWithMax]',ISNULL([sAlert].[fResultWithMaxGet](R.Id,@rSubjectId),'')),
			'[TotalMarks]',CONVERT(int,TotalMarks)),
			'[ObtainMarks]',CONVERT(int,TotalObtain)),
			'[ResultStatus]',R.ResultStatus),
			'[ResultGrade]',R.ResultGrade),
			'[ResultGradePoint]',R.ResultGradePoint),
			'[RankNumber]',R.RankNumber),
			'[Percentage]',R.Percentage),
			'[SubjectGrade]',ISNULL([sAlert].[fResultGet](R.Id,@rSubjectId,2),'')),
			'[Percentile]',R.Percentile),
			'[Subject]',ISNULL(@lSubjectCode,''))			-- MantisId : 0035349
			
			 AS Template,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 ES.Title AS ExamName,
			 CONVERT(int,TotalMarks) AS TotalMarks,
			 CONVERT(int,TotalObtain) AS ObtainMarks,
			 R.ResultStatus AS ResultStatus,
			 R.ResultGrade AS ResultGrade,
			 R.ResultGradePoint AS ResultGradePoint,
			 R.RankNumber AS RankNumber,
			 R.Percentage AS Percentage,
			 R.Percentile AS Percentile,
			 [sAlert].[fResultGet](R.Id,@rSubjectId,2) AS SubjectGrade,
			 [sAlert].[fResultWithMaxGet](R.Id,@rSubjectId) AS SubjectMarkWithMax,
			 SC.WhatsAppContactNo
		
	From 
	sStudent.vStudentCommunication SC
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SC.AcademicId AND (R.ExamId=@rExamId OR @rExamId=0)
	INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = E.ExamSubGroupId
	 
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))	 
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	ORDER BY SC.DivisionOrderIndex,SC.Rollno
	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 (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ExamName]',ES.Title),
			'[SubjectMark]',ISNULL([sAlert].[fResultGetWithLineBreak](R.Id,@rSubjectId,1),'')),
			'[SubjectMarkWithMax]',ISNULL([sAlert].[fResultWithMaxGetWithLineBreak](R.Id,@rSubjectId),'')),
			'[TotalMarks]',CONVERT(int,TotalMarks)),
			'[ObtainMarks]',CONVERT(int,TotalObtain)),
			'[ResultStatus]',R.ResultStatus),
			'[ResultGrade]',R.ResultGrade),
			'[ResultGradePoint]',R.ResultGradePoint),
			'[RankNumber]',R.RankNumber),
			'[Percentage]',R.Percentage),
			'[SubjectGrade]',ISNULL([sAlert].[fResultGetWithLineBreak](R.Id,@rSubjectId,2),'')),
			'[Percentile]',R.Percentile),
			'[Subject]',ISNULL(@lSubjectCode,''))			-- MantisId : 0035349
			
			 AS Template,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 ES.Title AS ExamName,
			 CONVERT(int,TotalMarks) AS TotalMarks,
			 CONVERT(int,TotalObtain) AS ObtainMarks,
			 R.ResultStatus AS ResultStatus,
			 R.ResultGrade AS ResultGrade,
			 R.ResultGradePoint AS ResultGradePoint,
			 R.RankNumber AS RankNumber,
			 R.Percentage AS Percentage,
			 R.Percentile AS Percentile,
			 [sAlert].[fResultGet](R.Id,@rSubjectId,2) AS SubjectGrade,
			 [sAlert].[fResultWithMaxGet](R.Id,@rSubjectId) AS SubjectMarkWithMax,
			 SC.WhatsAppContactNo
		
	From 
	sStudent.vStudentCommunication SC
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SC.AcademicId AND (R.ExamId=@rExamId OR @rExamId=0)
	INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = E.ExamSubGroupId
	 
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))	 
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	ORDER BY SC.DivisionOrderIndex,SC.Rollno
	END
END
GO
PRINT N'Altering Procedure [sAlert].[pResultWithSubjectGet]...';


GO


ALTER PROCEDURE [sAlert].[pResultWithSubjectGet]
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rExamId int,
	 	 @rSubjectId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Declare @lSubjectCode nvarchar(20)
	IF(@rSubjectId > 0)
		BEGIN
		Select @lSubjectCode = Code from sSetup.tSubjectMaster Where Id = @rSubjectId
		END
	ELSE
		BEGIN
		SET @lSubjectCode = 'All'
		END

	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 (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ExamName]',ES.Title),
			'[SubjectMark]', CHAR(13) + ISNULL([sAlert].[fResultGet](R.Id,@rSubjectId,1),'')),
			'[SubjectMarkWithMax]', ISNULL([sAlert].[fResultWithMaxGet](R.Id,@rSubjectId),'')),
			'[TotalMarks]',CONVERT(int,TotalMarks)),
			'[ObtainMarks]',CONVERT(int,TotalObtain)),
			'[ResultStatus]',R.ResultStatus),
			'[ResultGrade]',R.ResultGrade),
			'[ResultGradePoint]',R.ResultGradePoint),
			'[RankNumber]',R.RankNumber),
			'[Percentage]',R.Percentage),
			'[SubjectGrade]', ISNULL([sAlert].[fResultGet](R.Id,@rSubjectId,2),'')),
			'[Percentile]',R.Percentile),
			'[ExamTopic]',ISNULL(sAlert.fExamDetailGet(@rExamId,@rSubjectId,1),'')),
			'[ExamTime]',ISNULL(sAlert.fExamDetailGet(@rExamId,@rSubjectId,2),'')),
			'[ExamDate]',ISNULL(sAlert.fExamDetailGet(@rExamId,@rSubjectId,3),'')),
			'[HighestMark]',ISNULL([sAlert].[fHighestMarkGet](E.Id, @rSubjectId, @rDivisionId, @rClassId, @rBatchId),'')), --Added for Mantis : 35024 by Nilesh
			'[Subject]',ISNULL(@lSubjectCode,''))		-- MantisId : 0035349
			
			 AS Template,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 ES.Title AS ExamName,
			 CONVERT(int,TotalMarks) AS TotalMarks,
			 CONVERT(int,TotalObtain) AS ObtainMarks,
			 R.ResultStatus AS ResultStatus,
			 R.ResultGrade AS ResultGrade,
			 R.ResultGradePoint AS ResultGradePoint,
			 R.RankNumber AS RankNumber,
			 R.Percentage AS Percentage,
			 R.Percentile AS Percentile,
			 [sAlert].[fResultGet](R.Id,@rSubjectId,2) AS SubjectGrade,
			 [sAlert].[fResultWithMaxGet](R.Id,@rSubjectId) AS SubjectMarkWithMax,
			 SC.WhatsAppContactNo
		
	From 
	sStudent.vStudentCommunication SC
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SC.AcademicId AND (R.ExamId=@rExamId OR @rExamId=0)
	INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = E.ExamSubGroupId
	 
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))	 
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	ORDER BY SC.DivisionOrderIndex,SC.Rollno
END
GO
PRINT N'Altering Procedure [sAlert].[pStudentBiometricFirstInTimeGet]...';


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

	

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

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

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

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


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

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


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

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

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

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

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

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


GO
ALTER PROCEDURE [sAlert].[pStudentGatePassGet]
	
		 @rStudentGatePassId int,
	 	 @rAcademicId bigint,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			replace (		--add for mantis: 35426
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[EntryModeStatus]',SM.Title),
			'[GatePassDate]',CONVERT(varchar(11),ISNULL(SGP.GatePassDate,'') ,103)),
			'[GatePassTime]',CONVERT(varchar(15),ISNULL(SGP.GatePassTime,''),100)),
			'[ReasonOfGatePass]',SGP.ReasonOfGatePass),
			'[ReceivedBy]',SGP.VisitorName),
			'[Class]',SC.ClassName)		--add for mantis: 35426
			AS MsgText,
			'' AS Subject,
			 2001 AS ReceiverSourceTypeId,
			 SC.AcademicId AS ReceiverSourceId,
			 2001 AS SourceTypeId,
			 SC.AcademicId AS SourceId,
			 SM.Title AS EntryModeStatus,
			 CONVERT(varchar(11),ISNULL(SGP.GatePassDate,'') ,103) AS GatePassDate,
			 CONVERT(varchar(15),ISNULL(SGP.GatePassTime,''),100) AS GatePassTime,
			 SGP.ReasonOfGatePass AS ReasonOfGatePass,
			 SGP.VisitorName AS ReceivedBy,
			 SC.WhatsAppContactNo

	FROM 
		sStudent.vStudentCommunication SC
	INNER JOIN 	sFrontOffice.tStudentGatePass SGP ON SC.AcademicId = SGP.AcademicId
	INNER JOIN sCommon.tStatusMaster SM ON SM.Id = SGP.EntryModeStatusId
	WHERE
		SGP.Id=@rStudentGatePassId
		AND SC.AcademicId = @rAcademicId
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
END
GO
PRINT N'Altering Procedure [sAssessment].[pExamScheduleClassWiseGet]...';


GO
ALTER PROCEDURE [sAssessment].[pExamScheduleClassWiseGet]	 
	 @rOrgId int ,
	 @rBatchId int,	 
	 @rUserId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

	DECLARE @lEmployeeId bigint=0
	SELECT @lEmployeeId=SourceId FROM sSecurity.tUser WHERE Id=@rUserId

	DECLARE @lMarkEntryBasedOn nvarchar(50)=''
	SELECT @lMarkEntryBasedOn=ItemValue FROM [sConfig].[tConfigurationSetup] where ConfigurationId=188 and SourceId=@rOrgId

IF(@lMarkEntryBasedOn = 'Class Teacher' AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,		
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId= CM.Id
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 		
		AND (DM.InchargeemployeeID=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		CM.Id
END
ELSE IF(@lMarkEntryBasedOn = 'Class Teacher Batch'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,		
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId		
		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id 
		INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 		
		AND (DIE.EmployeeId=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		CM.Id
END
ELSE IF(@lMarkEntryBasedOn = 'Academic Setup'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,		
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id	
		INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = CM.Id AND vTSD.SubjectId = SM.Id 
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 		
		AND (vTSD.EmployeeId=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		CM.Id
END

ELSE IF(@lMarkEntryBasedOn = 'User Access'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,		
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id 
		INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND SourceTypeId = 2005
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 		
		AND (U.UserId=@rUserId OR ISNULL(@rUserId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		CM.Id
END
END
GO
PRINT N'Altering Procedure [sAssessment].[pExamScheduleDateWiseGet]...';


GO
ALTER PROCEDURE [sAssessment].[pExamScheduleDateWiseGet]	 
	 @rOrgId int ,
	 @rBatchId int,
	 @rExamDate Date,
	 @rUserId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

	DECLARE @lEmployeeId bigint=0
	SELECT @lEmployeeId=SourceId FROM sSecurity.tUser WHERE Id=@rUserId

	DECLARE @lMarkEntryBasedOn nvarchar(50)=''
	SELECT @lMarkEntryBasedOn=ItemValue FROM [sConfig].[tConfigurationSetup] where ConfigurationId=188 and SourceId=@rOrgId

IF(@lMarkEntryBasedOn = 'Class Teacher' AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,
		SM.Title AS SubjectName,
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId,				
		ISNULL(ED.ExamDate,'') as ExamDate,
		ISNULL(ED.ExamTime,'') as ExamTime,
		ISNULL(ED.ExamTopic,'') as ExamTopic		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON CM.Id = DM.ClassId
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 
		AND ((ED.ExamDate=@rExamDate) OR (ISNULL(@rExamDate,'')=''))
		AND (DM.InchargeemployeeID=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		ExamDate
END
ELSE IF(@lMarkEntryBasedOn = 'Class Teacher Batch'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,
		SM.Title AS SubjectName,
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId,				
		ISNULL(ED.ExamDate,'') as ExamDate,
		ISNULL(ED.ExamTime,'') as ExamTime,
		ISNULL(ED.ExamTopic,'') as ExamTopic		
		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON CM.Id = DM.ClassId
		INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 
		AND ((ED.ExamDate=@rExamDate) OR (ISNULL(@rExamDate,'')=''))
		AND (DIE.EmployeeId=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		ExamDate
END
ELSE IF(@lMarkEntryBasedOn = 'Academic Setup'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,
		SM.Title AS SubjectName,
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId,				
		ISNULL(ED.ExamDate,'') as ExamDate,
		ISNULL(ED.ExamTime,'') as ExamTime,
		ISNULL(ED.ExamTopic,'') as ExamTopic		
		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id	
		INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = CM.Id AND vTSD.SubjectId = SM.Id 
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 
		AND ((ED.ExamDate=@rExamDate) OR (ISNULL(@rExamDate,'')=''))
		AND (vTSD.EmployeeId=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		ExamDate
END

ELSE IF(@lMarkEntryBasedOn = 'User Access'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT DISTINCT		 
		EM.Id AS ExamId,
		SM.Title AS SubjectName,
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId,				
		ISNULL(ED.ExamDate,'') as ExamDate,
		ISNULL(ED.ExamTime,'') as ExamTime,
		ISNULL(ED.ExamTopic,'') as ExamTopic		
		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON CM.Id = DM.ClassId
		INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND SourceTypeId = 2005
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 
		AND ((ED.ExamDate=@rExamDate) OR (ISNULL(@rExamDate,'')=''))
		AND (U.UserId=@rUserId OR ISNULL(@rUserId,0)=0)
		AND EM.IsPublishExamSchedule = 1			-- MantisId : 0035503
	ORDER BY 
		ExamDate
END
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptBrightStudentAnalysisListSubjectWiseGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptBrightStudentAnalysisListSubjectWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rSubjectId int=0,
	 --@rFromPercentage decimal(5,2)=0,
	 --@rToPercentage decimal(5,2)=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass nvarchar(max)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0,
	 @rDepartmentId int = 0,
	 @rFromMark decimal (5,2)=0,
	 @rToMark decimal (5,2)=0,
	@rSubject nvarchar(max)='',--Added by dhananjay mantis id : 0035435
	 @rIsMultipleSubjects bit = 0  --Added by dhananjay mantis id : 0035435
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT r1.*
FROM
(	SELECT 	
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			ROW_NUMBER() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END  ORDER BY RD.Obtain DESC) rn,
			
			
			ESGM.Title AS Exam,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName  AS Name,
			
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			Sub.Title AS SubjectName,
			Sub.Id AS SubjectId,
			RD.Obtain ,
			R.TotalMarks,
			ED.Maximum,
			RD.SubjectGrade,
			@rIsMultipleSubjects AS IsMultipleSubjects--Added by dhananjay mantis id : 0035435
			  
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId		
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId =R.Id	
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId=A.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id 
			INNER JOIN sSetup.tSubjectMaster SUB ON CS.SubjectId =  SUB.Id
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		--AND SUB.Id=@rSubjectId
		AND (SUB.Id=@rSubjectId OR @rSubjectId=0) --Added by dhananjay mantis id : 0035435
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		AND ((Dept.Id = @rDepartmentId) OR (@rDepartmentId =0))
		AND ((RD.Obtain >= @rFromMark) OR (@rFromMark=0))
		AND ((RD.Obtain <= @rToMark) OR (@rToMark=0))
		AND (ISNULL(SUB.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')--Added by dhananjay mantis id : 0035435
	)r1
	WHERE ((r1.rn <= @rTop) Or (@rTop = 0))
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetCoScholasticSubCombineNewGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultSheetCoScholasticSubCombineNewGet]
	
	@rAcademicId bigint,
	@rExamId bigint ,
	@rCoScholasticScopeId int=0,
	@rBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE
	@lIsCoScholasticGrade	bit,
	@lIsCoScholasticGradeIndicator bit, 
	@lIsCoScholasticGradeDesIndicator bit,
	@lIsCoScholasticCombine bit,
	@lCoScholasticTitle nvarchar(150)	 	 


	SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,
	@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,
	@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator,
	@lIsCoScholasticCombine = IsCoScholasticCombine,
	@lCoScholasticTitle = CoScholasticTitle
	FROM sAssessment.tExamMaster WHERE Id = @rExamId
 
	IF OBJECT_ID('tempdb..#CoScholasticTempTable') IS NOT NULL
		BEGIN
			DROP TABLE #CoScholasticTempTable;
		END

	IF OBJECT_ID('tempdb..#SubExamIdTemp') IS NOT NULL
		BEGIN
			DROP TABLE #SubExamIdTemp;
		END

	CREATE TABLE #SubExamIdTemp
	(
		Id int Identity(1,1),
		ExamId int,
		SubExamId int
	)

	INSERT INTO #SubExamIdTemp
	(ExamId, SubExamId)
		SELECT @rExamId, SubExamId FROM sAssessment.tExamCombine
		WHERE ExamId = @rExamId Order by ExamOrder


	CREATE TABLE #CoScholasticTempTable(
	ExamIdText nvarchar(20),
	AcademicIdText nvarchar(20),
	BatchIdText nvarchar(20),
	AcademicId BigInt,
	ExamId Int,
	CCECSId Int,
	CoScholasticScopeIdText nvarchar(20),
	CoSubject nvarchar(100),
	CoSubjectGroup nvarchar(100),
	CoSubjectGroupOrder SmallInt,
	CoSubjectOrder SmallInt,
	ExamTerm1 nvarchar(100),
	ExamTerm2 nvarchar(100),
	ExamTerm3 nvarchar(100),
	ExamTerm4 nvarchar(100),
	Grade1 nvarchar(10),
	Grade2 nvarchar(10),
	Grade3 nvarchar(10),
	Grade4 nvarchar(10),
	GradeIndicator1 nvarchar(50),
	GradeIndicator2 nvarchar(50),
	GradeIndicator3 nvarchar(50),
	GradeIndicator4 nvarchar(50),
	DescriptiveIndicator1 nvarchar(max),
	DescriptiveIndicator2 nvarchar(max),
	DescriptiveIndicator3 nvarchar(max),
	DescriptiveIndicator4 nvarchar(max),
	IsCoScholasticGrade bit,
	IsCoScholasticGradeIndicator bit,
	IsCoScholasticGradeDesIndicator bit,
	GroupTypeId tinyInt,
	GroupType nvarchar(100),
	ExamTerm nvarchar(100),
	CoScholasticTitle nvarchar(150)
	)

	INSERT INTO #CoScholasticTempTable
	(
	ExamIdText,
	AcademicIdText,
	BatchIdText,
	AcademicId,
	ExamId,
	CCECSId,
	CoSubject,
	CoSubjectGroup,
	CoSubjectGroupOrder,
	CoSubjectOrder,
	CoScholasticScopeIdText,
	IsCoScholasticGrade,
	IsCoScholasticGradeIndicator,
	IsCoScholasticGradeDesIndicator,
	CoScholasticTitle,
	GroupTypeId,
	GroupType
	)

	SELECT
		DISTINCT
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,
		Convert(nvarchar(20),@rBatchId) AS   BatchIdText,
		@rAcademicId AS AcademicId,
		@rExamId AS ExamId,
		cceCSM.Id AS CCECSId,
		cceCSM.Title AS CoSubject,
		cceCSGM.Title AS CoSubjectGroup,
		cceCSGM.OrderIndex AS CoSubjectGroupOrder,
		cceCSM.OrderIndex AS CoSubjectOrder,
		Convert(nvarchar(20), @rCoScholasticScopeId ) AS CoScholasticScopeIdText,
		@lIsCoScholasticGrade AS IsCoScholasticGrade,
		@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
		@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
		ISNULL(@lCoScholasticTitle,'') AS CoScholasticTitle,
		cceCST.Id AS GroupTypeId,
		cceCST.Title AS GroupType
	FROM 
		sAssessment.tCCECSExamScore cceCSS		 
		INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
		INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
		INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
		INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
		INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
		INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
		INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = EM.ClassId AND cceCSM.Id = FC.CCECSId AND FC.BatchId = @rBatchId
		LEFT JOIN sAssessment.tOptionalCCECS OCS ON OCS.AcademicId = cceCSS.AcademicId AND OCS.CCECSId = cceCSS.CCECSId	
	WHERE
		cceCSS.ExamId IN (SELECT SubExamId FROM #SubExamIdTemp)     
		AND cceCSS.AcademicId=@rAcademicId
		AND CCC.BatchID=@rBatchId
		AND (FC.IsOptional = 0 OR (FC.IsOptional = 1 AND OCS.AcademicId IS NOT NULL))

	--SELECT * FROM #CoScholasticTempTable

	DECLARE @lCount SmallInt, @query NVarchar(Max), @lSubExamId Int
	SELECT @lCount = MAX(Id) FROM #SubExamIdTemp
	WHILE (@lCount > 0)
	BEGIN
		SELECT @lSubExamId = SubExamId FROM #SubExamIdTemp WHERE Id = @lCount

		SET @query ='update T SET
		Grade'  + convert(nvarchar(15),@lCount)+ '= cceCSS.Grade,
		GradeIndicator'  + convert(nvarchar(15),@lCount)+ '= cceCSS.GradeIndicator,
		DescriptiveIndicator'  + convert(nvarchar(15),@lCount)+ '= cceCSS.DescriptiveIndicator,
		ExamTerm'  + convert(nvarchar(15),@lCount)+ '= ESM.Title
		FROM 
		sAssessment.tCCECSExamScore cceCSS	
		INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
		INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
		INNER JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
		INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
		INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
		INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
		INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = EM.ClassId AND cceCSM.Id = FC.CCECSId AND FC.BatchId =' + convert(nvarchar(15),@rBatchId)+ '
		LEFT JOIN sAssessment.tOptionalCCECS OCS ON OCS.AcademicId = cceCSS.AcademicId AND OCS.CCECSId = cceCSS.CCECSId
		INNER JOIN #CoScholasticTempTable T ON T.AcademicId = A.Id AND cceCSS.CCECSId = T.CCECSId 

		WHERE		     
		cceCSS.AcademicId=' + convert(nvarchar(20),@rAcademicId) + '
		AND CCC.BatchID=' + convert(nvarchar(15),@rBatchId)+ '
		AND (FC.IsOptional = 0 OR (FC.IsOptional = 1 AND OCS.AcademicId IS NOT NULL))
		AND ISNULL(cceCSS.ExamId,0) ='  + convert(nvarchar(15), @lSubExamId)
		EXECUTE (@query)
		--PRINT @query

		SET @lCount = @lCount - 1
	END

	SELECT * FROM #CoScholasticTempTable


	--For SP Drag and Drop in Dataset
	--SELECT
	--'' AS ExamIdText,
	--'' AS AcademicIdText,
	--'' AS BatchIdText,
	--Convert(BigInt,0) AS AcademicId,
	--0 AS ExamId,
	--'' AS CoScholasticScopeIdText,
	--'' AS CoSubject,
	--'' AS CoSubjectGroup,
	--0 AS CoSubjectGroupOrder,
	--0 AS CoSubjectOrder,
	--'' AS ExamTerm1,
	--'' AS ExamTerm2,
	--'' AS ExamTerm3,
	--'' AS ExamTerm4,
	--'' AS Grade1,
	--'' AS Grade2,
	--'' AS Grade3,
	--'' AS Grade4,
	--'' AS GradeIndicator1,
	--'' AS GradeIndicator2,
	--'' AS GradeIndicator3,
	--'' AS GradeIndicator4,
	--'' AS DescriptiveIndicator1,
	--'' AS DescriptiveIndicator2,
	--'' AS DescriptiveIndicator3,
	--'' AS DescriptiveIndicator4,
	--Convert(bit,0) AS IsCoScholasticGrade,
	--Convert(bit,0) AS IsCoScholasticGradeIndicator,
	--Convert(bit,0) AS IsCoScholasticGradeDesIndicator,
	--Convert(tinyInt,0) AS GroupTypeId,
	--'' AS GroupType,
	--'' AS ExamTerm,
	--'' AS CoScholasticTitle

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


GO

ALTER PROCEDURE [sAssessment].[pStudentResultRemarkGet]
	 
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rBatchId int,
	 @rIsBlank bit,
	 @rStatusId int,
	 @rOrderBy int,
	 @rExamId int,
	 @rDepartmentId int =0	
	 
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1),@lOrderBy nvarchar(10)
		if(@rOrderBy=1)
		BEGIN
		  SET @lOrderBy='RollNo';
		END
		ELSE if(@rOrderBy=2)
		BEGIN 
		 SET @lOrderBy='Code';
		END
		ELSE if(@rOrderBy=3)
		BEGIN 
		 SET @lOrderBy='FirstName';
		END
		ELSE if(@rOrderBy=4)
		BEGIN 
		 SET @lOrderBy='MiddleName';
		END
		ELSE if(@rOrderBy=5)
		BEGIN 
		 SET @lOrderBy='LastName';
		END

		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		
		--IF(@rSubCategory = 'Gender' OR @rSubCategory = 'Religion' OR @rSubCategory = 'BloodGroup' 
		--	OR @rSubCategory = 'CastCategory' OR @rSubCategory = 'TransportMode' OR @rSubCategory = 'House'
		--	OR @rSubCategory = 'MotherTongue' OR @rSubCategory = 'Nationality' OR @rSubCategory = 'AdmissionStandard' OR  @rSubCategory = 'AdmissionCategory'
		--	)
		--BEGIN
		--	SET @rSubCategory = @rSubCategory + 'Id'
		--END
		 Declare @Sql nvarchar(max)
		 if(@rCategoryId=1) 
		 BEGIN
		 SET @Sql =  CASE @rCategoryId					  
					 WHEN 1 THEN -- Result
						'Select SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SR.'+@rSubCategory+','''') 
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SR.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SR.'+@rSubCategory+',''False'') 
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SR.'+@rSubCategory+',''0001/01/01'') 
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SR.'+@rSubCategory+',''0'') 
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
							LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId=SA.AcademicId AND (SR.ExamId='+CAST(@rExamId AS nvarchar(15))+')
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+' AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ ' OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ ' OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND (CM.DepartmentId =' +CAST (@rDepartmentId as nvarchar(15)) + ' OR ' + CAST (@rDepartmentId AS Nvarchar(15))+'=0)
							
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SR.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SR.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SR.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SR.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
								OR ('+@lDataTypeId+'=5 AND ISNULL(SR.'+@rSubCategory+',''0'')=''0'')'+--Added by dhananjay for mantis id - 35452
								+'
							)
							ORDER BY SA.' + @lOrderBy
					END
							
					
		print @Sql    
		
	   
	  EXECUTE  sp_executesql @Sql
		END	
			ELSE IF(@rCategoryId=2)	
			BEGIN
			Declare @lExamRemarkSetupId int
			Select @lExamRemarkSetupId = Id from sAssessment.tExamRemarkSetup Where Title = @rSubCategory
			Select 
					SA.AcademicId,
					SA.Code,
					SA.Name,
					SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
					SA.RollNo,
					SA.Number,
					ISNULL(SR.Remark,'') AS SubCategory
			FROM 
					sStudent.vStudentAcademic SA
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
					LEFT JOIN sAssessment.tStudentExamRemark SR ON SR.AcademicId=SA.AcademicId AND (SR.ExamId=@rExamId) AND SR.ExamRemarkSetupId = @lExamRemarkSetupId
					Where SA.OrgId=@rOrgId AND (SA.ClassId=@rClassId OR @rClassId=0)
					AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (SA.StatusId=@rStatusId OR @rStatusId=0)
					AND (SA.BatchId=@rBatchId)
					AND (CM.DepartmentId =@rDepartmentId OR @rDepartmentId=0)
			ORDER BY case When @rOrderBy=1 then  SA.RollNo 
					When @rOrderBy=2 then  SA.Code  
					When @rOrderBy=3 then  SA.FirstName  
					When @rOrderBy=4 then  SA.MiddleName
					else SA.LastName END
			END
END
GO
PRINT N'Altering Procedure [sBiometric].[pRptTimeSheetListGet]...';


GO
ALTER PROCEDURE [sBiometric].[pRptTimeSheetListGet]
  @rBuilder1 nvarchar(max)='',
  @rBuilder2 nvarchar(max)='',
  @rEmployeeId bigint=0,  
  @rFromDate DateTime,  
  @rToDate DateTime,  
  @rTimeSheetStatus nvarchar(10) = '0',  
  @rOrgId int = 0  ,
  @rOrgGroupId int,
  @rEmployeeStatusId int = 0,
  @rOrganizationDepartmentId int=0,
  @rOrgGroupDepartmentId int = 0,
  @rGradeId nvarchar(max)= '0'

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 

CREATE TABLE #TempMonthTrans  
 (  
 Id int,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20),
 ShiftName nvarchar(25)  
 )  
    Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		DECLARE @lBatchID int
		DECLARE @lForYear nvarchar(20),@lForMonth nvarchar(20)
		Set @lForYear = Year(@rFromDate)
		
		Set @lForMonth = Month(@rFromDate)
		
		Set @ldate= CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@lForMonth,@lForYear)
		
		set @Firstdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @Lastdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), @Days)

 INSERT INTO #TempMonthTrans 
  select *
   from [sBiometric].[fBiometricTempMonthTransGet](@rOrgId ,@rOrganizationDepartmentId ,@rFromDate,@rToDate,@rEmployeeId)  
 

		
	 SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 as Builder2,
		TM.Id,
		TM.EmployeeId,
		TM.Attn_Date,
		OGD.Title AS [OrganizationGroupDepartment],
		TM.PresentStatus as PresentStatus,
		TM.FirstIn,
		TM.LastOut,
		TM.OverTime,
		TM.LateBy,
		TM.Duration,
		TM.EarlyBy,
		TM.ShiftName,
		 MT.Tot_Attn,
		 EM.FirstName + ' ' + EM.LastName As ShortName,
		 EM.Code as EmpCode ,   
		[sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus ,  
		ISNULL(ELS.Id,0) AS EmployeeLateStatusId, 
		ISNULL(SM.Id,0) AS StatusId,  
		ISNULL(SM.Title,'') AS Status ,
		 OM.Id AS OrgId,
		OM.Title AS OrganizationTitle,
		LRM.Title as LeaveReason  --mantis - 35817 
	 FROM #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
	 INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId  
	 LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)  
	 LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId  
	 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(cast(rtrim(YEAR(EJD.DateOfJoining) *10000+ Month(EJD.DateOfJoining) *100+ 01) as datetime),'1900/01/01'))
	 INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
	 LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id
	 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	 LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId=Tm.EmployeeId AND EAR.AttendanceDate=TM.Attn_Date			--mantis - 35817 
	 LEFT JOIN sHrm.tLeaveReasonMaster LRM ON LRM.Id = EAR.AbsentReasonId		--mantis - 35817 
	 WHERE   
	 TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate    
	 AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
	 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
	 AND (( @rTimeSheetStatus = '1' AND (TM.Duration < '09:30')) OR ( @rTimeSheetStatus != '1' AND ((PresentStatus = @rTimeSheetStatus OR @rTimeSheetStatus='0'))))
	 AND (EM.OrgId = @rOrgId OR @rOrgId = 0)
	 AND (OM.OrgGroupId = @rOrgGroupId)
	 AND ((EM.StatusId = @rEmployeeStatusId) OR (@rEmployeeStatusId = 0))
	 AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
	 AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
	 AND  ISNULL(EM.IsOtherUser,0) = 0
	 AND (EJD.DateOfJoining<= @Lastdate OR ISNULL(EJD.DateOfJoining,'')='')
	 AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
	 AND (EmployeeGradeId in ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGradeId,',')) OR @rGradeId=0) 
	 Order By TM.EmployeeId,TM.Attn_Date

 --SELECT  @rBuilder1 AS Builder1,
	--@rBuilder2 as Builder2,
	--0 as Id,
	--CAST(0 AS bigint) AS EmployeeId,
	--CAST('1999-01-01 00:00:00' AS datetime) as Attn_Date,
	--'' AS OldPresentStatus,
	--'' AS [OrganizationGroupDepartment],
	--'' as PresentStatus,
	--'' as FirstIn,
	--'' AS LastOut,
	--'' as OverTime,
	--'' as LateBy,
	--'' as Duration,
	--'' as EarlyBy,
	--'' as ShiftName, 
	--'' As ShortName,
	--'' as EmpCode ,
	--'' AS LeaveStatus , 
	--'' AS LeavePendingStatus, 
	--'' AS EmployeeTravel,
	--0 AS EmployeeLateStatusId, 
	--0 AS StatusId, 
	--'' AS Status,
	--0 AS OrgId,
	--  '' AS OrganizationTitle,
	-- '' AS LeaveReason		--mantis - 35817 

 end
GO
PRINT N'Altering Procedure [sCertificate].[pRptBonafiedCertificateGet]...';


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

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

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


	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 177 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	
	Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	
	
	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			B.Id,
			B.Number,
			B.AcademicId,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			B.BonafideDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			--OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			--OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			ATM.Title AS AffiliationType,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			@lIsShowPhoto AS IsShowPhoto,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			B.Remark AS ReceiptNo,
			SF.FatherName,
			SA.AdmissionDate,
			DP.Title AS DepartmentName,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4,
			REPLICATE(',',OM.LetterHeadMargin)    AS LetterHeadMargin,
			ISNULL(B.BonafiedReason,'') AS BonafiedReason,
			CT.Title AS Category,
			SF.MotherName,
			C.PermanentStreetOne,
			C.PermanentStreetTwo,
			C.PermanentStreetThree,
			C.PermanentCountry,
			C.PermanentState,
			C.PermanentCity,
			C.PermanentZipCode,
			C.PermanentContactNo,
			C.PresentStreetOne,
			C.PresentStreetTwo,
			C.PresentStreetThree,
			C.PresentCountry,
			C.PresentState,
			C.PresentCity,
			C.PresentContactNo,
			C.PresentZipCode,
			SM.SUId,
			SO.AdhaarNumber,
			CM.DisplayTitle AS ClassName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			OM.PrincipalSignature,
			ISnull(AR.SourceId,0) AS StudentidForhostel,
			DM.DisplayTitle AS Divisionname,
			@lIDConfigValue AS ItemValue ,
			SM.RecordStatusId,
			SO.BirthState AS BirthState,
			CM1.Title AS AdmissionStandard,
			RRG.SchoolRemark1,
			RRG.SchoolRemark2,
			RRG.SchoolRemark3,
			SF.FatherAdhaarNumber AS FatherAadharNo,
			SF.MotherAdhaarNumber AS MotherAadharNo,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			--OI.CertificateHeaderA4,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			SM.Id AS StudentId,
			(CASE WHEN RRG.SchoolRequiredSignature IS NULL THEN NULL ELSE RRG.SchoolRequiredSignature END) AS SchoolRequiredSignature ,
			SO.UIDNumber,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			BM.FromDate AS BatchFromDate,
			BM.ToDate AS BatchToDate ,

			ISNULL(U.DisplayTitle,'') AS UserName ,
		
		    ISNULL(EM.FirstName,'') +' '+ISNULL(EM.LastName,'') AS PrincipalName,
			ISNULL(CM.ClassNameInWord,'') AS ClassNameInWord,
			CM2.Title AS LeftStandard,
			CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,			--add for 27638 mantis
			ISNULL(SI.QRCode,'') AS QRCode,							--add for 27638 mantis
			SA.LeftDate AS LeftDate,	
			SM.PENNumber, -- add for Mentis : 0033432
			ISNULL(SO.BirthCountry,'') AS BirthCountry,--added by dhananjay for mantis id : 0035561
			ISNULL(SM.LocalName,'')	AS LocalName,  -- add for mantis : 0035669
			B.Number as BonafideNumber  --Mantis - 35686
	FROM 
			sCertificate.tBonafide B
			
			INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id = SA.AdmissionStandardId
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN SHostel.tAssignRoom Ar On Ar.SourceId=A.StudentId AND Ar.OrgGroupBatchId=@rOrgGroupBatchId 
			LEFT JOIN sCommon.tReportRemarkGroupOrg RRG ON RRG.OrgId = OM.Id AND ReportRemarkGroupId=6
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId 
			LEFT JOIN sSecurity.tUser U	ON U.Id=B.CreatedUserId

			Left join sHrm.tEmployeeMaster EM on EM.Id = OM.EmployeeId
			LEFT JOIN sSetup.tClassMaster CM2 ON CM2.Id = SA.LeftStandardId
			--INNER JOIN sSetup.tTermMaster TM ON  TM.ID=
	WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			--AND ((B.BonafideDate=@rBonafiedDate) OR (ISNULL(@rBonafiedDate,'')=''))
			AND ((B.Number=@rNumber) OR (@rNumber=''))
			AND ((B.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((B.Number <= @rToNo) OR (@rToNo=''))
			AND ((B.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((B.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--Group By B.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
			--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,B.BonafideDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,
			--OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering 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
		ISNULL(SM.LocalName,'') AS LocalName, -- added by dhananjay for mantis id - 0035713
        ISNULL(CMM.Title,'')	AS LeftStandard	  --added by dhananjay for mantis id - 35764                                  

	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
			LEFT JOIN  sSetup.tClassMaster CMM ON CMM.Id= SA.LeftStandardId   --added by dhananjay for mantis id - 35764

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


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

DECLARE @lIsShowPhoto bit = 0
DECLARE @lIsOnPrePrinted bit = 0
DECLARE @lIsDisplayReligion bit=0
DECLARE @lIsDisplayImageHeader bit=0
DECLARE @lConfigValue nvarchar(50)
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0


	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsShowPhoto = 0
	--ELSE
	--SET @lIsShowPhoto = 1
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 181 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayReligion = 0
	--ELSE
	--SET @lIsDisplayReligion = 1
	
	SELECT @lOrgGroupId = OrgGroupId FROM  sSetup.tOrganizationMaster WHERE Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId
	
	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			OC.Id,
			OC.Number,
			OC.AcademicId,
			SM.Code,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			CONVERT(nvarchar,BM.FromDate,103) AS Batch,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			OC.CertificateDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			ATM.Title AS AffiliationType,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			@lIsShowPhoto AS IsShowPhoto,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			OC.Remark AS ReceiptNo,
			SF.FatherName,
			SA.AdmissionDate,
			SA.LeftDate,
			DP.Title AS DepartmentName,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4,
			REPLICATE(',',OM.LetterHeadMargin) AS LetterHeadMargin,
			CT.Title AS Category,
			SF.MotherName,
			C.PermanentStreetOne,
			C.PermanentStreetTwo,
			C.PermanentStreetThree,
			C.PermanentCountry,
			C.PermanentState,
			C.PermanentCity,
			C.PermanentZipCode,
			C.PermanentContactNo,
			C.PresentStreetOne,
			C.PresentStreetTwo,
			C.PresentStreetThree,
			C.PresentCountry,
			C.PresentState,
			C.PresentCity,
			C.PresentContactNo,
			C.PresentZipCode,
			SA.PreviousStandard,
			SA.PreviousSchool, 
			SM.SUId,
			SO.AdhaarNumber,
			SO.UIDNumber,
			CM.DisplayTitle AS ClassName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			OM.PrincipalSignature,
			ISnull(AR.SourceId,0) AS StudentidForhostel,
			DM.DisplayTitle AS Divisionname,
			@lIDConfigValue AS ItemValue ,
			SM.RecordStatusId,
			SO.BirthState AS BirthState,
			CM1.DisplayTitle AS AdmissionStandard,
			CM2.DisplayTitle AS LeftStandard,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			SO.MotherTongue,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCNumber,
			CM.DisplayTitle AS CurrentStandard,
			BM.Title AS BatchTitle,
			ISNULL(SM.PENNumber,0) AS PENNumber  --add for mantis : 0035811	
	FROM 
			sCertificate.tOtherCertificate OC
			INNER JOIN sStudent.tAcademic A ON OC.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sHostel.tAssignRoom AR On AR.SourceId=A.StudentId AND AR.OrgGroupBatchId=@rOrgGroupBatchId 
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id= SA.AdmissionStandardId
			--LEFT JOIN sStudent.tStudentAdmission SA1 ON SA1.AdmissionStandardId = CM1.Id
			LEFT JOIN sSetup.tClassMaster CM2 ON CM2.Id= SA.LeftStandardId
			--LEFT JOIN sStudent.tStudentAdmission SA2 ON SA2.LeftStandardId = CM2.Id
			LEFT JOIN sCertificate.tLeaving L ON L.AcademicId=A.Id
			
	WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			AND ((OC.Number=@rNumber) OR (@rNumber=''))
			AND ((OC.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((OC.Number <= @rToNo) OR (@rToNo=''))
			AND ((OC.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OC.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OC.CertificateTypeId = @rCertificateTypeId) OR (@rCertificateTypeId = 0))
	END
GO
PRINT N'Altering Procedure [sCommonService].[pZoomEmployeeSearchGet]...';


GO
ALTER PROCEDURE [sCommonService].[pZoomEmployeeSearchGet]
    @rOrgId [int],
    @rEmployeeCode [nvarchar](20) = '',
    @rFirstName [nvarchar](30) = '',
    @rMobileNumber [nvarchar](20) = '',
    @rDOB [datetime] = '1/1/1900',
    @rLastName [nvarchar](30) = '',
    @rParticipantSourceTypeId int = 0,
    @rDepartmentId int = 0,
    @rEmployeeId bigint = 0,
    @rStatusId smallint,
    @rMeetingMode int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    IF (@rMeetingMode = 1)
    BEGIN
        SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
        SET @rLastName = sCommon.fSearchStringGet(@rLastName)
        SET @rMobileNumber = sCommon.fSearchStringGet(@rMobileNumber)

        SELECT OrgID,
               EM.Id,
               EM.EmployeeId,
               Code,
               FirstName,
               MiddleName,
               LastName,
               EmployeeName,
               GenderId,
               ISNULL(DateOfBirth, '1900/01/01') AS DateOfBirth,
               ISNULL(DateOfJoining, '1900/01/01') AS DateOfJoining,
               '' AS Gender,
               StatusId,
               EM.IsObsolete,
               PhoneNoCompany,
               CompanyEmail,
               ExtensionNo,
               DepartmentId,
               DepartmentCode,
               DepartmentName,
               ISNULL(MobileNumber, 0) AS MobileNumber,
               ISNULL(DATEDIFF(yy, DateOfBirth, sCommon.fGetDate()), 0) AS Age,
               DesignationId,
               ParticipantSourceTypeId
        FROM sHrm.vExtEmployeeMaster EM
            INNER JOIN sAcademic.tOnlineMeetingAccount OA
                On OA.EmployeeId = EM.EmployeeId
        WHERE (
                  (EM.Code = @rEmployeeCode)
                  OR (ISNULL(@rEmployeeCode, '') = '')
              )
              AND (
                      (EM.FirstName Like @rFirstName)
                      OR (ISNULL(@rFirstName, '') = '')
                  )
              AND (
                      (EM.LastName Like @rLastName)
                      OR (ISNULL(@rLastName, '') = '')
                  )
              AND (
                      (EM.MobileNumber Like @rMobileNumber)
                      OR (ISNULL(@rMobileNumber, '') = '')
                  )
              AND EM.IsObsolete = 0
              AND (
                      (EM.OrgId = @rOrgId)
                      OR (@rOrgId = 0)
                  )
              AND (
                      (EM.DepartmentId = @rDepartmentId)
                      OR (@rDepartmentId = 0)
                  )
              AND (
                      (EM.StatusId = @rStatusId)
                      OR (@rStatusId = 0)
                  )
              AND ISNULL(EM.IsOtherUser, 0) = 0
    END
    ELSE IF (@rMeetingMode = 0 or @rMeetingMode = 2)
    BEGIN
        SELECT OrgID,
               EM.Id,
               EM.EmployeeId,
               Code,
               FirstName,
               MiddleName,
               LastName,
               EmployeeName,
               GenderId,
               ISNULL(DateOfBirth, '1900/01/01') AS DateOfBirth,
               ISNULL(DateOfJoining, '1900/01/01') AS DateOfJoining,
               '' AS Gender,
               StatusId,
               EM.IsObsolete,
               PhoneNoCompany,
               CompanyEmail,
               ExtensionNo,
               DepartmentId,
               DepartmentCode,
               DepartmentName,
               ISNULL(MobileNumber, 0) AS MobileNumber,
               ISNULL(DATEDIFF(yy, DateOfBirth, sCommon.fGetDate()), 0) AS Age,
               DesignationId,
               ParticipantSourceTypeId
        FROM sHrm.vExtEmployeeMaster EM
        WHERE (
                  (EM.Code = @rEmployeeCode)
                  OR (ISNULL(@rEmployeeCode, '') = '')
              )
              AND (
                      (EM.FirstName Like @rFirstName)
                      OR (ISNULL(@rFirstName, '') = '')
                  )
              AND (
                      (EM.LastName Like @rLastName)
                      OR (ISNULL(@rLastName, '') = '')
                  )
              AND (
                      (EM.MobileNumber Like @rMobileNumber)
                      OR (ISNULL(@rMobileNumber, '') = '')
                  )
              AND EM.IsObsolete = 0
              AND (
                      (EM.OrgId = @rOrgId)
                      OR (@rOrgId = 0)
                  )
              AND (
                      (EM.DepartmentId = @rDepartmentId)
                      OR (@rDepartmentId = 0)
                  )
              AND (
                      (EM.StatusId = @rStatusId)
                      OR (@rStatusId = 0)
                  )
              AND ISNULL(EM.IsOtherUser, 0) = 0
    END
END
GO
PRINT N'Altering Procedure [sCommunication].[pPollMemberGet]...';


GO


ALTER PROCEDURE [sCommunication].[pPollMemberGet]
	 
	 @rPollId bigint,
	 @rOrgId smallint,
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 		
		
	SELECT 
			DM.Id  as SourceId,
			CM.Title+'-'+DM.Title as ClassDept,
			2005 as SourceTypeId,
			CASE WHEN PM.SourceId IS NULL OR PM.PollId!=@rPollId THEN 0 ELSE 1 END AS IsObsolete,
			OM.DisplayTitle AS Organization,
			--CM.OrderIndex+DM.OrderIndex AS OrderIndex --Commented for mantis : 35038
			/******Added for mantis : 35038 by Nilesh******/
			CM.OrderIndex AS OrderIndex,
			DM.OrderIndex As DivisionOrderIndex
  FROM 
			sSetup.tDivisionMaster DM
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId --Commented for mantis : 35038 by Nilesh
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId AND DM.IsObsolete = 0 --Added for mantis : 35038 by Nilesh
			LEFT JOIN sCommunication.tPollMember PM ON PM.SourceId=DM.Id AND PM.SourceTypeId=2005 AND PM.PollId=@rPollId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId AND OM.OrgGroupId=@rOrgGroupId
	 WHERE
		((DM.OrgId=@rOrgId) OR (@rOrgId=0))
		UNION
	SELECT 
			ODM.Id  as SourceId,
			ODM.Title as ClassDept,
			2004 as SourceTypeId,
			CASE WHEN PM.SourceId IS NULL OR PM.PollId!=@rPollId THEN 0 ELSE 1 END AS IsObsolete,
			OM.DisplayTitle AS Organization,
			/******Added for mantis : 35038 by Nilesh******/
			0 AS OrderIndex,
			0 As OrderIndexDivision
  FROM 
			sSetup.tDepartmentMaster ODM
			LEFT JOIN sCommunication.tPollMember PM ON PM.SourceId=ODM.Id AND PM.SourceTypeId=2017 AND PM.PollId=@rPollId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ODM.OrgId AND OM.OrgGroupId=@rOrgGroupId
	WHERE
		((ODM.OrgId=@rOrgId) OR (@rOrgId=0))

		Order By OrderIndex,DivisionOrderIndex --Added for mantis : 35038 by Nilesh
END
GO
PRINT N'Altering Procedure [sFee].[pOldFeeImportWithNAAdd]...';


GO
ALTER PROCEDURE [sFee].[pOldFeeImportWithNAAdd] 
	@rOldOrgGroupBatchId int,
	@rNewOrgGroupBatchId int,
	@rOldBatchId int,
	@rNewBatchId int,
	@rOldAdmissionCategoryId int,
	@rNewAdmissionCategoryId int,
	@rOldReceiptBookId int,
	@rNewReceiptBookId int,
	@rFeeId int,
	@rOrgId int,
	@rCreatedUserId bigint,
	@rIdNos nvarchar(max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 

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

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

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

	DECLARE @lCount int
	-- Old Fee Import Temp Table
	CREATE TABLE #TempOldFeeImportWithNA
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[PendingAmount] decimal(12,2) NULL,
		[FeeSetupId] int
	)
	CREATE TABLE #TempTotalOldFeeImportWithNA
	(
		[AutoId] int identity,
		[StudentId] bigint NULL ,
		[AcademicId] bigint NULL,
		[TotalPendingAmount] decimal(12,2) NULL
	)
	-- End Old Fee Import Temp Table
	
	INSERT INTO #TempOldFeeImportWithNA
	SELECT 
		SA.StudentId,
		SA.AcademicId,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) AS PendingAmount,
		FS.Id AS FeeSetupId
		--SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOldOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOldOrgGroupBatchId
			    AND ((FS1.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
			    AND ((FS1.ReceiptBookId=@rOldReceiptBookId) OR (@rOldReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
			
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOldOrgGroupBatchId
		WHERE
		    SA1.OrgGroupBatchId = @rOldOrgGroupBatchId
		    AND ((FS1.AdmissionCategoryId=@rOldAdmissionCategoryId) OR (@rOldAdmissionCategoryId=0))
		    AND ((FS1.ReceiptBookId=@rOldReceiptBookId) OR (@rOldReceiptBookId=0))
			AND (FS1.IsOptional=1)
			AND ((FS1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
			AND ((SA1.BatchId=@rOldBatchId) OR (@rOldBatchId=0))	
			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOldOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOldOrgGroupBatchId)
				AND ((R.BatchId=@rOldBatchId) OR (@rOldBatchId=0))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
			GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
	WHERE
		SA.OrgGroupBatchId = @rOldOrgGroupBatchId
		AND SA.OrgId = @rOrgId 
		AND SA.BatchId=@rOldBatchId
		AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
		AND (SA.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	--GROUP BY SA.StudentId,SA.AcademicId
	
	INSERT INTO #TempTotalOldFeeImportWithNA
	SELECT StudentId, AcademicId, SUM(PendingAmount) AS TotalPendingAmount
	FROM #TempOldFeeImportWithNA
	GROUP BY StudentId, AcademicId

	SELECT @lCount = COUNT(AutoId) FROM #TempTotalOldFeeImportWithNA

	IF EXISTS 
	(
		SELECT 1 FROM sFee.tReceipt R
		INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SA ON R.SourceId = SA.AcademicId AND SA.BatchId = @rNewBatchId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.BatchId = @rNewBatchId
		AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId AND FS.FeeId = @rFeeId 
		AND FS.ReceiptBookId = @rNewReceiptBookId
		AND (SA.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	)
	BEGIN
		SELECT -101 AS Result
		RETURN
	END
	
	IF OBJECT_ID('tempdb..#TempOldFeeImportWithNA') IS NOT NULL 
		DROP TABLE #TempOldFeeImportWithNA

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

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

	BEGIN TRANSACTION
	
	---- Delete Fee Optional
	DELETE FO 
	FROM sFee.tFeeOptional FO 
	INNER JOIN sStudent.tAcademic SA ON FO.SourceId = SA.Id AND SA.BatchId = @rNewBatchId	
	INNER JOIN sFee.tFeeSetup FS ON FO.FeeSetupId = FS.Id AND SA.ClassId = FS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA1 ON SA.Id = SA1.AcademicId AND SA1.BatchId = @rNewBatchId AND FS.BatchId = @rNewBatchId 
		AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId AND FS.FeeId = @rFeeId  
		AND FS.ReceiptBookId = @rNewReceiptBookId AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')

	-- Delete Fee Allocation
	DELETE FA 
	FROM sFee.tFeeAllocation FA 
	INNER JOIN sStudent.tAcademic SA ON FA.SourceId = SA.Id AND SA.BatchId = @rNewBatchId
	INNER JOIN sFee.tFeeSetup FS ON FA.FeeSetupId = FS.Id AND SA.ClassId = FS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA1 ON SA.Id = SA1.AcademicId AND SA1.BatchId = @rNewBatchId AND FS.BatchId = @rNewBatchId 
		AND FS.AdmissionCategoryId = @rNewAdmissionCategoryId AND FS.FeeId = @rFeeId AND FA.FeeSetupId = FS.Id
		AND FS.ReceiptBookId = @rNewReceiptBookId AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
	
	WHILE (@lCount > 0)
	BEGIN
		DECLARE @lAcademicId bigint = NULL, @lOldAcademicId bigint = NULL
		DECLARE @lStudentId bigint = NULL
		DECLARE @lClassId int = NULL
		DECLARE @lFeeSetupId int = NULL
		DECLARE @lTotalPendingAmount decimal(12,2)
		
		SELECT @lStudentId = StudentId,@lTotalPendingAmount=TotalPendingAmount,@lOldAcademicId=AcademicId FROM #TempTotalOldFeeImportWithNA WHERE AutoId = @lCount
		SELECT @lAcademicId = Id, @lClassId=ClassId FROM  sStudent.tAcademic SA WHERE StudentId = @lStudentId AND BatchId = @rNewBatchId
		SELECT @lFeeSetupId = Id FROM sFee.tFeeSetup WHERE  ClassId = @lClassId AND AdmissionCategoryId = @rNewAdmissionCategoryId AND BatchId=@rNewBatchId AND FeeId = @rFeeId AND ReceiptBookId = @rNewReceiptBookId
		
		IF @lAcademicId IS NOT NULL AND @lFeeSetupId IS NOT NULL AND @lClassId IS NOT NULL
		BEGIN
			
			-- Insert Fee Optional
			INSERT INTO sFee.tFeeOptional
			(
				FeeSetupId,
				SourceTypeId,
				SourceId,
				BatchId
			)
			VALUES
			(
				@lFeeSetupId,
				2001,
				@lAcademicId,
				@rNewBatchId
			)
			 
			-- Insert Fee Allocation
			INSERT INTO sFee.tFeeAllocation
			(
			    SourceTypeId,
			    SourceId,
			    FeeSetupId,
			    VariableAmount,
			    DiscountAmount,
			    AdditionalAmount,
			    NotApplicableAmount,
			    Remark,
			    ReferenceTypeId,
			    ReferenceSourceId,
			    CreatedUserId,
			    CreatedDateTime,
			    UpdatedUserId,
			    UpdatedDateTime
			)
			VALUES
			(
				2001,
				@lAcademicId,
				@lFeeSetupId,
				@lTotalPendingAmount,
				0,
				NULL,
				NULL,
				'Old Year Pending Fee',
				NULL,
				NULL,
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL
			)

			--DECLARE @lCount1 int = 0
			--SELECT @lCount1 = COUNT(1) FROM #TempOldFeeImportWithNA WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId
		
			IF OBJECT_ID('tempdb..#TempOldFeeSetup') IS NOT NULL 
				DROP TABLE #TempOldFeeSetup

			CREATE TABLE #TempOldFeeSetup
			(
				[AutoId] int identity,
				[StudentId] bigint NULL ,
				[AcademicId] bigint NULL,
				[PendingAmount] decimal(12,2) NULL,
				[FeeSetupId] int
			)

			INSERT INTO #TempOldFeeSetup
			SELECT StudentId,AcademicId,PendingAmount,FeeSetupId FROM #TempOldFeeImportWithNA WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId

			DECLARE @lCount1 int = 0
			SELECT @lCount1 = COUNT(1) FROM #TempOldFeeSetup WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId

			WHILE(@lCount1 > 0)
			BEGIN
				DECLARE @lPendingAmount decimal(12,2), @lOldFeeSetupId int
				SELECT @lPendingAmount = PendingAmount, @lOldFeeSetupId = FeeSetupId FROM #TempOldFeeSetup WHERE StudentId = @lStudentId AND AcademicId = @lOldAcademicId AND AutoId = @lCount1
				
				IF EXISTS(SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId = 2001 AND SourceId = @lOldAcademicId AND FeeSetupId = @lOldFeeSetupId)
				BEGIN
					-- Update Fee Allocation
					UPDATE sFee.tFeeAllocation
					SET NotApplicableAmount = (ISNULL(NotApplicableAmount,0) + ISNULL(@lPendingAmount,0)), Remark = 'Transferred to New Batch', UpdatedUserId = @rCreatedUserId, UpdatedDateTime = sCommon.fGetDate()
					WHERE SourceTypeId = 2001 AND SourceId = @lOldAcademicId AND FeeSetupId = @lOldFeeSetupId
				END
				ELSE
				BEGIN
					-- Insert Fee Allocation
					INSERT INTO sFee.tFeeAllocation
					(
						SourceTypeId,
						SourceId,
						FeeSetupId,
						VariableAmount,
						DiscountAmount,
						AdditionalAmount,
						NotApplicableAmount,
						Remark,
						ReferenceTypeId,
						ReferenceSourceId,
						CreatedUserId,
						CreatedDateTime,
						UpdatedUserId,
						UpdatedDateTime
					)
					VALUES
					(
						2001,
						@lOldAcademicId,
						@lOldFeeSetupId,
						0,
						0,
						0,
						@lPendingAmount,
						'Transferred to New Batch',
						NULL,
						NULL,
						@rCreatedUserId,
						sCommon.fGetDate(),
						@rCreatedUserId,
						sCommon.fGetDate()
					)
				END
				SET @lCount1 = @lCount1 - 1
			END
		END
		
		SET @lCount = @lCount - 1
	END

	DROP TABLE #TempTotalOldFeeImportWithNA
	DROP TABLE #TempOldFeeImportWithNA
	--DROP TABLE #TempOldFeeSetup
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
	DROP TABLE #TempTotalOldFeeImportWithNA
	DROP TABLE #TempOldFeeImportWithNA
	IF OBJECT_ID('tempdb..#TempOldFeeSetup') IS NOT NULL 
		DROP TABLE #TempOldFeeSetup
	ROLLBACK TRANSACTION
	SELECT -1 AS Result, ERROR_MESSAGE() AS msg
END CATCH	
END
GO
PRINT N'Altering Procedure [sFee].[pPostDatedPaymentGet]...';


GO


ALTER PROCEDURE [sFee].[pPostDatedPaymentGet]
	@rId bigint = 0,
	@rOrgGroupBatchId int=0,
	@rOrgId int = 0,
	@rBatchId int = 0,
	@rAdmissionCategoryId int = 0,
	@rIdNo nvarchar(20) = NULL,
	@rDepartmentId int = 0,
	@rClassId int = 0,
	@rDivisionId int = 0,
	@rReceiptBookId int = 0,
	@rCollectionGroupId int = 0,
	@rPayTypeId int = 0,
	@rStatusId int = 0,
	@rFirstName nvarchar(50) = NULL,
	@rFromReceiptNumber nvarchar(50) = NULL,
	@rToReceiptNumber nvarchar(50) = NULL,
	@rChequeNo nvarchar(50) = NULL,
	@rFromPaymentClearanceDate date = NULL,
	@rToPaymentClearanceDate date = NULL,
	@rOrgGroupId int = 0,
	@rSourceId bigint =0,
	@rSourceTypeId smallint = 0,
	@rUserId bigint = 0,
	@rStatusIds nvarchar(100) = '',
	@rFromCreatedDate date = NULL, --Added for mantis : 35660 by Nilesh
	@rToCreatedDate date = NULL --Added for mantis : 35660 by Nilesh

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 		
	BEGIN
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rChequeNo = sCommon.fSearchStringGet(@rChequeNo)  
	END
	--Select @rFromCreatedDate , @rToCreatedDate
	SELECT DISTINCT 	 
		 PDP.Id
		,PDP.OrgId
		,ISNULL(OM.Title, '') AS Organization
		,PDP.BatchId
		,ISNULL(BM.Title, '') AS Batch
		,ISNULL(SA.Code, '') AS IdNo
		,ISNULL(SA.ClassName, '') + ' - ' + ISNULL(SA.DivisionName, '') AS ClassDivision
		,ISNULL(SA.Name, '') AS StudentName
		,PDP.OrgGroupBatchId
		,PDP.SourceTypeId
		,PDP.SourceId
		,ISNULL(PDP.ReceiptId, 0) AS ReceiptId
		,PDP.ReceiptBookId
		,PDP.PayTypeId
		,PDP.PaymentClearanceDate
		,PDP.ChequeNo
		,PDP.BankName
		,PDP.Amount AS ReceiptAmount
		,ISNULL(PDP.Remark, '') AS Remark
		,PDP.CreatedUserId
		,PDP.CreatedDateTime
		,PDP.UpdatedUserId
		,PDP.UpdatedDateTime
		,PDP.StatusId
		,ISNULL(R.ReceiptNumber, '') AS ReceiptNumber
		,ISNULL(RBM.Title, '') AS ReceiptBookTitle
		,ISNULL(R.ReceiptDate, '') AS ReceiptDate
		,ISNULL(PTM.Title, '') AS PayType
        ,ISNULL(SM.Title, '') AS StatusTitle
		,ISNULL(PDP.DepositedDate, '') AS DepositedDate
		,ISNULL(PDP.ReceiptDate, '') AS PDPReceiptDate	-- Added for mantis 0034852 by Foram
	FROM
		sFee.tPostDatePayment PDP
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = PDP.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = PDP.BatchId
		INNER JOIN [sStudent].[vStudentAcademic] SA ON SA.AcademicId = PDP.SourceId AND PDP.SourceTypeId = 2001
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PDP.PayTypeId
		INNER JOIN sFee.vUserReceiptBook RBM ON RBM.Id=PDP.ReceiptBookId AND RBM.UserId=@rUserId    
		--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = PDP.ReceiptBookId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id = PDP.StatusId
		LEFT JOIN sFee.tReceipt R ON R.Id = PDP.ReceiptId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = RBM.Id
	WHERE
		(PDP.Id = @rId OR @rId = 0)
		AND (PDP.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND (PDP.OrgId = @rOrgId OR @rOrgId = 0)
		AND (PDP.BatchId = @rBatchId OR @rBatchId = 0)
		AND (SA.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
		AND ((SA.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (SA.ClassId = @rClassId OR @rClassId = 0)
		AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
		AND (PDP.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		AND (CGM.Id = @rCollectionGroupId OR @rCollectionGroupId = 0)
		AND (PDP.PayTypeId = @rPayTypeId OR @rPayTypeId = 0)
		AND (PDP.StatusId = @rStatusId OR @rStatusId = 0)
		AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
		AND (PDP.ChequeNo like @rChequeNo OR ISNULL(@rChequeNo, '') = '')
		AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(ISNULL(@rFromReceiptNumber, 0) =0))    
		AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(ISNULL(@rToReceiptNumber,0)=0))   
		AND (PDP.PaymentClearanceDate >= @rFromPaymentClearanceDate OR ISNULL(@rFromPaymentClearanceDate, '') = '')
		AND (PDP.PaymentClearanceDate <= @rToPaymentClearanceDate OR ISNULL(@rToPaymentClearanceDate, '') = '')
		AND (PDP.SourceId = @rSourceId OR @rSourceId = 0)
		AND (PDP.SourceTypeId = @rSourceTypeId OR @rSourceTypeId = 0)
		AND (PDP.StatusId IN (SELECT item FROM sCommon.fnSplit(@rStatusIds,',')) OR ISNULL(@rStatusIds, '') = '')
		AND ((CONVERT(date,PDP.CreatedDateTime) >= @rFromCreatedDate) OR ISNULL(@rFromCreatedDate, '') = '') --Added for mantis : 35660 by Nilesh
		AND ((CONVERT(date,PDP.CreatedDateTime) <= @rToCreatedDate) OR ISNULL(@rToCreatedDate, '') = '') --Added for mantis : 35660 by Nilesh
END
GO
PRINT N'Altering Procedure [sFee].[pRptDepositStudentLedgerGet]...';


GO
ALTER PROC [sFee].[pRptDepositStudentLedgerGet]

	 @rOrgId int,
	 @rCode  nvarchar(max)='',
	 @rDepositHeadId int,
	 @rFromDate date='',
     @rToDate date='',
	 @rClassId int=0
     
AS
BEGIN
WITH Tb0 as
( 
			SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
			VA.SUId,
		    --CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
		     DA.CreatedDateTime,
		     '' AS ExpenseType,
			VA.ClassId,
			ISNULL([sProcurement].[fnGetStockDepositeDetail](DA.DepositHeadId , DA.AcademicId, @rFromDate ,@rToDate ),'')AS StockItemName,--Added by dhananjay for mantis - 0034487
			(CASE WHEN DA.ReferenceSourceTypeId=1021 THEN 'Stock Return' ELSE 'Deposit Add' END) AS DepositType		--add for mantis: 35522
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
			Where 
			((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			--AND VA.BatchId = @rBatchId
			--AND ((VA.ClassId=@rClassId) OR (@rClassId=0))
			--AND ((VA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(VA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='')
		    --AND ((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND (DA.DepositHeadId = @rDepositHeadId)
		    
			
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    --CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
			VA.SUId,
		    DAJ. CreatedDateTime,
		   ISNULL(ETM.Title,'')AS ExpenseType,
		   VA.ClassId,
		   ISNULL([sProcurement].[fnGetStockDepositeDetail](DAJ.DepositHeadId , VA.AcademicId, @rFromDate ,@rToDate),'')AS StockItemName,--Added by dhananjay for mantis - 0034487
		   '' AS DepositType		--add for mantis: 35522
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  INNER JOIN sFee.tFeeDepositExpenseTypeMaster ETM ON ETM.Id =DAJ.FeeDepositExpenseTypeId
			Where 
			((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			--AND VA.BatchId = @rBatchId
			--AND ((VA.ClassId=@rClassId) OR (@rClassId=0))
			--AND ((VA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		    AND (ISNULL(VA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='')
			AND (DAJ.DepositHeadId = @rDepositHeadId)
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     --CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
			 VA.SUId,
		    DR.CreatedDateTime,
		     '' AS ExpenseType,
			 VA.ClassId,
			 ISNULL([sProcurement].[fnGetStockDepositeDetail](DR.DepositHeadId , VA.AcademicId, @rFromDate ,@rToDate),'')AS StockItemName,--Added by dhananjay for mantis - 0034487
			 '' AS DepositType		--add for mantis: 35522
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			Where 
			((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			--AND VA.BatchId = @rBatchId
			--AND ((VA.ClassId=@rClassId) OR (@rClassId=0))
			--AND ((VA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		    AND (ISNULL(VA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='')
			AND (DR.DepositHeadId = @rDepositHeadId)
)
,Tb1 as
( 
	SELECT DepositDate,Credit,Debit,SUId,Row_Number() over (order by CreatedDateTime asc) as OrderId,AcademicId,Code,StudentName,Class ,CreatedDateTime,ExpenseType,ClassId,StockItemName,DepositType FROM Tb0--Added StockItemName by dhananjay for mantis - 0034487
	--add DepositType for mantis: 35522
)
  SELECT T1.DepositDate,
         T1.[Credit],
         T1.[Debit],(Sum(T2.Credit) - Sum(T2.Debit)) as Balance,
         T1.SUId,
         --CASE WHEN @rIsBasedOnSUId=0 THEN  T1.Code Else ISNULL(T1.SUId,'') END AS Code,
		 T1.Code AS Code,
         T1.StudentName,
         T1.Class,
        T1.CreatedDateTime,
        T1.ExpenseType,
		T1.StockItemName,
		T1.DepositType		--add for mantis: 35522
		 FROM Tb1 as T1
		 INNER JOIN Tb1 as T2 ON T1.OrderId >= T2.OrderId
		 Where 
		 ((T1.DepositDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((T1.DepositDate <= @rToDate) OR (ISNUll(@rToDate,'')=''))
		 AND ((T1.ClassId=@rClassId) OR (@rClassId=0))
		 Group By T1.DepositDate,T1.Credit,T1.Debit,T1.AcademicId,T1.SUId,T1.Code,T1.StudentName,T1.Class,T1.CreatedDateTime,T1.ExpenseType,T1.StockItemName,T1.DepositType--Added StockItemName by dhananjay for mantis - 0034487
		 --add T1.DepositType for mantis: 35522
		 Order by T1.CreatedDateTime
END
GO
PRINT N'Altering Procedure [sFee].[pRptFeeReceiptDetailListGet]...';


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

	END


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

	  
  FROM   
   sFee.tReceipt R  
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  INNER JOIN sFee.tFeeSetup FS  
   ON FS.Id=RD.FeeSetupId  
  INNER JOIN sFee.tFeeMaster FM  
   ON FM.Id=FS.FeeId  
  INNER JOIN sFee.tFeeHeadMaster FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId 
  LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = O.Id
  LEFT JOIN [sSecurity].[tUser] U ON U.Id=R.CreatedUserId -- Change innerjoin to left join for mantis id :0029242
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.StudentId = SA.StudentId  
    LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
     LEFT JOIN  
 (SELECT AT.SourceId FROM sTransport.tAssignRoute AT   
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
 INNER JOIN sSetup.tBatchMaster TBM ON TBM.Id=R.BatchId AND ((TBM.OrgId=@rOrgId) OR (@rOrgId=0))

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


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

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

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

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

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

			(CASE WHEN ISNULL(FA.VariableAmount,0) > 0 Then FA.VariableAmount 
			      When ISNULL(FS.Amount,0) > 0 Then FS.Amount END) + ISNULL(FA.AdditionalAmount,0) - ISNULL(FA.DiscountAmount,0) - ISNULL(FA.NotApplicableAmount,0) As TotalPayableAmount,
			OGM.Title AS OrgGroupTitle,
			 NID.CollectionGroupName AS NextInstallmentName, --Mantis End- 0031305
			ISNULL(HM.Title,'') AS House,	--add for mantis: 32658
			NID.StartDate AS NextInstallmentStartDate, --Mantis -  Start 32760
			NID.EndDate AS NextInstallmentEndDate,
			NID.PendingAmount AS NextInstallmentAmount,   --Mantis -  End 32760			
			ISNULL([sFee].[fFeeActualAmountSumGet](FR.SourceId),0) AS FeeActualAmount,	-- MantisId : 0032658
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo, -- MantisId : 0032895
			--mantis Start - 0033973
			ISNULL(SC.PermanentStreetOne,'')AS PermanentStreetOne,
			ISNULL(SC.PermanentStreetTwo,'')AS PermanentStreetTwo,
			ISNULL(SC.PermanentStreetThree,'')AS PermanentStreetThree,
			--mantis End - 0033973
			--mantis Start - 0034206
			ISNull(SC.PermanentCountry,'')AS PermanentCountry,
			ISNull(SC.PermanentState,'')AS PermanentState,
			ISNull(SC.PermanentCity,'')AS PermanentCity,
			ISNull(SC.PermanentZipCode,'')AS PermanentZipCode,
			--mantis End - 0034206
			FS.StartDate,          --mantis : 0034274
			FS.EndDate,          --mantis : 0034274
			ISNull(CSM.Title,'') AS CasteCategory,  --mantis : 0034588
			LM.Title AS Medium,   --mantis : 0034588
			CASE WHEN @rOrgGroupId = 1134 OR @rOrgGroupId = 1742 THEN
			ISNULL([sFee].[fPaidFeeAmountReceiptBookwiseGet](FR.SourceId,RBM.Id),0)
			ELSE
			ISNULL([sFee].[fPaidFeeAmountReceiptBookwiseGet](FR.SourceId,0),0)END AS TotalPaidAmount, --mantis : 0034862
			ISNULL(SO.UIDNumber,'')AS UID,  --Mantis - 35268
			ISNULL((SELECT TOP 1 BusRoute FROM [sFee].[fStudentWiseBusRoute](SA.StudentId, FR.OrgGroupBatchId)), '') AS BusRoute,  --Mantis - 35545
			ISNULL((SELECT TOP 1 PickupPoint FROM [sFee].[fStudentWiseBusRoute](SA.StudentId, FR.OrgGroupBatchId)), '') AS PickupPoint,  --Mantis - 35545
			--RR.RefundAmount AS RefundAmount		--mantis : 35909
			ISNULL((Select SUM(RefundAmount) from sFee.tReceiptRefund Where ReceiptId = FR.Id),0)AS RefundAmount	--mantis : 35909

 	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId  -- Mantis : 0029314
			LEFT JOIN (SELECT * FROM [sFee].[fNextInstallmentDetailsGet](@rReceiptBookId, @rReceiptId)) NID -- Mantis Start - 0031305
			ON NID.SourceId = FR.SourceId AND NID.SourceTypeId = FR.SourcetypeId -- Mantis End - 0031305
			LEFT JOIN sStudent.tStudentOther AS SO ON SO.StudentId = SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId		--add for mantis: 32658
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId --mantis : 0034588
			INNER JOIN sSetup.tLanguageMaster LM ON LM.Id = OM.LanguageId --mantis : 0034588
			--LEFT JOIN sFee.tReceiptRefund RR ON RR.ReceiptId = FR.Id		--mantis : 35909
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
			AND ((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0) )
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
END

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


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


GO
ALTER PROCEDURE [sFee].[pRptFeeSummaryGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0,
	@rClassIds nvarchar(max) = '',
	@rDivisionIds nvarchar(max) = ''   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	
	IF(@rReportId=20624)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status,
			SA.SUId AS SUId,
			CONVERT(Date,NULL) AS LeftDate, -- For DataSet Refresh
			'' AS ExemptedRemarkFeeWise,		-- For DataSet Refresh
			'' AS RemarkWithComma,
			'' AS AdditionalRemark,
			'' AS NotApplicableRemark,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,--Added by dhananjay for Mantis Id : 35270
			'' AS StudentContactNo,  --Mantis - 35489
			'' AS FatherName		 --Mantis - 35489
			
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId --Added by dhananjay for Mantis Id : 35270
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  	
		Order by  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo
	END
	ELSE IF (@rReportId=20842 OR @rReportId=10150 OR @rReportId=30714 OR @rReportId=30831)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status,
			SA.SUId AS SUId,
			SAD.LeftDate,
			'' AS ExemptedRemarkFeeWise,
			'' AS ParentContactNo,--Added by dhananjay for Mantis Id : 35270
			'' AS StudentContactNo, --Mantis - 35489
			'' AS FatherName		--Mantis - 35489
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		Order by  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo
	END
	ELSE IF(@rReportId=30655)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			'' AS ExemptedRemarkFeeWise,
			'' AS ParentContactNo,--Added by dhananjay for Mantis Id : 35270	
			'' AS StudentContactNo,	--Mantis - 35489
			'' AS FatherName		--Mantis - 35489
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  ISNULL(FA.NotApplicableAmount,0) > 0) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
		AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')	
		Order by SA.RollNo
	END
	ELSE IF(@rReportId=30799)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R1.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R1.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			ISNULL(R2.TotalReceiptAmount,0.00) AS CancelAmount,
			'' AS ExemptedRemarkFeeWise,
			'' AS ParentContactNo,--Added by dhananjay for Mantis Id : 35270	
			'' AS StudentContactNo, --Mantis - 35489
			'' AS FatherName		--Mantis - 35489
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId,R.TotalReceiptAmount
			
			) R1 ON R1.FeeSetupId = FS.Id AND SA.AcademicId = R1.SourceId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 1) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId,R.TotalReceiptAmount
			
			) R2 ON R2.FeeSetupId = FS.Id AND SA.AcademicId = R2.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
		 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		Order by SA.RollNo 
	END
	ELSE IF(@rReportId=30825)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			'' AS ExemptedRemarkFeeWise,
			'' AS ParentContactNo,--Added by dhananjay for Mantis Id : 35270	
			'' AS StudentContactNo,	--Mantis - 35489
			'' AS FatherName		--Mantis - 35489
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					--AND (tSA.AdmissionDate <= @rUptoDate)
					AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA1.StatusId = 1))
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			--AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		--AND (tSA.AdmissionDate <= @rUptoDate)
		AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA.StatusId = 1))
		 --AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
		 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		Order by SA.RollNo 
	END
	--ELSE IF(@rReportId=30821)
	--BEGIN
	--	SELECT 
	--		@rBuilder1 AS Builder1,
	--		@rBuilder2 AS Builder2,
	--		@rIsDetail AS IsDetail,
	--		@rIsFilter As IsFilter,
	--		@rIsHeader As IsHeader, 
	--		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
	--		SA.AcademicId,
	--		SA.RollNo,
	--		SA.Name,
	--		SA.Code,
	--		SA.ClassId,
	--		SA.DivisionId,
	--		SA.ClassName,
	--		SA.DivisionName,
	--		SA.DivisionOrder AS DivisionOrderIndex,
	--		SA.ClassOrderIndex AS ClassOrderIndex,
	--		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
	--		FS.Id AS FeeSetupId,
	--		ISNULL(FS.IsVariable,0)AS IsVariable,
	--		ISNULL(FS.Amount,0)AS Amount,
	--		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
	--		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
	--		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
	--		ISNULL(R.DiscountAmount,0.00)AS DiscountAmount,
	--		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
	--		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
	--		ISNULL(R.PaidAmount,0) AS PaidAmount,
	--		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
	--		ISNULL(FA.Remark,'') AS Remark,
	--		FS.ReceiptBookId,
	--		FS.FeeName,
	--		FS.FeeCode,
	--		SA.OrgId,
	--		O.DisplayTitle AS OrgName,
	--		O.OrderIndex AS OrgOrderIndex,
	--		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
	--		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
	--		SA.DepartmentId,
	--		SA.DepartmentName,
	--		SA.ExemptionTypeId,
	--		ISNULL(ETM.Title,'') AS ExemptionType,
	--		FHM.Id AS FeeHeadId,
	--		FHM.Title AS FeeHeadName,
	--		FHM.OrderIndex AS FeeHeadOrderIndex,
	--		@rFeeGroupId As FeeGroup,
	--		SA.OrgGroupBatchId AS BatchId,
	--		SA.BatchName AS BatchName,
	--		0.00 AS CancelAmount,
	--		(Select ISNULL(SUM(R.DiscountAmount),0) FROM  sFee.tReceipt R Where R.SourceId=SA.AcademicId)AS Discount
	--  FROM 
	--		sStudent.vStudentAcademic SA
	--		INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
	--		INNER JOIN 
	--		(
	--			SELECT 
	--				FS1.FeeId,
	--				FS1.Id,
	--				ISNULL(FS1.IsOptional,0)AS IsOptional,
	--				ISNULL(FS1.IsVariable,0)AS IsVariable,
	--				ISNULL(FS1.Amount,0)AS Amount,
	--				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
	--				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
	--				FS1.BatchId,
	--				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
	--				SA1.AcademicId,
	--				FM.Title AS FeeName,
	--				FM.Code AS FeeCode,
	--				FM.FeeHeadId
	--			FROM sFee.tFeeSetup FS1
	--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	--			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
	--			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	--			WHERE 
	--				((FS1.ClassId=@rClassId) OR (@rClassId=0))
	--				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	--				AND (FS1.IsOptional=0)
	--				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--				UNION ALL
					
	--			SELECT 
	--				FS1.FeeId,
	--				FS1.Id,
	--				ISNULL(FS1.IsOptional,0)AS IsOptional,
	--				ISNULL(FS1.IsVariable,0)AS IsVariable,
	--				ISNULL(FS1.Amount,0)AS Amount,
	--				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
	--				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
	--				FS1.BatchId,
	--				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
	--				SA1.AcademicId,
	--				FM.Title AS FeeName,
	--				FM.Code As FeeCode,
	--				FM.FeeHeadId
	--			FROM sFee.tFeeSetup FS1
	--		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	--		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
	--		AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	--			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
	--			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--		WHERE
	--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
	--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	--			AND (FS1.IsOptional=1)
	--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
	--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
	--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--			AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
	--		) FS ON FS.AcademicId=SA.AcademicId
	--		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
	--		LEFT JOIN
	--		(
	--			SELECT 
	--					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,R.DiscountAmount
	--			FROM
	--					sFee.tReceipt R 
	--				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
	--				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
	--				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
	--				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
	--				INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
	--				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
	--				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
	--			WHERE		
	--				(R.SourceTypeId = 2001)
	--				AND (R.IsObsolete = 0) 
	--				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	--				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	--				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--				AND (R.ReceiptDate <= @rUptoDate)
	--				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
	--				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--				--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--				AND (tSA.AdmissionDate <= @rUptoDate)
	--					GROUP BY FeeSetupId,R.SourceId,R.DiscountAmount
			
	--		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
	--		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
	--		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
	--		 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
	--		 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
	--		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	--		 LEFT JOIN
	--		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
	--		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
	--		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
	--		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	--		WHERE	
	--		((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
	--		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
	--		AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
	--		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--		--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	--		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--		AND ((SA.Code=@rCode) OR (@rCode=''))
	--		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	--		AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	--		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	--		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	--		 AND (
	--				 (@rFilterId = 0) -- All
	--				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
	--				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
	--				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
	--				 )	
	--	AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
	--	AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--	--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--	AND (tSA.AdmissionDate <= @rUptoDate)
	--	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
	--	Order by SA.RollNo 
	--END
	ELSE IF(@rReportId=30920)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.StatusId,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

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

			''  AdditionalRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			'' AS ExemptedRemarkFeeWise,
			'' AS ParentContactNo,--Added by dhananjay for Mantis Id : 35270	
			'' AS StudentContactNo,	--Mantis - 35489
			'' AS FatherName		--Mantis - 35489
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
			AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
			AND (tSA.AdmissionDate <= @rUptoDate)
			AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		Order by SA.RollNo
	END

	ELSE IF(@rReportId=30232) -- Mantis : 0028532  #Start 
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.StatusId,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

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

			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId) END  as ExampltedRemark,

			--CASE WHEN ISNULL(FA.AdditionalRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,3) END as AdditionalRemark,
			''  AdditionalRemark,
			--CASE WHEN ISNULL(FA.NotApplicableRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,4) END as NotApplicableRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			SAD.LeftDate,
			'' AS ExemptedRemarkFeeWise,
			'' AS ParentContactNo,--Added by dhananjay for Mantis Id : 35270
			'' AS StudentContactNo,	--Mantis - 35489
			'' AS FatherName		--Mantis - 35489
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')  
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
			WHERE	
			((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		Order by SA.RollNo
	END -- #End

	ELSE
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.StatusId,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

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

			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId) END  as ExampltedRemark,

			--CASE WHEN ISNULL(FA.AdditionalRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,3) END as AdditionalRemark,
			''  AdditionalRemark,
			--CASE WHEN ISNULL(FA.NotApplicableRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,4) END as NotApplicableRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			SAD.LeftDate,
			(STUFF((SELECT  ','+ tFA.DiscountRemark	FROM sFee.tFeeAllocation tFA INNER JOIN sFee.tFeeSetup tFS On tFS.Id = tFA.FeeSetupId
			WHERE tFA.SourceId = FA.SourceId AND (tFS.FeeId IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,',')) OR @rFeeId='')
			ORDER BY tFA.DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) AS ExemptedRemarkFeeWise	,	-- Mantis Id : 0030870
			--'' AS ParentContactNo, --Added by dhananjay for Mantis Id : 35270
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,	--Mantis - 35489
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,	--Mantis - 35489
			ISNULL(SA.MiddleName,'') AS FatherName	--Mantis - 35489
	  FROM	
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')  
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId		--Mantis - 35489


			WHERE	
			((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		Order by SA.RollNo
	END
	
	
	
END
GO
PRINT N'Altering Procedure [sFee].[pRptPendingFee100PercentGet]...';


GO
ALTER PROCEDURE [sFee].[pRptPendingFee100PercentGet]

 @rOrgId int = 0,
 @rBatchId int = 0,
 @rOrgGroupBatchId int = 0,
 @rClassId int = 0,
 @rDivisionId int = 0,
 @rReceiptBookId int = 0,
 @rDepartmentId int = 0,
 @rCommonBatch nvarchar(100) = '',
 @rAdmissionCategoryId int = 0,
 @rClassStatusId int = 0,
 @rIsDisplayOrgGroup bit=0,
 @rIsFilter bit=0,
 @rBuilder1 nvarchar(max) = '',
 @rBuilder2 nvarchar(max) = ''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF object_id('tempdb..#tTable') IS NOT NULL
	BEGIN
		DROP TABLE #tTable
	END
CREATE TABLE #tTable(
	AcademicId BIGINT NOT NULL,
	AdmissionCategoryId int,
	ReceiptBookId int
)
INSERT INTO #tTable
	SELECT SA.AcademicId, FS.AdmissionCategoryId, FS.ReceiptBookId
	FROM sFee.tFeeSetup FS
	INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId=FS.ClassId AND FS.BatchId = SA.BatchId AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
	--INNER JOIN sSetup.tBatchMaster BM ON FS.BatchId = BM.Id 
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
	WHERE 
	((SA.OrgId = @rOrgId)OR(@rOrgId = 0)) 
	AND ((SA.BatchId = @rBatchId) OR (@rBatchId = 0))
	AND (SA.BatchName = @rCommonBatch OR @rCommonBatch = '') 
	AND (SA.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND (SA.ClassStatusId = @rClassStatusId OR @rClassStatusId = 0)
	AND (SA.ClassId = @rClassId OR @rClassId = 0)
	AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
	AND (FS.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
	AND (FS.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
	GROUP BY FS.ClassId,SA.AcademicId,FS.AdmissionCategoryId, FS.ReceiptBookId


SELECT F.AcademicId, F.RollNo, F.Name, F.Code, F.ClassName , F.DivisionName , @rIsFilter AS IsFilter ,
	 @rIsDisplayOrgGroup AS IsDisplayOrgGroup, F.ClassOrderIndex, F.DivisionOrder AS DivisionOrderIndex,
	 @rBuilder1 AS Builder1, @rBuilder2 AS Builder2, 
	 --Mantis Start-0031251
	   F.ParentContactNo,
	 --Mantis End 
	  --add by dhananjay for mantis - 35664 
	  F.ClassId,
	  F.DivisionId, 
	  --add by dhananjay for mantis - 35664 
	  --startAdd for mantis : 0035819
	  [sFee].[fPendingFeeAmountAcademicIdwiseGet](F.AcademicId) AS PendingAmount,
	  F.DepartmentId,
	  F.OrgId,
	  F.DepartmentName,
	  F.OrganizationName 
	  --End Add for mantis : 0035819
	FROM
		(

		SELECT 
			Distinct --Add for mantis : 0035819
			SA.AcademicId, SA.RollNo,SA.Name,SA.Code, ISNULL(T.AcademicId,0) AS Pending, ISNULL(PS.AcademicId,0) AS [Partial]
			,SA.ClassName , SA.DivisionName , SA.ClassOrderIndex , SA.DivisionOrder
			,(
				SELECT (SUM(FS1.Amount)+Sum(FA1.VariableAmount)+ SUM(FA1.AdditionalAmount)) - (SUM(FA1.DiscountAmount)+ SUM(FA1.NotApplicableAmount)) 
				FROM sFee.tFeeAllocation FA1
				INNER JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId AND FA1.FeeSetupId = FS1.Id
				WHERE FA1.SourceId = SA.AcademicId 
					AND (FS1.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
					AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
			) AS IsFeePayAmount, 
			--Mantis Start-0031251
			ISNULL(SC.ParentContactNo, '') AS ParentContactNo,
			--Mantis End
			 --add by dhananjay for mantis - 35664 
			SA.ClassId, 
			SA.DivisionId ,
			 --add by dhananjay for mantis - 35664 
			 --Start Add for mantis : 0035819
			 SA.DepartmentId, 
			 SA.OrgId,
			 SA.DepartmentName,
			 SA.OrganizationName
			 --End Add for mantis : 0035819
		FROM sStudent.vStudentAcademic SA 
		INNER JOIN #tTable FS  on  FS.AcademicId = SA.AcademicId
		LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,R.SourceId AS AcademicId--, SA.Code,SA.Name 
			FROM sFee.tReceipt R
			--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 --AND((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((R.BatchId = @rBatchId) OR (@rBatchId = 0)) AND (R.IsObsolete = 0)
			AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0) 
			GROUP BY R.SourceId--, SA.Code,SA.Name
			)T ON T.AcademicId = SA.AcademicId
		LEFT JOIN 
			(
				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
					(
					SELECT 
						SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
					FROM sFee.tReceiptDetail RD
					INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					WHERE R.SourceTypeId = 2001
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
					Group By R.SourceId,FS.Id
					) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
					(
					SELECT Distinct SourceId 
					FROM sFee.tReceipt 
					) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 0
					AND ISNULL(FS1.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.Amount,0.00) > 0
					AND (FS1.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
					AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
							
				UNION 

				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
					SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
					FROM sFee.tReceiptDetail RD
					INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					WHERE R.SourceTypeId = 2001
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
					Group By R.SourceId,FS.Id
					) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
					SELECT Distinct SourceId 
					FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 1
					AND ISNULL(FS1.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.Amount,0.00) > 0
					AND (FS1.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
					AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)

			) PS ON PS.AcademicId=SA.AcademicId
			--Mantis Start-0031251
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =SA.StudentId 
			--Mantis End

		WHERE 
			
		((SA.OrgId = @rOrgId)OR(@rOrgId = 0)) 
		AND SA.StatusId =1
		AND ((SA.BatchId = @rBatchId) OR (@rBatchId = 0))
		AND (SA.BatchName = @rCommonBatch OR @rCommonBatch = '') 
		AND (SA.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND (SA.ClassStatusId = @rClassStatusId OR @rClassStatusId = 0)
		AND (SA.ClassId = @rClassId OR @rClassId = 0)
		AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
		AND (FS.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		AND (FS.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)	
		) 
		AS F 
		
	WHERE ISNULL(F.IsFeePayAmount,1) <> 0 AND F.Pending = 0 AND F.Partial = 0


	----For Dataset Drag and Drop
	--SELECT
	--CONVERT(BigInt,0) AS AcademicId,
	--0 AS RollNo,
	--'' AS Name,
	--'' AS Code,
	--'' AS ClassName,
	--'' AS DivisionName,
	--CONVERT(bit,0) AS IsFilter,
	--CONVERT(bit,0) AS IsDisplayOrgGroup,
	--0 AS ClassOrderIndex,
	--0 AS DivisionOrderIndex,
	--'' AS Builder1,
	--'' AS Builder2,
	--'' AS ParentContactNo, --Mantis 0031251
	-- --add by dhananjay for mantis35664 
	--0 AS ClassId,
	--0 As DivisionId,
	-- --add by dhananjay for mantis35664 
	-- 0 AS PendingAmount,
	-- 0 AS DepartmentId,
	-- 0 AS OrgId,
	-- '' AS DepartmentName,
	-- '' AS OrganizationName
END
GO
PRINT N'Altering Procedure [sFee].[pRptStudentLedgerGet]...';


GO
ALTER PROC [sFee].[pRptStudentLedgerGet]

	 @rAcademicId bigint,
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rDepositHeadId int,
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
     @rBatchId int
AS
BEGIN
WITH Tb0 as
( 
			SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
		     DA.CreatedDateTime,
		     '' AS ExpenseType,
			 VA.RollNo,
			 SA.AdmissionNumber,	
			 CASE WHEN DA.ReferenceSourceTypeId = 1021 THEN [sFee].[fnGetStockDepositeAdd] (DA.ReferenceSourceId)
			 ELSE '' END AS StockItemNameQuantity, --add for mantis : 0035191
			 (CASE WHEN DA.ReferenceSourceTypeId=1021 THEN 'Stock Return' ELSE 'Deposit Add' END) AS DepositType		--add for mantis: 35522
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = VA.StudentId

			Where 
		   ((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.DepositHeadId = @rDepositHeadId)
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
		    --AND VA.BatchId = @rBatchId
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
		    DAJ. CreatedDateTime,
		   ISNULL(ETM.Title,'')AS ExpenseType,
		   VA.RollNo,
		   SA.AdmissionNumber,
		   CASE WHEN DAJ.ReferenceSourceTypeId = 2039 THEN [sFee].[fnGetStockDepositeAdjustment] (DAJ.ReferenceSourceId)
			 ELSE '' END AS StockItemNameQuantity, --add for mantis : 0035191
			 '' AS DepositType		--add for mantis: 35522
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  INNER JOIN sFee.tFeeDepositExpenseTypeMaster ETM ON ETM.Id =DAJ.FeeDepositExpenseTypeId
			  INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = VA.StudentId
			Where 
			((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
		  -- AND VA.BatchId = @rBatchId
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
		    DR.CreatedDateTime,
		     '' AS ExpenseType,
			 VA.RollNo,
			 SA.AdmissionNumber,
			 '' AS StockItemNameQuantity,
			 '' AS DepositType		--add for mantis: 35522
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			  INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = VA.StudentId
			Where 
			((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			--AND VA.BatchId = @rBatchId
)
,Tb1 as
( 
	SELECT DepositDate,Credit,Debit,Row_Number() over (order by CreatedDateTime asc) as OrderId,AcademicId,Code,SUId,StudentName,Class ,CreatedDateTime,ExpenseType,RollNo,AdmissionNumber,StockItemNameQuantity,DepositType FROM Tb0	--add DepositType for mantis: 35522
)

--SELECT * FROM Tb1

  SELECT T1.DepositDate,
         T1.[Credit],
         T1.[Debit],(Sum(T2.Credit) - Sum(T2.Debit)) as Balance,
         T1.SUId,
         T1.Code,
         T1.StudentName,
         T1.Class,
        T1.CreatedDateTime,
        T1.ExpenseType,
		T1.RollNo,
		T1.AdmissionNumber,
		@rIsBasedOnSUId AS BasedOnSUID,
		T1.StockItemNameQuantity,
		T1.DepositType		--add for mantis: 35522

		 FROM Tb1 as T1
		 INNER JOIN Tb1 as T2 ON T1.OrderId >= T2.OrderId
		 Group By T1.DepositDate,T1.Credit,T1.Debit,T1.AcademicId,T1.SUId,T1.Code,T1.StudentName,T1.Class,T1.CreatedDateTime,T1.ExpenseType,T1.RollNo,T1.AdmissionNumber,T1.StockItemNameQuantity,T1.DepositType		--add T1.DepositType for mantis: 35522
		 Order by T1.CreatedDateTime 
END
GO
PRINT N'Altering Procedure [sFee].[pStudentLedgerGet]...';


GO
ALTER PROCEDURE [sFee].[pStudentLedgerGet]  
   
  @rCode  nvarchar(20)='',  
  @rSUId nvarchar(50)='',  
  @rDepositHeadId int,  
  @rOrgId int,  
  @rBatchId int=0,  
  @rAcademicId bigint=0  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON   
BEGIN   
 SELECT A.DepositDate ,  
        A.Credit,  
        A.Debit,  
  A.ExpenseType,  
  A.TransactionType, 
  A.BatchName, 
  (CASE WHEN A.Debit = 0 THEN 'Credited' ELSE 'Debited' END)AS PayType,
  A.DepositType		--add for mantis: 35522
         FROM(  
   SELECT   
   DA.DepositDate AS DepositDate,  
   ISnull (DA.Amount,0) AS Credit,  
      0 AS Debit,  
   '' AS ExpenseType,  
   'Deposit Add' AS TransactionType  ,
   DA.CreatedDateTime,
   VA.BatchName,
   (CASE WHEN DA.ReferenceSourceTypeId=1021 THEN 'Stock Return' ELSE 'Deposit Add' END) AS DepositType		--add for mantis: 35522
   FROM sStudent.vStudentAcademic  VA  
   INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId   
   Where   
   ((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))  
   AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))  
   AND (DA.DepositHeadId = @rDepositHeadId)   
   AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))   
   AND VA.StudentId= @rAcademicId  
   ---AND VA.BatchId = @rBatchId  
   UNION ALL   
   SELECT   
   DAJ.AdjustmentDate As DepositDate,  
   0  AS Credit,  
   ISnull (DAJ.Amount,0)  AS Debit,  
   ISNULL(ETM.Title,'')AS ExpenseType,  
   ('Expense'+' '+ISNULL(ETM.Title,'')) AS TransactionType  ,
   DAJ.CreatedDateTime,
   VA.BatchName,
   '' AS DepositType		--add for mantis: 35522
   FROM sStudent.vStudentAcademic  VA  
     INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId  
     INNER JOIN sFee.tFeeDepositExpenseTypeMaster ETM ON ETM.Id =DAJ.FeeDepositExpenseTypeId  
   Where   
   ((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))  
   AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))  
   AND (DAJ.DepositHeadId = @rDepositHeadId)   
   AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))   
   --AND VA.BatchId = @rBatchId  
   AND VA.StudentId = @rAcademicId  
   UNION ALL   
   SELECT   
   DR.RefundDate As DepositDate,  
   0  AS Credit,  
   ISnull (DR.RefundAmount,0)  AS Debit,  
   '' AS ExpenseType,  
   'Deposit Refund' AS TransactionType ,
    DR.CreatedDateTime,
	VA.BatchName,
	'' AS DepositType		--add for mantis: 35522
   FROM sStudent.vStudentAcademic  VA  
     INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId  
   Where   
   ((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))  
   AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))  
   AND (DR.DepositHeadId = @rDepositHeadId)   
   AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))   
     -- AND VA.BatchId = @rBatchId  
      AND VA.StudentId = @rAcademicId  
   )A   
   Order BY A.DepositDate,A.CreatedDateTime
     
END
GO
PRINT N'Altering Procedure [sHostel].[pDepositAddBulkGet]...';


GO


ALTER PROCEDURE [sHostel].[pDepositAddBulkGet]
       
       @rOrgId int=0,          
       @rHostelId int=0,
       @rCode nvarchar(20)='',
       @rRoomCategoryId int=0,
       @rBuildingId int=0,
       @rRoomId int=0,
       @rOrgGroupBatchId int=0,
	   @rStrSuid nvarchar(max)=''--Added for mantis : 35982 by Nilesh
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    SELECT  
		vSA.OrgId,
		vSA.StudentId,
		vSA.AcademicId,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
       ISNULL(VSA.SUID,'') AS SUID
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = vSA.StudentId AND AR.SourceTypeId=2003
		AND AR.OrgGroupBatchId = vSA.OrgGroupBatchId
		INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
  WHERE  
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (RM.HostelId=@rHostelId OR @rHostelId=0)
		AND (RM.RoomCategoryId=@rRoomCategoryId OR @rRoomCategoryId=0)
		AND (RM.BuildingId=@rBuildingId OR @rBuildingId=0)
		AND (RM.Id=@rRoomId OR @rRoomId=0)
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND AR.OrgGroupBatchId=@rOrgGroupBatchId
		AND (ISNULL(vSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rStrSuid,',')) OR @rStrSuid='')--Added for mantis : 35982 by Nilesh
   ORDER BY vSA.OrgId,vSA.ClassOrderIndex,vSA.DivisionOrder,vSA.RollNo
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployee360ProfileFullGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pEmployee360ProfileFullGet]
	 
	@rEmployeeId bigint,
	
	--newly added parameter for report 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint = 0,
	@rOrgId smallint = 0,
	@rStrEmployeeId nvarchar(max)='',
	@rEmployeeTypeId [int] =0,
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rGenderId [int]= 0,	
	@rDesignationId [int]= 0,	
	@rAgeFrom nvarchar(10)='',
	@rAgeTo nvarchar(10)='',
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint= 0,
	@rEmployeeStatusId smallint=0
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	
SELECT 
		 --Personal Details
		 EM.Id,
		 EM.Code,
		 ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName,
		 ISNULL(EP.UIDNumber,'') AS UIDNumber,
		 ISNULL(EP.DateOfBirth,'') AS DateOfBirth,
		 CONVERT(varchar(20) ,ISNULL(EP.DateOfBirth,''),105) AS DateOfBirthJSON,
		 ISNULL(GM.Title,'') AS Gender,
		 ISNULL(MM.Title,'') AS MeritalStatus,
		 ISNULL(BGM.Title,'') AS BloodGroup,
		 ISNULL(EP.Qualification,'') AS Qualification,
		 ISNULL(EP.FamilyCast,'') AS FamilyCast,
		 
		 --Communication
		 ISNULL(EC.PresentStreetOne,'')+' '+ISNULL(EC.PresentStreetTwo,'')+' '+ISNULL(EC.PresentStreetThree,'') AS PresentAddress,
		 ISNULL(EC.PresentCity,'') AS PresentCity,
		 ISNULL(EC.PresentState,'') AS PresentState,
		 ISNULL(EC.PresentCountry,'') AS PresentCountry,
		 ISNULL(EC.PresentZipCode,'') AS PresentZipCode,
		 ISNULL(EC.PresentContactNo,'') AS PresentContactNo,
		
		 ISNULL(EC.PermanentStreetOne,'')+' '+ISNULL(EC.PermanentStreetTwo,'')+' '+ISNULL(EC.PermanentStreetThree,'') AS PermanentAddress,
		 ISNULL(EC.PermanentCity,'') AS PermanentCity,
		 ISNULL(EC.PermanentState,'') AS PermanentState,
		 ISNULL(EC.PermanentCountry,'') AS PermanentCountry,
		 ISNULL(EC.PermanentZipCode,'') AS PermanentZipCode,
		 ISNULL(EC.PermanentContactNo,'') AS PermanentContactNo,
		 
		 ISNULL(EC.EmergencyStreetOne,'')+' '+ISNULL(EC.EmergencyStreetTwo,'')+' '+ISNULL(EC.EmergencyStreetThree,'') AS EmergencyAddress,
		 ISNULL(EC.EmergencyCity,'') AS EmergencyCity,
		 ISNULL(EC.EmergencyState,'') AS EmergencyState,
		 ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,
		 ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,
		 ISNULL(EC.EmergencyContactNo,'') AS EmergencyContactNo,
		
		 --Job Details
		 ISNULL(EJ.DateOfJoining,'') AS DateOfJoining,	
		 CONVERT(varchar(20),ISNULL(EJ.DateOfJoining,''),105) AS DateOfJoiningJSON,		
		 (COALESCE(CAST(EJ.DateOfleaving AS NVARCHAR(23)),'')) AS DateOfleaving,
		 (CONvert(varchar(20),EJ.DateOfleaving, 105)) AS DateOfleavingJSON,
		 ISNULL(EJ.JobRemark,'') AS JobRemark,
		 ISNULL(EJ.ReferenceRemark,'') AS ReferenceRemark,
		 ISNULL(EDM.Title,'') AS EmployeeDesignation,
		 ISNULL(DM.Title,'') AS OrganizationDepartment,
		 ISNULL(EGM.Title,'') AS EmployeeGrade,
		 ISNULL(GrpM.Title,'') AS EmployeeGroup,
		 ISNULL(ETM.Title,'') AS EmployeeType,
		
		 ----Previous Employment
		 --ISNULL(EPE.CompanyName,'') AS PrevCompanyName,
		 --ISNULL(EPE.Designation,'') AS PrevDesignation,
		 --ISNULL(EPE.Duration,'') AS Duration,
		 --ISNULL(EPE.LastSalary,0) AS LastSalary,
		 --ISNULL(EPE.ReasonForLeaving,'') AS ReasonForLeaving,
		 --ISNULL(EPE.JobDescription,'') AS JobDescription,
		
		 --Notification Details
		 ISNULL(EC.PersonalEmail,'') As PersonalEmail,
		 ISNULL(EC.MobileNumber,'') AS MobileNumber,
		 ISNULL(EC.PhoneNoCompany,'') AS PhoneNoCompany,
		 ISNULL(EC.ExtensionNo,'') AS ExtensionNo,
		 ISNULL(EC.CompanyEmail,'') AS CompanyEmail,
		
		 --EI.EmployeePhoto,
		 ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		 ISNULL(ESO.BankName,'') AS BankName,
		 ISNULL(ESO.Branch,'') AS BankBranch,
		 ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
		 ISNULL(ESO.PanNumber,'') AS PanNumber,
		 ISNULL(ESO.EPFNumber,'') AS EPFNumber,
		 ISNULL(ESO.IncrementDate,'') AS IncrementDate,
		 Convert( varchar(20),ISNULL(ESO.IncrementDate,''),105) AS IncrementDateJSON,
		 ISNULL(ESO.BasicPay,0) AS BasicPay,
	     --ISNULL(EFD.Occupation,'') AS Occupation,
		 convert(nvarchar(20),EM.Id) AS EmployeeIdText,
		 convert(nvarchar(20),@rOrgId) AS OrgIdText,
		 ISNULL(EJ.OrganizationDepartmentId,0) AS DepartmentId,
		 OM.DisplayTitle AS OrgTitle,
		 ISNULL(EP.AdhaarNumber,'') AS AdhaarNumber,
		 ISNULL(ESO.Payscale,'') AS Payscale,
		 --[sHrm].[fTeachingSubjectGet] (EM.Id) AS TeachingSubject
		 EJ.Subjects AS TeachingSubject,
		 RM.Title AS Religion,
		 CCM.Title AS CasteCategory,
		 EP.FamilyCast AS FamilyCast,
		 EP.UIDNumber,
		 EP.IdentificationMark1,
		 EP.AdhaarNumber,
		 EP.Qualification,
		 EmployeePhoto = (SELECT CAST(EI.EmployeePhoto as varbinary(max)) FOR XML PATH(''), BINARY BASE64)	-- MantisId : 0035912	
  FROM 
		sHrm.tEmployeeMaster EM 
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.ID = EC.EmployeeId
		INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId = EM.Id
		INNER JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.ID	
		--INNER JOIN sHrm.tEmployeePreviousEmployment EPE ON EPE.EmployeeId=EM.ID
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = EP.BloodGroupId    
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EP.GenderId
		LEFT JOIN sCommon.tMaritalStatusMaster MM ON MM.Id =  EP.MaritalstatusId
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EP.ReligionId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.ID = EJ.EmployeeDesignationId
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJ.OrganizationDepartmentId
		LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id=EJ.EmployeeTypeId
		LEFT JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id=EJ.EmployeeGradeId
		LEFT JOIN sHrm.tEmployeeGroupMaster GrpM ON GrpM.Id=EJ.EmployeeGroupId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = EP.CastCategoryId
		--LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON EFD.EmployeeId = EM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId  
  WHERE 
		(EM.Id=@rEmployeeId OR @rEmployeeId = 0)
		AND (ISNULL(EM.Id,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
		AND ((EM.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
		AND (ETM.Id = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
		AND (DM.Id = @rDepartmentId OR @rDepartmentId = 0)
		AND (EM.StatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
		AND (GrpM.Id=@rEmployeeGroupId OR @rEmployeeGroupId=0) 
		AND (EGM.Id = @rGradeId OR @rGradeId = 0)
		AND (EDM.Id = @rDesignationId OR @rDesignationId = 0)
		AND (GM.Id = @rGenderId OR @rGenderId = 0)
		AND ((DATEDIFF(yy,EP.DateOfBirth,sCommon.fGetDate()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
		AND ((DATEDIFF(yy,EP.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
		AND  ( EM.OrgId = @rOrgId OR @rOrgId = 0)
		AND ISNULL(EM.IsOtherUser,0) = 0 	 
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeReplacementDelete]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeReplacementDelete]
	 
        @rExistingEmployeeId BIGINT,
		@rTitle NVARCHAR(500)
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF (@rTitle = 'Assign Teacher')
	BEGIN
		delete from sTimetable.tAssignTeacher where EmployeeId = @rExistingEmployeeId
	END

	IF (@rTitle = 'Teacher Subject Division')
	BEGIN
		
		delete from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId
		
		delete from sAcademic.tTeacherSubjectDivision where EmployeeId = @rExistingEmployeeId		
	END

	IF (@rTitle ='Time Table')
	BEGIN
		Delete sTimetable.tTimeTable where EmployeeId  = @rExistingEmployeeId
		
		DELETE sTimetable.tTeacherWorkLoad  WHERE EmployeeId = @rExistingEmployeeId 
	END
	
	IF (@rTitle ='User Access')
	BEGIN

		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		
		IF (@lExistingUserId IS NULL)
		BEGIN
			Return
		END
		ELSE
		BEGIN
		
			delete from sSecurity.tUserOrganization  WHERE UserId=@lExistingUserId

			delete from sSecurity.tUserAccess  WHERE UserId=@lExistingUserId
		END
	END

	IF (@rTitle ='Class Teacher')
	BEGIN
		Update sSetup.tDivisionMaster SET InchargeEmployeeId = 0 where  InchargeEmployeeId =  @rExistingEmployeeId
	END

	-- #Start Remove for MantisId : 0035518
	--IF (@rTitle ='Lesson Plan')
	--BEGIN
	--	Delete sAcademic.tLessonPlan where EmployeeId =  @rExistingEmployeeId
	--END
	-- #End Remove for MantisId : 0035518
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeReplacementDeleteAndTransfer]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeReplacementDeleteAndTransfer]
	 
        @rExistingEmployeeId BIGINT,
		@rNewEmployeeId BIGINT,
		@rTitle NVARCHAR(500)
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--IF OBJECT_ID('tempdb..#tmpSplitTable') IS NOT NULL DROP TABLE #tmpSplitTable

	--CREATE Table #tmpSplitTable
	--(
	--	Id NVARCHAR(150)
	--)

	--INSERT INTO #tmpSplitTable
	--SELECT CAST(item AS NVARCHAR(150)) AS Id FROM  sCommon.fnsplit(@rId,',')
	
	IF (@rTitle = 'Assign Teacher')
	BEGIN
		IF NOT EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rNewEmployeeId)
		begin
			INSERT INTO sTimetable.tAssignTeacher
			Select TimeTableSchemaId, @rNewEmployeeId from sTimetable.tAssignTeacher WHERE EmployeeId = @rExistingEmployeeId
			delete from sTimetable.tAssignTeacher where EmployeeId = @rExistingEmployeeId
		end		
	END

	IF (@rTitle = 'Teacher Subject Division')
	BEGIN
		INSERT INTO sAcademic.tTeacherSubject
		Select @rNewEmployeeId,SubjectId from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId 
		and SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		
		delete from sAcademic.tTeacherSubject where EmployeeId = @rExistingEmployeeId
		
		Insert into sAcademic.tTeacherSubjectDivision 
		select @rNewEmployeeId, SubjectId, DivisionId,SubjectCordinatorEmployeeId 
		from sAcademic.tTeacherSubjectDivision 
		where SubjectId NOT IN (select SubjectId from sAcademic.tTeacherSubjectDivision  where EmployeeId = @rNewEmployeeId)
		AND EmployeeId = @rExistingEmployeeId
		
		delete from sAcademic.tTeacherSubjectDivision where EmployeeId = @rExistingEmployeeId		
	END

	IF (@rTitle ='Time Table')
	BEGIN
		Update sTimetable.tTimeTable
		Set EmployeeId = @rNewEmployeeId from sTimetable.tTimeTable where EmployeeId  = @rExistingEmployeeId
		
		UPDATE sTimetable.tTeacherWorkLoad SET EmployeeId = @rNewEmployeeId WHERE EmployeeId = @rExistingEmployeeId 
	END
	
	IF (@rTitle ='User Access')
	BEGIN
		declare @lExistingUserId bigint= (select Id from sSecurity.tUser where SourceId = @rExistingEmployeeId AND SourceTypeId = 95)
		declare @lNewUserId bigint= (select Id from sSecurity.tUser where SourceId = @rNewEmployeeId AND SourceTypeId = 95)

		IF (@lNewUserId IS NULL)
		BEGIN
			Return
		END
		ELSE
		BEGIN
		Insert into sSecurity.tUserOrganization 
		select OrgId, @lNewUserId from sSecurity.tUserOrganization WHERE UserId=@lExistingUserId
		AND OrgId NOT in (select OrgId from sSecurity.tUserOrganization WHERE UserId=@lNewUserId)

		delete from sSecurity.tUserOrganization  WHERE UserId=@lExistingUserId

		INSERT INTO sSecurity.tUserAccess
		SELECT SourceTypeId, SourceId, @lNewUserId FROM sSecurity.tUserAccess WHERE UserId=@lExistingUserId
		AND SourceId not in (select SourceId from  sSecurity.tUserAccess WHERE UserId=@lNewUserId)

		delete from sSecurity.tUserAccess  WHERE UserId=@lExistingUserId
		END
	END

	IF (@rTitle ='Class Teacher')
	BEGIN
		Update sSetup.tDivisionMaster SET InchargeEmployeeId = @rNewEmployeeId where  InchargeEmployeeId = @rExistingEmployeeId
	END

	-- #Start Remove for MantisId : 0035518
	--IF (@rTitle ='Lesson Plan')
	--BEGIN
	--	Update sAcademic.tLessonPlan SET EmployeeId = @rNewEmployeeId where EmployeeId = @rExistingEmployeeId
	--END
	-- #End Remove for MantisId : 0035518

	--Drop Table #tmpSplitTable
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeReplacementGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeReplacementGet]
	 
        @rEmployeeId bigint
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Declare @lTeacherSubjectId bigint = 0 , @lTeacherDivisionId bigint = 0
	IF OBJECT_ID('tempdb..#tmpTable') IS NOT NULL DROP TABLE #tmpTable
	CREATE Table #tmpTable 
	(
		Id bigint IDENTITY,
		Title nvarchar(50)
	)

	IF EXISTS(select top 1 1 from sTimetable.tAssignTeacher where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Assign Teacher'
		)
	END


	set @lTeacherSubjectId = (select top 1 1 from sAcademic.tTeacherSubject where EmployeeId = @rEmployeeId)
	SET @lTeacherDivisionId = (select top 1 1 from sAcademic.tTeacherSubjectDivision where EmployeeId = @rEmployeeId)
	IF ((@lTeacherSubjectId = 1) OR (@lTeacherDivisionId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Teacher Subject Division'
		)
	END

	IF EXISTS (select top 1 1 from sTimetable.tTimeTable where EmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Time Table'
		)
	END
		
	declare @lUserId bigint= (select top 1 Id from sSecurity.tUser where SourceId = @rEmployeeId AND SourceTypeId = 95)
	declare @lUserOrganizationId int ,@lUserAccessId int
	SET @lUserOrganizationId = (SELECT Top 1 1 FROM sSecurity.tUserOrganization WHERE UserId=@lUserId)
	SET @lUserAccessId= (SELECT top 1 1 FROM sSecurity.tUserAccess WHERE UserId=@lUserId)
	IF ((@lUserOrganizationId = 1) OR (@lUserAccessId = 1))
	BEGIN
		Insert INTO #tmpTable Values
		(
			'User Access'
		)
	END

	IF EXISTS (select top 1 1 from sSetup.tDivisionMaster where InchargeEmployeeId = @rEmployeeId)
	BEGIN
		Insert INTO #tmpTable Values
		(
			'Class Teacher'
		)
	END	

	-- #Start Remove for MantisId : 0035518
	--IF EXISTS (select top 1 1 from sAcademic.tLessonPlan where EmployeeId = @rEmployeeId)
	--BEGIN
	--	Insert INTO #tmpTable Values
	--	(
	--		'Lesson Plan'
	--	)
	--END
	-- #End Remove for MantisId : 0035518

	select * from #tmpTable order by Title

	Drop Table #tmpTable
END
GO
PRINT N'Altering Procedure [sHrm].[pLeaveHierarchyListingAllGet]...';


GO



ALTER PROCEDURE [sHrm].[pLeaveHierarchyListingAllGet]  
(  
	@rOrgId int,  
	@rLeaveHierarchyLevelId bigint = 0,
    @rEmployeeId  bigint,     
    @rFromDate date,  
    @rLeaveTypeId int,  
    @rTodate date,  
    @rOrgGroupBatchId int,  
    @rEmployeeCode nvarchar(100)='',  
    @rEmployeeName nvarchar(100)='',  
    @rStatusId int = 0,  
    @rDepartmentId int,
	@rIsAdmin bit = 0
 )  
AS  
SET NOCOUNT ON  
  
IF(@rIsAdmin = 0)

BEGIN  
 
IF OBJECT_ID('tempdb..#EmployeeListTemp') IS NOT NULL
	BEGIN
		DROP TABLE #EmployeeListTemp;
	END     
	CREATE Table #EmployeeListTemp(EmployeeId Bigint, EmployeeName nvarchar(50))

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

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

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

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

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

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

	END


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

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

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


While @lHierarchyLevel > @lCount2

	BEGIN

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

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

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

	END


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

ELSE

BEGIN

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


GO


ALTER PROCEDURE [sHrm].[pStaffAttendaceDashboardGet]
	 
	 @rTypeId smallint,
	 @rUptoDate date='',
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDepartmentId int=0,
	 @rCommonOrgGroupBatchId int=0,
	 @rSyncDate int =0,
	 @rUserId bigint =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

if @rTypeId=1
BEGIN
	IF(@rSyncDate=1)
		BEGIN
			DELETE  sHrm.tTempStaffAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			INSERT INTO sHrm.tTempStaffAttendance
	SELECT     
    OGM.Id AS OrgGroupId,
    OGM.Title As OrgGroupTitle,
    0 As OrgId,
	'' As OrgTitle,
 --TotalCount
			ISNULL((SELECT COUNT(EM.Id) FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
			INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
			--INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
			--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 AND  ISNULL(EM.IsOtherUser,0) = 0),0) 
			AS TotalCount,

 --PresentCount
    ISNULL((SELECT 
        COUNT(ETRP.EmployeeId) 
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DME.OrgGroupId=OGM.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
      ),0) AS PresentCount,
--AbsentCount
      ISNULL((SELECT 
         COUNT(ETRP.EmployeeId) 
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
      WHERE DME.OrgGroupId=OGM.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
            AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
      ),0) As AbsentCount,
--LeaveCount
    ISNULL( (SELECT 
        COUNT(EM.Id)
     FROM sHrm.tLeave SHT
          INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId				
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		  INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				
	 WHERE DME.OrgGroupId=OGM.Id  AND COGBM.Id=@rCommonOrgGroupBatchId   and EM.statusid=7 
		  AND  ISNULL(EM.IsOtherUser,0) = 0
		  AND((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	),0) As LeaveCount,
--AB10Count
	 ISNULL((SELECT 
	    COUNT(EmployeeId) 
	FROM(
         SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,
             (OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR						
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
		WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
		
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	 ) AS Tmp),0) As 'AB10Count',
--AB3DaysCount
    ISNULL((SELECT 
	   COUNT(EmployeeId) FROM(
	      SELECT 
	          ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		      d.EmployeeId,
		      AttendanceDate,
		      d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
              INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			  INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
         WHERE
              DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
              IsPresent IN(0) 
              AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
         GROUP BY d.EmployeeId,AttendanceDate,IsPresent
         ) as sfsf
     WHERE rowno=3),0) as AB3DaysCount,
--Leave3DayCount    
  ISNULL((SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d
		 	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
             INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
             LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
           DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
          d.ToDate=CONVERT(char(10), @rUptoDate,126)
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
    ),0)  As Leave3DayCount,
   
--HundredPerAttnCount		
    ISNULL((SELECT 
      COUNT(EmployeeId) FROM (
          SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,(OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) as PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(numeric(10,2),((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage												
		  FROM sHrm.tEmployeeAttendanceRegister EAR						
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID						
						INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID						
		  WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)		
		  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	   ) AS Tmp),0) As 'HundredPerAttnCount',
--PendingCount	  
	    ISNULL((SELECT 
        COUNT(EM.Id) 
		 FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE OGM.Id=OGMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 AND  ISNULL(EM.IsOtherUser,0) = 0
	 
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ),0) AS PendingCount,
	   
	   @rUptoDate,
		  @rCommonOrgGroupBatchId,GetDate()	
	   
    FROM sSetup.tOrgGroupMaster OGM
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    WHERE OGM.Id<>1 AND COGBM.Id=@rCommonOrgGroupBatchId   AND ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
	And ISNULL(OGM.IsObsolete,0) = 0
	SELECT * FROM sHrm.tTempStaffAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		END
	ELSE
		Print 1
		BEGIN
			  IF  Exists(select 1 from sHrm.tTempStaffAttendance    where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND EmployeeAttendanceDate=  CONVERT(date,@rUptoDate,102)AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
			BEGIN
	
				SELECT * FROM sHrm.tTempStaffAttendance   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN
			DELETE  sHrm.tTempStaffAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			INSERT INTO sHrm.tTempStaffAttendance
--TotalCount	
				SELECT     
    OGM.Id AS OrgGroupId,
    OGM.Title As OrgGroupTitle,
    0 As OrgId,'' As OrgTitle,
	    ISNULL((SELECT 
        COUNT(EM.Id) 
     FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
          --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				    
		  --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		  --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID          
	 WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0),0) AS TotalCount,
  --  (SELECT 
  --      COUNT(EM.Id) 
  --   FROM sHrm.tEmployeeMaster EM
		--  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		--  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--  --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --        --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
  --        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				    
		--  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		--  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID          
	 --WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
	 --and EM.statusid=7) AS Total,

    ISNULL((SELECT 
        COUNT(ETRP.EmployeeId) 
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DME.OrgGroupId=OGM.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
		   and EM.statusid=7
      ),0) AS PresentCount,

     ISNULL((SELECT 
         COUNT(ETRP.EmployeeId) 
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
      WHERE DME.OrgGroupId=OGM.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
            AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			 and EM.statusid=7
      ),0) As AbsentCount,
      
    ISNULL((SELECT 
        COUNT(EM.Id)
     FROM sHrm.tLeave SHT
          INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId				
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		  INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				
	 WHERE DME.OrgGroupId=OGM.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
		  AND((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  and EM.statusid=7
	),0) As LeaveCount,

	ISNULL((SELECT 
	    COUNT(EmployeeId) 
	FROM(
         SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,
             (OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR						
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
		WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
		
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	 ) AS Tmp),0) As 'AB10Count',

   ISNULL((SELECT 
	   COUNT(EmployeeId) FROM(
	      SELECT 
	          ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		      d.EmployeeId,
		      AttendanceDate,
		      d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
              INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			  INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
         WHERE
              DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
              IsPresent IN(0) 
              AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			  and EM.statusid=7
         GROUP BY d.EmployeeId,AttendanceDate,IsPresent
         ) as sfsf
     WHERE rowno=3),0) as AB3DaysCount,
    
 ISNULL((SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d
		 	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
             INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
             LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
           DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
          d.ToDate=CONVERT(char(10), @rUptoDate,126) 
		  and EM.statusid=7
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
    ),0)  As Leave3DayCount,
   
		
   ISNULL((SELECT 
      COUNT(EmployeeId) FROM (
          SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,(OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) as PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(numeric(10,2),((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage												
		  FROM sHrm.tEmployeeAttendanceRegister EAR						
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID						
						INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID						
		  WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)		
		  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	   ) AS Tmp),0) As 'HundredPerAttnCount',

	   ISNULL((SELECT COUNT(EM.Id) 
		 FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		 WHERE OGM.Id=OGMM.Id 
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
							WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ),0) AS PendingCount,
	   @rUptoDate,
		  @rCommonOrgGroupBatchId,GetDate()	
	   
    FROM sSetup.tOrgGroupMaster OGM
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    WHERE OGM.Id<>1 AND COGBM.Id=@rCommonOrgGroupBatchId  AND ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
	And ISNULL(ISNULL(OGM.IsObsolete,0),0) = 0
	SELECT * FROM sHrm.tTempStaffAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			END
		END
  END
  
ELSE IF @rTypeId=2  

BEGIN
IF(@rUserId = 0)
  BEGIN
  SELECT 
     OGMT.Id As OrgGroupId,
     OM.Id AS OrgId, 
     OM.DisplayTitle AS OrgTitle,
     OGMT.Title As OrgGroupTitle,
	 (SELECT 
         COUNT(EM.Id) 
      FROM sHrm.tEmployeeMaster EM
		 INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
         --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
         INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
       WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
       AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) As TotalCount,
   --  (SELECT 
   --      COUNT(EM.Id) 
   --   FROM sHrm.tEmployeeMaster EM
		 --INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 --INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 ----INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --      --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
   --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
   --    WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
   --    AND EM.statusid=7) As Total,
        
      (SELECT 
          COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
       WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=1  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS PresentCount,
        
      (SELECT 
           COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEM ON OMEM.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OMEM.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=0  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS AbsentCount, 	

	   (SELECT 
	         COUNT(EM.Id)
        FROM sHrm.tLeave SHT
           INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
           INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
		   INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		      
		   INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	       LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID				
		 WHERE EJD.OrgId=OM.Id AND				
			  ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			   AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  AND COGBM.Id=@rCommonOrgGroupBatchId		
			   and EM.statusid=7		
		) As LeaveCount,
		
   (SELECT 
	   COUNT(EmployeeId) FROM(
           SELECT    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DME.Id,DME.Code As DeptCode,
              (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  (EC.MobileNumber) AS ContactNo,
			   COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
               CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
			FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID												
			WHERE EJD.OrgId=OM.Id AND 
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
				and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	      ) AS Tmp) As 'AB10Count',
	
	(SELECT COUNT(EmployeeId) from(
	    SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
		FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
              AND COGBM.Id=@rCommonOrgGroupBatchId
			  and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) as T
        WHERE rowno=3) AS AB3DaysCount,
        
     (SELECT 
        COUNT(EmployeeId) FROM(
	       SELECT 
			d.EmployeeId,
			d.FromDate,
			d.ToDate
		  FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
		and EM.statusid=7
        ) AS Temp 
        WHERE (DATEDIFF(d, FromDate, ToDate)=2)
        )  AS Leave3DayCount,
      
    (SELECT 
        COUNT(EmployeeId) FROM  (
           SELECT    
             OGMEL.Id as OrgGroupId,
             OGMEL.Title As OrgGroupTitle,
             OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
             DME.Id,DME.Code As DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 (EC.MobileNumber) AS ContactNo,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
              convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage

            FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		    WHERE EJD.OrgId=OM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                 EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				 and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	     ) AS Tmp) As 'HundredPerAttnCount'
		 ,
	(SELECT  COUNT(EM.Id) 
		FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE OM.Id=OMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ) AS PendingCount,
	   getdate()AS UpdateDate
			
    FROM 
       sSetup.tOrgGroupMaster OGMT 
    INNER JOIN sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId    
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
    WHERE OGMT.Id=@rOrgGroupId AND COGBML.Id=@rCommonOrgGroupBatchId 
	And ISNULL(OGMT.IsObsolete,0) = 0
	ORDER BY OM.OrderIndex
  END   
ELSE IF(@rUserId <> 0)
  BEGIN
  SELECT 
     OGMT.Id As OrgGroupId,
     OM.Id AS OrgId, 
     OM.DisplayTitle AS OrgTitle,
     OGMT.Title As OrgGroupTitle,
	 (SELECT 
         COUNT(EM.Id) 
      FROM sHrm.tEmployeeMaster EM
		 INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
         --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
         INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
       WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
       AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) As TotalCount,
   --  (SELECT 
   --      COUNT(EM.Id) 
   --   FROM sHrm.tEmployeeMaster EM
		 --INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 --INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 ----INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --      --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
   --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
   --    WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
   --    AND EM.statusid=7) As Total,
        
      (SELECT 
          COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
       WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=1  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS PresentCount,
        
      (SELECT 
           COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEM ON OMEM.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OMEM.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=0  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS AbsentCount, 	

	   (SELECT 
	         COUNT(EM.Id)
        FROM sHrm.tLeave SHT
           INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
           INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
		   INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		      
		   INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	       LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID				
		 WHERE EJD.OrgId=OM.Id AND				
			  ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			   AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  AND COGBM.Id=@rCommonOrgGroupBatchId		
			   and EM.statusid=7		
		) As LeaveCount,
		
   (SELECT 
	   COUNT(EmployeeId) FROM(
           SELECT    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DME.Id,DME.Code As DeptCode,
              (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  (EC.MobileNumber) AS ContactNo,
			   COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
               CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
			FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID												
			WHERE EJD.OrgId=OM.Id AND 
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
				and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	      ) AS Tmp) As 'AB10Count',
	
	(SELECT COUNT(EmployeeId) from(
	    SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
		FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
              AND COGBM.Id=@rCommonOrgGroupBatchId
			  and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) as T
        WHERE rowno=3) AS AB3DaysCount,
        
     (SELECT 
        COUNT(EmployeeId) FROM(
	       SELECT 
			d.EmployeeId,
			d.FromDate,
			d.ToDate
		  FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
		and EM.statusid=7
        ) AS Temp 
        WHERE (DATEDIFF(d, FromDate, ToDate)=2)
        )  AS Leave3DayCount,
      
    (SELECT 
        COUNT(EmployeeId) FROM  (
           SELECT    
             OGMEL.Id as OrgGroupId,
             OGMEL.Title As OrgGroupTitle,
             OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
             DME.Id,DME.Code As DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 (EC.MobileNumber) AS ContactNo,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
              convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage

            FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		    WHERE EJD.OrgId=OM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                 EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				 and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	     ) AS Tmp) As 'HundredPerAttnCount'
		 ,
	(SELECT  COUNT(EM.Id) 
		FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE OM.Id=OMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ) AS PendingCount,
	   getdate()AS UpdateDate
			
    FROM 
       sSetup.tOrgGroupMaster OGMT 
    INNER JOIN sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId    
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
	INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id
    WHERE OGMT.Id=@rOrgGroupId AND COGBML.Id=@rCommonOrgGroupBatchId 
	And OGMT.IsObsolete = 0 AND U.UserId = @rUserId
  END 
  END
  
  
else if @rTypeId=3   
  BEGIN
--TotalCount
    (SELECT 
      (DME.Id) As DepartmentId,
        DME.Code As DepartmentCode,OGMM.Id AS OrgGroupId,
        OGMM.Title As OrgGroupTitle,0 As OrgId,'' As OrgTitle,
        COUNT(DME.Id) As TotalCount,
--PresentCount
	(SELECT 
            COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	   WHERE DME.Id=DMER.Id 
			and ETRP.IsPresent=1 
			AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
	   ) AS PresentCount,
--AbsentCount			
	  (SELECT COUNT(ETRP.EmployeeId) 
            FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
	   WHERE DME.Id=DMER.Id and ETRP.IsPresent=0 
			AND ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
			and EM.statusid=7
		) AS AbsentCount,
--LeaveCount			
   (SELECT    
        COUNT(EM.Id)
    FROM sHrm.tLeave SHT
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
	WHERE DME.Id=DMER.Id AND				
			((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		     AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))		
			 and EM.statusid=7		
	) AS LeaveCount,
				
--AB10%Count				
     (SELECT 
         COUNT(EmployeeId) 
      FROM (
         SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id) AS FLOAT))*100)) as Percentage		
		FROM sHrm.tEmployeeAttendanceRegister EAR
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
		WHERE DME.Id=DMER.Id AND 
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
	    GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	    HAVING CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id) AS FLOAT))*100))<=90
	     ) AS Tmp) AS 'AB10Count',
	           
--AB3DaysCount	           
      (SELECT 
          COUNT(EmployeeId) FROM(
	         SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
	   FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	    WHERE
            DME.Id=DMER.Id  AND IsPresent IN(0) 
            AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) AS T
        WHERE rowno=3) as AB3DaysCount,
  --Leave3DayCount
   (SELECT COUNT(EmployeeId) FROM(
	   SELECT
			d.EmployeeId,d.FromDate,d.ToDate
	   FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE
			 DME.Id=DMER.Id AND 
			 d.ToDate=CONVERT(char(10), @rUptoDate,126)   
			 and EM.statusid=7     
        ) AS Temp WHERE (DATEDIFF(d, FromDate, ToDate)=2)        
      )  AS Leave3DayCount,
        
--HundredPerAttnCount     
        
  (SELECT 
      COUNT(EmployeeId) FROM(
         SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,
            (OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) as Percentage		
	      FROM sHrm.tEmployeeAttendanceRegister EAR			
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE DME.Id=DMER.Id AND 		
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	  ) AS Tmp) As 'HundredPerAttnCount',

--PendingCount


	  (	select COUNT(*) from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
	where    EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126)) AND DMER.Id = DME.Id AND DMER.OrgGroupId = OGMM.Id and EM.statusid=7) 
	AS PendingCount

	FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
        --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	WHERE OGMM.ID=@rOrgGroupId AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 --AND COGBML.Id=@rCommonOrgGroupBatchId AND 
	And ISNULL(OGMM.IsObsolete,0) = 0
	GROUP BY DME.Id,DME.Code,OGMM.Id,OGMM.Title
	) 
					
  END
  
  
else if @rTypeId=4 
  BEGIN     
     SELECT (DME.Id) As DepartmentId,
         DME.Code As DepartmentCode,
         OGMM.Id AS OrgGroupId,OGMM.Title As OrgGroupTitle,
         OM.Id As OrgId,OM.DisplayTitle As OrgTitle,
         COUNT(DME.Id) As TotalCount, 
         (SELECT 
            COUNT(ETRP.EmployeeId) 
          FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE DME.Id=DMER.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId  
			AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7
           ) As PresentCount,
			
	  (SELECT 
	      COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
       WHERE DME.Id=DMER.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId  
	   and EM.statusid=7
	   AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId  
			AND ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
	  ) AS AbsentCount,
			
			
      (SELECT 
       COUNT(EM.Id)
      FROM sHrm.tLeave SHT
            INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
	        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	       
	        INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
            LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
	  WHERE DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  				
			((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			 AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			 and EM.statusid=7
	  ) As LeaveCount,
				
				
     (SELECT 
         COUNT(EmployeeId) FROM  (
            SELECT    
                OGMEL.Id as OrgGroupId,
                OGMEL.Title AS OrgGroupTitle,
                OMEL.Id AS OrgId,(OMEL.Title) As OrgTitle,
                DMER.Id,DMER.Code AS DepartmentCode,
                (EM.Id)EmployeeID,
                (EM.FirstName+' '+EM.LastName) AS EmployeeName,
				(EC.MobileNumber) AS ContactNo,
				COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
                CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) as Percentage

			 FROM sHrm.tEmployeeAttendanceRegister EAR				
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
			 WHERE DME.Id=DMER.Id AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
				and EM.statusid=7
			 GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	         HAVING CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100))<=90
	       ) AS Tmp) As 'AB10Count',
	           
	           
   (SELECT 
       COUNT(EmployeeId) FROM(
	      SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
			    d.EmployeeId,
			    AttendanceDate,
			    d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId  AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  
			IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, CONVERT(DATE, @rUptoDate, 126)) AND @rUptoDate    
			and EM.statusid=7           
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) AS T
        WHERE rowno=3) AS AB3DaysCount,
        
  (SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT 
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d		
 			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId	
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		  
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE
			 DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND 
			 d.ToDate=CONVERT(CHAR(10), @rUptoDate,126)     
			 and EM.statusid=7   
        ) AS Temp WHERE (DATEDIFF(d, FromDate, ToDate)=2)       
    )  AS Leave3DayCount,
        
        
    (SELECT 
       COUNT(EmployeeId) FROM  (
          SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(Count(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE DME.Id=DMER.Id AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
			and EM.statusid=7
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	) AS Tmp) As 'HundredPerAttnCount',
	 (	select COUNT(*) from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
	where  OM.Id=OMM.Id and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126)) AND DMER.Id = DME.Id AND DMER.OrgGroupId=OGMM.Id and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) 
	AS PendingCount
  
   FROM sHrm.tEmployeeMaster EM
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
     --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
    INNER JOIN sHrm.tEmployeeJobDetail EJD1 ON EJD1.EmployeeId=EM.ID
    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD1.OrgGroupDepartmentId
	LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID              
  WHERE DME.OrgGroupId=@rOrgGroupId And EJD1.OrgId=@rOrgId and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 --AND COGBML.Id=@rCommonOrgGroupBatchId 
  And ISNULL(OGMM.IsObsolete,0) = 0
  GROUP BY DME.Id,DME.Code,OGMM.Id,OGMM.Title,OM.Id,OM.DisplayTitle
	 
END  
   
   
else if @rTypeId=5   

BEGIN
   (SELECT(DM.code) As Dept,
          (EM.Id) As EmployeeId,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
          (EC.MobileNumber) AS ContactNo
    FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
			INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DM.Id=@rDepartmentId --AND COGBM.Id=@rCommonOrgGroupBatchId 
	  And ISNULL(OGMM.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
     )
END
   
ELSE IF @rTypeId=31
 BEGIN
     SELECT 
        (OGMM.id) AS OrgGroupId,(OGMM.Title) As OrgGroupTitle,
        (OM.id) OrgId,(OM.Title) OrgTitle,
        (DME.Code) As DepartmentCode,
		(EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo,
		NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
     FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --      INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	    
        LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID                    
	 WHERE DME.OrgGroupId=@rOrgGroupId --AND COGBM.Id=@rCommonOrgGroupBatchId 
	  And ISNULL(OGMM.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	 AND DME.Id=@rDepartmentId--) As Total
	 Order By EM.Code
       
 END   
 
ELSE IF @rTypeId=41 
 BEGIN
	SELECT 
	   (OGMM.id) As OrgGroupId,
	   (OGMM.Title) As OrgGroupTitle,
	   (OM.id) OrgId,(OM.Title) OrgTitle,
	   DME.Code As DepartmentCode,(EM.Id)EmployeeID,
	   (EM.Code)EmployeeCode,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
	   ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
	   (EC.MobileNumber) AS ContactNo,
	   NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
     FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --      INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	   
        LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	WHERE 
		EJD.OrgId=@rOrgId --AND COGBM.Id=@rCommonOrgGroupBatchId 
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0	
		 And ISNULL(OGMM.IsObsolete,0) = 0
		AND ((@rDepartmentId <>1 AND DME.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))   
	Order By EM.Code
 END   
 
ELSE IF @rTypeId=32   

BEGIN
    SELECT 
        (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
        ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo,
		NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
    FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	 WHERE DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId and  ETRP.IsPresent=1
	  And ISNULL(OGME.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
	Order By EM.Code
END

else if @rTypeId=42  

BEGIN
    SELECT 
        (OGME.id) As OrgGroupId,
        (OGME.Title) As OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code As DepartmentCode,
        (EM.Id)EmployeeID,
		(EM.Code)EmployeeCode,
        (EM.FirstName+' '+EM.LastName) AS EmployeeName,
        ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo,
		NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE EJD.OrgId=@rOrgId
		and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		and  ETRP.IsPresent=1
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		And ISNULL(OGME.IsObsolete,0) = 0
		and ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
	Order By EM.Code
END


else if @rTypeId=33  
  BEGIN
     SELECT 
        (OGME.id) As OrgGroupId,
        (OGME.Title) As OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code As DepartmentCode,
		(EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo,
		NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			
	where DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId and  ETRP.IsPresent=0  AND COGBM.Id=@rCommonOrgGroupBatchId 
	And ISNULL(OGME.IsObsolete,0) = 0
	and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	    AND ETRP.AttendanceDate = CONVERT(CHAR(10),  @rUptoDate,126)
	Order By EM.Code
  END   
  
  ELSE IF @rTypeId=43   
  BEGIN
     SELECT 
       (OGME.id) As OrgGroupId,
       (OGME.Title) As OrgGroupTitle,
 (OME.id) OrgId,(OME.Title) OrgTitle,
       DMER.Code As DepartmentCode,
       (EM.Id)EmployeeID,
	   (EM.Code)EmployeeCode,
       (EM.FirstName+' '+EM.LastName) AS EmployeeName,
       ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
       (EC.MobileNumber) AS ContactNo,
	   NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	  WHERE EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId 
		and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		and  ETRP.IsPresent=0 
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		And ISNULL(OGME.IsObsolete,0) = 0
		and ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
	Order By EM.Code
  END 
   
 ELSE IF @rTypeId=34
   
   BEGIN
      
       select (OGMEL.id) As OrgGroupId,
              (OGMEL.Title) As OrgGroupTitle,
              (OMEL.id) OrgId,(OMEL.Title) OrgTitle,
              DMER.Code As DepartmentCode,
              (EM.Id)EmployeeID,
			  (EM.Code)EmployeeCode,
              (EM.FirstName+' '+EM.LastName) AS EmployeeName,
              ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
              (EC.MobileNumber) AS ContactNo,
			  ISNULL(SM.Title,'') AS LeaveStatus--Added for mantis : 35520 by Nilesh
       FROM sHrm.tLeave SHT
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id = SHT.StatusId--Added for mantis : 35520 by Nilesh
	   WHERE DMER.OrgGroupId=@rOrgGroupId AND DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId 
	   And OGMEL.IsObsolete = 0
	   and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   AND			
				((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		Order By EM.Code
   END
   
   
 ELSE IF @rTypeId=44    
   BEGIN
       SELECT (OGMEL.id) As OrgGroupId,
              (OGMEL.Title) As OrgGroupTitle,
              (OMEL.id) OrgId,(OMEL.Title) OrgTitle,
              DMER.Code As DepartmentCode,
			  (EM.Id)EmployeeID,
              (EM.Code)EmployeeCode,
			  (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
              (EC.MobileNumber) AS ContactNo,
			   ISNULL(SM.Title,'') AS LeaveStatus--Added for mantis : 35520 by Nilesh
       FROM sHrm.tLeave SHT
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id = SHT.StatusId--Added for mantis : 35520 by Nilesh
	   WHERE EJD.OrgId=@rOrgId	AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And OGMEL.IsObsolete = 0
	   and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
				AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And				
				 ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			     AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		Order By EM.Code
   END
   
 ELSE IF @rTypeId=35 
   
   BEGIN

    select * from (
          select    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,--DMER.Id,DMER.Code As DeptCode,
              (EM.Id)EmployeeID,
			  (EM.Code)EmployeeCode,
			  (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			  (EC.MobileNumber) AS ContactNo,DMER.Code As DepartmentCode,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
			  convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		  FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			
		  WHERE DMER.OrgGroupId=@rOrgGroupId  AND DMER.Id=@rDepartmentId 
		  And OGMEL.IsObsolete = 0
		  
		  AND COGBM.Id=@rCommonOrgGroupBatchId AND
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,EJD.DateOfJoining,EDM.title,
				EM.Id,(EM.Code),(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),DMER.Code
	       HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	   ) AS Tmp
      
   END
   
   
   else if @rTypeId=45 
   
   BEGIN
   
    SELECT * FROM (
          SELECT    
               OGMEL.Id as OrgGroupId,
               OGMEL.Title As OrgGroupTitle,
               OMEL.Id As OrgId,
               (OMEL.Title) As OrgTitle,
               (EM.Id)EmployeeID,
			   (EM.Code)EmployeeCode,
               (EM.FirstName+' '+EM.LastName) AS EmployeeName,
               ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
				(EC.MobileNumber) AS ContactNo,DMER.Code As DepartmentCode,
				count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
                convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		  FROM sHrm.tEmployeeAttendanceRegister EAR				
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId			
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE EJD.OrgId=@rOrgId  AND COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
			    and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) AND
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
				GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,EJD.DateOfJoining,EDM.title
				,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),DMER.Code 
	       HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	    ) AS Tmp
      
   END
   
   
 ELSE IF @rTypeId=36
  
  BEGIN
    (SELECT Temp.OrgGroupId,
            Temp.OrgGroupTitle,
            Temp.OrgId,Temp.OrgTitle,
            (EMR.Id) As EmployeeId,
			EMR.Code As EmployeeCode,
            (EMR.FirstName+' '+EMR.LastName) AS EmployeeName,
            ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
            (ECR.PresentContactNo) AS ContactNo,
			DepartmentCode
     FROM(select ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		    d.EmployeeId,(EM.Code)EmployeeCode,
		    AttendanceDate,d.IsPresent,
		    OGMEL.Id As OrgGroupId,
		    OGMEL.Title As OrgGroupTitle,
		    OMEL.Id As OrgId,OMEL.Title As OrgTitle,
		    DMER.Code As DepartmentCode
          FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
        WHERE
            DMER.OrgGroupId=@rOrgGroupId And DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
			AND 
            IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate       
        Group By d.EmployeeId,EM.Code,AttendanceDate,IsPresent,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Code 
        ) As Temp
            INNER JOIN sHrm.tEmployeeMaster EMR ON EMR.ID=Temp.EmployeeId AND  ISNULL(EMR.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMR.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications ECR on EMR.ID=ECR.EmployeeID        
        where rowno=3
      ) 
       
  END
  
  
  
 ELSE IF @rTypeId=46 
 
  BEGIN
  (SELECT Temp.OrgGroupId,
          Temp.OrgGroupTitle,
          Temp.OrgId,Temp.OrgTitle,
          (EMR.Id) As EmployeeId,
		  EMR.Code As EmployeeCode,
          (EMR.FirstName+' '+EMR.LastName) AS EmployeeName,	
          ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,	
          (ECR.PresentContactNo) AS ContactNo,DepartmentCode
      FROM(
	      select 
	         ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
			 d.EmployeeId,
			 EM.Code As EmployeeCode,
			 AttendanceDate,d.IsPresent,
			 OGMEL.Id As OrgGroupId,
			 OGMEL.Title As OrgGroupTitle,
			 OMEL.Id As OrgId,
			 OMEL.Title As OrgTitle,
			 DMER.Code As DepartmentCode
		   FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
        EJD.OrgId=@rOrgId 
        AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And OGMEL.IsObsolete = 0
		and EM.statusid=7
		AND
        IsPresent IN(0) AND COGBM.Id=@rCommonOrgGroupBatchId 
        AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
        Group By d.EmployeeId,EM.Code,AttendanceDate,IsPresent,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Code 
        ) As Temp
		INNER JOIN sHrm.tEmployeeMaster EMR ON EMR.ID=Temp.EmployeeId AND  ISNULL(EMR.IsOtherUser,0) = 0
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMR.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications ECR on EMR.ID=ECR.EmployeeID
      WHERE rowno=3
    ) 
    
  END

  ELSE IF @rTypeId=37
  
  BEGIN
     (SELECT * FROM(
	     SELECT
			d.FromDate,
			d.ToDate,
			OGMEL.Id As OrgGroupId,
			OGMEL.Title As OrgGroupTitle,
			OMEL.Id As OrgId,
			OMEL.Title As OrgTitle,
			EM.Code As EmployeeId,
			EM.ID As EmployeeCode,
			(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
            (EC.MobileNumber) AS ContactNo,
            DME.Code As DepartmentCode
		FROM sHrm.tLeave d
	 	    INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
		    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		    LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		    LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE
			d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
			and DME.OrgGroupId=@rOrgGroupId AND DME.Id=@rDepartmentId And OGMEL.IsObsolete = 0
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
      ) 
  END

  ELSE IF @rTypeId=47   
  
  BEGIN
  
     (SELECT * from(
	     SELECT
			d.FromDate,
			d.ToDate,
			OGMEL.Id As OrgGroupId,
			OGMEL.Title As OrgGroupTitle,
			OMEL.Id As OrgId,OMEL.Title As OrgTitle,
			EM.Code As EmployeeId,
			EM.Id As EmployeeCode,
			(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			(EC.MobileNumber) AS ContactNo,DME.Code As DepartmentCode
		  FROM sHrm.tLeave d
		 	    INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			    LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			    LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE
          d.ToDate=CONVERT(char(10), @rUptoDate,126)
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
          AND EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
          AND ((@rDepartmentId <>1 AND DME.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) 
        ) AS Temp where (DATEDIFF(d, FromDate, ToDate)=2)        
      ) 
  
  
  END 
  
  
  else if @rTypeId=38
  
  BEGIN
      SELECT    
          OGMEL.Id as OrgGroupId,
          OGMEL.Title As OrgGroupTitle,
          OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
          DMER.Id,DMER.Code As DepartmentCode,
          (EM.Id)EmployeeID,
		  (EM.Code)EmployeeCode,
          (EM.FirstName+' '+EM.LastName) AS EmployeeName,
           ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
		  (EC.MobileNumber) AS ContactNo,
		   count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
		   convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
	  FROM sHrm.tEmployeeAttendanceRegister EAR		
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	  WHERE DMER.OrgGroupId=@rOrgGroupId AND DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0 
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	  AND		
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
	  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),EJD.DateOfJoining,EDM.title
	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
  
  END
  
  
  ELSE IF @rTypeId=48 
  
  BEGIN
      
      SELECT    
           OGMEL.Id as OrgGroupId,
           OGMEL.Title As OrgGroupTitle,
           OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
           DMER.Id,DMER.Code As DepartmentCode,
           (EM.Id)EmployeeID,
		   (EM.Code)EmployeeCode,
           (EM.FirstName+' '+EM.LastName) AS EmployeeName,
            ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage						
		FROM sHrm.tEmployeeAttendanceRegister EAR			
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId  And OGMEL.IsObsolete = 0
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
			and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),EJD.DateOfJoining,EDM.title
		HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
  END

  ELSE IF @rTypeId=39   

BEGIN
    SELECT 
       (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo,
		NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
	 from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	where DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId And ISNULL(OGME.IsObsolete,0) = 0
	and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	AND EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))		
	Order By EM.Code
END

  ELSE IF @rTypeId=49   

BEGIN
    SELECT 
        (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,
		(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo,
		NULL AS LeaveStatus--Added for mantis : 35520 by Nilesh
	 from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		

		WHERE EJD.OrgId=@rOrgId
		AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		And ISNULL(OGME.IsObsolete,0) = 0
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		AND   EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10),@rUptoDate,126))		
		Order By EM.Code
END


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
				--ISNULL(U.DisplayTitle,'') AS UserName-- added by dhananjay for mantis : 0035757

		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 AND IS1.LibraryId = BL.LibraryId --Added LibraryId for mantis : 35942 by Nilesh
				INNER JOIN sSetup.tBatchMaster B ON SA.BatchId = B.Id --AND B.IsActive = 1
				LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
				--LEFT JOIN sSecurity.tUser U ON U.Id=BL.CreatedUserId-- added by dhananjay for mantis : 0035757
		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
				--ISNULL(U.DisplayTitle,'') AS UserName-- added by dhananjay for mantis : 0035757
		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 AND IS1.LibraryId = BL.LibraryId--Added LibraryId for mantis : 35942 by Nilesh
				LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
				--LEFT JOIN sSecurity.tUser U ON U.Id=BL.CreatedUserId-- added by dhananjay for mantis : 0035757
		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
			AND (EM.Code=@rCode OR @rCode='') --mantis id : 0035097
	END
END
GO
PRINT N'Altering Procedure [sPayroll].[pCalculateStaticPayElement]...';


GO
ALTER PROCEDURE [sPayroll].[pCalculateStaticPayElement] 
	      
	        @rPayProcessEmployeeId bigint,
	        @rOrgGroupId int,
	        @rSalary DECIMAL(22,6),
	        @rSourceId bigint,
	        @rDeductionAmount DECIMAL(22,6),
	        @rPayrollId int,
	        @rPayrollYearId int,
			@lPayrollGroupId int =0,
			@rSalaryMonth tinyint = 0,
			@rSalaryYear smallint = 0,
			@rEmployeeId bigint = 0
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lIsRoundOffToWholeNumber nvarchar(50)
	DECLARE @lRoundOffToWholeNumber int
	DECLARE @lProfessionalTaxAgeRestriction int
	
	SELECT @lProfessionalTaxAgeRestriction = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 406 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	SELECT @lIsRoundOffToWholeNumber = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 248 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	IF (@lIsRoundOffToWholeNumber IS NULL) OR (@lIsRoundOffToWholeNumber = 'True')
		SET @lRoundOffToWholeNumber = 0
	ELSE
		SET @lRoundOffToWholeNumber = 2	

	IF (@lProfessionalTaxAgeRestriction IS NULL) OR (LEN(@lProfessionalTaxAgeRestriction) = 0)
		SET @lProfessionalTaxAgeRestriction = 65
	
	BEGIN
	
	DECLARE @lNextNumber BIGINT 
	DECLARE @1Basic DECIMAl(22,6) 
	DECLARE @1PfSalaryLimit DECIMAL(22,6)
	DECLARE @1PayProcesdsElementId bigint
	DECLARE @1ESISalaryLimit DECIMAL(22,6) 
    DECLARE @1Tax DECIMAL(22,6)
    --DECLARE @1EmployeePfAmount Decimal(22,6)
    DECLARE @1EmployeeESIAmount Decimal(22,6)
    DECLARE @1TotalDeductionAmount DECIMAL(22,6)
    
    DECLARE @1EmployeePfPercent DECIMAL(22,2)
    DECLARE @1EmployerPfPercent DECIMAL(22,2)
    DECLARE @1EmployerFpsPercent DECIMAL(22,2)
    DECLARE @1EmployeeESIPercent DECIMAL(22,2)
    DECLARE @1EmployerESIPercent DECIMAL(22,2)
    DECLARE @1EmployeePfAmount DECIMAL(22,2)
    DECLARE @1EmployerPfAmount DECIMAL(22,2)
    DECLARE @1AdminChargesPercent DECIMAL(22,2)
    DECLARE @1EdliPercent DECIMAL(22,3)
    DECLARE @1InspectionChargesPercent DECIMAL(22,3)
    
    
    DECLARE @lEmployerFpsPercent DECIMAL(22,2)
    DECLARE @lValuesforMax DECIMAL(22,2) 
    DECLARE @1Max DECIMAL(22,2)
    DECLARE @lRestrictionEmployerFpsPercent DECIMAL(22,2)
    DECLARE @1Bal DECIMAL(22,2)
    DECLARE @lEmployerPfPercent DECIMAL(22,2)

	SET @1Tax = 0.0
	SET @1EmployeePfAmount = 0.0
	SET @1EmployeeESIAmount = 0.0
	SET @1Basic = 0.0
	SET @1PfSalaryLimit = 0.0
	
	SET @1EmployeePfPercent = 0.0
    SET @1EmployerPfPercent = 0.0
    SET @1EmployerFpsPercent = 0.0
    SET @1AdminChargesPercent = 0.0
    SET @1EdliPercent = 0.0
    SET @1InspectionChargesPercent = 0.0
    
     
    SET @lEmployerFpsPercent = 0.0
    SET @lValuesforMax = 0.0
    SET @1Max = 0.0
    SET @lRestrictionEmployerFpsPercent = 0.0
    SET @1Bal = 0.0
    SET @lEmployerPfPercent = 0.0
       
    SET @1EmployeeESIPercent = 0.0
    SET @1EmployerESIPercent = 0.0
    DECLARE @lPTPayElementId int    
    DECLARE @lPFPayElementId int
    DECLARE @lBasicPayElementId int
    DECLARE @lESIPayElementId int
    DECLARE @1EmployeePfPercentEmpSetup DECIMAL(12,2)
	
	SELECT @lPTPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 57
	SELECT @lPFPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 56
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	SELECT @lESIPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 55


	 --For Professional Tax
	IF EXISTS (SELECT 1 FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPTPayElementId)     	    
	BEGIN
	
		DECLARE @lDOB date 
		DECLARE @lMonthBeginDate date
		DECLARE @lMonthEndDate date
		DECLARE @lAge smallint
		DECLARE @lGenderId tinyint --mantis :27611

		SELECT @lDOB = DateOfBirth,@lGenderId=GenderId FROM sHrm.tEmployeePersonalDetail WHERE EmployeeId = @rEmployeeId	--mantis :27611	
		SET @lMonthBeginDate= CAST(CAST(@rSalaryYear AS varchar) + '-' + CAST(@rSalaryMonth AS varchar) + '-' + '1' AS date)		
		SET @lMonthEndDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lMonthBeginDate)+1,0))
		SET @lAge = [sCommon].[fAgeAtDate] (@lDOB,@lMonthEndDate)
		
		IF(@lAge <= @lProfessionalTaxAgeRestriction OR @lDOB is null)
		BEGIN
		DECLARE @lGrossBasic decimal(22,6)=0
		  --      Select * from sPayroll.tProfessionalTaxRange
		        
		  --      SELECT  TOP 1  Tax  FROM sPayroll.tProfessionalTaxRange 
				--where Salary < @rSalary Order By Salary Desc


      DECLARE @lConfigValueForPTCalculation nvarchar(50)=''
	  SELECT @lConfigValueForPTCalculation = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 378 AND SourceId = @rOrgGroupId

	  IF(@lConfigValueForPTCalculation  IS NOT NULL AND  @lConfigValueForPTCalculation!='')
	  BEGIN
		IF(@lConfigValueForPTCalculation ='TotalEarning')
		  BEGIN
				SELECT  TOP 1  @1Tax = Tax  FROM sPayroll.tProfessionalTaxRange 
				where Salary <= @rSalary AND PayrollYearId = @rPayrollYearId AND (isnull(GenderId,0)=@lGenderId OR isnull(GenderId,0)=0) Order By Salary Desc --mantis :27611
		        -- Professional Tax 
		        
		        IF @1Tax <> 0
		        BEGIN 
					SET @1Tax = ROUND(@1Tax,@lRoundOffToWholeNumber)
		        	UPDATE sPayroll.tPayProcessElement  
					SET AMOUNT = @1Tax
					WHERE PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPTPayElementId	 
		        END
		  END	
		  ELSE IF(@lConfigValueForPTCalculation ='GrossBasic')   
		  BEGIN  
		  
			  SELECT @lGrossBasic = ISNULL(SUM(GrossBasic),0) FROM sPayroll.tPayProcessEmployee WHERE ID =  @rPayProcessEmployeeId

			  SELECT  TOP 1  @1Tax = Tax  FROM sPayroll.tProfessionalTaxRange 
			  where Salary <= @lGrossBasic AND PayrollYearId = @rPayrollYearId AND (isnull(GenderId,0)=@lGenderId OR isnull(GenderId,0)=0) 
			  Order By Salary Desc --mantis :27611
		       
		        IF @1Tax <> 0
		        BEGIN 
					SET @1Tax = ROUND(@1Tax,@lRoundOffToWholeNumber)
		        	UPDATE sPayroll.tPayProcessElement  
					SET AMOUNT = @1Tax
					WHERE PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPTPayElementId	 
		        END
		  END
	  END
	  ELSE
	  BEGIN
	      
				SELECT  TOP 1  @1Tax = Tax  FROM sPayroll.tProfessionalTaxRange 
				where Salary <= @rSalary AND PayrollYearId = @rPayrollYearId AND (isnull(GenderId,0)=@lGenderId OR isnull(GenderId,0)=0) Order By Salary Desc --mantis :27611
		        -- Professional Tax 
		        
		        
		        IF @1Tax <> 0
		        BEGIN 
					SET @1Tax = ROUND(@1Tax,@lRoundOffToWholeNumber)
		        	UPDATE sPayroll.tPayProcessElement  
					SET AMOUNT = @1Tax
					WHERE PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPTPayElementId	 
		        END
	  END
	END
END	
	
	 --For PfElement
	 
	  IF EXISTS(SELECT 1 FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPFPayElementId)
	  BEGIN
	  -- start for age calculation
	  DECLARE @lEmployeeId bigint = 0
	  DECLARE @lPayProcessId int = 0
	  DECLARE @lSalaryMonth tinyint = 0
	  DECLARE @lSalaryYear smallint = 0  
	  DECLARE @lEmployeeAge smallint = 0  
	  DECLARE @lDateOfBirth date	
	  DECLARE @lFirstDateOfMonth date
	  DECLARE @lLastDateOfMonth date
	  
	  SELECT @lEmployeeId = EmployeeId,@lPayProcessId = PayProcessId FROM sPayroll.tPayProcessEmployee WHERE ID = @rPayProcessEmployeeId
	  SELECT @lDateOfBirth = DateOfBirth FROM sHrm.tEmployeePersonalDetail WHERE EmployeeId = @lEmployeeId
	  SELECT @lSalaryMonth = SalaryMonth,@lSalaryYear = SalaryYear  FROM sPayroll.tPayProcess WHERE Id = @lPayProcessId
	 
      SET @lFirstDateOfMonth= CAST(CAST(@lSalaryYear AS varchar) + '-' + CAST(@lSalaryMonth AS varchar) + '-' + '1' AS date)
      SET @lLastDateOfMonth=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDateOfMonth)+1,0))
      SET @lEmployeeAge = [sCommon].[fAgeAtDate] (@lDateOfBirth,@lLastDateOfMonth)
      
      -- end for age calculation
      

	  
			  SET @1Basic = 0.0	          
	          SET @1PayProcesdsElementId = 0.0
	      
	   --   SELECT @1Basic = ISNULL(Amount,0) from sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lBasicPayElementId	      
		  --SELECT @1Basic =  Amount FROM sPayroll.tPaySetup Where SourceId = @rSourceId AND PayElementId = @lBasicPayElementId  --Basic Pay Element
		  
		  SELECT @1Basic = ISNULL(SUM(amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement PE 
		  ON PPE.PayElementId = PE.ID  WHERE  PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId IN 
		  (SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS 
		  ON  PD.PaySetupId = PS.ID
		  INNER JOIN sPayroll.tPayElement PE 
		  ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId
		  AND PE.PayElementDefaultId = 56 AND SourceID = @lPayrollGroupId)	     
		  
	     
	      -- For PF Process(sPayroll.tPfProcess) 
	      
	      SELECT 
			  @1PfSalaryLimit = PfSalaryLimit,
			  @1EmployeePfPercent=EmployeePfPercent,
			  @1EmployerPfPercent=EmployerPfPercent, 
			  @1EmployerFpsPercent=EmployerFpsPercent,
			  @1AdminChargesPercent=AdminChargesPercent,
			  @1EdliPercent=EdliPercent,
			  @1InspectionChargesPercent=InspectionChargesPercent
	      FROM  
			  sPayroll.tPfSetup Where PayrollYearId = @rPayrollYearId 
	      
	      
	      SELECT @1EmployeePfPercentEmpSetup = Percentage  FROM sPayroll.tPaySetup WHERE SourceTypeId = 95 AND SourceId = (SELECT EmployeeId FROM sPayroll.tPayProcessEmployee WHERE ID = @rPayProcessEmployeeId)
				AND PayElementId = @lPFPayElementId AND PayrollYearId = @rPayrollYearId
	   
	   IF @1EmployeePfPercentEmpSetup IS NOT NULL
	   SET @1EmployeePfPercent = @1EmployeePfPercentEmpSetup
	  
	      
	   SELECT @1PayProcesdsElementId = Id  FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPFPayElementId
	       
	       --SET @1AdminChargesPercent =  ROUND(@1Basic*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
	       
	       
	        IF(@lEmployeeAge >= 58)
			BEGIN
				SET @lEmployerFpsPercent =  0
			END
			ELSE
			BEGIN
				SET @lEmployerFpsPercent =  ROUND(@1Basic*@1EmployerFpsPercent/100,@lRoundOffToWholeNumber)
			END
	      
	       SET @lValuesforMax = ROUND(@1PfSalaryLimit*@1EmployerFpsPercent/100,@lRoundOffToWholeNumber)
	       
	       IF(@lEmployerFpsPercent>@lValuesforMax)
			BEGIN
				SET @1Max = ROUND(@lEmployerFpsPercent-@lValuesforMax,@lRoundOffToWholeNumber)
			END
		   ELSE
			BEGIN
				SET @1Max = ROUND(@lEmployerFpsPercent,0)
			END
			
			IF(@lEmployerFpsPercent = @1Max)
			BEGIN
				SET @lRestrictionEmployerFpsPercent = ROUND(@lEmployerFpsPercent,@lRoundOffToWholeNumber)
			END
		   ELSE
			BEGIN
				SET @lRestrictionEmployerFpsPercent = ROUND(@lEmployerFpsPercent-@1Max,@lRoundOffToWholeNumber)
			END
			
			IF(@lEmployerFpsPercent > @lValuesforMax)
			BEGIN
				SET @1Bal = ROUND(@lEmployerFpsPercent-@lValuesforMax,0)
			END
		   ELSE
			BEGIN
				SET @1Bal = 0
			END
			
		   	SET @lEmployerPfPercent = ROUND(@1Basic*@1EmployerPfPercent/100,@lRoundOffToWholeNumber)
		   		        
	       IF(@1Basic < @1PfSalaryLimit)
			   BEGIN
			   
				 IF(@lEmployeeAge >= 58)
				 BEGIN
					  SET @1EmployeePfAmount =  ROUND(@1Basic*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EmployerPfAmount =  ROUND(@1Basic*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EdliPercent =  ROUND(@1Basic*ISNULL(@1EdliPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1InspectionChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1InspectionChargesPercent,0)/100,@lRoundOffToWholeNumber)
					  
					  SET @1AdminChargesPercent =  ROUND(@1Basic*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
				 END
				 ELSE 
				 BEGIN
					  SET @1EmployeePfAmount =  ROUND(@1Basic*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EmployerPfAmount =  ROUND(@1Bal+ @lEmployerPfPercent,@lRoundOffToWholeNumber)
					  SET @1EdliPercent =  ROUND(@1Basic*ISNULL(@1EdliPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1InspectionChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1InspectionChargesPercent,0)/100,@lRoundOffToWholeNumber)
					  
					  SET @1AdminChargesPercent =  ROUND(@1Basic*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
				 END
			   END
	       ELSE
			   BEGIN
			   
			   IF(@lEmployeeAge >= 58)
				 BEGIN
					  SET @1EmployeePfAmount =  ROUND(@1PfSalaryLimit*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EmployerPfAmount =  ROUND(@1PfSalaryLimit*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EdliPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1EdliPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1InspectionChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1InspectionChargesPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1AdminChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
				 END
				 ELSE 
				 BEGIN
					  SET @1EmployeePfAmount =  ROUND(@1PfSalaryLimit*ISNULL(@1EmployeePfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EmployerPfAmount =  ROUND(@1PfSalaryLimit*ISNULL(@1EmployerPfPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1EdliPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1EdliPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1InspectionChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1InspectionChargesPercent,0)/100,@lRoundOffToWholeNumber)
					  SET @1AdminChargesPercent =  ROUND(@1PfSalaryLimit*ISNULL(@1AdminChargesPercent,0)/100,@lRoundOffToWholeNumber)
				 END
			   END
	       
	       --IF(@1Basic > @1PfSalaryLimit)
	       --   BEGIN
	           --SET @1EmployeePfAmount = @1Basic*@1EmployeePfPercent/100 
	             INSERT INTO  [sPayroll].[tPfProcess]
							   (
							    [PayProcessElementId]
							   ,[EmployeePfAmount]
							   ,[EmployerPfAmount]
							   ,[EmployerFpsAmount]
							   ,[EligibleFpsAmount]
							   ,[AdminChargesAmount]
							   ,[EdliChargesAmount]
							   ,[InspectionChargesAmount]
							   )
							   Values
							   (
							     @1PayProcesdsElementId,
							     @1EmployeePfAmount,
							     @1EmployerPfAmount,
							     @lRestrictionEmployerFpsPercent,
							     0.0,
							     @1AdminChargesPercent,
							     @1EdliPercent,
                                 @1InspectionChargesPercent	    
							    ) 
					
				 IF(@1PfSalaryLimit > 0)			    
				 BEGIN
					UPDATE sPayroll.tPayProcessElement 
					SET Amount = @1EmployeePfAmount WHERE  PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPFPayElementId			    
				 END	
				--END
	  END
	  
	  --FOR Esi Element
	 IF EXISTS(SELECT 1 FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lESIPayElementId)
	  BEGIN 
			   SET @1PayProcesdsElementId = 0.0  
			   SET @1ESISalaryLimit = 0.0			
			   SELECT  @1ESISalaryLimit = EsiSalaryLimit,@1EmployeeESIPercent=EmployeeEsiPercent,@1EmployerESIPercent = EmployerEsiPercent FROM sPayroll.tEsiSetup Where PayrollYearId = @rPayrollYearId
			   SELECT @1PayProcesdsElementId = Id FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lESIPayElementId
			    
		   IF(@1ESISalaryLimit > @rSalary)					   
			  BEGIN
			  SET @1EmployeeESIAmount = @rSalary * @1EmployeeESIPercent/100	
			   INSERT INTO [sPayroll].[tEsiProcess]
						   (
							    [PayProcessElementId]
							   ,[EmployeeEsiAmount]
							   ,[EmployerEsiAmount]
						   )
						   Values
						   (
						       @1PayProcesdsElementId
						      ,@rSalary * @1EmployeeESIPercent/100
						      ,@rSalary * @1EmployerESIPercent/100
						   )
				SET @1EmployeeESIAmount = ROUND(@1EmployeeESIAmount,@lRoundOffToWholeNumber)						   
				UPDATE sPayroll.tPayProcessElement SET Amount = @1EmployeeESIAmount WHERE  PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lESIPayElementId  
			   END	 
	  END  
	  
	  SET @1TotalDeductionAmount = @rDeductionAmount + @1Tax + @1EmployeePfAmount + @1EmployeeESIAmount
	  
	  UPDATE sPayroll.tPayProcessEmployee  
	  SET  
	      TotalEarning = ROUND(@rSalary,@lRoundOffToWholeNumber),
	      TotalDeduction = ROUND(@1TotalDeductionAmount,@lRoundOffToWholeNumber),	       
		  NetAmount = ROUND(@rSalary,@lRoundOffToWholeNumber) - ROUND(@1TotalDeductionAmount,@lRoundOffToWholeNumber)  
	  WHERE ID =  @rPayProcessEmployeeId   
	    
    END
	 
END
GO
PRINT N'Altering Procedure [sPayroll].[pPayProcessEmployeeAdd]...';


GO
ALTER PROCEDURE [sPayroll].[pPayProcessEmployeeAdd] 
	      	        
            @rPayProcessId int            
           ,@rOrgGroupId int
		   ,@rPayrollId int
		   ,@rPayrollYearId int
		   ,@rSalaryMonth tinyint
           ,@rSalaryYear smallint
           ,@rEmployeeId bigint=0
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lNextNumber BIGINT
	DECLARE @1PayProcessElementId bigint
	DECLARE @1Count int
	DECLARE @1EmployeeId bigint
	DECLARE @lPayrollGroupId int
	DECLARE @1PayElementCount int
	DECLARE @1TotalEarningAmount DECIMAL(22,6)
	DECLARE @1PaySetupId int
	DECLARE @1SourceId bigint
    DECLARE @1Percentage decimal(5,2)
	DECLARE @1Result decimal(22,6)
	DECLARE @1Amount decimal(22,6)
	DECLARE @1IsDepend bit
	DECLARE @1PayElementId int
	DECLARE @1LWPDeduction decimal(22,6) 
	DECLARE @1IsLwp Bit
	DECLARE @1PayElementTypeId int
	DECLARE @1TotalDeductionAmount DECIMAL(22,6)
	DECLARE @1EmployeeBasicPay DECIMAL(22,6)
	
	DECLARE @1WorkingDays int
	DECLARE @1Lwp Decimal(12,2)
	DECLARE @lPaidLeave Decimal(12,2)
	DECLARE @1GrossBasic Decimal(12,2)
	DECLARE @1PayElementDefaultId int
    DECLARE @lIsIncludeInTotal Bit
	DECLARE @lFormula nvarchar(200)=''
    
    
    DECLARE @lLastDayOfMonth int = DAY(sCommon.GetLastDateofMonth (CONVERT(nvarchar(4),@rSalaryYear)+'-'+CONVERT(nvarchar(2),@rSalaryMonth)+'-01'))
    -- Loan Configuration
    DECLARE @lConfigValue nvarchar(50)
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 206 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	DECLARE @lIsCalculateAllPayElementAsPerJoining nvarchar(50)
	SELECT @lIsCalculateAllPayElementAsPerJoining = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 307 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	DECLARE @lIsPayrollCountBasedOnWorkingDays nvarchar(50)
	SELECT @lIsPayrollCountBasedOnWorkingDays = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 310 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
    
    DECLARE @lIsPayrollEvaluationOnFixDay nvarchar(50)
	SELECT @lIsPayrollEvaluationOnFixDay = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 324 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
    
	DECLARE @lIsRoundOffToWholeNumber nvarchar(50)
	DECLARE @lRoundOffToWholeNumber int
	SELECT @lIsRoundOffToWholeNumber = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 248 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	IF (@lIsRoundOffToWholeNumber IS NULL) OR (@lIsRoundOffToWholeNumber = 'True')
		SET @lRoundOffToWholeNumber = 0
	ELSE
		SET @lRoundOffToWholeNumber = 2	
	--IF (@rId = 0)
	IF(@rEmployeeId=0)
	BEGIN
		CREATE TABLE #tmpEmpDetail
		(
			Id INT IDENTITY (1, 1),
			EmployeeId  bigint,
			PayrollGroupId int
		)
		 
		INSERT INTO #tmpEmpDetail
		Select ES.EmployeeId,PayrollGroupId FROM sHrm.tEmployeeStatutoryAndOther ES
		INNER JOIN  sHrm.tEmployeeAttendance EA ON ES.EmployeeId = EA.EmployeeId
		INNER JOIN sSetup.tBatchMaster BM ON EA.BatchId = BM.Id AND BM.IsActive = 1
		Where PayrollId = @rPayrollId AND PayrollGroupId IS NOT NULL
		AND EA.ForMonth = @rSalaryMonth AND EA.ForYear = @rSalaryYear
   
		Select @1Count = COUNT(*) FROM #tmpEmpDetail 
      
		WHILE @1Count > 0 
		BEGIN	 
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcessEmployee', 0, 1, 1,@outNextNumber = @lNextNumber output	
		    SELECT @1EmployeeId = EmployeeId,@lPayrollGroupId = PayrollGroupId FROM #tmpEmpDetail WHERE ID = @1Count
		   
		    SELECT @1WorkingDays = TotalWorkingDays,@1Lwp = LWP, @lPaidLeave=ISNULL(PaidLeave,0) FROM sHrm.tEmployeeAttendance EA
		    INNER JOIN sSetup.tBatchMaster BM ON EA.BatchId = BM.Id AND BM.IsActive = 1
		    Where EA.EmployeeId=@1EmployeeId AND EA.ForYear=@rSalaryYear AND EA.ForMonth=@rSalaryMonth
					
		    SELECT @1GrossBasic = PS.Amount FROM sPayroll.tPaySetup PS 
			INNER JOIN sPayroll.tPayElement PE ON PE.Id=PS.PayElementId
			Where PS.SourceTypeId = 95 
			AND PS.SourceId=@1EmployeeId 
			AND PS.PayrollId=@rPayrollId 
			AND PS.PayrollYearId = @rPayrollYearId 
			AND PE.PayElementDefaultId=1 
		   
		    IF EXISTS (SELECT 1 FROM sPayroll.tPaySetup WHERE SourceTypeId=2020 AND SourceId=@lPayrollGroupId AND PayrollId=@rPayrollId AND PayrollYearId=@rPayrollYearId)
		    BEGIN		    
		    INSERT INTO  [sPayroll].[tPayProcessEmployee]
				   (
				    [ID]
				   ,[PayProcessId]
				   ,[EmployeeId]
				   ,[PayrollGroupId]
				   ,TotalEarning
				   ,TotalDeduction
				   ,NetAmount
				   ,WorkingDays
				   ,Lwp
				   ,GrossBasic
				   ,PaidLeave
				   )
			VALUES
				   (
				    @lNextNumber
				   ,@rPayProcessId
				   ,@1EmployeeId 
				   ,@lPayrollGroupId
				   ,0.0
				   ,0.0
				   ,0.0
				   ,@1WorkingDays
				   ,@1Lwp
				   ,@1GrossBasic
				   ,@lPaidLeave
				   )
				   
		      
	     -- FOR Counting Total Earning
	 
		 CREATE TABLE #tmpPaysetupElement
		(
		   Id INT IDENTITY (1, 1),
		   PaySetupId int,
		   SourceId bigint,
		   SourceTypeId int,
		   PayElementId int,
		   Amount DECIMAl(22,6) NULL,
		   Percentage DECIMAl(5,2) NULL,
		   IsDepend bit,
		   PayElementTypeId int,
		   ProcessOrder int,
		   PayElementDefaultId int  ,
		   Formula nvarchar(200)
		)  
		   
		   BEGIN
		 --IF EXISTS (select 1 from sPayroll.tpaysetup where SourceId = @1EmployeeId AND SourceTypeId = 3016) --For Pay Setup Employee
		     INSERT INTO #tmpPaysetupElement
		     SELECT PE.ID,PE.SourceId,PE.SourceTypeId,PE.PayElementId,PE.Amount,PE.Percentage,PE.IsDepend,PE.PayElementTypeId,PE.ProcessOrder,PayElementDefaultId,PE.Formula FROM 
		     (		     
		     SELECT PS.ID,SourceId,95 AS SourceTypeId ,PayElementId,Amount,Percentage,ISNULL(IsDepend,0) AS IsDepend,PayElementTypeId,ProcessOrder,PE.PayElementDefaultId,ISNULL(PS.Formula,'') As Formula
		     FROM sPayroll.tPaySetup PS INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @1EmployeeId 
			 AND SourceTypeId = 95 
			 AND PS.PayrollId=@rPayrollId 
			 AND PS.PayrollYearId = @rPayrollYearId
		 
		 --ELSE 
		     UNION ALL
		      
		     --INSERT INTO #tmpPaysetupElement
		     SELECT PS.ID,SourceId,2020 AS SourceTypeId,PayElementId,Amount,Percentage,IsDepend,PayElementTypeId,ProcessOrder 
			 ,PE.PayElementDefaultId,ISNULL(PS.Formula,'') As Formula
		     FROM sPayroll.tPaySetup  PS  INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @lPayrollGroupId AND SourceTypeId = 2020 AND PS.PayrollId=@rPayrollId AND PS.PayrollYearId = @rPayrollYearId
			 AND PayElementId NOT IN (SELECT  PayElementId FROM sPayroll.tPaySetup  PS 
		     INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId 
		     WHERE SourceId = @1EmployeeId 
		     AND SourceTypeId = 95 
		     AND PS.PayrollId=@rPayrollId 
		     AND PS.PayrollYearId = @rPayrollYearId)  			 
			 
		     ) PE  ORDER BY ProcessOrder  DESC
		  	END	
		  	  
		    --Select * FROM #tmpPaysetupElement
		  
		  	SELECT @1PayElementCount = COUNT(*) FROM #tmpPaysetupElement
			
			SET @1TotalDeductionAmount = 0
			SET   @1TotalEarningAmount = 0
			WHILE @1PayElementCount > 0
				BEGIN				
					SET @1PaySetupId = 0
					SET @1SourceId = 0
					SET @1Percentage = 0.0
					SET @1Result = 0.0
					SET @1Amount = 0.0 			
					SET @1PayElementId = 0
					SET @1IsLwp = 0
					SET @1LWPDeduction = 0
					SET @1PayElementDefaultId = 0
					SET @lFormula = ''
			  
			    SELECT @1PaySetupId = PaySetupId,@1SourceId = SourceId,@1PayElementId = PayElementId,@1Result = Amount,
			    @1Percentage = Percentage,@1IsDepend = IsDepend,@1PayElementTypeId=PayElementTypeId,@1PayElementDefaultId =PayElementDefaultId,
				@lFormula=Formula
				FROM #tmpPaysetupElement WHERE Id = @1PayElementCount
			      
			    SELECT @1IsLwp = IsLwp, @lIsIncludeInTotal=IsIncludeInTotal FROM sPayroll.tPayElement Where Id = @1PayElementId AND PayrollId = @rPayrollId
			    
			    IF(@1PayElementDefaultId=1)
			    BEGIN
					IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')
						BEGIN
							IF (@lIsPayrollEvaluationOnFixDay IS NULL) OR (@lIsPayrollEvaluationOnFixDay = 'False')
								SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
							ELSE
								SET @1Result = (ISNULL(@1Result,0)/30) * @1WorkingDays
						END	
					ELSE
						SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			    END
			    
			    IF(@1PayElementDefaultId!=1 AND @1IsDepend = 0 AND @lIsCalculateAllPayElementAsPerJoining IS NULL) OR (@lIsCalculateAllPayElementAsPerJoining = 'False')
			    BEGIN 
					IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')	
						BEGIN
							IF (@lIsPayrollEvaluationOnFixDay IS NULL) OR (@lIsPayrollEvaluationOnFixDay = 'False')
								SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
							ELSE
								SET @1Result = (ISNULL(@1Result,0)/30) * @1WorkingDays
						END	
					ELSE
						SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			    END	    
			       
			    IF(@1IsLwp = 1) 			     
			        SELECT @1LWPDeduction = [sPayroll].[fCalculateLWP] (@1EmployeeId, @rPayProcessId,ISNULL(@1Result,0))			      
			               
			    IF(@1IsDepend = 1 AND @1PayElementDefaultId NOT IN(55,56,57)) -- ESI,PF,PT seperatly calculated
			        EXECUTE [sPayroll].[pCalculatePayrollAmount]  @1PaySetupId,@1PayElementId,@1Percentage,@1SourceId,@rOrgGroupId,@1EmployeeId,@lNextNumber,@rPayrollId,@rPayrollYearId,@lFormula,@1Result OUTPUT
			    
			    IF(@1WorkingDays = 0)      
					SET @1Result =  0    
			    ELSE
					SET @1Result =  ROUND(ISNULL(@1Result,0.0) -  ISNULL(@1LWPDeduction,0.00),@lRoundOffToWholeNumber)	         
			      
			    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcessElement', 0, 1, 1,@outNextNumber = @1PayProcessElementId output	
		
	        	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')	
	        	BEGIN
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,@1Result
						   )  
	        	END
	        	ELSE
	        	BEGIN
	        		IF(@1PayElementDefaultId = 58)
	        		BEGIN
						SET @1Result= [sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,58)
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						  ,[sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,58)
						   )  
					END
					
	        		ELSE IF(@1PayElementDefaultId = 63)
	        		BEGIN
					SET @1Result= [sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,63)
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,[sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,63)
						   )  
					END
					ELSE
					BEGIN
					INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,@1Result
						   )  
					END
						   
				END
			       
			    
			    
			     IF( @1PayElementTypeId = 1)
			     BEGIN	      	 
			      IF(@lIsIncludeInTotal = 1)
					SET @1TotalEarningAmount = ISNULL(@1TotalEarningAmount,0) + ISNULL(@1Result,0)		      
				  ELSE
					SET @1TotalEarningAmount = ISNULL(@1TotalEarningAmount,0)	      
			     END
			     
			     ELSE 
			       BEGIN 
			        IF(@lIsIncludeInTotal = 1)
						SET @1TotalDeductionAmount = ISNULL(@1TotalDeductionAmount,0) + ISNULL(@1Result,0) 	      
					ELSE
						SET @1TotalDeductionAmount = ISNULL(@1TotalDeductionAmount,0)	  
			            --- ISNULL(@1LWPDeduction,0)      
			       END   
			     		    
			    SET @1PayElementCount = @1PayElementCount -1			     
			  END	 
		    --SELECT * from #tmpPaysetupElement
			DROP TABLE #tmpPaysetupElement
		       
			END	   
		   EXECUTE [sPayroll].[pCalculateStaticPayElement]  @lNextNumber,@rOrgGroupId,@1TotalEarningAmount,@1SourceId,@1TotalDeductionAmount,@rPayrollId,@rPayrollYearId,@lPayrollGroupId,@rSalaryMonth,@rSalaryYear,@1EmployeeId
			--SELECT  TOP 1 @lTax = Tax  FROM sPayroll.tProfessionalTaxRange where Salary < @rSalary Order By Salary Desc
  		    
		 SET @1Count = @1Count - 1	
	END	    
	--DROP TABLE #tmpPaysetupElement
	DROP TABLE #tmpEmpDetail
	SELECT @lNextNumber AS Result	
	
	END
	ELSE
	BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcessEmployee', 0, 1, 1,@outNextNumber = @lNextNumber output	
		    
			SELECT @lPayrollGroupId = PayrollGroupId FROM sHrm.tEmployeeStatutoryAndOther WHERE EmployeeId = @rEmployeeId
		    
		    SELECT @1WorkingDays = TotalWorkingDays,@1Lwp = LWP, @lPaidLeave=ISNULL(PaidLeave,0) FROM sHrm.tEmployeeAttendance EA
		    INNER JOIN sSetup.tBatchMaster BM ON EA.BatchId = BM.Id AND BM.IsActive = 1
		     Where EA.EmployeeId=@rEmployeeId AND EA.ForYear=@rSalaryYear AND EA.ForMonth=@rSalaryMonth


		    SELECT @1GrossBasic = PS.Amount FROM sPayroll.tPaySetup PS 
			INNER JOIN sPayroll.tPayElement PE ON PE.Id=PS.PayElementId
			Where PS.SourceTypeId = 95 
			AND PS.SourceId=@rEmployeeId 
			AND PS.PayrollId=@rPayrollId 
			AND PS.PayrollYearId = @rPayrollYearId 
			AND PE.PayElementDefaultId=1 
					  
		   INSERT INTO  [sPayroll].[tPayProcessEmployee]
				   (
				    [ID]
				   ,[PayProcessId]
				   ,[EmployeeId]
				   ,[PayrollGroupId]
				   ,TotalEarning
				   ,TotalDeduction
				   ,NetAmount
				   ,WorkingDays
				   ,Lwp
				   ,GrossBasic
				   ,PaidLeave
				   )
			 VALUES
				   (
				    @lNextNumber
				   ,@rPayProcessId
				   ,@rEmployeeId 
				   ,@lPayrollGroupId
				   ,0.0
				   ,0.0
				   ,0.0
				   ,@1WorkingDays
				   ,@1Lwp
				   ,@1GrossBasic
				   ,@lPaidLeave
				   )
		   
	     -- FOR Counting Total Earning
	 
			CREATE TABLE #TempPaysetupElement
		(
		   Id INT IDENTITY (1, 1),
		   PaySetupId int,
		   SourceId bigint,
		   SourceTypeId int,
		   PayElementId int,
		   Amount DECIMAl(22,6) NULL,
		   Percentage DECIMAl(5,2) NULL,
		   IsDepend bit,
		   PayElementTypeId int,
		   ProcessOrder int,
		   PayElementDefaultId int,
		   Formula nvarchar(200)
		)  
		   
			BEGIN
		     INSERT INTO #TempPaysetupElement
		     SELECT PE.ID,PE.SourceId,PE.SourceTypeId,PE.PayElementId,PE.Amount,PE.Percentage,PE.IsDepend,PE.PayElementTypeId,PE.ProcessOrder,PayElementDefaultId,PE.Formula FROM 
		     (		     
		     SELECT PS.ID,SourceId,95 AS SourceTypeId ,PayElementId,Amount,Percentage,ISNULL(IsDepend,0) AS IsDepend,PayElementTypeId,ProcessOrder,PE.PayElementDefaultId,ISNULL(PS.Formula,'') AS  Formula
		     FROM sPayroll.tPaySetup PS INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @rEmployeeId 
			 AND SourceTypeId = 95 
			 AND PS.PayrollId=@rPayrollId 
			 AND PS.PayrollYearId = @rPayrollYearId
		     UNION ALL
		     SELECT PS.ID,SourceId,2020 AS SourceTypeId,PayElementId,Amount,Percentage,IsDepend,PayElementTypeId,ProcessOrder ,PE.PayElementDefaultId,ISNULL(PS.Formula,'') AS  Formula
		     FROM sPayroll.tPaySetup  PS  INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId
			 WHERE SourceId = @lPayrollGroupId AND SourceTypeId = 2020 AND PS.PayrollId=@rPayrollId AND PS.PayrollYearId = @rPayrollYearId
			 AND PayElementId NOT IN (SELECT  PayElementId FROM sPayroll.tPaySetup  PS 
		     INNER JOIN sPayroll.tPayElement  PE ON PE.ID = PS.PayElementId 
		     WHERE SourceId = @rEmployeeId 
		     AND SourceTypeId = 95 
		     AND PS.PayrollId=@rPayrollId 
		     AND PS.PayrollYearId = @rPayrollYearId)  			 
		     ) PE  ORDER BY ProcessOrder  DESC
		  	END	
		  	  
		  	SELECT @1PayElementCount = COUNT(*) FROM #TempPaysetupElement
			
			SET @1TotalDeductionAmount = 0
			SET   @1TotalEarningAmount = 0
			WHILE @1PayElementCount > 0
			BEGIN				
					SET @1PaySetupId = 0
					SET @1SourceId = 0
					SET @1Percentage = 0.0
					SET @1Result = 0.0
					SET @1Amount = 0.0 			
					SET @1PayElementId = 0
					SET @1IsLwp = 0
					SET @1LWPDeduction = 0
					SET @1PayElementDefaultId = 0
					SET @lFormula=''
			  
			    SELECT @1PaySetupId = PaySetupId,@1SourceId = SourceId,@1PayElementId = PayElementId,@1Result = Amount,
			    @1Percentage = Percentage,@1IsDepend = IsDepend,@1PayElementTypeId=PayElementTypeId,@1PayElementDefaultId =PayElementDefaultId, @lFormula=Formula FROM #TempPaysetupElement WHERE Id = @1PayElementCount
			      
			    SELECT @1IsLwp = IsLwp, @lIsIncludeInTotal=IsIncludeInTotal FROM sPayroll.tPayElement Where Id = @1PayElementId AND PayrollId = @rPayrollId
			    					      
			    IF(@1PayElementDefaultId=1)
			    BEGIN
					IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')
						BEGIN
							IF (@lIsPayrollEvaluationOnFixDay IS NULL) OR (@lIsPayrollEvaluationOnFixDay = 'False')
								SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
							ELSE
								SET @1Result = (ISNULL(@1Result,0)/30) * @1WorkingDays
						END	
					ELSE
						SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			    END
			    
			    IF(@1PayElementDefaultId!=1 AND @1IsDepend = 0 AND @lIsCalculateAllPayElementAsPerJoining IS NULL) OR (@lIsCalculateAllPayElementAsPerJoining = 'False')
			    BEGIN 
					IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')	
						BEGIN
							IF (@lIsPayrollEvaluationOnFixDay IS NULL) OR (@lIsPayrollEvaluationOnFixDay = 'False')
								SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
							ELSE
								SET @1Result = (ISNULL(@1Result,0)/30) * @1WorkingDays
						END	
					ELSE
						SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			    END	    
			    
			  --  IF(@1PayElementDefaultId=1)
			  --  BEGIN 
					--IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')	
					--	SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
					--ELSE
					--	SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays 
			  --  END	 
			    
			  --  IF(@1PayElementDefaultId!=1 AND @1IsDepend = 0 AND @lIsCalculateAllPayElementAsPerJoining IS NULL) OR (@lIsCalculateAllPayElementAsPerJoining = 'False')
			  --  BEGIN 
					--IF (@lIsPayrollCountBasedOnWorkingDays IS NULL) OR (@lIsPayrollCountBasedOnWorkingDays = 'False')	
					--	SET @1Result = (ISNULL(@1Result,0)/@lLastDayOfMonth) * @1WorkingDays
					--ELSE
					--	SET @1Result = (ISNULL(@1Result,0)/@1WorkingDays) * @1WorkingDays
			  --  END	    
			       
			    IF(@1IsLwp = 1) 			     
			        SELECT @1LWPDeduction = [sPayroll].[fCalculateLWP] (@rEmployeeId, @rPayProcessId,ISNULL(@1Result,0))			      
			               
			    IF(@1IsDepend = 1 AND @1PayElementDefaultId NOT IN(55,56,57)) -- ESI,PF,PT seperatly calculated
					BEGIN 
						
						EXECUTE [sPayroll].[pCalculatePayrollAmount]  @1PaySetupId,@1PayElementId,@1Percentage,@1SourceId,@rOrgGroupId,@rEmployeeId,@lNextNumber,@rPayrollId,@rPayrollYearId,@lFormula,@1Result OUTPUT
						-- PRINT CAST(@1Result As varchar) + 'FormulaAmount' + CAST(@1PayElementDefaultId As nvarchar) 
					END
			    
			           
			    IF(@1WorkingDays = 0)      
					SET @1Result =  0    
			    ELSE
					SET @1Result =  ROUND(ISNULL(@1Result,0.0) -  ISNULL(@1LWPDeduction,0.00),@lRoundOffToWholeNumber)	       
				
			    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPayProcessElement', 0, 1, 1,@outNextNumber = @1PayProcessElementId output	
			        
			    IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')	
	        	BEGIN
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,@1Result
						   ) 
						   -- PRINT CAST(@1Result As varchar) + ' Config, '  + CAST(@1PayProcessElementId  As varchar) 
	        	END
	        	ELSE
	        	BEGIN
	        		IF(@1PayElementDefaultId = 58)
	        		BEGIN
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						  ,[sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,58)
						  
						   )  
						   -- PRINT CAST(@1Result As varchar) + ' 58, '  + CAST(@1PayProcessElementId  As varchar)
					END
	        		ELSE IF(@1PayElementDefaultId = 63)
	        		BEGIN
	        		INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,[sLoan].[fEmployeeLoanInstalmentGet](@rSalaryMonth,@rSalaryYear,@1EmployeeId,63)
						   
						   )  
						   -- PRINT CAST(@1Result As varchar) + ' 63, '  + CAST(@1PayProcessElementId  As varchar)
					END
					ELSE
					BEGIN
					INSERT INTO  [sPayroll].[tPayProcessElement]
						   (
						    [ID]
						   ,[PayProcessEmployeeId]
						   ,[PayElementId]
						   ,[Amount]
						   )
					 VALUES
						   (
						    @1PayProcessElementId
						   ,@lNextNumber
						   ,@1PayElementId
						   ,@1Result
						   ) 
						   -- PRINT CAST(@1Result As varchar) + ' else, '  + CAST(@1PayProcessElementId  As varchar)
					END	
					
				END
			    
			      IF(@1WorkingDays = 0)
			      BEGIN
						IF( @1PayElementTypeId = 1)
						 BEGIN	      	 
						  IF(@lIsIncludeInTotal = 1)
							SET @1TotalEarningAmount = 0 
						  ELSE
							SET @1TotalEarningAmount = 0
						 END
						 ELSE 
						 BEGIN 
							IF(@lIsIncludeInTotal = 1)
								SET @1TotalDeductionAmount = 0
							ELSE
								SET @1TotalDeductionAmount = 0
						 END   
			      END
			      ELSE
			      BEGIN
			             IF( @1PayElementTypeId = 1)
						 BEGIN	      	 
						  IF(@lIsIncludeInTotal = 1)
							SET @1TotalEarningAmount = ISNULL(@1TotalEarningAmount,0) + ISNULL(@1Result,0)		      
						  ELSE
							SET @1TotalEarningAmount = ISNULL(@1TotalEarningAmount,0)	      
						 END
						 ELSE 
						 BEGIN 
							IF(@lIsIncludeInTotal = 1)
								SET @1TotalDeductionAmount = ISNULL(@1TotalDeductionAmount,0) + ISNULL(@1Result,0) 	      
							ELSE
								SET @1TotalDeductionAmount = ISNULL(@1TotalDeductionAmount,0)	  
						 END   
			      END
			       
			     SET @1PayElementCount = @1PayElementCount -1	
			   	
			   	 END
			   	 
			DROP TABLE #TempPaysetupElement
				   
		   EXECUTE [sPayroll].[pCalculateStaticPayElement]  @lNextNumber,@rOrgGroupId,@1TotalEarningAmount,@1SourceId,@1TotalDeductionAmount,@rPayrollId,@rPayrollYearId,@lPayrollGroupId,@rSalaryMonth,@rSalaryYear,@rEmployeeId
	    
		
	SELECT @lNextNumber AS Result	
	
	END	
    
	 
END
GO
PRINT N'Altering Procedure [sPayroll].[pPayProcessElementGet]...';


GO
ALTER PROCEDURE [sPayroll].[pPayProcessElementGet]
	  
	  @rPayProcessEmployeeId bigint 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
		 PPE.PayElementId,
		 PE.Title AS PayElement,
		 PPE.Amount,
		 PET.Title AS PayElementType,
		 PayElementTypeId,
		 PPE.PayProcessEmployeeId,
		 ISNULL(PE.IsIncludeInTotal,0) AS IsIncludeInTotal
	 FROM 
		 sPayroll.tPayProcessElement PPE 
		 INNER JOIN sPayroll.tPayElement PE ON PPE.PayElementId = PE.ID
		 INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PE.PayElementTypeId
		 
	 WHERE PayProcessEmployeeId = @rPayProcessEmployeeId  AND PE.IsIncludeInPaySlip = 1
	 ORDER BY SortOrder
	
END
GO
PRINT N'Altering Procedure [sPayroll].[pRptEmployeeSalaryDetail]...';


GO
ALTER PROCEDURE [sPayroll].[pRptEmployeeSalaryDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rReportId smallint=0,
	 @rOrderByField nvarchar(20)='',
	 @rMonths nvarchar(50)='',
	 @rOrgId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0,
	 @rDesignationId int= 0,		-- MantisId : 0032059
	 @rGradeId int= 0				-- MantisId : 0032059	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

		SELECT
			@rOrderByField AS OrderByField,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			EM.EmployeeId, 
			PP.ID As PayProcessId,
			PPE.ID AS PayProcessEmployeeId,
			PP.SalaryMonth,
			PP.SalaryYear,
			tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
			EM.Code AS EmployeeCode,
			EM.EmployeeDesignation,
			EM.EmployeeGrade,
			ESO.EPFNumber,
			ESO.PanNumber,
			PPE.TotalEarning,		
			PPE.TotalDeduction,
			PPE.NetAmount,
			(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
			(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
			(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
			PE.Amount As PPEAmount,
			P.Title AS PayElementTitle,
			P.ID AS PayElementId,
			P.PayElementTypeId,
			ISNULL(ESO.BankName,'') AS BankName,
			ISNULL(ESO.AccountNumber,'') AS AccountNumber, 
			MM.Title AS MonthName,
			P.Title AS PayElementName,
			P.Code AS PayElementCode,
			(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.WorkingDays,@lMonthDay) else 0 END) AS WorkingDays,
			(CASE WHEN PayElementId = @lBasicPayElementId then PPE.Lwp else 0 END) AS Lwp,
			(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.PaidLeave,0) else 0 END) AS PaidLeave,
			P.SortOrder,
			PY.Title AS PayrollYearName,
			PGM.Id AS PayrollGroupId,
			PGM.Title AS PayrollGroupName,
			PPE.GrossBasic,
			P.PayElementDefaultId,
			ISNULL(EPD.Qualification,'') AS Qualification,
			EJD.DateOfJoining AS DateOfAppointment,
			ISNULL(ESO.PayScale,'') AS PayScale,
			EPD.DateOfBirth,
			ISNULL(ROG.SelectableField,'') AS SelectableField,
			RGO.SchoolRequiredSignature ,
			RGO.SchoolRemark1,
			ISNULL(ESO.BasicPay,0) AS BasicPay,
			DAY(DATEADD(DD,-1,DATEADD(mm, DATEDIFF(mm, 0, CONVERT(DATE,CONVERT(nvarchar,PP.SalaryMonth) +'/01/'+CONVERT(nvarchar,PP.SalaryYear)) ) + 1, 0))) AS MonthDay,
			ESO.UAN,
			EPD.GenderId,
			ISNULL(PPR.Remark,'') AS PayProcessEmployeeRemark,
			tEM.FirstName,
			tEm.LastName,
			EM.DateOfJoining,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			ISNULL(REPLACE(REPLACE(
			(SELECT STUFF(
			(
			  SELECT  ' ' + Leave FROM -- create comma separated values
				(
						Select '<br>'+('<b>'+ LTM.Code +'</b>' +' - '+ CAST(SUM(CAST(L.NoOfLeave AS FLOAT)) AS varchar(50)) ) + '</br>'AS Leave 
						from 
						sHrm.tLeaveTypeMaster LTM  
						INNER JOIN sHrm.tLeave L ON  EM.EmployeeId = L.EmployeeId 
						INNER JOIN sCommon.tStatusMaster SM ON SM.Id=L.StatusId
						Where EM.EmployeeId=EM.EmployeeId AND LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0 
						AND LTM.Id = L.LeaveTypeId AND SM.Id=550
						AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
						AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
						GROUP BY LTM.Code
						)AS T FOR XML PATH('')
			)
			,1,1,'')),'&lt;','<'),'&gt;','>')
			,'') AS LeaveCount,
			tEM.Number,
			(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
			ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
			ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
			ISNULL(EPD.AdhaarNumber,'') AS AdhaarNumber,
			EM.DepartmentName, --Mantis : 0029371
			ESO.ESINumber,
			CASE 
				WHEN ISNULL(P.IsEmployeeSpecific,0) = 1
				THEN
					(SELECT PS.Amount 
						FROM sPayroll.tPaySetup PS 
						WHERE PS.PayElementId = P.Id 
						AND (PS.SourceId = tEM.Id AND PS.SourceTypeId = 95) 
						AND PS.PayrollYearId = PP.PayrollYearId)
				ELSE
					(SELECT PS.Amount 
						FROM sPayroll.tPaySetup PS 
						WHERE PS.PayElementId = P.Id 
						AND (PS.SourceId = PPE.PayrollGroupId AND PS.SourceTypeId = 2020) 
						AND PS.PayrollYearId = PP.PayrollYearId) 
			END AS PaySetupAmount,					--MantisId = 0030726
			tEM.CreatedDateTime AS CreatedDateTime, --mantis - 0030732
			[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise,	--MantisId = 0030726
			ISNULL(PPR.ChequeNo,'') ChequeNo,	--#Start Mantis Id : 0031036
			PPR.PayDate,
			CASE WHEN ISNULL(PPR.PayTypeId,0) = 0 THEN ISNULL(ESO.PayTypeId,0)
				ELSE ISNULL(PPR.PayTypeId,0) END AS PayTypeId,
			CASE WHEN ISNULL(PPR.PayTypeId,0) = 0 THEN ISNULL(PTM2.Title,'')
				ELSE ISNULL(PTM.Title,'') END AS PayTypeName,	--#End Mantis Id : 0031036
			ESO.RetirementDate AS RetirementDate, --Mantis - 0031406
			PM.Title AS PayrollTitle,				-- Mantis Id : 0032059
			ISNULL(EI.EmployeePhoto,0x) AS EmployeePhoto               -- Add for mentis : 0034079
		FROM 
			sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
			LEFT JOIN sCommon.tReportOrgGroup ROG ON ROG.OrgGroupId=PY.OrgGroupId AND (ROG.ReportId = @rReportId OR @rReportId = 0) 
			LEFT JOIN sCommon.tReportRemarkGroupOrg RGO ON RGO.OrgId = tEM.OrgID AND RGO.ReportRemarkGroupId =  4
			LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
			AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
			LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PPR.PayTypeId		--#Start Mantis Id : 0031036
			LEFT JOIN sFinanceCommon.tPayTypeMaster PTM2 ON PTM2.Id = ESO.PayTypeId		--#End Mantis Id : 0031036
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = tEM.Id                -- Add for mentis : 0034079
		where 
			(EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			AND (P.IsObsolete=0)
			AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
			AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
			AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
			AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
			AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
			AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
			AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
			AND ((EJD.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
			AND (EM.EmployeeGradeId = @rGradeId OR @rGradeId = 0)						-- MantisId : 0032059
			AND (EM.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	-- MantisId : 0032059
	
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockInwardReturnSearchGet]...';


GO

ALTER PROCEDURE [sProcurement].[pStockInwardReturnSearchGet]

	@rInwardNumber nvarchar(30) = '',
	@rStoreLocationId int,
	@rReturnByName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	    SELECT		
				Id AS InwardReturnId, 
				Number AS InwardReturnNumber,
				ReturnByName, 
				FromStoreLocationId, 
				CONVERT(varchar,TransactionDate,103) AS TransactionDate
		FROM		
				sProcurement.tStockInwardReturn SIR
		WHERE 
				((SIR.Number = @rInwardNumber) OR (@rInwardNumber = ''))
   				AND ((SIR.ReturnByName like @rReturnByName+'%') OR (@rReturnByName = ''))
   				AND ((SIR.FromStoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((SIR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
	   		  
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockInwardSearchGet]...';


GO
ALTER PROCEDURE [sProcurement].[pStockInwardSearchGet]

	@rInwardNumber nvarchar(30) = '',
	@rStoreLocationId int,
	@rInwardByName nvarchar,
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		If @rInwardNumber = NULL SET @rInwardNumber=''
		If @rInwardByName = NULL SET @rInwardByName=''

	    SELECT		
				Id AS StockInwardId, 
				Number AS InwardNumber,
				InwardByName, 
				ToStoreLocationId, 
				TransactionDate
		FROM		
				sProcurement.tStockInward SI
		WHERE 
				((SI.Number = @rInwardNumber) OR (@rInwardNumber = ''))
   				AND ((SI.InwardByName like @rInwardByName+'%') OR (@rInwardByName = ''))
   				AND ((SI.ToStoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((SI.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
	   		  
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockIssueReturnSearchGet]...';


GO
ALTER PROCEDURE [sProcurement].[pStockIssueReturnSearchGet]

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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		BEGIN
			SET @rIssueToName = sCommon.fSearchStringGet(@rIssueToName)
		END
	    SELECT 
	          SIR.Id AS StockIssueReturnId,
			  SIR.Number AS IssueReturnNumber,
			  SIR.ToStoreLocationId,
			  SI.Number AS IssueNumber,
			  SIR.TransactionDate,
			  U.DisplayTitle AS UserName,
			  (CASE WHEN SI.IssueToSourceTypeId = 2003 then SA.Name ELSE SI.IssueToName END) AS IssueToName -- chnages in name for mantis Id :0035260
		FROM 
			  sProcurement.tStockIssueReturn SIR 
			  INNER JOIN sProcurement.tStockIssue SI ON SI.Id=SIR.StockIssueId
			  LEFT JOIN sSecurity.tUser U ON U.Id = SIR.CreatedUserId
			  LEFT JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = SI.IssuetoSourceId
	   	WHERE 
	   	      ((SIR.Number = @rIssueReturnNumber) OR (@rIssueReturnNumber = ''))
	   	      AND ((SIR.ToStoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
	   		  AND ((SI.IssueToName like @rIssueToName OR ISNULL(@rIssueToName,'')='')
			  OR (SA.Name like @rIssueToName OR ISNULL(@rIssueToName,'')='')	)	
	   		  AND ((SIR.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
	   		  
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockIssueSearchGet]...';


GO
ALTER PROCEDURE [sProcurement].[pStockIssueSearchGet]

	@rIssueNumber nvarchar(30) = '',
	@rStoreLocationId int,
	@rIssueToName nvarchar(150), -- changes for mantis Id:0035260
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

	    SELECT		
				SI.Id AS StockIssueId,
				SI.Number AS Number,
				(CASE WHEN SI.IssueToSourceTypeId = 2003 then  SA.Name ELSE SI.IssueToName END) AS IssueToName, -- chnages in name for mantis Id :0035260
				SI.FromStoreLocationId,
				SI.CreatedUserId AS UserId,
				SI.CreatedDateTime AS IssuedDate
		FROM		
				sProcurement.tStockIssue SI 
				INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = SI.FromStoreLocationId
				LEFT JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = SI.IssuetoSourceId

		WHERE 
				((SI.Number = @rIssueNumber) OR (@rIssueNumber = ''))
				AND (SI.IssueToName like @rIssueToName OR ISNULL(@rIssueToName,'')='')
   				AND ((SLM.Id = @rStoreLocationId) OR (@rStoreLocationId = 0))
   				AND ((SI.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
	   		  
END
GO
PRINT N'Altering Procedure [sSecurity].[pAppPermissionGet]...';


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

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


GO
ALTER PROCEDURE [sSecurity].[pDashletGet]
	@rOrgGroupId int=0,
	@rDate date='',
	@rDashletId int=0,
	@rOrgGroupBatchId int=0,
	@rUserId bigint=0,
	@rUserSourceId bigint=0,
	@rUserSourceTypeId int=0,
	@rOrgId Int=0,
	@rSourceTypeId smallint=0,
	@rSourceId bigint=0,
	@rBatchId int=0,
	@rExamId int=0,
	@rStatusId int =0
	
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
DECLARE @TimeZoneDate datetime
SET  @TimeZoneDate=sCommon.fGetDate()
if(@rDashletId='1')
       BEGIN
        exec sCommunication.pCircularListGet @rUserSourceId=@rUserSourceId,@rOrgGroupBatchId=@rOrgGroupBatchId,@rUserSourceTypeId=@rUserSourceTypeId,@rUserId=@rUserId,@rStartDate=@rDate
        END
 if(@rDashletId='2')
        BEGIN
        SELECT  N.Id,N.Title FROM sCommunication.tNews N WHERE N.OrgGroupBatchId=@rOrgGroupBatchId AND Convert(date,N.CreatedDateTime)=convert(date,@TimeZoneDate)
        END
 if(@rDashletId='3')
          BEGIN
        exec sActivity.pMyEventGet @rSourceTypeId=@rSourceTypeId,@rSourceId=@rSourceId,@rOrgId=@rOrgId,@rBatchId=@rBatchId,@rFromDate=@rDate,@rToDate=@rDate
          END
if(@rDashletId='4')
        BEGIN
        exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=1,@rStatus=0,@rIsSearch=1
        END
 if(@rDashletId='5')
        BEGIN
        exec sCommunication.pAssignTaskGet @rId=0,@rOrgId=@rOrgId,@rCreatedUserId=@rUserId,@rIsAssignTaskToMe=0,@rStatus=0,@rIsSearch=1
        END
 if(@rDashletId='6')
        BEGIN
		DECLARE @BirthdayDays int=0
		IF EXISTS (SELECT 1 FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 355 AND SourceTypeId = 1016 AND SourceId = @rOrgId)
			BEGIN
			SET @BirthdayDays = (SELECT ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 355 AND SourceTypeId = 1016 AND SourceId = @rOrgId)
			END
		ELSE 
			BEGIN
			SET @BirthdayDays = 7
			END
        SELECT 	EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName AS Name,	EM.DepartmentName, EM.DateOfBirth AS DateOfBirth  FROM [sHrm].[vExtEmployeeMaster] EM	
        WHERE  	EM.OrgId = @rOrgId  
     --    AND (MONTH(EM.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND EM.DateOfBirth!='' AND EM.StatusId=7
	    --AND (DAY(EM.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))
		--AND(MONTH(EM.DateOfBirth) <= CAST(MONTH(@TimeZoneDate) AS varchar(2)) AND MONTH(EM.DateOfBirth) >= CAST(MONTH(@TimeZoneDate) AS varchar(2)))
		--AND(DAY(EM.DateOfBirth) <= CAST(DAY(@TimeZoneDate+@BirthdayDay) AS varchar(2)) AND DAY(EM.DateOfBirth) >= CAST(DAY(@TimeZoneDate) AS varchar(2)))

		AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) <= CONVERT(VARCHAR(5),@TimeZoneDate+@BirthdayDays,110) 
		AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) >= CONVERT(VARCHAR(5),@TimeZoneDate,110)
		AND EM.DateOfBirth!='' AND EM.StatusId=7
		ORDER BY CONVERT(VARCHAR(5),EM.DateOfBirth,110)
		
        END
 if(@rDashletId='7')
        BEGIN
        SELECT SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name, SC.ClassName+' '+SC.DivisionName AS ClassName FROM sStudent.vStudentAllDetail SC WHERE SC.OrgId=@rOrgId AND SC.BatchId=@rBatchId
         AND (MONTH(SC.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND SC.DateOfBirth!='' AND SC.StatusId=1
	    AND (DAY(SC.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))   
        END
         if(@rDashletId='10')
        BEGIN
       exec sAttendance.pDashletAttendanceStatusGet @rAcademicId=@rSourceId
        END
   
   if(@rDashletId='11')
        BEGIN
       SELECT EM.EmployeeName,L.FromDate,L.ToDate FROM  sHrm.tLeave L 
        INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId	
        INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
         WHERE  
			BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND L.OrgId = @rOrgId
			AND (EJD.EmployeeManagerId = @rUserSourceId OR @rUserSourceId = 0)
			--AND ((L.FromDate >= @rDate) OR (ISNULL(@rDate,'') = '')) --comment for Mantis Id: 0030464
			AND EM.EmployeeStatusId=7
			AND L.StatusId = 549
       -- exec [sHrm].[pLeaveListingGet] @rOrgId=@rOrgId,@rEmployeeId=@rUserSourceId,@rLeaveTypeId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromDate=@rDate,@rTodate=''
        END
   if(@rDashletId='12')
        BEGIN
     exec sCommunication.pPollGet @rOrgGroupBatchId=@rOrgGroupBatchId,@rSourceTypeId=@rUserSourceTypeId,@rCreatedUserId=@rUserId,@rCreatedDateTime=@rDate
        END
  if(@rDashletId='14')
       BEGIN
        exec sCommunication.pMyBookGet @rReaderSourceTypeId=@rUserSourceTypeId,@rReaderSourceId=@rUserSourceId,@rBatchId=@rBatchId,@rStatusId=@rStatusId

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

        END
  if(@rDashletId='18')
        BEGIN
     exec sCommunication.pBlogGet @rId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rTitle=NULL,@rCreatedUserId=0,@rOrgId=@rOrgId,@rCreatedDateTime=@rDate
        END
 if(@rDashletId='19')
        BEGIN
     exec sAssessment.pStudentResultGet @rAcademicId=@rSourceId,@rStudentId=@rUserSourceId,@rBatchId=@rBatchId,@rExamId=@rExamId
     END
  if(@rDashletId='21')
       BEGIN
       SELECT vCD.ClassDivisionName,ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
	   CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,@rDate,1,0)) =0 THEN 'Pending' ELSE 'Complete' END ELSE 'Complete' END AS PresentStatus
        FROM sStudent.tAcademic A INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId 
       AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId  AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
       INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId 
       LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceTypeId = 1 
       AND SR.IsPresent=1 AND SR.AttendanceDate=@rDate GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName ORDER BY vCD.OrderIndex
         END
  if(@rDashletId='22')
       BEGIN
        SELECT VL.Id,VL.VisitorName, VL.NoOfVisitor,  (isnull(case when isnull(VL.WhomToMeet,0)!=0 then isnull(EM.EmployeeName,'') else ISNULL(VL.WhomToMeetName,'') end,'' )) AS WhomToMeetName
		FROM sFrontOffice.tVisitorLog VL  
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId 
		 LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=VL.WhomToMeet
        WHERE VL.OrgId=@rOrgId AND VL.VisitDate=@rDate ORDER BY VL.VisitDate DESC,VL.InTime DESC
        END
  if(@rDashletId='23')
       BEGIN
        SELECT DispatchedTo, DispatchedCity  FROM sFrontOffice.tCourierDispatch  WHERE OrgGroupId=@rOrgGroupId AND DispatchDate=@rDate  AND @rDashletId='23' ORDER BY DispatchDate
        END
    if(@rDashletId='24')
       BEGIN
        SELECT ReceiveFrom, ReceiveFor  FROM  sFrontOffice.tCourierReceive  WHERE OrgGroupId=@rOrgGroupId  AND ReceiveDate=@rDate  AND @rDashletId='24' ORDER BY ReceiveDate
    END
     if(@rDashletId='25')
        BEGIN
     SELECT ISNULL(Ps.LectureNumber,'') AS LactureNumber,PS.EmployeeId,ISNULL(SMT.Title,'') AS Subject,ISNULL(EM1.FirstName,'') + ' '+ISNULL(EM1.LastName,'') AS EmployeeName,ISNULL(Em.FirstName,'') + ' '+ISNULL(Em.LastName,'') AS ProxyEmployeeName, ISNULL



(DV.Code,'') AS ClassDivisionName,ISNULL(SM.Title,'') AS ProxySubject from sTimetable.tProxySetting PS 
     INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId INNER JOIN sCommon.tDayMaster DM ON DM.Id = PS.DayId INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = PS.DivisionId
     INNER JOIN sTimetable.tTimeTable TT ON TT.Id=PS.TimeTableId 
     INNER JOIN sSetup.tSubjectMaster SMT ON SMT.Id = TT.SubjectId 
     INNER JOIN sHrm.tEmployeeMaster EM1  ON TT.EmployeeId=EM1.Id 
     INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = PS.EmployeeId  WHERE PS.ProxyDate=@rDate AND PS.BatchId=@rBatchId AND ((PS.EmployeeId=@rSourceId) OR (@rSourceId=0))  ORDER BY PS.ProxyDate
        END
        
        if(@rDashletId='27')
        BEGIN
     --Asset Check
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),AM.CheckedLastDate,103) AS CheckedLastDate
        FROM sAssetManagement.tAssetMaster AM INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
        INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
        WHERE ISNULL(AM.IsCheckRequired,0) = 1 AND (AM.CheckFrequencyId=1 AND AM.CheckedLastDate <=  DATEADD(dd,1,@TimeZoneDate) OR AM.CheckFrequencyId=2 AND AM.CheckedLastDate <=  DATEADD(dd,7,@TimeZoneDate) OR AM.CheckFrequencyId=3 AND AM.CheckedLastDate <= DATEADD(dd,30,@TimeZoneDate))
        AND AU.InchargeUserId =   @rUserId AND AM.OrgGroupId = @rOrgGroupId
     
     
     
  --      SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
		--AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate
		--FROM sAssetManagement.tAssetMaster AM 
		--INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
		--INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		-- WHERE AU.InchargeUserId = @rUserId AND AM.OrgGroupId = @rOrgGroupId
		 END
		if(@rDashletId='28')
        BEGIN
     --Asset maintenance
			 SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
			 AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate 
             FROM sAssetManagement.tAssetMaster AM 
             INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
             INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
                                WHERE AU.InchargeUserId =@rUserId  AND AM.OrgGroupId = @rOrgGroupId
		 END
		if(@rDashletId='29')
        BEGIN
     --Asset Renew
        SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),
         AM.RenewLastDate,103) AS RenewLastDate, CONVERT(nvarchar(12), AM.RenewNextDate,103) AS RenewNextDate
           FROM sAssetManagement.tAssetMaster AM INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId 
           INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId 
            WHERE ISNULL(AM.IsRenewRequired,0) = 1
            -- AND AM.RenewNextDate >= DATEADD(dd,ISNULL(AM.RenewAlertBeforeDays,0),AM.RenewLastDate) 
             AND convert(Date,@TimeZoneDate) >=  DATEADD(dd,-ISNULL(AM.RenewAlertBeforeDays,0), AM.RenewNextDate)
                           AND AU.InchargeUserId =  @rUserId  AND AM.OrgGroupId = @rOrgGroupId
        END
        --Inward
       IF(@rDashletId='30')
        BEGIN
        DECLARE @InwardRegisterGrid VARCHAR(max)=''
        SELECT  @InwardRegisterGrid = @InwardRegisterGrid + '<tr>
	       <td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterFrom,'') + '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(ReceivedDate,'01/01/0001'),103) + '</td>
	 	</tr>'		
	 	FROM
	 	 sFrontOffice.tInwardRegister
	 	 WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId
	 	 AND ReceivedDate<=convert(Date,@TimeZoneDate)
		 Order by ReceivedDate Desc

	   SELECT Isnull(@InwardRegisterGrid,'') As	InwardRegisterGrid
        END
            --Outward
         IF(@rDashletId='31')
        BEGIN
        DECLARE @OutwardRegisterGrid VARCHAR(max)=''
        SELECT  @OutwardRegisterGrid = @OutwardRegisterGrid + '<tr>
	    <td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterTo,'') + '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(OutWardDate,'01/01/0001'),103) + '</td>
	 	</tr>'	
	 	FROM
	 	 sFrontOffice.tOutwardRegister
	 	 WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId
	 	 AND OutwardDate<=convert(Date,@TimeZoneDate)
		 Order by OutwardDate Desc

	   SELECT Isnull(@OutwardRegisterGrid,'') As	OutwardRegisterGrid
	   END
	   
	   IF(@rDashletId='32')
        BEGIN
        DECLARE @ReorderQuantityGrid VARCHAR(max)=''
        SELECT   @ReorderQuantityGrid=@ReorderQuantityGrid+'<tr>
		     <td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
	        <td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
	      <td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(SP.ReOrderQuantity,0)) + '</td>
	 	 </tr>'	
	 	FROM
	 	 sProcurement.tStockBatch SB
	 	  INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
	 	 INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
	 	 INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
	 	 --INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
	 	 WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0 
	 	 group by SE.Title,SM.Title,SP.ReOrderQuantity,SP.ReOrderPoint
	 	 HAVING SUM(SB.AvailableQuantity) < SP.ReOrderPoint
	   
		SELECT Isnull(@ReorderQuantityGrid,'') As	ReorderQuantityGrid
		END
		
		 IF(@rDashletId='33')
        BEGIN
        DECLARE @SafetyStockGrid VARCHAR(max)=''
        SELECT   @SafetyStockGrid=@SafetyStockGrid+'<tr>
		     <td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
	        <td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
	      <td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(SP.SafetyStock,0)) + '</td>
	 	 </tr>'	
	 	FROM
	 	 sProcurement.tStockBatch SB
	 	  INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
	 	 INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
	 	 INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
	 	 --INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
	 	 WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0 
	 	 group by SE.Title,SM.Title,SP.SafetyStock,SP.ReOrderPoint
	 	 HAVING SUM(SB.AvailableQuantity) < SP.SafetyStock
	   
		SELECT Isnull(@SafetyStockGrid,'') As	SafetyStockGrid
        END
		 IF(@rDashletId='34')
		 BEGIN 
		 DECLARE @Increment varchar(max)=''
		 SELECT @Increment=@Increment+'<tr>
		  <td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
	        <td align="left" scope="col">' +convert(varchar,isnull(IncrementDate,'01/01/0001'),103)  + '</td></tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE IncrementDate BETWEEN GETDATE()-1 AND GETDATE()+7
		AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Increment, '') As	IncrementGrid
		END
		
			 IF(@rDashletId='78')
		 BEGIN 
		 DECLARE @Retirement varchar(max)=''
		 SELECT @Retirement=@Retirement+'<tr>
		  <td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
	        <td align="left" scope="col">' +convert(varchar,isnull(RetirementDate,'01/01/0001'),103)  + '</td></tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE RetirementDate BETWEEN GETDATE()-1 AND GETDATE()+30
		AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Retirement, '') As RetirementGrid
		END

	if(@rDashletId='83')
        BEGIN
			SELECT SA.Name,L.LeaveFromDate,L.LeaveToDate 
			FROM  sAttendance.tStudentLeaveRequest L   
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
			WHERE  
				 SA.BatchId = @rBatchId
				AND SA.OrgId = @rOrgId
				--Comment for Mantis Id:0029925
				--AND ((L.LeaveFromDate <= @rDate) OR (ISNULL(@rDate,'') = ''))
				--AND ((L.LeaveToDate >= @rDate) OR (ISNULL(@rDate,'') = ''))
				AND SA.StatusId=1
				AND L.StatusId IS NULL
		END

	 IF(@rDashletId='85')
	 BEGIN 
		SELECT  
			AF.Id,
			AF.AdmissionInquiryId,
			ISNULL(AF.FollowupDate,'') AS  FollowupDate,
			AF.FollowupRemark,
			AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name,
			AI.Number AS InquiryNumber			
		FROM 
            sAdmission.tAdmissionInquiryFollowup AF
            INNER JOIN sAdmission.tAdmissionInquiry AI ON AI.Id=AF.AdmissionInquiryId
            INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
		WHERE  ((AF.FollowupDate < @rDate) OR (ISNULL(@rDate,'')=''))
			AND ((AI.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	  Order by AF.FollowupDate DESC 
	 END

	 IF(@rDashletId='86')
	 BEGIN 
		SELECT  
			AF.Id,
			AF.AdmissionInquiryId,
			ISNULL(AF.FollowupDate,'') AS  FollowupDate,
			AF.FollowupRemark,
			AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name,
			AI.Number AS InquiryNumber			
		FROM 
            sAdmission.tAdmissionInquiryFollowup AF
            INNER JOIN sAdmission.tAdmissionInquiry AI ON AI.Id=AF.AdmissionInquiryId
            INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
		WHERE  ((AF.FollowupDate = @rDate) OR (ISNULL(@rDate,'')=''))
			AND ((AI.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	  Order by AF.FollowupDate DESC 
	 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) ,
 @rScreenGroupId int = 0     
      
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
    
BEGIN    
 IF(@rIsCoreMenu=0)    
 BEGIN    
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)    
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
    PageURL  AS PagePath,    
    IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermissionUser P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
       WHERE    
        T.IsObsolete = 0 AND P.UserId = @rUserId    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 ELSE     
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
     PageURL  AS PagePath,    
     IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermission P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
        INNER JOIN    
        (    
        SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0    
        ) B ON B.RoleId = P.RoleId    
       WHERE    
        T.IsObsolete = 0    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       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     
 if (@rScreenGroupId = 0)
 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,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215)) -- 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,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215))
	OR (@rEnvironmentName = 'Production' AND Menu.Id in(24,55,2411,2412,2711,2714))
	)
	
  --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,30411,30412,30409,30410,30447,30449,20949,20197,20056,20952,20059,20150,20153, --17/05/2023
		20951,20679,20233,31016,20124,30007,20120,20123,20375,20676,20986,20376,20122,30544,20194,30777,30193,30041,20131,20132,20133,20134,20374,20135,20136,20137,30381,30382,20677,20199,30292,20121,20413,31013,10160,20676,30390,30391,
		30100,30102,30105,30110,30107,30108,30113,
		31224,20930,20932,30936,30951,20284,20696,20698,20700,20776,20918,30164,30579,20570,20567,20568,20173,20174,
		20187,20188,20189,30059,30034,
		20325,20379,20380,20631,20235,20043,
		20997,20201,20215,20297,20848,30235,30687,30688,30689,31307,20170,20195,30546,30547,20216,20221,30582,20961,20960,20962,
		20243,20244,20247,20945,30599,30755,30932,31179,30680,30116,30176,30070,20538,20687,20743,20816,20817,20248,20245,30694,20280,20537,10201,10202,10203,20846,30080,30081,30137,30346,30375,30682
		,30685,30580,30178,30180,20948,20919,20920,31382,
		30661,20845,20844,20843,20653,20681,20663,20658,30966,
		8,9,10,11,19,21,9013,9029,20018,20037,20142,20143,20144,20145,20146,20157,20173,20174,20332,20419,20678,20689,20835,20860,20941,30267,30698,30950,30985,31036,20728,20730,20831,7,20931,20,9030,18,
		138,139,20175,20176,20250,20309,20327,141,142,30783,30603,20158,30854,30862,30956,31183,31185,31186,149,150,30656,20642,30120,30122,30499,30577,20596,31343,
		20001,20002,20003,20004,20006,20007,20008,20285,30021,30338,30509,20953,31173,31379,20967,30995,20323,20616,20913,20055,30801,
		441,459,460,476,500,30699,30716,30847,31003,31004,31020,31021,31022,30852,30991,31177,31187,31257,30388,30627,20908,20909,20910,30269,30517,30567,30617,20035,601,602,603,604,605,606,9084,20270,20339,20402,20230,20573,20586,20629,20836,31174,10117,524,30446,30451,30675,30676,30619,10217,30923,31025,31034,31035,10097,20904,20905,20638,20729,20834,20613,20432,20433,20435,31176,10118,31262,31303,30774,30849,30337,20223,20249,20841
		)
  --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,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215)) -- 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,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215))
	OR (@rEnvironmentName = 'Production' AND MenuTable.MenuId in(24,55,2411,2412,2711,2714))
	)
  --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
  ELSE
  BEGIN
	IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
	BEGIN
		Select 
			

				ISNULL(0, 0) AS MenuID,     
				ISNULL(0, 0) AS ParentMenuID,     
				ISNULL(S.Title,'') AS MenuTitle,       
				ISNULL(S.Title, '') AS ScreenTitle,        
				ISNULL(S.Page, '')  AS PageURL,
				ISNULL(S.ScreenGroupId,0) AS ScreenGroupId,    
				ISNULL(S.Id, 0) AS ScreenId,    
				ISNULL(0, 0) AS Permission,    
				ISNULL(0, 0) AS OrderNumber,    
				ISNULL(S.TaskId,0) AS TaskId,    
				ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
				ISNULL(MP.ModuleId,0) AS ModuleId,    
				ISNULL(1,1) AS MenuIsObsolete,    
				ISNULL(S.IconPath,'') AS Icon
			  		  
			   From sSecurity.tScreen S
		INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId
		--INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId
		INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId
		INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.ID = T.ResourceTypeId
		INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
		INNER JOIN sSecurity.tModulePermission MP ON T.ModuleId = MP.ModuleId And OT.OrgGroupId = MP.OrgGroupId
	 
		WHERE 
		(P.Permission & 2) =2
		AND ( ScreenGroupId=@rScreenGroupId OR @rScreenGroupId = 0)
		AND P.UserId=@rUserId 
		AND T.IsObsolete = 0
		AND S.IsObsolete = 0
		AND S.IsHideInScreenGroup = 0
		Order by RTM.OrderIndex,S.OrderIndex 
	END
	ELSE
	BEGIN
		Select 
			
				ISNULL(0, 0) AS MenuID,     
				ISNULL(0, 0) AS ParentMenuID,     
				ISNULL(S.Title,'') AS MenuTitle,       
				ISNULL(S.Title, '') AS ScreenTitle,        
				ISNULL(S.Page, '')  AS PageURL,
				ISNULL(S.ScreenGroupId,0) AS ScreenGroupId,    
				ISNULL(S.Id, 0) AS ScreenId,    
				ISNULL(0, 0) AS Permission,    
				ISNULL(0, 0) AS OrderNumber,    
				ISNULL(S.TaskId,0) AS TaskId,    
				ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
				ISNULL(MP.ModuleId,0) AS ModuleId,    
				ISNULL(1,1) AS MenuIsObsolete,    
				ISNULL(S.IconPath,'') AS Icon

					  
			   From sSecurity.tScreen S
		INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId
		INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId
		INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId
		INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.ID = T.ResourceTypeId
		INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
		INNER JOIN sSecurity.tModulePermission MP ON T.ModuleId = MP.ModuleId And OT.OrgGroupId = MP.OrgGroupId
	 
		WHERE 
		(P.Permission & 2) =2
		AND ( ScreenGroupId=@rScreenGroupId OR @rScreenGroupId = 0)
		 AND U.IsObsolete=0
		AND U.UserId=@rUserId 
		AND T.IsObsolete = 0
		AND S.IsObsolete = 0
		AND S.IsHideInScreenGroup = 0
		Order by RTM.OrderIndex,S.OrderIndex 
	END
  END
 END    
END
GO
PRINT N'Altering Procedure [sSecurity].[pSecuritySummaryDashboard]...';


GO

 
 
ALTER PROCEDURE [sSecurity].[pSecuritySummaryDashboard]
	@rType nvarchar(40)='',
	@rOrgId int =0,
	@rOrgGroupId int =0,
	@rOrgGroupBatchId int=0,
	@rDepositHeadId int =0,
	--@rLibraryId int =0
	@rBatchId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'SecurityList')
		BEGIN
				SELECT 
				CASE WHEN U.SourceTypeId = 95 THEN  'Employee' 
				WHEN U.SourceTypeId = 2003 THEN  'Student' ELSE  'NA' END AS 'Source Type',

				CASE WHEN U.SourceTypeId = 2003 THEN ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND((OM.Id =  @rOrgId)OR(@rOrgId=0)) AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003),0) WHEN U.SourceTypeId = 95 THEN ISNULL(COUNT(U.Id),0) END AS 'Created User',

				CASE WHEN U.SourceTypeId = 2003 THEN ISNULL((SELECT COUNT(ISNULL(U.Id,0)) FROM sStudent.vStudentCommunication SC LEFT JOIN  sSecurity.tUser U ON SC.StudentId = U.SourceId AND U.SourceTypeId=2003
            	WHERE ((U.LoginPassWord is Null)) AND (SC.OrgId = @rOrgId) AND SC.StatusId = 1 AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0))),0) WHEN U.SourceTypeId = 95 THEN ISNULL((SELECT COUNT(ISNULL(U.Id,0)) FROM sHrm.vEmployeeCommunication EC LEFT JOIN  sSecurity.tUser U ON EC.EmployeeId = U.SourceId
            	WHERE ((U.LoginPassWord is Null)) AND (EC.OrgId = @rOrgId) AND EC.StatusId = 7),0) ELSE 0 END As 'Pending User' ,

				CASE WHEN U.SourceTypeId = 2003 THEN  ISNULL((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND ((OM1.Id =  @rOrgId)OR(@rOrgId=0)) AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0)) LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 2003 AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1),0) WHEN U.SourceTypeId = 95 THEN ISNULL(COUNT(RU.UserId),0) END  AS 'Registered',

				 
				CASE WHEN U.SourceTypeId = 2003 THEN ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId LEFT JOIN (SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers) AS A ON A.UserId = U1.Id
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND((OM.Id =  @rOrgId)OR(@rOrgId=0)) AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003 AND A.UserId IS NULL),0) WHEN U.SourceTypeId = 95 THEN ISNULL((COUNT(U.Id) - COUNT(RU.UserId)),0) END AS 'Not Registered',

				CASE WHEN U.SourceTypeId = 2003 THEN ISNULL(Convert(decimal(10,2),((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND ((OM1.Id =  @rOrgId)OR(@rOrgId=0)) AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0)) LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 2003 AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1)*100)/(SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND((OM.Id =  @rOrgId)OR(@rOrgId=0)) AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003)),0.00)
				WHEN U.SourceTypeId = 95 THEN ISNULL(Convert(decimal(10,2),(COUNT(RU.UserId)*100)/COUNT(U.Id)),0.00) END AS Percentage

				FROM
				 
				sSecurity.tUser U
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
				LEFT JOIN (
				SELECT RU.UserId AS  UserId  
				FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND ((OM1.Id =  @rOrgId)OR(@rOrgId=0))
				AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
				WHERE U1.IsObsolete = 0 GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
				 
				WHERE U.IsObsolete = 0
				AND((OM.Id =  @rOrgId)OR(@rOrgId=0))
				AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1)
				GROUP BY U.SourceTypeId
		END
		 ELSE IF (@rType = 'StudentRegisteredUsers')
			BEGIN
				SELECT CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision
				,COUNT(U.Id) AS UserCount,	COUNT(RU.UserId) AS RegisteredUsers
				,(COUNT(U.Id)-COUNT(RU.UserId)) As NotRegister
				FROM  sStudent.vStudentCommunication SC
				INNER JOIN sSecurity.tUser U ON SC.StudentId=U.SourceId AND U.SourceTypeId = 2003
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SC.DivisionId  
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
				LEFT JOIN ( 				
				SELECT RU.UserId AS  UserId  
				FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1)AND((OM1.Id =  @rOrgId)OR(@rOrgId=0))
				AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
				WHERE U1.IsObsolete = 0 GROUP BY RU.UserId				
				) RU ON RU.UserId = U.Id 
				WHERE ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0)) AND SC.StatusId = 1
				AND(OM.Id !=1) AND ((OM.Id = @rOrgId) OR (@rOrgId=0)) AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) 
				GROUP BY CM.OrderIndex, DM.OrderIndex,CM.DisplayTitle,DM.DisplayTitle,DM.Id--Changed For mantis : 35931 by Nilesh
				Order By CM.OrderIndex, DM.OrderIndex --Added For mantis : 35931 by Nilesh
			END
			ELSE IF (@rType = 'EmployeeRegisteredUsers')
				BEGIN
					SELECT R.Title AS RoleName,COUNT(U.Id) AS UserCount,COUNT(RU.UserId) AS RegisteredUsers,
						(COUNT(U.Id)- COUNT(RU.USerId)) AS NotRegisterUsers
						FROM sSecurity.tUser U
						INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
						INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId AND R.Title != 'SuperAdmin'
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
						--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
						--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
						LEFT JOIN (SELECT RU.UserId AS UserId  
						FROM sCommunication.tRegisteredUsers RU   
						GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
						WHERE ((O.Id = @rOrgGroupId) OR (@rOrgGroupId=0)) AND  U.IsObsolete = 0 AND UR.IsObsolete=0
						AND ((U.CreatedUserId != 1) OR (U.DisplayTitle = 'Admin'))
						AND ((U.SourceTypeId = 95)OR(95=0))
						AND(OM.Id !=1) AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
						--AND ((COGBM.Id=1 )OR(1=0 ))
						GROUP BY R.Title,R.Id
				END
END
GO
PRINT N'Altering Procedure [sStudent].[pChangeClassGet]...';


GO

ALTER PROCEDURE [sStudent].[pChangeClassGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rStrIDNo nvarchar(500),
	 @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

		DECLARE @ListofIDs TABLE(IDs nvarchar(20), ID INT IDENTITY(1,1));
		INSERT INTO @ListofIDs

		select q2.value from
		(SELECT cast('<x>'+replace(@rStrIDNo,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
		(SELECT x.value('.','nvarchar(20)') as value FROM thexml.nodes('x') as f(x))q2
		
		
	 --IF(@rIsSearch=1)
		--BEGIN
			--SET @rGRNo = sCommon.fSearchStringGet(@rGRNo)
			--SET @rLastName = sCommon.fSearchStringGet(@rLastName)
			--SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		--END
	
	SELECT 
			SN.AcademicId,
			--A.StudentId,
			--SO.GenderId,
			SN.ClassId,
			SN.DivisionId,
			SN.RollNo AS RollNo,
			SN.FirstName,
			SN.MiddleName,
			SN.LastName,
			--SN.FirstName + ' ' + SN.MiddleName + ' ' + SN.LastName AS Name, --Commented for mantis : 35931 by Nilesh
			SN.Name, --Added for mantis : 35931 by Nilesh
			SN.Number,
			SN.Code
      
  FROM 
			[sStudent].[vStudentName] SN
           --sStudent.tAcademic A
           --INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId 
           ----INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId  
  WHERE 
				(SN.ClassId=@rClassId OR @rClassId=0)
			AND (SN.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND ((SN.Code IN(SELECT IDs FROM @ListofIDs)) OR (ISNULL(@rStrIDNo,'') = ''))
			AND SN.OrgID=@rOrgId 
			AND SN.BatchID=@rBatchId

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


GO
 ALTER PROCEDURE [sStudent].[pIDNoGenerationUpdate]
	 
	@rStudentId bigint,
	@rIDNo nvarchar(20),
	@rCreatedUserId bigint,
	@rOrgId smallint,
	@rIsNumber bit,
	@rRecordStatusId smallint,
	@rRollNo int = 0,
	@rDivisionId int = 0,
	@rAcademicId bigint = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		   DECLARE @lCode nvarchar(20)
		   SELECT @lCode=Code FROM sStudent.tStudentMaster WHERE Code=@rIDNo AND OrgId=@rOrgId AND Id<>@rStudentId
		   IF @lCode IS NOT NULL
		   BEGIN
					SELECT -103 AS Result,@lCode AS Code
					RETURN
		   END 		   
		   
		 --  IF EXISTS(SELECT @lCode=Code FROM sStudent.tStudentMaster WHERE Code=@rIDNo AND OrgId=@rOrgId AND Id<>@rStudentId)
			--	BEGIN
			--	SELECT -103 AS RESULT
			--	RETURN
			--END 
	--BEGIN TRY
	-- BEGIN TRANSACTION	
	 BEGIN
	    UPDATE  sStudent.tStudentMaster
	    SET
		    Code=@rIDNo,
			Number = (CASE WHEN @rIsNumber = 0 THEN Number WHEN @rIsNumber = 1 THEN @rIDNo END), 
			RecordStatusId = @rRecordStatusId,				  
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
	      WHERE Id = @rStudentId 
		  
		IF(@rAcademicId <> 0 AND @rRollNo <> 0 AND @rDivisionId <> 0)
		BEGIN
		DECLARE @lRollNo int
		DECLARE @lBatchId int = (SELECT BatchId FROM sStudent.tAcademic WHERE Id = @rAcademicId)

		SELECT @lRollNo=RollNo FROM sStudent.tAcademic WHERE RollNo=@rRollNo AND OrgId=@rOrgId AND DivisionId = @rDivisionId AND BatchId = @lBatchId AND Id<>@rAcademicId
		IF @lRollNo IS NOT NULL
		BEGIN
				SELECT -104 AS Result,@lRollNo AS RollNo
				RETURN
		END 

		UPDATE sStudent.tAcademic SET RollNo = @rRollNo, DivisionId = @rDivisionId WHERE Id = @rAcademicId
		END
	 END  
		SELECT 1 AS RESULT
	--	COMMIT TRANSACTION
	--END TRY
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS RESULT
	--END CATCH	
		
END
GO
PRINT N'Altering Procedure [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
   ISNULL(SGM.Title,'') AS StudentGroup --add for mantis : 0035772
 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  sStudent.tStudentGroupMaster SGM ON SD.StudentGroupId = SGM.Id --add for mantis : 0035772

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


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

BEGIN 
	
	IF @rClassStatusId IS NULL SET @rClassStatusId = 0
--DECLARE @lConfigValue nvarchar(50)
--DECLARE @lIsDisplayImageHeader bit=0


--   SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 176 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
--	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
--	SET @lIsDisplayImageHeader = 0
--	ELSE
--	SET @lIsDisplayImageHeader = 1	
	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,
			SA.Code,
			SA.RollNo AS RollNo,			
			SA.FirstName,			
			SA.LastName,
			SA.Name,		
			SA.ClassName,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber,
			SA.ClassStatusName,
			SAA.AdmissionDate,
			--@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--ISNULL(SA.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
	     --   ISNULL(SA.ReportOrgTitle,'') AS ReportOrgTitle,
	       -- (CASE OI.CertificateHeaderA4 WHEN 1 THEN
			--OI.CertificateHeaderA4
			--ELSE NULL END ) AS CertificateHeaderA4 
			SA.GenderId AS Gender,  -- Mantis - 35671
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo  -- Mantis - 35671
	        
			
      
	FROM 
		 	sStudent.vStudentAcademic SA
		 	INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassId and BC.BatchId= @rBatchId
		 	INNER JOIN sStudent.tStudentAdmission SAA ON SAA.StudentId = SA.StudentId
		 	--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = SA.OrgId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId  -- Mantis - 35671
	WHERE 
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentStrengthDivisionWiseGet]...';


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

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

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


GO
ALTER PROCEDURE [sTransport].[pRptRoutewiseStudentListGet]	 
	 @rOrgGroupBatchId int=0,
	 @rOrgId int=0,
	 @rDepartmentId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rRouteId int=0,
	 @rDestinationId int=0,
	 @rTransportId int =0,
	 @rDropDestinationId int=0,
	 @rDropBusRouteId int=0,
	 @rStatusId int=0,
	 @rStrRouteId nvarchar(500)=null,
	 @rDestinationTitle nvarchar(50)=null,
	 @rIsWithDetail bit,
	 @rReportId int=0			-- add by dhruvik for 27333 mantis
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
-- add by dhruvik for 27333 mantis start
IF(@rReportId=30177 OR @rReportId=20394)
BEGIN
SELECT DISTINCT * FROM 
	(
		SELECT 
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			AR.SourceId,
			SM.Code,
			SM.FirstName+' '+SM.LastName AS Name,
			DM.Id AS DivisionId,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			BRDM.Title AS DestinationPoint,
			BRM.Id AS BusRouteId,
			BRM.Title AS BusRoute,
			A.RollNo,
			VM.Title AS Vehicle,
			VM.NoOfSeats,
			BRM.OrderIndex AS RouteOrder,
			BRDM.OrderIndex AS PickupOrder,
			DM.OrderIndex AS DivisionOrderIndex,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrganizationName,
			DMast.Id AS DepartmentId,
			DMast.Title AS DepartmentName,
			SC.ParentContactNo AS ParentContactNo,
			ISNULL(SC.PresentStreetone,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS PresentAddress,
			ISNULL(VM.RegistrationNumber,'') AS RegistrationNumber,
			ISNULL(BRM.DriverName,'') AS DriverName,
			ISNULL(BRM.DriverMobileNo,'') AS DriverMobileNo,
			ISNULL(BRM.ConductorName,'') AS ConductorName,
			ISNULL(BRM.ConductorMobileNo,'') AS ConductorMobileNo,
			BRDM.Amount,
			ISNULL(BRM1.DriverName,'') AS DropRoutDriverName,
			ISNULL(BRM1.DriverMobileNo,'') AS DropRoutDriverMobileNo,
			ISNULL(BRM1.ConductorName,'') AS DropRoutConductorName,
			ISNULL(BRM1.ConductorMobileNo,'') AS DropRoutConductorMobileNo,
			BRM1.Id AS DropRoutBusRouteId,
			BRM1.Title AS DropRoutBusRoute,
			ISNULL(VM1.RegistrationNumber,'') AS DropRoutRegistrationNumber,
			VM1.Title AS DropRoutVehicle,
			VM1.NoOfSeats AS DropRoutVehicleNoOfSeats,
			BRM1.OrderIndex AS DropRoutRouteOrder,
			BRDM1.OrderIndex AS DropRoutOrder,
			BRDM1.Title AS DropDestinationPoint ,
			BRDM1.DropTime,
			BRDM.PickUpTime,
			@rIsWithDetail As WithDetails ,
			SM.SUId As SUID
			
		FROM 
			sTransport.tAssignRoute AR
			INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 
			LEFT JOIN sStudent.tStudentCommunication SC ON A.StudentId=SC.StudentId AND SM.StatusId=1
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tDepartmentMaster DMast ON DMast.Id=CM.DepartmentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
			LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
			LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR.DropDestinationId 
			LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND (BRM1.OrgGroupBatchId=@rOrgGroupBatchId)
			INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = BRM.OrgGroupBatchId AND BMM.Id = A.BatchId 
			LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
		WHERE 
			--((AR.SourceId=@rAcademicId) OR (@rAcademicId=0))
			(BRM.OrgGroupBatchId=@rOrgGroupBatchId)
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((DMast.Id=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((CM.Id=@rClassId) OR (@rClassId=0))
			AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
			AND ((BRM.Id=@rRouteId) OR (@rRouteId=0))
			AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
			AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
			AND ((BRDM1.BusRouteId=@rDropBusRouteId) OR (@rDropBusRouteId=0))
			AND ((BRDM1.Id=@rDropDestinationId) OR (@rDropDestinationId=0))
			AND ((SM.StatusId = @rStatusId) OR (@rStatusId=0))
			AND BMM.IsInContext = 1
			AND (BRM.Id IN (SELECT item from sCommon.fnSplit(@rStrRouteId,',')) OR ISNULL(@rStrRouteId,'') = '')
			AND (BRDM.Title Like @rDestinationTitle OR ISNULL(@rDestinationTitle,'') = '')
	) A
END
-- 27333 mantis end
ELSE
BEGIN
	SELECT DISTINCT * FROM 
	(
		SELECT 
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			AR.SourceId,
			SM.Code,
			SM.FirstName+' '+SM.LastName AS Name,
			DM.Id AS DivisionId,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			BRDM.Title AS DestinationPoint,
			BRM.Id AS BusRouteId,
			BRM.Title AS BusRoute,
			A.RollNo,
			VM.Title AS Vehicle,
			VM.NoOfSeats,
			BRM.OrderIndex AS RouteOrder,
			BRDM.OrderIndex AS PickupOrder,
			DM.OrderIndex AS DivisionOrderIndex,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrganizationName,
			DMast.Id AS DepartmentId,
			DMast.Title AS DepartmentName,
			SC.ParentContactNo AS ParentContactNo,
			ISNULL(SC.PresentStreetone,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS PresentAddress,
			ISNULL(VM.RegistrationNumber,'') AS RegistrationNumber,
			ISNULL(BRM.DriverName,'') AS DriverName,
			ISNULL(BRM.DriverMobileNo,'') AS DriverMobileNo,
			ISNULL(BRM.ConductorName,'') AS ConductorName,
			ISNULL(BRM.ConductorMobileNo,'') AS ConductorMobileNo,
			BRDM.Amount,
			ISNULL(BRM1.DriverName,'') AS DropRoutDriverName,
			ISNULL(BRM1.DriverMobileNo,'') AS DropRoutDriverMobileNo,
			ISNULL(BRM1.ConductorName,'') AS DropRoutConductorName,
			ISNULL(BRM1.ConductorMobileNo,'') AS DropRoutConductorMobileNo,
			BRM1.Id AS DropRoutBusRouteId,
			BRM1.Title AS DropRoutBusRoute,
			ISNULL(VM1.RegistrationNumber,'') AS DropRoutRegistrationNumber,
			VM1.Title AS DropRoutVehicle,
			VM1.NoOfSeats AS DropRoutVehicleNoOfSeats,
			BRM1.OrderIndex AS DropRoutRouteOrder,
			BRDM1.OrderIndex AS DropRoutOrder,
			BRDM1.Title AS DropDestinationPoint ,
			BRDM1.DropTime,
			BRDM.PickUpTime,
			@rIsWithDetail As WithDetails ,
			SM.SUId As SUID
			
		FROM 
			sTransport.tAssignRoute AR
			INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id 
			LEFT JOIN sStudent.tStudentCommunication SC ON A.StudentId=SC.StudentId AND SM.StatusId=1
			INNER JOIN sSetup.tClassMaster CM ON A.ClassId=CM.Id
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tDepartmentMaster DMast ON DMast.Id=CM.DepartmentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
			LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
			LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR.DropDestinationId 
			LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND (BRM1.OrgGroupBatchId=@rOrgGroupBatchId)
			INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = BRM.OrgGroupBatchId AND BMM.Id = A.BatchId 
			LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
		WHERE 
			--((AR.SourceId=@rAcademicId) OR (@rAcademicId=0))
			(BRM.OrgGroupBatchId=@rOrgGroupBatchId)
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((DMast.Id=@rDepartmentId) OR (@rDepartmentId=0))
			AND ((CM.Id=@rClassId) OR (@rClassId=0))
			AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
			AND ((BRM.Id=@rRouteId) OR (@rRouteId=0))
			AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
			AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
			AND ((BRDM1.BusRouteId=@rDropBusRouteId) OR (@rDropBusRouteId=0))
			AND ((BRDM1.Id=@rDropDestinationId) OR (@rDropDestinationId=0))
			AND ((SM.StatusId = @rStatusId) OR (@rStatusId=0))
			AND BMM.IsInContext = 1
			AND (BRM.Id IN (SELECT item from sCommon.fnSplit(@rStrRouteId,',')) OR ISNULL(@rStrRouteId,'') = '')
			AND (BRDM.Title Like @rDestinationTitle OR ISNULL(@rDestinationTitle,'') = '')

		UNION ALL 

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


GO


CREATE PROCEDURE [sAccounting].[pRptExpenditureSummaryGet] 
	@rBuilder1 NVARCHAR(max) = ''
	,@rBuilder2 NVARCHAR(max) = ''
	,@rStartDate DATE
	,@rEndDate DATE
	,@rOrgGroupId INT = 0
	,@rAccountingYearId [int]
	,@rAccountId INT = 0
	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 = @rOrgGroupId
	WHERE CM.Id = 548

	DECLARE @lLedgerId INT
	DECLARE @lTransactionYear INT
	DECLARE @lTransactionMonth INT
	DECLARE @lAccOpBalance DECIMAL(25, 5)
	DECLARE @lLedgerTypeId INT
	DECLARE @1ExpenceCount INT
	DECLARE @1IncomeCount INT
	DECLARE @ReportOrgTitle NVARCHAR(200)
	DECLARE @SmallAddress1 NVARCHAR(200)
	DECLARE @SmallAddress2 NVARCHAR(200)
	DECLARE @lCount int
	DECLARE @AccOpBalance DECIMAL(25, 5)
	DECLARE @LedgerTypeId Int
	DECLARE @LedgerId int
	DECLARE @OpeningBalance DECIMAL(25, 5)
	DECLARE @TransactionBalance DECIMAL(25, 5)
	DECLARE @ClosingBalance DECIMAL(25, 5)
	DECLARE @lAccountingYear NVARCHAR(100)


	SELECT @ReportOrgTitle = ReportOrgTitle
		,@SmallAddress1 = SmallAddress1
		,@SmallAddress2 = SmallAddress2
	FROM sAccounting.tAccountMaster AM
	WHERE AM.Id = @rAccountId

	SELECT @lAccountingYear = Title FROM sAccounting.tAccountingYearMaster WHERE Id = @rAccountingYearId

	IF OBJECT_ID('tempdb..#tempUpdateClosingBalance') IS NOT NULL
	BEGIN
		DROP TABLE #tempUpdateClosingBalance;
	END

	CREATE TABLE #tempUpdateClosingBalance (
		Id INT IDENTITY(1, 1)
		,LedgerId INT
		,TransactionYear INT
		,TransactionMonth INT
		,Temp_Op_Balance DECIMAL(12, 2)
		,Closing_Balance DECIMAL(12, 2)
		,Transaction_Balance DECIMAL(12, 2)
		)

	IF OBJECT_ID('tempdb..#tempLedgerMaster') IS NOT NULL
	BEGIN
		DROP TABLE #tempLedgerMaster;
	END

	CREATE TABLE #tempLedgerMaster (
		Id INT IDENTITY(1, 1)
		,LedgerId INT
		,TransactionYear INT
		,TransactionMonth INT
		,AccOpBalance DECIMAL(25, 5)
		,LedgerTypeId INT
		)

	INSERT INTO #tempLedgerMaster
	SELECT Distinct L.Id AS LedgerId
		,YEAR(T.TransactionDate) AS TransactionYear
		,MONTH(T.TransactionDate) AS TransactionMonth
		,OpeningBalance
		,LedgerTypeId
	FROM sAccounting.tLedgerMaster L
	INNER JOIN sAccounting.tTransactionDetail TD ON L.Id = TD.LedgerId
	INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
	WHERE L.AccountingYearId = @rAccountingYearId

	SELECT @lCount =  COUNT(Id) FROM #tempLedgerMaster

	WHILE (@lCount > 0)
	BEGIN
		SELECT @AccOpBalance = AccOpBalance
			,@LedgerTypeId = LedgerTypeId
			,@LedgerId = LedgerId
			,@lTransactionYear = TransactionYear
			,@lTransactionMonth = TransactionMonth
		FROM #tempLedgerMaster
		WHERE Id = @lCount

		-- Opening Balance Calulation
		BEGIN
			SELECT @OpeningBalance = ISNULL(SUM(AMOUNT), 0)
			FROM sAccounting.tTransactionDetail TD
			INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
			WHERE T.OrgGroupId = @rOrgGroupId
				AND T.AccountingYearId = @rAccountingYearId
				AND T.TransactionDate < @rStartDate
				AND TD.LedgerId = @LedgerId

				AND YEAR(T.TransactionDate) = @lTransactionYear
				AND MONTH(T.TransactionDate) = @lTransactionMonth
		END

		-- Transaction Balance
		BEGIN
			SELECT @TransactionBalance = ISNULL(SUM(AMOUNT), 0)
			FROM sAccounting.tTransactionDetail TD
			INNER JOIN sAccounting.tTransaction T ON T.ID = TD.TransactionId
			WHERE T.OrgGroupId = @rOrgGroupId
				AND T.AccountingYearId = @rAccountingYearId
				AND T.TransactionDate >= @rStartDate
				AND T.TransactionDate <= @rEndDate
				AND TD.LedgerId = @LedgerId
				AND YEAR(T.TransactionDate) = @lTransactionYear
				AND MONTH(T.TransactionDate) = @lTransactionMonth
		END

		--
		IF @LedgerTypeId = 1
		BEGIN
			SET @TransactionBalance = - 1 * @TransactionBalance
			SET @OpeningBalance = - 1 * @OpeningBalance
		END
		ELSE
		BEGIN
			SET @TransactionBalance = @TransactionBalance
			SET @OpeningBalance = @OpeningBalance
		END

		SET @OpeningBalance = @OpeningBalance + @AccOpBalance
		SET @ClosingBalance = @OpeningBalance + @TransactionBalance
			
		INSERT INTO #tempUpdateClosingBalance (
			LedgerId
			,TransactionYear
			,TransactionMonth
			,Temp_Op_Balance
			,Closing_Balance
			,Transaction_Balance
			)
		VALUES (
			@LedgerId
			,@lTransactionYear
			,@lTransactionMonth
			,@OpeningBalance
			,@ClosingBalance
			,ISNULL(@TransactionBalance, 0)
			)

		SET @lCount = @lCount - 1
	END

	--Select * from #tempUpdateClosingBalance

	CREATE TABLE #TempExpenseGroup (
		Id INT IDENTITY(1, 1)
		,TransactionYear INT
		,TransactionMonth INT
		,ExpenseGroupId INT
		,ExpenseGroup NVARCHAR(200)
		,ExpenseLedger NVARCHAR(200)
		,Expense DECIMAL(22, 2)
		,OpeningBalance DECIMAL(22, 2)
		,ExpenseTransactionBalance DECIMAL(12, 2)
		)

	INSERT INTO #TempExpenseGroup
	SELECT UC.TransactionYear
		,UC.TransactionMonth
		,ISNULL(Lg.Id, 0) AS ExpenseGroupId
		,ISNULL(LG.Title, '') AS ExpenseGroup
		,ISNULL(L.Title, '') AS ExpenseLedger
		,ISNULL(SUM(UC.Closing_Balance), 0) AS Expense
		,ISNULL(SUM(L.OpeningBalance), 0) AS OpeningBalance
		,ISNULL(SUM(UC.Transaction_Balance), 0) AS ExpenseTransactionBalance
	FROM sAccounting.tLedgerMaster L
	INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
	INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
	INNER JOIN #tempUpdateClosingBalance UC ON L.Id = UC.LedgerId
	WHERE LMG.ID = 4
		AND L.AccountingYearId = @rAccountingYearId
		AND LG.AccountingYearId = @rAccountingYearId
	GROUP BY UC.TransactionYear
		,UC.TransactionMonth
		,LG.Title
		,LMG.ID
		,L.Title
		,LG.Id
	HAVING ISNULL(SUM(UC.Closing_Balance), 0) > 0
	ORDER BY LMG.Id

	BEGIN
		SELECT 
			TransactionYear
			,TransactionMonth
			,@ReportOrgTitle AS OrgTitle
			,@SmallAddress1 AS SmallAddress1
			,@SmallAddress2 AS SmallAddress2
			,@rBuilder1 AS Builder1
			,@rBuilder2 AS Builder2
			,ISNULL(ExpenseGroupId, 0) AS ExpenseGroupId
			,ExpenseGroup AS ExpenseGroup
			,ExpenseLedger
			,[sAccounting].[fDecimalValueGet](OpeningBalance, @DecimalCount) AS OpeningBalance
			,[sAccounting].[fDecimalValueGet](Expense, @DecimalCount) AS Expense
			,[sAccounting].[fDecimalValueGet](ISNULL(EG.ExpenseTransactionBalance, 0.00), @DecimalCount) AS ExpenseTransactionBalance
			,@lAccountingYear AS AccountingYear

		FROM #TempExpenseGroup EG
	END

	DROP TABLE #TempExpenseGroup
--BEGIN
--		SELECT
--		  0 AS TransactionYear,
--		  0 AS TransactionMonth,
--			'' AS OrgTitle,
--			'' AS SmallAddress1,
--			'' AS SmallAddress2,
--			'' AS Builder1,
--			'' AS Builder2,
--			0 AS ExpenseGroupId,
--			'' AS ExpenseGroup,
--			'' AS ExpenseLedger,
--			0.00 AS OpeningBalance,
--			0.00 AS Expense,
--			0.00 AS ExpenseTransactionBalance,
--			'' AS AccountingYear
END
GO
PRINT N'Creating Procedure [sCertificate].[pStudentCustomFiledDataGet]...';


GO

CREATE PROCEDURE [sCertificate].[pStudentCustomFiledDataGet]
	 
	 @rAcademicId bigint = 0,
	 @rOrgGroupId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @lStudentId BigInt = 0;
SELECT @lStudentId = StudentId FROM sStudent.tAcademic WHERE Id = @rAcademicId

DECLARE @columns NVARCHAR(MAX);
DECLARE @sql NVARCHAR(MAX);

	SET @columns = STUFF(
		(
			SELECT ',' + QUOTENAME(LTRIM(RTRIM(FieldTitle)))
			FROM sStudent.tStudentCustomFieldMaster SM
			LEFT JOIN sStudent.tStudentCustomFieldData CM ON SM.Id = CM.StudentCustomFieldId AND CM.StudentId = @lStudentId
			WHERE SM.OrgGroupId = @rOrgGroupId AND SM.IsObsolete = 0
			GROUP BY FieldTitle
			FOR XML PATH(''), TYPE
		).value('.', 'NVARCHAR(MAX)')
		,1,1,''); -- Remove the leading comma


-- Construct the dynamic SQL query
	SET @sql = '
	SELECT StudentId, ' + @columns + '
	FROM
	(
		SELECT 
			CM.StudentId,
			LTRIM(RTRIM(SM.FieldTitle)) AS FieldTitle,
			CASE WHEN ISNULL(CM.FieldData, '''') = ''- Select -'' THEN ''''
                ELSE ISNULL(CM.FieldData, '''') END AS FieldData
		FROM sStudent.tStudentCustomFieldMaster SM
		LEFT JOIN sStudent.tStudentCustomFieldData CM ON SM.Id = CM.StudentCustomFieldId AND CM.StudentId = ' + Convert(varchar(20),@lStudentId) + ' 
		WHERE SM.OrgGroupId = ' + Convert(varchar(10),@rOrgGroupId) + ' AND SM.IsObsolete = 0 AND CM.StudentId IS NOT NULL
	) AS SourceTable
	PIVOT
	(
		MAX(FieldData)
		FOR FieldTitle IN (' + @columns + ')
	) AS PivotTable
	';

-- Print the SQL for debugging
	--PRINT @sql;

-- Execute the dynamic SQL
	EXEC sp_executesql @sql;

END
GO
PRINT N'Creating Procedure [sHrm].[pLessonPlanEmployeeReplacementDeleteAndTransfer]...';


GO
CREATE PROCEDURE [sHrm].[pLessonPlanEmployeeReplacementDeleteAndTransfer]
	 
        @rExistingEmployeeId BIGINT,
		@rNewEmployeeId BIGINT = 0,
		@rAction NVARCHAR(100),
		@rSubjectId Int,
		@rFromDate datetime='',
		@rToDate datetime='' 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF (@rAction ='DeleteAndTransfer')
	BEGIN
		--Update sAcademic.tLessonPlan SET EmployeeId = @rNewEmployeeId where EmployeeId = @rExistingEmployeeId
			UPDATE LP
			SET LP.EmployeeId = @rNewEmployeeId
			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.EmployeeId = @rExistingEmployeeId 
			AND SM.Id = @rSubjectId
			AND (LP.StartDate >= @rFromDate OR LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (LP.StartDate <= @rToDate OR LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')


	END
	ELSE IF(@rAction ='Delete')
	BEGIN
		--Delete sAcademic.tLessonPlan where EmployeeId =  @rExistingEmployeeId AND 
			DELETE LP
			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.EmployeeId = @rExistingEmployeeId 
			AND SM.Id = @rSubjectId
			AND (LP.StartDate >= @rFromDate OR LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
			AND (LP.StartDate <= @rToDate OR LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
	END

	--Drop Table #tmpSplitTable
END
GO
PRINT N'Creating Procedure [sHrm].[pLessonPlanEmployeeReplacementGet]...';


GO


CREATE PROCEDURE [sHrm].[pLessonPlanEmployeeReplacementGet]
	 
        @rEmployeeId bigint,
		@rFromDate datetime='',
		@rToDate datetime='' 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT DISTINCT SM.Id AS SubjectId, ISNULL(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 EmployeeId = @rEmployeeId
		AND (LP.StartDate >= @rFromDate OR LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
		AND (LP.StartDate <= @rToDate OR LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')

END
GO
PRINT N'Creating Procedure [sMis].[pRptStudentStrengthDivisionWiseGet]...';


GO

CREATE PROCEDURE [sMis].[pRptStudentStrengthDivisionWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rDepartmentId int,
	 --@rStudentCode varchar(20)='',
	 @rReportId int=0,
	 @rOrggroupBatchID int=0,
	 --@rAsOnDate Date ='',
    @rStatusId int=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

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


GO

CREATE PROCEDURE [sSecurity].[pMobValidateUser_new]

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

					SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP
			END	
		END
		IF(@rUserSourceTypeId = 2003)
		BEGIN
			IF EXISTS (SELECT 1 FROM sStudent.tStudentCommunication WHERE (ParentContactNo = @rUserMobileNumber or ParentEmail = @rUserMobileNumber) and StudentId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				
					EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId
					SELECT 1 AS Result,'student otp' 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'Creating Procedure [sStudent].[pGetClassDropDown]...';


GO
CREATE proc [sStudent].[pGetClassDropDown]
@rOrgGroupBatchId int,
@rOrgId int,
@rDepartmentId int=0
as
begin
	declare @lClassRes nvarchar(max)='', @lBatchId int =0 

	select @lBatchId = Id from sSetup.tBatchMaster WHERE OrgId = @rOrgId AND OrgGroupBatchId = @rOrgGroupBatchId

	select @lClassRes = @lClassRes + '<option value="0"> -- ALL -- </option>'
	select @lClassRes = @lClassRes + '<option value="' + convert( NVARCHAR,ClassId) + '">' + ClassName + '</option>'
	from sSetup.vBatchClass where IsObsolete = 0 AND BatchId = @lBatchId AND (DepartmentId = @rDepartmentId OR @rDepartmentId=0)
	
	select @lClassRes as ClassRes
end
GO


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

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

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

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

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

			RETURN
		END
		ELSE IF EXISTS (
				--SELECT 1
				--FROM [sFee].[tPostDatePayment]
				--WHERE ReceiptBookId = (SELECT ReceiptBookId FROM sFee.tFeeSetup WHERE Id = @rId)
				SELECT 1 FROM sFee.tPostDatePayment PDP 
				INNER JOIN sStudent.tAcademic A ON A.Id = PDP.SourceId AND PDP.SourceTypeId = 2001 
				WHERE A.ClassId = (SELECT ClassId FROM sFee.tFeeSetup WHERE Id = @rId) AND ReceiptBookId=(SELECT ReceiptBookId FROM sFee.tFeeSetup WHERE Id = @rId)
				AND PDP.BatchId = (SELECT BatchId FROM sFee.tFeeSetup where Id = @rId) -- Add Batch Id Filter for Mantis Id: 0036102
			)
		BEGIN
			SELECT - 54 AS Result

			RETURN
		END

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

			ALTER TABLE sfee.tReceiptDetail
				WITH CHECK CHECK CONSTRAINT FK_sFee_tReceiptDetail_FeeSetupId

			ALTER TABLE sFee.tFeeOptional
				WITH CHECK CHECK CONSTRAINT FK_sFee_tFeeOptional_tFeeSetupId

			ALTER TABLE sFee.tFeeAllocation
				WITH CHECK CHECK CONSTRAINT FK_sFee_tFeeAllocation_FeeSetupId

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

			COMMIT TRANSACTION
		END TRY

		BEGIN CATCH
			ROLLBACK TRANSACTION

			SELECT - 1 AS Result
		END CATCH

		SELECT 11 AS Result
	END
END

GO

PRINT N'Update complete.';


GO


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

