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



GO
PRINT N'Dropping Function [sHrm].[fEmployeeNameGetL]...';


GO
DROP FUNCTION [sHrm].[fEmployeeNameGetL];


GO
PRINT N'Altering Table [sAccounting].[tLedgerMaster]...';


GO
ALTER TABLE [sAccounting].[tLedgerMaster]
    ADD [IsShowInDashBoard] BIT NULL;


GO
PRINT N'Altering Table [sAccounting].[tTransaction]...';


GO
ALTER TABLE [sAccounting].[tTransaction] ALTER COLUMN [Narration] NVARCHAR (1000) NULL;


GO
PRINT N'Altering Table [sAccounting].[tTransactionApprove]...';


GO
ALTER TABLE [sAccounting].[tTransactionApprove] ALTER COLUMN [Narration] NVARCHAR (1000) NULL;


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


GO
ALTER TABLE [sFee].[tDepositAdd]
    ADD [ReferenceSourceTypeId] SMALLINT DEFAULT ((0)) NOT NULL,
        [ReferenceSourceId]     BIGINT   DEFAULT ((0)) NOT NULL;


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


GO
ALTER TABLE [sRecruitment].[tCandidateMaster]
    ADD [WhatsAppContactNo] NVARCHAR (20) NULL;


GO
PRINT N'Altering Table [sTally].[tReceiptPosting]...';


GO
ALTER TABLE [sTally].[tReceiptPosting]
    ADD [ChequeNo] NVARCHAR (40) NULL;


GO
PRINT N'Refreshing View [sAccounting].[vLedgerMaster]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAccounting].[vLedgerMaster]';


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


GO


ALTER VIEW [sHrm].[vEmployeeCommonDetail]

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

PRINT N'Altering View [sStudent].[vStudentColumnName]...';


GO
ALTER VIEW [sStudent].[vStudentColumnName]  
AS 
SELECT 	
	  --SA.AcademicId,	  
	  --SA.ClassId,
	  --SA.DivisionId,
	  SA.RollNo,
	  --SA.OrgId,
	  --SA.BatchId,
	  OM.Title AS Organization,
	  BM.Title AS Batch,
	  DM.Title AS Department,
	  --SA.StudentId,
	  SA.SUId,
	  SA.Code AS [ID No],
	  SA.Code AS [GR No],
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  --SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      SO.DateOfBirth,
      SO.BirthdateInWord,
      --SO.TransportModeId,
      TM.Title AS TransportMode,
      --SO.GenderId,
      GM.Title AS Gender,
      --SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast As FamilyCaste,
      --SO.FamilySubCast,
      --SO.CastCategoryId,
      
      CCM.Title AS CasteCategory,
      --SO.ReligionId,
      RM.Title AS Religion,
      --SO.HouseId,
      HM.Title AS House,
      --SO.MotherTongueId,
      MTM.Title AS MotherTongue,
      --SO.NationalityId,
      NM.Title AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity AS IsPhysicalDeformity,
      SH.PysicalDeformityRemark AS PhysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
    STUFF(
        COALESCE(',' + NULLIF(SC.PresentStreetOne, ''), '')  + 
        COALESCE(',' + NULLIF(SC.PresentStreetTwo, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentStreetThree, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentCountry, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentState, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentCity, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentZipCode, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentContactNo, ''), ''),
        1, 1, '') AS PresentAddress,
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
	   STUFF(
           COALESCE(',' + NULLIF(SC.PermanentStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.PermanentStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentStreetThree, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentCountry, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentState, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentCity, ''), '') +
            COALESCE(',' + NULLIF(SC.PermanentZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.PermanentContactNo, ''), ''),
           1, 1, '') AS PermanentAddress ,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
	   
      STUFF(
           COALESCE(',' + NULLIF(SC.EmergencyStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.EmergencyStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyStreetThree, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyCountry, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyState, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyCity, ''), '') +
            COALESCE(',' + NULLIF(SC.EmergencyZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.EmergencyContactNo, ''), ''),
           1, 1, '') AS EmergencyAddress ,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
      SC.StudentEmail,
	  --AR.PickupDestinationId AS BusRouteDestinationId,
	  BDM.Title AS BusRouteDestination,
	  SF.FatherName,
	  SF.FatherDateOfBirth,	 
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeContactNo,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome AS FatherAnnualIncome,	-- MantisId : 0029214
	  SF.MotherName,
	  SF.MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
	  SF.MotherOfficeContactNo,
      SF.MotherOfficeAddress,
      SF.MotherIncome AS MotherAnnualIncome,	-- MantisId : 0029214   
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  SAD.AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
      SAD.InactiveDate,
	  SAD.InActiveReason,
	  SAD.LCBook,
	  SAD.LeftStandardId AS LeftStandard,
	  SAD.LeftDate,
	  SAD.LCDate,
	  SAD.LCCopy,
	  SAD.LeftReason,
	  SAD.LCProgress,
	  SAD.LCConduct,
	  SAD.LCRemark,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.BankAccountNumber,
	  AD.BankName,
	  AD.BankBranch,
	  AD.BankIFSCCode,
	  AD.BankAccountHolderName,
	  BSM.Title AS StudentBatchStatus,
	  AD.Class9BoardRegistrationNumber,
	  AD.Class11BoardRegistrationNumber,
	  AD.PassportNumber,
	  AD.PassportType,
	  AD.PassportCountryCode,
	  AD.PassportIssueDate,
	  AD.PassportExpiryDate,
	  SS.SiblingName1,
	  SS.SiblingInstitue1,
	  SS.SiblingClass1,
	  SS.SiblingAge1,
	  SS.SiblingRelation1,
	  SS.SiblingName2,
	  SS.SiblingInstitue2,
	  SS.SiblingClass2,
	  SS.SiblingAge2,
	  SS.SiblingRelation2,
	  SS.SiblingName3,
	  SS.SiblingInstitue3,
	  SS.SiblingClass3,
	  SS.SiblingAge3,
	  SS.SiblingRelation3,
	  CD.SSCBoard,
	  CD.SSCSchool,
	  CD.SSCPassingYear,
	  CD.SSCObtainMarks,
	  CD.SSCOutOfMarks,
	  CD.SSCPercentage,
	  CD.SSCMathMarks,
	  CD.SSCMathOutOfMarks,
	  CD.HSCBoard,
	  CD.HSCSchool,
	  CD.HSCPassingYear,
	  CD.HSCObtainMarks,
	  CD.HSCOutOfMarks,
	  CD.HSCPercentage,
	  
	  CD.HSCBiologyMarks,
	  CD.HSCBiologyOutOfMarks,
	 
	  CD.HSCChemistryMarks,
	  CD.HSCChemistryOutOfMarks,
	  CD.HSCMathMarks,
	  CD.HSCMathOutOfMarks,
	  cd.HSCPhysicsMarks,
	  CD.HSCPhysicsOutOfMarks,
	  CD.PCMMarks,
	  CD.PCBMarks,
	  CD.JEERollNo,
	  CD.JEEMeritNo,
	  CD.JEEMeritMarks,
	  CD.JEEOutOfMarks,
	  CD.DiplomaBoard,
	  CD.DiplomaCollege,
	  CD.DiplomaPassingYear,
	  CD.DiplomaObtainMarks,
	  CD.DiplomaOutOfMarks,
	  CD.DiplomaPercentage,
	  CD.ApplicationNo,
	  CD.AdmissionRound,
	  CD.MaritalStatusId,
	  ISNULL(HHM.Title,'') AS HostelName,
	  ISNULL(HRM.Title,'') AS Room,
	  ISNULL(HBM.Title,'') AS BuildingName,
	  ISNULL(HAR.BedNumber,'') AS BedNumber,
	  ISNULL(SGM.Title,'') AS StudentGroup,
	  ISNULL(SGMO.Title,'') AS StudentOtherGroup,
	  SO.BirthState,
	  SO.BirthCountry,
	  ISNULL(BDM.PickupTime,'') AS PickupTime,
	  ISNULL(BDM.DropTime,'') AS DropTime,
	  ISNULL(BRM.Title,'') AS BusRoute,
	  ISNULL(SAD.PreviousStandard,'') AS PreviousStandard,
	  ISNULL(So.ReferenceRemark,'') AS ReferenceRemark,
	  ISNULL(SAD.LCNumber,'') AS LCNumber,
	  CM.Title AS AdmissionStandard,
	  SF.IsFatherExStudent,
	  SF.IsMotherExStudent,
	  SF.FatherOrganization,
	  SF.FatherDesignation,
	  SF.MotherOrganization,
	  SF.MotherDesignation,
	  SF.RelativeOrganization,
	  SF.RelativeDesignation,
	  SH.IsAllergy,
      SH.AllergyRemark,
      SO.FamilySubCast,
      SF.RelativeName,
      SF.RelativeDateOfBirth,
      SF.RelativeOccupation,
      SF.RelativeQualification,
      SF.RelativeContactNo,
      SF.RelativeMail,
      SF.RelativeOfficeAddress,      
      SF.RelativeIncome AS RelativeAnnualIncome,		-- MantisId : 0029214
     
    
		STUFF( (SELECT DISTINCT ',' + CTM.Title FROM sStudent.tStudentCustomTag SCT INNER JOIN sStudent.tCustomTagMaster CTM ON SCT.CustomTagId=CTM.Id 
							WHERE SCT.StudentId = SA.StudentId FOR XML PATH ('')), 1, 1, '')  AS CustomTag,
		STM.Title AS RecordTag,
		SC.WhatsAppContactNo,
        SC.IsStopApplicationAccess,
		CASE WHEN ISNULL(SO.DateOfBirth, '') = '' THEN '' ELSE (SELECT [sCommon].[fGetDateOfBirthInWord](SO.DateOfBirth)) END AS Age,
		BDM.Title AS PickupPoint,
		ISNULL(SA.LocalName,'') AS LocalName, -- Added for mantis : 34211
		ISNULL(BRM2.Title, '') AS DropRoute, -- Added for mantis : 34483
		ISNULL(SA.PENNumber,0) AS PENNumber    --Mantis - 35453
  FROM sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SAD.AdmissionStandardId
	INNER JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	INNER JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	INNER JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	INNER JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	INNER JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	INNER JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	INNER JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	INNER JOIN sCommon.tCountryMaster NM ON NM.Id=SO.NationalityId
	INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	INNER JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	INNER JOIN sStudent.tStudentadditional AD ON AD.StudentId= SA.StudentId
	INNER JOIN sStudent.tStudentBatchStatus SBS ON SBS.AcademicId = SA.AcademicId
	INNER JOIN sStudent.tBatchStatusMaster BSM ON BSM.Id = SBS.BatchStatusId
	INNER JOIN sStudent.tStudentSibling SS ON SS.StudentId= SA.StudentId
	INNER JOIN sStudent.tCollegeDetail CD ON CD.StudentId = SA.StudentId
	INNER JOIN sHostel.tAssignRoom HAR ON HAR.SourceId = SA.StudentId
	INNER JOIN sHostel.tRoomMaster HRM ON HRM.Id = HAR.RoomId
	INNER JOIN sHostel.tBuildingMaster HBM ON HBM.HostelId = HRM.HostelId
	INNER JOIN sHostel.tHostelMaster HHM ON HHM.Id = HRM.HostelId
	INNER JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SA.StudentGroupId
	INNER JOIN sStudent.tStudentOtherGroupMaster SGMO ON SGMO.Id = SA.StudentOtherGroupId
    INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId
	INNER JOIN sCommon.tStatusMaster STM ON STM.Id = SA.RecordStatusId AND STM.StatusTypeId=102
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
	LEFT JOIN sTransport.tBusRouteDestinationMaster BDM2 ON BDM2.Id=AR.DropDestinationId -- Added for mantis : 34483
	LEFT JOIN sTransport.tBusRouteMaster BRM2 ON BRM2.Id=BDM2.BusRouteId -- Added for mantis : 34483
GO
PRINT N'Altering View [sStudent].[vStudentCustomSearch]...';


GO
ALTER VIEW [sStudent].[vStudentCustomSearch]  
  
AS  
  
SELECT 	
	  SA.AcademicId,	  
	  SA.ClassId,
	  SA.DivisionId,
	  SA.RollNo,
	  SA.OrgId,
	  OM.Title AS Organization,
	  SA.BatchId,
	  BM.Title AS Batch,
	  BM.OrgGroupBatchId,
	  SA.DepartmentId,
	  DM.Title AS Department,
	  SA.StudentId,
	  SA.SUId,
	  SA.Code,
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      CONVERT(VARCHAR(10), SO.DateOfBirth, 111) AS DateOfBirth,
      SO.BirthdateInWord,
      SO.TransportModeId,
      TM.Title AS TransportMode,
      SO.GenderId,
      GM.Title AS Gender,
      SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast AS FamilyCaste,
      SO.FamilySubCast,
      
      
      SO.CastCategoryId,
      CCM.Title AS CasteCategory,
      SO.ReligionId,
      RM.Title AS Religion,
      SO.HouseId,
      HM.Title AS House,
      SO.MotherTongueId,
     SO.MotherTongue AS MotherTongue,
      SO.NationalityId,
      NM.Nationality AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity,
      SH.PysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
      
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
      SC.StudentEmail,
	  ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
	  RT.BusRouteDestinationId AS BusRouteDestinationId,
	  RT.PickupPoint AS BusRouteDestination, -- Changed Value as PickupPoint for mantis : 34483
	  SF.FatherName,
	  CONVERT(VARCHAR(10), SF.FatherDateOfBirth, 111)AS FatherDateOfBirth,
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome AS FatherAnnualIncome,	-- MantisId : 0029214
	  SF.FatherOfficeContactNo,
	  SF.MotherName,
	 CONVERT(VARCHAR(10),  SF.MotherDateOfBirth,111) AS MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
	  SF.MotherOfficeContactNo,
      SF.MotherOfficeAddress,
      SF.MotherIncome AS MotherAnnualIncome,    -- MantisId : 0029214  
	  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  CONVERT(VARCHAR(10), SAD.AdmissionDate, 111) AS AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
	  CONVERT(VARCHAR(10),SAD.LeftDate, 111) AS LeftDate,
	  SA.IsBlackList,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.RepeatCount,
	  ADI.BankAccountNumber,
	  ADi.BankBranch,
	  ADI.BankIFSCCode,
	  ADI.BankName,
	  ADI.BankAccountHolderName,
	  ESM.Title AS StudentBatchStatus,
	  EnrollmentStatusId AS StudentStatusId,
	  ADI.Class9BoardRegistrationNumber,
	  ADI.Class11BoardRegistrationNumber,
	  ADI.PassportNumber,
	  ADI.PassportType,
	  ADI.PassportCountryCode,
	CONVERT(VARCHAR(10),ADI.PassportIssueDate,111) AS PassportIssueDate,
	  ADI.PassportExpiryDate,
	  ISNULL(SS.SiblingName1,'') As SiblingName1,
	  ISNULL(SS.SiblingInstitue1,'') As SiblingInstitue1,
	  ISNULL(SS.SiblingClass1,'') As SiblingClass1,
	  ISNULL(SS.SiblingAge1,'') As SiblingAge1,
	  ISNULL(SS.SiblingRelation1,'') As SiblingRelation1,
	  ISNULL(SS.SiblingName2,'') As SiblingName2,
	  ISNULL(SS.SiblingInstitue2,'') As SiblingInstitue2,
	  ISNULL(SS.SiblingClass2,'') As SiblingClass2,
	  ISNULL(SS.SiblingAge2,'') As SiblingAge2,
	  ISNULL(SS.SiblingRelation2,'') As SiblingRelation2,
	  ISNULL(SS.SiblingName3,'') As SiblingName3,
	  ISNULL(SS.SiblingInstitue3,'') As SiblingInstitue3,
	  ISNULL(SS.SiblingClass3,'') As SiblingClass3,
	  ISNULL(SS.SiblingAge3,'') As SiblingAge3,
	  ISNULL(SS.SiblingRelation3,'') As SiblingRelation3,
	  ISNULL(HHM.Title,'') AS HostelName,
	  ISNULL(HRM.Title,'') AS Room,
	  ISNULL(HBM.Title,'') AS BuildingName,
	  ISNULL(HAR.BedNumber,'') AS BedNumber,
	  
	  ISNULL(SM.StudentGroupId,0) AS StudentGroupId,
	  ISNULL(SM.StudentOtherGroupId,0) AS StudentOtherGroupId,
	  
	  SGM.Title AS StudentGroup,
	  SOGM.Title AS StudentOtherGroup,
	  SO.BirthState,
	  So.BirthCountry,
	  ISNULL(RT.BusRouteId,0) AS BusRouteId,
	  ISNULL(RT.PickupTime,'') AS PickupTime,
	  ISNULL(RT.Droptime,'') AS Droptime,
	  ISNULL(RT.BusRoute,'' )AS BusRoute,
	   CD.SSCBoard,
	   CD.SSCSchool,
	  CD.SSCPassingYear,
	  CD.SSCObtainMarks,
	  CD.SSCOutOfMarks,
	  CD.SSCPercentage,
	  CD.SSCMathMarks,
	  CD.SSCMathOutOfMarks,
	  CD.HSCBoard,
	  CD.HSCSchool,
	  CD.HSCPassingYear,
	  CD.HSCObtainMarks,
	  CD.HSCOutOfMarks,
	  CD.HSCPercentage,
	  
	  CD.HSCBiologyMarks,
	  CD.HSCBiologyOutOfMarks,
	 
	  CD.HSCChemistryMarks,
	  CD.HSCChemistryOutOfMarks,
	  CD.HSCMathMarks,
	  CD.HSCMathOutOfMarks,
	  cd.HSCPhysicsMarks,
	  CD.HSCPhysicsOutOfMarks,
	  CD.PCMMarks,
	  CD.PCBMarks,
	  CD.JEERollNo,
	  CD.JEEMeritNo,
	  CD.JEEMeritMarks,
	  CD.JEEOutOfMarks,
	  CD.DiplomaBoard,
	  CD.DiplomaCollege,
	  CD.DiplomaPassingYear,
	  CD.DiplomaObtainMarks,
	  CD.DiplomaOutOfMarks,
	  CD.DiplomaPercentage,
	  CD.ApplicationNo,
	  CD.AdmissionRound,
	  CD.MaritalStatusId,
	  EX.Id As ExemptionTypeId,
	  SAD.PreviousStandard,
	  SO.ReferenceRemark,
	  SAD.LCNumber,
	  CM.Title AS AdmissionStandard,
	  SH.IsAllergy,
      SH.AllergyRemark,
      SF.RelativeName,
      SF.RelativeDateOfBirth,
      SF.RelativeOccupation,
      SF.RelativeQualification,
      SF.RelativeContactNo,
      SF.RelativeMail,
      SF.RelativeOfficeAddress,      
      SF.RelativeIncome AS RelativeAnnualIncome,		-- MantisId : 0029214
      STUFF(
           COALESCE(',' + NULLIF(SC.PresentStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.PresentStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentStreetThree, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentCountry, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentState, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentCity, ''), '') +
            COALESCE(',' + NULLIF(SC.PresentZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.PresentContactNo, ''), ''),
           1, 1, '') AS PresentAddress,
      STUFF(
           COALESCE(',' + NULLIF(SC.PermanentStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.PermanentStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentStreetThree, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentCountry, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentState, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentCity, ''), '') +
            COALESCE(',' + NULLIF(SC.PermanentZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.PermanentContactNo, ''), ''),
           1, 1, '') AS PermanentAddress ,
      STUFF(
           COALESCE(',' + NULLIF(SC.EmergencyStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.EmergencyStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyStreetThree, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyCountry, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyState, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyCity, ''), '') +
            COALESCE(',' + NULLIF(SC.EmergencyZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.EmergencyContactNo, ''), ''),
           1, 1, '') AS EmergencyAddress ,
	  (SELECT STUFF( (SELECT DISTINCT ',' + CTM.Title FROM sStudent.tStudentCustomTag SCT INNER JOIN sStudent.tCustomTagMaster CTM ON SCT.CustomTagId=CTM.Id 
							WHERE SCT.StudentId = SA.StudentId FOR XML PATH ('')), 1, 1, '')  AS CustomTag FROM sStudent.tStudentMaster SM1 WHERE SM1.Id = SM.Id GROUP BY SM1.Id) AS CustomTag,
		STM.Title AS RecordTag,
		SC.IsStopApplicationAccess,
		CASE WHEN ISNULL(SO.DateOfBirth, '') = '' THEN '' ELSE (SELECT [sCommon].[fGetDateOfBirthInWord](SO.DateOfBirth)) END AS Age,
		RT.PickupPoint as PickupPoint,
		ISNULL(SA.LocalName, '') AS LocalName, -- Added for mantis : 34211
		ISNULL(RT.DropRoute, '') AS DropRoute, -- Added for mantis : 34483
		ISNULL(SA.PENNumber,0) AS PENNumber    --Mantis - 35453

  FROM sStudent.vStudentAcademic SA
    INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId
	LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SAD.AdmissionStandardId
	LEFT JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	--LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	LEFT JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	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 sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	LEFT JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	LEFT JOIN sCommon.tCountryMaster NM ON NM.Id=SO.NationalityId
	--LEFT JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	LEFT JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = SA.AcademicId
	LEFT JOIN sStudent.tStudentadditional ADI ON ADI.StudentId = SA.StudentId
	LEFT JOIN sStudent.tEnrollmentStatusMaster ESM ON ESM.Id = SM.EnrollmentStatusId
	LEFT JOIN sStudent.tStudentSibling SS ON SS.StudentId = SA.StudentId
	LEFT JOIN sHostel.tAssignRoom HAR ON HAR.SourceId = SM.Id AND HAR.OrgGroupBatchId = SA.OrgGroupBatchId
	LEFT JOIN sHostel.tRoomMaster HRM ON HRM.Id = HAR.RoomId
	LEFT JOIN sHostel.tBuildingMaster HBM ON HRM.BuildingId = HBM.Id 
	LEFT JOIN sHostel.tHostelMaster HHM ON HHM.Id = HRM.HostelId
	
	LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id=SM.StudentGroupId
	LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id=SM.StudentOtherGroupId
	--LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId
	LEFT JOIN sStudent.tCollegeDetail CD ON CD.StudentId = SA.StudentId
	LEFT JOIN sFee.tExemptionTypeMaster EX ON Ex.Id=SA.ExemptionTypeId
   LEFT JOIN
	(SELECT AR.SourceId,AR.DropDestinationId AS BusRouteDestinationId,BDM2.Title AS BusRouteDestination,AR.PickupDestinationId AS BusRoutePickupDestinationId,BDM.Title AS PickupPoint, ISNULL(BRM.Id,0) AS BusRouteId,
	  ISNULL(BDM.PickupTime,'') AS PickupTime,
	  ISNULL(BDM.Droptime,'') AS Droptime,
	  ISNULL(BRM.Title,'' )AS BusRoute,BRM.OrgGroupBatchId,
	  ISNULL(BRM2.Title,'') AS DropRoute FROM sTransport.tAssignRoute AR  -- Added for mantis : 34483
    INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	LEFT JOIN sTransport.tBusRouteDestinationMaster BDM2 ON BDM2.Id=AR.DropDestinationId
    INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId AND  AR.SourceTypeId=2003
	LEFT JOIN sTransport.tBusRouteMaster BRM2 On BRM2.Id=BDM2.BusRouteId AND AR.SourceTypeId=2003 )  RT -- Added for mantis : 34483
    ON RT.SourceId = SA.StudentId     AND RT.OrgGroupBatchId =SA.OrgGroupBatchId
	INNER JOIN sCommon.tStatusMaster STM ON STM.Id = SA.RecordStatusId AND STM.StatusTypeId=102
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
GO
PRINT N'Altering Function [sAlert].[fExamDetailGet]...';


GO
 
ALTER FUNCTION [sAlert].[fExamDetailGet](@rExamId bigint,@rSubjectId int, @rTypeId tinyint)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult  VARCHAR(MAX)

IF(@rTypeId=1)
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE ISNULL(CS.SubjectCode,'') + ' - '  END +		-- MantisId : 0035349
			(
			ISNULL(ED.ExamTopic,'')
			)
			    + ' , '
	FROM 
		sAssessment.tExamDetail ED
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		 
	WHERE
		ED.ExamId=@rExamId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		AND SM. IsObsolete = 0
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END
ELSE IF (@rTypeId=2)
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE ISNULL(CS.SubjectCode,'') + ' - '  END +		-- MantisId : 0035349
			(
			ISNULL(ED.ExamTime,'')
			)
			    + ' , '
	FROM 
		sAssessment.tExamDetail ED
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		 
	WHERE
		ED.ExamId=@rExamId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		AND SM. IsObsolete = 0
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END

ELSE
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE ISNULL(CS.SubjectCode,'') + ' - '  END +		-- MantisId : 0035349
			(
			CONVERT(VARCHAR(10), ED.ExamDate, 103)
			)
			    + ' , '
	FROM  
		sAssessment.tExamDetail ED
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		 
	WHERE
		ED.ExamId=@rExamId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		AND SM. IsObsolete = 0
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END

    RETURN @lResult 
END
GO
PRINT N'Altering Function [sAlert].[fResultGet]...';


GO

 
ALTER FUNCTION [sAlert].[fResultGet](@rResultId bigint,@rSubjectId int, @rTypeId tinyint)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult  VARCHAR(MAX)

IF(@rTypeId=1)
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			--+ CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - ' +
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - '  END +		-- MantisId : 0035349
			(
			CASE  
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab , '
			WHEN  E.IsMarksInDecimal = 1 then
			CONVERT(VARCHAR(11),RD.Obtain)
			WHEN E.IsMarksInDecimal = 0 then
			CONVERT(VARCHAR(11),CAST(RD.Obtain AS INT))
			END)
			    + ' , '
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		 
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END
ELSE
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			--+ CONVERT(VARCHAR(11),CS.SubjectCode,106) + ' - ' +
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - '  END +		-- MantisId : 0035349
			(
			CASE  
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab'
			ELSE
			ISNULL(RD.SubjectGrade,'')
			END)
			    + ' , '
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		 
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END
    RETURN @lResult 
END
GO
PRINT N'Altering Function [sAlert].[fResultGetWithLineBreak]...';


GO

 
ALTER FUNCTION [sAlert].[fResultGetWithLineBreak](@rResultId bigint,@rSubjectId int, @rTypeId tinyint)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult  VARCHAR(MAX)

IF(@rTypeId=1)
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CHAR(13) --+ CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - ' +
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - '  END +		-- MantisId : 0035349
			(
			CASE  
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab , '
			WHEN  E.IsMarksInDecimal = 1 then
			CONVERT(VARCHAR(11),RD.Obtain)
			WHEN E.IsMarksInDecimal = 0 then
			CONVERT(VARCHAR(11),CAST(RD.Obtain AS INT)) 
			END)
			    + ' , ' 
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		 
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END
ELSE
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+  CHAR(13) --+ CONVERT(VARCHAR(11),CS.SubjectCode,106) + ' - ' +
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - '  END +		-- MantisId : 0035349
			(
			CASE  
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab'
			ELSE
			ISNULL(RD.SubjectGrade,'') 
			END)
			    + ' , ' 
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		 
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END
    RETURN @lResult 
END
GO
PRINT N'Altering Function [sAlert].[fResultWithMaxGet]...';


GO

ALTER FUNCTION [sAlert].[fResultWithMaxGet](@rResultId bigint,@rSubjectId int)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult  VARCHAR(MAX)
(SELECT @lResult  = COALESCE(@lResult ,'') 
			--+ CONVERT(VARCHAR(11),CS.SubjectCode,106) + ' - ' +
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - '  END +		-- MantisId : 0035349
			(
			CASE 
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab , '
			WHEN E.IsMarksInDecimal = 1 THEN  CONVERT(VARCHAR(11),RD.Obtain)
			else CONVERT(VARCHAR(11),CAST(RD.Obtain AS INT))END)
			+(CASE 
			WHEN RD.IsPresent = 0 THEN ''
			WHEN RD.IsPresent != 0 THEN + ' / ' + CONVERT(VARCHAR(11),Cast(Round(ED.Maximum,0) AS int)) + ' , ' END)
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult)- 1)
    RETURN @lResult 
END
GO
PRINT N'Altering Function [sAlert].[fResultWithMaxGetWithLineBreak]...';


GO

ALTER FUNCTION [sAlert].[fResultWithMaxGetWithLineBreak](@rResultId bigint,@rSubjectId int)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lResult  VARCHAR(MAX)
(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CHAR(13) -- + CONVERT(VARCHAR(11),CS.SubjectCode,106) + ' - ' +
			+ CASE WHEN @rSubjectId > 0 THEN '' ELSE CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - '  END +		-- MantisId : 0035349
			(
			CASE 
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab , '
			WHEN E.IsMarksInDecimal = 1 THEN  CONVERT(VARCHAR(11),RD.Obtain)
			else CONVERT(VARCHAR(11),CAST(RD.Obtain AS INT))END)
			+(CASE 
			WHEN RD.IsPresent = 0 THEN ''
			WHEN RD.IsPresent != 0 THEN + ' / ' + CONVERT(VARCHAR(11),Cast(Round(ED.Maximum,0) AS int)) + ' , ' END)
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult)- 1)
    RETURN @lResult 
END
GO
PRINT N'Creating Function [sAccounting].[fNarrationSearchStringGet]...';


GO

CREATE FUNCTION [sAccounting].[fNarrationSearchStringGet](@rSearchString [nvarchar](1000))
RETURNS [nvarchar](1000) WITH EXECUTE AS CALLER
AS 
BEGIN
	SET @rSearchString = sCommon.fReplace(@rSearchString, '*', '%')
	IF SUBSTRING(@rSearchString, 1, 1) <> '%'
	AND SUBSTRING(@rSearchString, LEN(@rSearchString), 1) <> '%'
	AND @rSearchString <> ''
		BEGIN
			SET @rSearchString = @rSearchString + '%'
		END
		
	RETURN @rSearchString
END
GO
PRINT N'Creating Function [sAlert].[fHighestMarkGet]...';


GO



CREATE FUNCTION [sAlert].[fHighestMarkGet](@rExamId bigint, @rSubjectId int, @rDivisionId int, @rClassId int, @rBatchId int )

RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER

AS
BEGIN

DECLARE @lHighestMark NVARCHAR(MAX)

--SELECT @lHighestMark = MAX(
--							   CASE 
--            WHEN @rSubjectId > 0 THEN ''
--            ELSE ISNULL(CS.SubjectCode,'') + ' - '
--        END +
--        CASE  
--            WHEN RD.IsPresent IS NULL THEN '0'
--            WHEN RD.IsPresent = 0 THEN '0'
--            WHEN E.IsMarksInDecimal = 1 THEN CONVERT(NVARCHAR(11), RD.Obtain)
--            WHEN E.IsMarksInDecimal = 0 THEN CONVERT(NVARCHAR(11), CAST(RD.Obtain AS INT))
--        END)
	(SELECT @lHighestMark  = COALESCE(@lHighestMark ,'')
		+ CASE WHEN @rSubjectId > 0 THEN '' ELSE ISNULL(CS.SubjectCode,'') + ' - ' END +
		Convert(varchar(11),ISNULL(MAX(RD.Obtain),0)) + ','

                                 
    FROM sAssessment.tResult R 
    INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
    INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
    INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
    INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
	INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
	INNER JOIN sStudent.tStudentMaster SAM ON  A.StudentId = SAM.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
    WHERE
        E.Id=@rExamId
        AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		AND ((A.DivisionId=@rDivisionId) OR @rDivisionId=0)
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((E.BatchId=@rBatchId) OR @rBatchId=0)
		AND SAM.StatusId = 1
	GROUP BY CS.SubjectCode
	)
    SET @lHighestMark = LEFT(@lHighestMark, LEN(@lHighestMark) - 1)   
    RETURN @lHighestMark;
END;
GO
PRINT N'Creating Function [sFee].[fPaidFeeAmountAcademicIdwiseGet]...';


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


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


GO
CREATE FUNCTION [sFee].[fStudentWiseBusRoute](@rStudentId bigint, @rOrgGroupBatchId int)
RETURNS @BusRouteTable TABLE (
    BusRoute nvarchar(max),
    PickupPoint nvarchar(max)
)
WITH EXECUTE AS CALLER
AS 
BEGIN	 
    INSERT INTO @BusRouteTable (BusRoute, PickupPoint)
    SELECT 
        ISNULL(BRM.Title, '') AS BusRoute,
        ISNULL(BRDM.Title, '') AS PickupPoint
    FROM 
        sTransport.tAssignRoute AR
        INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
        INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.id = BRDM.BusRouteId
        --INNER JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id = AR.DropDestinationId
    WHERE 
        AR.SourceId = @rStudentId AND AR.SourceTypeId = 2003
        AND BRM.OrgGroupBatchId = @rOrgGroupBatchId
   
    RETURN
END
GO
PRINT N'Altering Procedure [sAccounting].[pLedgerMasterGet]...';


GO
ALTER PROCEDURE [sAccounting].[pLedgerMasterGet]

		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rId int = 0,
		--@rAffiliationId int,
		@rTitle nvarchar(100),
		@rCode nvarchar(20),
		@rLedgerGroupId int,
		@rAccountingYearId int,
		@rOrgGroupId int,
		@rAccountId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	Declare @1AccountId int
      
	BEGIN
		select @1AccountId = AccountId from sAccounting.tAccountingYearMaster Where Id = @rAccountingYearId
			
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END

	--change by dhruvik
	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
	 
	  SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		LM.Id,
		LM.Code,
		LM.Title,
		([sAccounting].[fDecimalValueGet] (LM.OpeningBalance, @DecimalCount)) AS OpeningBalance,	--change by dhruvik
		LM.IsObsolete,
		LGM.Id AS LedgerGroupId,
		LTM.Id AS LedgerTypeId,
		LGM.Title AS LedgerGroupTitle,
		LTM.Title AS LedgerTypeTitle,
		AM.ReportOrgTitle As OrgTitle,
		AM.SmallAddress1 AS SmallAddress1,
		AM.SmallAddress2 AS SmallAddress2,
		ISNULL(LM.IsShowInDashBoard,0) AS IsShowInDashBoard  -- Mantisid : 0035149
	      
	  FROM 
		   sAccounting.tLedgerMaster LM
			INNER JOIN sAccounting.tLedgerTypeMaster LTM
			ON LM.LedgerTypeId= LTM.Id
			 INNER JOIN sAccounting.tLedgerGroupMaster LGM
			ON LM.LedgerGroupId= LGM.Id 
			  LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=LGM.AccountId
        
  WHERE  
        ((LM.Id = @rId) OR (@rId = 0))
        AND  ((LM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
        AND  ((LM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
        AND  ((LM.LedgerGroupId = @rLedgerGroupId) OR (@rLedgerGroupId = 0))
        AND ((LM.AccountingYearId =  @rAccountingYearId))
        AND ((LGM.AccountingYearId = @rAccountingYearId))
        And LGM.AccountId = @1AccountId AND LM.OrgGroupId = @rOrgGroupId
        	AND (LGM.AccountId=@rAccountId OR @rAccountId=0) 
        --AND ((LGM.OrgGroupId=@rOrgGroupId))
        
        --Do not Change Order By 
        order by LM.Id asc
		
END
GO
PRINT N'Altering Procedure [sAccounting].[pVoucherListWithBalanceGet]...';


GO

ALTER PROCEDURE [sAccounting].[pVoucherListWithBalanceGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rVoucherTypeId int = 0,
	 @rTransactionDate Date,
	 @rTransactionDateTo Date,
	 @rVoucherNumber int,
	 @rVoucherNumberTo int,
	 @rLedgerId int,
	 @rNarration nvarchar(1000),    --Change by dhananjay 150->1000 size for mantis id - 0035082
	 @rAmount Decimal(20,5),
	 @rAccountingYearId int = 0,
	 @rIsApproved bit=0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN

	  BEGIN
			SET @rNarration = sAccounting.fNarrationSearchStringGet(@rNarration) --added New function by dhananjay for mantis id - 0035082
	  END

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

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

	CREATE TABLE #tempTransaction
	(
		AutoId INT PRIMARY KEY Identity(1,1),
		Builder1 nvarchar(max),
		Builder2 nvarchar(max),
		Id bigint,
		VoucherType nvarchar(100),
		VoucherNo bigint,
		VoucherDate date,
		Ledger nvarchar(100),
		Credit decimal(25,5),
		Debit decimal(25,5),
		Narration nvarchar(1000),  --Change by dhananjay 150->1000 size for mantis id - 0035082
		OrgTitle nvarchar(200),
		SmallAddress1 nvarchar(200),
		SmallAddress2 nvarchar(200),
		TransactionApproveId bigint
	)

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

	--select * from #tempTransaction

--Common Table Expression
	WITH RunningBalance AS (
		SELECT	AutoId,
				Builder1,
				Builder2,
				Id,
				VoucherType,
				VoucherNo,
				VoucherDate,
				Ledger,
				([sAccounting].[fDecimalValueGet] (Credit,@DecimalCount)) AS Credit,
				([sAccounting].[fDecimalValueGet] (Debit,@DecimalCount)) AS Debit,
				Narration,
				OrgTitle,
				SmallAddress1,
				SmallAddress2,
				TransactionApproveId,
				(Debit - Credit) AS net_amount,
				([sAccounting].[fDecimalValueGet] ((SELECT	SUM(Debit - Credit) 
				FROM #tempTransaction AS inner_trans
				WHERE inner_trans.AutoId <= outer_trans.AutoId),@DecimalCount)) AS Balance
		FROM
			#tempTransaction AS outer_trans
	)

	SELECT	Builder1,
			Builder2,
			Id,
			VoucherType,
			VoucherNo,
			VoucherDate,
			Ledger,
			Credit,
			Debit,
			Narration,
			OrgTitle,
			SmallAddress1,
			SmallAddress2,
			TransactionApproveId,
			Balance
	FROM
		RunningBalance

	drop table #tempTransaction
END

--SELECT	'' AS Builder1,
--		'' AS Builder2,
--		CAST(0 AS bigint) AS Id,
--		'' AS VoucherType,
--		CAST(0 AS bigint) AS VoucherNo,
--		CAST('' AS date) AS VoucherDate,
--		'' AS Ledger,
--		0.00 AS Credit,
--		0.00 AS Debit,
--		'' AS Narration,
--		'' AS OrgTitle,
--		'' AS SmallAddress1,
--		'' AS SmallAddress2,
--		CAST(0 AS bigint) AS TransactionApproveId,
--		0.00 AS Balance

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


GO
ALTER PROCEDURE [sAccounting].[pVoucherListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rVoucherTypeId int = 0,
	 @rTransactionDate Date,
	 @rTransactionDateTo Date,
	 @rVoucherNumber int,
	 @rVoucherNumberTo int,
	 @rLedgerId int,
	 @rNarration nvarchar(1000),   --Change by dhananjay 150->1000 size for mantis id - 0035082
	 @rAmount Decimal(20,5),
	 @rAccountingYearId int = 0,
	 @rIsApproved bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	  BEGIN
			SET @rNarration = sAccounting.fNarrationSearchStringGet(@rNarration) --added New function by dhananjay for mantis id - 0035082
	  END

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

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

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


GO
ALTER PROCEDURE [sAccounting].[pLedgerMasterAdd]
	 
	@rId int,
	@rCode nvarchar(100),
	@rTitle nvarchar(100),
	@rLedgerGroupId int,
	@rAccountingYearId int,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOpeningBalance decimal(20,5),
	@rLedgerTypeId int,
	@rIsObsolete bit,
	@rOrgGroupId int,
	@rIsShowInDashBoard bit = 0		-- Mantisid : 0035149
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY 
		IF(@rId = 0)	
	BEGIN
		IF Exists(select 1 from sAccounting.tLedgerMaster where Code=@rCode  AND AccountingYearId = @rAccountingYearId)
			BEGIN
			SELECT -101 AS Result
			RETURN
		END  
		   IF Exists(select 1 from sAccounting.tLedgerMaster where   Title = @rTitle AND AccountingYearId = @rAccountingYearId)
			BEGIN
			SELECT -102 AS Result
			RETURN
		END  
	END
	ELSE
	BEGIN
 
	   IF Exists(select 1 from sAccounting.tLedgerMaster where Code=@rCode  AND AccountingYearId = @rAccountingYearId AND ID <> @rId)
			BEGIN
			SELECT -101 AS Result
			RETURN
		END  
		   IF Exists(select 1 from sAccounting.tLedgerMaster where   Title = @rTitle AND AccountingYearId = @rAccountingYearId AND ID <> @rId)
			BEGIN
			SELECT -102 AS Result
			RETURN
		END  

	END 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
 BEGIN 
	DECLARE @lNextNumber INT
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tLedgerMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tLedgerMaster',@lNextNumber = @lNextNumber output

	INSERT INTO sAccounting.tLedgerMaster
		(
			Id,
			Code,
			Title,
			LedgerGroupId,
			AccountingYearId,
			CreatedUserId,
			CreatedDateTime,
			OpeningBalance,
			LedgerTypeId,
		    IsObsolete,
		    OrgGroupId,
			IsShowInDashBoard			-- Mantisid : 0035149
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rLedgerGroupId,
			@rAccountingYearId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOpeningBalance,
			@rLedgerTypeId,
			@rIsObsolete,
			@rOrgGroupId,
			@rIsShowInDashBoard			
		)
		 SELECT 1 AS RESULT            
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sAccounting.tLedgerMaster
	    SET
	      Code=@rCode,
	      Title=@rTitle,
	      LedgerGroupId=@rLedgerGroupId,	    
	      IsObsolete=@rIsObsolete,
	      UpdatedUserId=@rUpdatedUserId,
	      UpdatedDateTime= sCommon.fGetDate(),
	      OpeningBalance=@rOpeningBalance,
	      LedgerTypeId=@rLedgerTypeId,
		  IsShowInDashBoard = @rIsShowInDashBoard -- Mantisid : 0035149
	      WHERE Id = @rId 	AND AccountingYearId = @rAccountingYearId   
	 END  
		SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAccounting].[pValidateTransactionBulk]...';


GO

 
ALTER PROC [sAccounting].[pValidateTransactionBulk]
		@rXmlDoc nvarchar(MAX)
		,@rResult nvarchar(max)='' OUT

			
AS
SET NOCOUNT ON

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

DECLARE @lCount int = 0, @lValidationMsg nvarchar(max) = '' 
DECLARE @lOrgGroupId bigint = 0,
		@lAccountingYearId int = 0,
		@lVoucherDate date = '',
		@lNarration nvarchar(1000) = '',   --Change by dhananjay 150->1000 size for mantis id - 0035082
		@lVoucherNumber bigint = 0,
		@lVoucherType nvarchar(50) = '',
		@lVoucherTypeId tinyint = 0,		 
		@lCreatedUserId bigint = 0,
		@lCreatedDateTime datetime = '',
		@lAccountId int = 0,
		@lChequeNo nvarchar(20) = '',		
		@lChequeDate date = '',
		@lTransactionApproveId bigint = NULL,
		@lCreditAmount decimal(12,2) = 0,
		@lDebitAmount decimal(12,2) = 0,
		@lToLedger nvarchar(50) = '',
		@lByLedger nvarchar(50) = '',
		@lToLedgerId bigint = 0,
		@lByLedgerId bigint = 0

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


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

	--SELECT * FROM #tTable

	EXEC sp_xml_removedocument @intDoc

DECLARE @lTotal int = 0
DECLARE @lValidationMsgAll nvarchar(max) = ''
SELECT @lTotal = COUNT(Id) FROM #tTable
SELECT @lCount = 1
WHILE @lCount <= @lTotal 
BEGIN
	
	SELECT
	@lOrgGroupId = OrgGroupId,
	@lAccountingYearId = AccountingYearId,
	@lVoucherDate = VoucherDate,
	@lNarration = Narration,
	@lVoucherNumber = VoucherNumber,
	@lVoucherType = VoucherType,	 
	@lCreatedUserId = CreatedUserId,		
	@lChequeNo = ChequeNo,	
	@lChequeDate = ChequeDate,
	@lCreditAmount = CreditAmount,
	@lDebitAmount = DebitAmount,
	@lToLedger = ToLedger,
	@lByLedger = ByLedger,
	@lAccountId = AccountId	
	FROM #tTable WHERE Id = @lCount

	SET @lVoucherTypeId = '' SET @lToLedgerId = '' SET @lByLedgerId = ''
	SELECT @lVoucherTypeId = Id FROM sAccounting.tVoucherTypeMaster WHERE Title = @lVoucherType
	SELECT @lToLedgerId = Id FROM sAccounting.tLedgerMaster WHERE Title = @lToLedger
	SELECT @lByLedgerId = Id FROM sAccounting.tLedgerMaster WHERE Title = @lByLedger

	--print(@lVoucherType)
	--print(@lToLedger)
	--print(@lByLedger)
	--print(@lVoucherType)
	--print(@lOrgGroupId)
	--print(@lVoucherNumber)
	--print(@lByLedgerId)
	print(@lVoucherTypeId)
	print(@lToLedgerId)
	
	SET @lValidationMsg = ''
	IF(@lVoucherTypeId = '' OR LEN(@lVoucherTypeId) = 0 OR @lVoucherTypeId is null)
	BEGIN
		SET @lValidationMsg = 'Voucher Type does not Exist,'
	END	

	IF(@lToLedgerId = '' OR LEN(@lToLedgerId) = 0 OR @lVoucherTypeId is null)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + 'To Ledger does not Exist,'
	END

	IF(@lByLedgerId = '' OR LEN(@lByLedgerId) = 0 OR @lByLedgerId is null)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + 'By Ledger does not Exist,'
	END

	IF (@lOrgGroupId  = '' OR LEN(@lOrgGroupId) = 0 OR @lOrgGroupId is null)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + 'OrgGroupId cannot be empty,'
	END	

	IF (@lCreatedUserId = '' OR LEN(@lCreatedUserId) = 0 OR @lCreatedUserId is null)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + ' CreatedUserId cannot be empty,'
	END	

	IF (@lAccountingYearId  = '' OR LEN(@lAccountingYearId) = 0 OR @lAccountingYearId is null)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + ' AccountingYearId cannot be empty,'
	END	

	IF (@lVoucherDate  = '' OR LEN(@lVoucherDate) = 0 OR @lVoucherDate is null)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + ' VoucherDate cannot be empty,'
	END		

	IF EXISTS(Select 1 FROM sAccounting.tTransaction T INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id = T.VoucherTypeId WHERE T.AccountingYearId = @lAccountingYearId AND T.VoucherNumber = @lVoucherNumber AND T.OrgGroupId = @lOrgGroupId AND VTM.Title = @lVoucherType)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + ' Voucher Number Exists,'
	END	

	IF (@lCreditAmount <> @lDebitAmount)
	BEGIN
		SET @lValidationMsg = @lValidationMsg + ' Credit and Debit Amount do not match,'
	END

	IF(@lVoucherTypeId = 2)
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE LedgerGroupId IN (@lOrgGroupId*100000 + 2,@lOrgGroupId*100000 + 3) AND AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lToLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' To Ledger does match Voucher Type'
		END

		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE LedgerGroupId NOT IN (@lOrgGroupId*100000 + 2,@lOrgGroupId*100000 + 3) AND AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lByLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' By Ledger does match Voucher Type'
		END
	END	
	IF(@lVoucherTypeId = 3)
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE LedgerGroupId IN (@lOrgGroupId*100000 + 2,@lOrgGroupId*100000 + 3) AND AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lToLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' To Ledger does match Voucher Type'
		END

		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE LedgerGroupId NOT IN (@lOrgGroupId*100000 + 2,@lOrgGroupId*100000 + 3) AND AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lByLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' By Ledger does match Voucher Type'
		END
	END
	IF(@lVoucherTypeId = 4)
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lToLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' To Ledger does match Voucher Type'			
		END
		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lByLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' By Ledger does match Voucher Type'				
		END
	END			
	IF(@lVoucherTypeId = 1)
	BEGIN
		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE LedgerGroupId IN (@lOrgGroupId*100000 + 2,@lOrgGroupId*100000 + 3) AND AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lToLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' To Ledger does match Voucher Type'
		END

		IF NOT EXISTS(SELECT 1 FROM sAccounting.vLedgerMaster WHERE LedgerGroupId IN (@lOrgGroupId*100000 + 2,@lOrgGroupId*100000 + 3) AND AccountingYearId = @lAccountingYearId AND AccountId = @lAccountId AND Title = @lByLedger)
		BEGIN
			SET @lValidationMsg = @lValidationMsg + ' By Ledger does match Voucher Type'
		END
	END
		

	SET @lCount = @lCount + 1		
				
	SELECT @lValidationMsg AS ValidationMsg
	SET @rResult = @lValidationMsg

END

--COMMIT TRANSACTION

	--END TRY
	--BEGIN CATCH
	--ROLLBACK TRANSACTION
	--SELECT -1
	--END CATCH

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


GO

ALTER PROCEDURE [sAccounting].[pVoucherApproveListGet]

	 @rVoucherTypeId int = 0,
	 @rTransactionDate Date,
	 @rTransactionDateTo Date,
	 @rVoucherNumber int,
	 @rVoucherNumberTo int,
	 @rLedgerId int,
	 @rNarration nvarchar(1000), --Change by dhananjay 150->1000 size for mantis id - 0035082
	 @rAmount int,
	 @rAccountingYearId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	  BEGIN
			SET @rNarration = sAccounting.fNarrationSearchStringGet(@rNarration)--Add New Function by dhananjay 150->1000 size for mantis id - 0035082
	  END
	 
  SELECT  
		  T.Id
		  ,VTM.Title AS VoucherType
		  ,T.VoucherNumber AS VoucherNo
		  ,T.TransactionDate AS VoucherDate
		  ,LM.Title AS Ledger
		  ,CASE WHEN ISNULL(TD.Amount,0) < 0 THEN ISNULL(TD.Amount,0) * -1 ELSE 0 END AS Credit
		  ,CASE WHEN ISNULL(TD.Amount,0) > 0 THEN ISNULL(TD.Amount,0) ELSE 0 END AS Debit
		  ,T.Narration AS Narration
		  ,AM.ReportOrgTitle As OrgTitle
		  ,AM.SmallAddress1 AS SmallAddress1
		  ,AM.SmallAddress2 AS SmallAddress2
		 
		
  FROM 
          sAccounting.tTransactionApprove T
          INNER JOIN sAccounting.tTransactionApproveDetail TD ON T.Id=TD.TransactionId
          INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id = T.VoucherTypeId
          INNER JOIN sAccounting.tLedgerMaster LM ON LM.Id=TD.LedgerId 
          INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
         
        
         WHERE 
		  (T.VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId = 0) 
			AND ((T.Narration like @rNarration) OR (ISNULL(@rNarration,'') = '')) 		
			AND (T.TransactionDate >= @rTransactionDate OR ISNULL(@rTransactionDate,'') = '') 
			And (T.TransactionDate <= @rTransactionDateTo OR ISNULL(@rTransactionDateTo,'') = '')
			AND (T.VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0) 
			AND (T.VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0)
			AND (TD.LedgerId = @rLedgerId OR @rLedgerId=0)
			AND (TD.Amount = @rAmount OR ISNULL(@rAmount,0) = 0)
			AND LM.AccountingYearId = @rAccountingYearId
			AND T.AccountingYearId = @rAccountingYearId
			AND  NOT EXISTS( SELECT 1 FROM sAccounting.tTransaction TA Where TA.TransactionApproveId=T.Id AND  TA.AccountingYearId = @rAccountingYearId )
			
            Order By T.VoucherTypeId,T.TransactionDate,T.VoucherNumber,Credit,Debit
END
GO
PRINT N'Altering Procedure [sFee].[pFeePostingGet]...';


GO
ALTER PROCEDURE [sFee].[pFeePostingGet]
				
	--@rClassId int,
    @rReceiptBookId int,
	@rBatchId int,
	@rOrgGroupId int,
	@rReceiptDate date,
	@rReceiptDateTo date,
	@rChequePosting nvarchar(50),
	@rPayTypeId int = 0 -- mantisid -- 0034607
           
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	IF @rChequePosting = 'Single'
	BEGIN
			SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					SUM(RD.Amount) AS ReceiptAmount,
					R.ChequeNo AS ChequeNo, R.ChequeDate AS ChequeDate, R.BankName AS BankName, R.ChequeClearDate AS ChequeClearDate,R.PayTypeId AS PayTypeId	, 
					ISNULL(AYM.ISLocked,0) AS ISLocked,
					R.ReceiptNumber,
					ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId  -- Added for mantis 0035150 by Foram
			FROM 
					sFee.tAccountMapping AM
					INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
					INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
						AND R.PayTypeId = AM.PayTypeId
						AND R.ReceiptDate >= @rReceiptDate 
						AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
						AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
					INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
					--AND (FS.ClassId=@rClassId) 
						AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0) -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
						AND (R.OrgGroupBatchId=@rBatchId)
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId			
					GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ReceiptNumber	
					,R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,R.PayTypeId,R.ReceiptBookId -- Add for kenya client for check details
	 END
	 ELSE
		BEGIN		
		
			
		DECLARE @lConfigValue nvarchar(50)
		DECLARE @lIsAccountPostingBankNameWise bit=0

		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 244 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

		IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
		SET @lIsAccountPostingBankNameWise = 0
		ELSE
		SET @lIsAccountPostingBankNameWise = 1	
		
		IF @lIsAccountPostingBankNameWise = 1	
			BEGIN
				  SELECT  
						R.ReceiptDate,
						AMast.Title AS AccountName,
						AYM.Title AS AccountingYearName,
						AM.CreditLedgerId,
						CLM.Title AS CreditLedgerName,
						AM.DebitLedgerId,
						DLM.Title AS DebitLedgerName,
						SUM(RD.Amount) AS ReceiptAmount,
						'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,'' AS ChequeClearDate,0 AS PayTypeId	,
						ISNULL(AYM.ISLocked,0) AS ISLocked,
						0 as ReceiptNumber,
						ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId	 -- Added for mantis 0035150 by Foram
					FROM 
						sFee.tAccountMapping AM
						INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
						INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
							AND R.PayTypeId = AM.PayTypeId
							AND R.ReceiptDate >= @rReceiptDate 
							AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
							AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
						INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
						--AND (FS.ClassId=@rClassId) 
							AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0) -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
							AND (R.OrgGroupBatchId=@rBatchId)
						INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
						INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
						INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
						INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
					WHERE 
						AMast.OrgGroupId=@rOrgGroupId AND R.PayTypeId = 1
					GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ReceiptBookId
						
					UNION ALL
					
					SELECT  
						R.ReceiptDate,
						AMast.Title AS AccountName,
						AYM.Title AS AccountingYearName,
						AM.CreditLedgerId,
						CLM.Title AS CreditLedgerName,
						R.DepositedLedgerId AS DebitLedgerId, 
						DLM.Title AS DebitLedgerName,
						Sum(RD.Amount) AS ReceiptAmount,
						R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,2 AS PayTypeId,
						ISNULL(AYM.ISLocked,0) AS ISLocked,			
						R.ReceiptNumber,
						ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId -- Added for mantis 0035150 by Foram
					FROM 
						sFee.tAccountMapping AM
						INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
						INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
							AND R.PayTypeId = AM.PayTypeId
							AND R.ReceiptDate >= @rReceiptDate 
							AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
							AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
						INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
							AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0)  -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
							AND (R.OrgGroupBatchId=@rBatchId)
						INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
						INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
						INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
						INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=R.DepositedLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
					WHERE  R.PayTypeId <> 1 AND	 AMast.OrgGroupId=@rOrgGroupId			
					Group By R.ReceiptDate,AMast.Title,AYM.Title,AM.CreditLedgerId,
						CLM.Title,R.DepositedLedgerId,DLM.Title,
						R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,AYM.IsLocked,R.ReceiptNumber,R.ReceiptBookId
				END
		ELSE
		BEGIN				
				SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					SUM(RD.Amount) AS ReceiptAmount,
					'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,'' AS ChequeClearDate,0 AS PayTypeId	,
					ISNULL(AYM.ISLocked,0) AS ISLocked,
					0 as ReceiptNumber,
					ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId -- Added for mantis 0035150 by Foram
				FROM  
					sFee.tAccountMapping AM
					INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
					INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
						AND R.PayTypeId = AM.PayTypeId
						AND R.ReceiptDate >= @rReceiptDate 
						AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
						AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
					INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
					--AND (FS.ClassId=@rClassId) 
						AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0)  -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
						AND (R.OrgGroupBatchId=@rBatchId)
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId AND R.PayTypeId = 1
				GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ReceiptBookId
					
				UNION ALL
				
				SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					Sum(RD.Amount) AS ReceiptAmount,
					R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,2 AS PayTypeId,
					ISNULL(AYM.ISLocked,0) AS ISLocked,
					R.ReceiptNumber,
					ISNULL(R.ReceiptBookId, 0) AS ReceiptBookId -- Added for mantis 0035150 by Foram
				FROM 
					sFee.tAccountMapping AM
					INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
					INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
						AND R.PayTypeId = AM.PayTypeId
						AND R.ReceiptDate >= @rReceiptDate 
						AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
						AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0)) -- mantisid -- 0034607
					INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
						AND (FS.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId = 0)  -- Added OR @rReceiptBookId = 0 for mantis 0035150 by Foram
						AND (R.OrgGroupBatchId=@rBatchId)
					INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
					INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
					INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
					INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
				WHERE  R.PayTypeId <> 1 AND	 AMast.OrgGroupId=@rOrgGroupId			
				Group By R.ReceiptDate,AMast.Title,AYM.Title,AM.CreditLedgerId,
					CLM.Title,AM.DebitLedgerId,DLM.Title,
					R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,AYM.IsLocked,R.ReceiptNumber,R.ReceiptBookId
			END
		END
END
GO
PRINT N'Altering Procedure [sFee].[pChargePostingAdd]...';


GO
ALTER PROCEDURE [sFee].[pChargePostingAdd]
	 
	        @rAccount nvarchar(100),
	        @rAccountingYear nvarchar(100),
	        @rOrgGroupId int,
            @rTransactionDate date,
            @rNarration nvarchar(1000),  --Change by dhannajay from 150->1000 size for mantis id - 0035082
            @rVoucherTypeId tinyint,
            @rIsProfitAndLoss int,
            @rRepeatLedger int,
            @rCreatedUserId bigint,
            @rCreditLedgerId int,
            @rDebitLedgerId int,
            @rReceiptBookId int,
            @rChequeNo nvarchar(10),
			@rBankName nvarchar(50),
			@rChequeDate datetime,
			@rPayTypeId int,
			@rSourceTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
		
		
	DECLARE @lNextNumber BIGINT
	DECLARE @lNextNumberPosting INT
	DECLARE @1AccountId int 
	DECLARE @1AccountYearId int 
	DECLARE @lVoucherNumber bigint
	
    SELECT @1AccountId = AYM.AccountId, @1AccountYearId = AYM.Id FROM sAccounting.tAccountingYearMaster AYM 
    INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
    WHERE AM.Title= sSetup.fPortalXMLTagsReplaceReverse(@rAccount) AND AYM.Title = @rAccountingYear
    
    SELECT @lVoucherNumber = ISNULL(Max(T.VoucherNumber),0) + 1 FROM sAccounting.tTransaction T
	WHERE VoucherTypeId=@rVoucherTypeId AND AccountingYearId = @1AccountYearId
    
    IF NOT EXISTS (SELECT 1 FROM sFee.tChargeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId 
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId AND SourceTypeId=@rSourceTypeId)
    BEGIN
		 
		SELECT @lNextNumberPosting = ISNULL(MAX(Id),0) + 1 FROM sFee.tChargeAccountPosting
		INSERT INTO sFee.tChargeAccountPosting
		(
			Id,
			AccountYearId,
			AccountId,
			TransactionDate,
			VoucherTypeId,
			CreditLedger,
			DebitLedger,
			ReceiptBookId,
			SourceTypeId
		)
		VALUES
		(
			@lNextNumberPosting,
			@1AccountYearId,
			@1AccountId,
			@rTransactionDate,
			@rVoucherTypeId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rReceiptBookId,
			@rSourceTypeId
		)
    END
	
	SELECT @lNextNumberPosting = Id FROM sFee.tChargeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId AND SourceTypeId=@rSourceTypeId
  
 
	IF EXISTS (SELECT 1 FROM [sAccounting].[tTransaction] WHERE SOURCEID=@lNextNumberPosting and Narration like '%Charge Receipt%')
	BEGIN
		delete from [sAccounting].[tTransactionDetail] Where TransactionId in (Select Id From sAccounting.tTransaction Where SourceId =@lNextNumberPosting AND SourceTypeId=2 )
		Select Id as result From sAccounting.tTransaction Where SourceId =@lNextNumberPosting AND SourceTypeId=2
		COMMIT TRANSACTION				
		RETURN 
		--SELECT 101 AS Result
		--COMMIT TRANSACTION				
		--RETURN 
	END
    
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output		
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id],
			    [OrgGroupId],
			    [AccountingYearId],
			    [TransactionDate],
			    [Narration],
			    [VoucherNumber],
			    [VoucherTypeId],
			    [IsProfitAndLoss],
			    [RepeatLedger],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [AccountId],
			    [SourceTypeId],
			    [SourceId],
			    [ChequeNo],
			    [BankName],
			    [ChequeDate],
			    [ChequeClearDate],
			    [PayTypeId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rOrgGroupId,
			    @1AccountYearId,
			    @rTransactionDate,
			    @rNarration,
			    @lVoucherNumber,
			    @rVoucherTypeId,
			    @rIsProfitAndLoss,
			    @rRepeatLedger,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @1AccountId,
			    2,
			    @lNextNumberPosting,
			    @rChequeNo,
			    @rBankName,
			    @rChequeDate,
			    '',
			    @rPayTypeId
			   )
		    SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sFee].[pDepositePostingAdd]...';


GO


ALTER PROCEDURE [sFee].[pDepositePostingAdd]
	 
	        @rAccount nvarchar(100),
	        @rAccountingYear nvarchar(100),
	        @rOrgGroupId int,
            
            @rNarration nvarchar(1000), --Change by dhananjay 150->1000 size for mantis id - 0035082
            @rTransactionDate date,
            @rVoucherTypeId tinyint,
            @rIsProfitAndLoss int,
            @rRepeatLedger int,
            @rCreatedUserId bigint,
            @rCreditLedgerId int,
            @rDebitLedgerId int,
            @rDepositeHeadId int ,
            
			@rPayTypeId int,
			@rSourceId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
		
		
	DECLARE @lNextNumber BIGINT
	DECLARE @lNextNumberPosting INT
	DECLARE @1AccountId int 
	DECLARE @1AccountYearId int 
	DECLARE @lVoucherNumber bigint
	
    SELECT @1AccountId = AYM.AccountId, @1AccountYearId = AYM.Id FROM sAccounting.tAccountingYearMaster AYM 
    INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
    WHERE AM.Title= sSetup.fPortalXMLTagsReplaceReverse(@rAccount) AND AYM.Title = @rAccountingYear
    
    SELECT @lVoucherNumber = ISNULL(Max(T.VoucherNumber),0) + 1 FROM sAccounting.tTransaction T
	WHERE VoucherTypeId=@rVoucherTypeId AND AccountingYearId = @1AccountYearId
    
    IF NOT EXISTS (SELECT 1 FROM sFee.tDepositeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate= @rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId 
    AND DebitLedger = @rDebitLedgerId AND DepositeHeadId=@rDepositeHeadId)
    BEGIN
		SELECT @lNextNumberPosting = ISNULL(MAX(Id),0) + 1 FROM sFee.tDepositeAccountPosting
		INSERT INTO sFee.tDepositeAccountPosting
		(
			Id,
			AccountYearId,
			AccountId,
			TransactionDate,
			VoucherTypeId,
			CreditLedger,
			DebitLedger,
			DepositeHeadId
		)
		VALUES
		(
			@lNextNumberPosting,
			@1AccountYearId,
			@1AccountId,
			 sCommon.fGetDate(),
			@rVoucherTypeId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rDepositeHeadId
		)
    END
	
	SELECT @lNextNumberPosting = Id FROM sFee.tDepositeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=  @rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId
    AND DebitLedger = @rDebitLedgerId AND DepositeHeadId=@rDepositeHeadId
  
	IF EXISTS (SELECT 1 FROM [sAccounting].[tTransaction] WHERE SOURCEID=@lNextNumberPosting and Narration='Deposite Receipt' AND SourceTypeId=3)
	BEGIN
		--SELECT 101 AS Result
		--COMMIT TRANSACTION				
		--RETURN 
		Delete from [sAccounting].[tTransactionDetail] Where TransactionId in (Select Id From sAccounting.tTransaction Where SourceId =@lNextNumberPosting AND SourceTypeId=3 )
		Select Id as result From sAccounting.tTransaction Where SourceId =@lNextNumberPosting
		COMMIT TRANSACTION				
		RETURN 
	END
    
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id],
			    [OrgGroupId],
			    [AccountingYearId],
			    [TransactionDate],
			    [Narration],
			    [VoucherNumber],
			    [VoucherTypeId],
			    [IsProfitAndLoss],
			    [RepeatLedger],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [AccountId],
			    [SourceTypeId],
			    [SourceId],
			    [ChequeNo],
			    [BankName],
			    [ChequeDate],
			    [ChequeClearDate],
			    [PayTypeId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rOrgGroupId,
			    @1AccountYearId,
			    @rTransactionDate,
			    @rNarration,
			    @lVoucherNumber,
			    @rVoucherTypeId,
			    @rIsProfitAndLoss,
			    @rRepeatLedger,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @1AccountId,
			    3,
			    @rSourceId,
			    '',
			    '',
			    '',
			    '',
			    @rPayTypeId
			   )
		    SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sFee].[pFeePostingAdd]...';


GO

            ALTER PROCEDURE [sFee].[pFeePostingAdd]
	 
	        @rAccount nvarchar(100),
	        @rAccountingYear nvarchar(100),
	        @rOrgGroupId int,
            @rTransactionDate date,
            @rNarration nvarchar(1000),  --Change by dhananjay 150->1000 size for mantis id - 0035082
            @rVoucherTypeId tinyint,
            @rIsProfitAndLoss int,
            @rRepeatLedger int,
            @rCreatedUserId bigint,
            @rCreditLedgerId int,
            @rDebitLedgerId int,
            @rReceiptBookId int,
            @rChequeNo nvarchar(10),
			@rBankName nvarchar(50),
			@rChequeDate datetime,
			@rChequeClearDate datetime=NULL,
			@rPayTypeId int,
			@rSourceTypeId smallint = 0,
			@rSourceId bigint = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
		
		
	DECLARE @lNextNumber BIGINT
	DECLARE @lNextNumberPosting INT
	DECLARE @1AccountId int 
	DECLARE @1AccountYearId int 
	DECLARE @lVoucherNumber bigint
	
    SELECT @1AccountId = AYM.AccountId, @1AccountYearId = AYM.Id FROM sAccounting.tAccountingYearMaster AYM 
    INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
    WHERE AM.Title= sSetup.fPortalXMLTagsReplaceReverse(@rAccount) AND AYM.Title = @rAccountingYear
    
    SELECT @lVoucherNumber = ISNULL(Max(T.VoucherNumber),0) + 1 FROM sAccounting.tTransaction T
	WHERE VoucherTypeId=@rVoucherTypeId AND AccountingYearId = @1AccountYearId
    
    IF NOT EXISTS (SELECT 1 FROM sFee.taccountposting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId 
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId And ChequeNo=@rChequeNo AND BankName=@rBankName AND ChequeDate=@rChequeDate
    AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId
    )
    BEGIN
		SELECT @lNextNumberPosting = ISNULL(MAX(Id),0) + 1 FROM sFee.tAccountPosting
		INSERT INTO [sFee].[tAccountPosting]
		(
			Id,
			AccountId,
			AccountYearId,
			TransactionDate,
			VoucherTypeId,
			CreditLedger,
			DebitLedger,
			ReceiptBookId,
			ChequeNo,
			BankName,
			ChequeDate,
			SourceTypeId,
			SourceId
		)
		VALUES
		(
			@lNextNumberPosting,
			@1AccountId,
			@1AccountYearId,
			@rTransactionDate,
			@rVoucherTypeId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rReceiptBookId,
			@rChequeNo,
			@rBankName,
			@rChequeDate,
			@rSourceTypeId,
			@rSourceId
		)
    END
	
	SELECT @lNextNumberPosting = Id FROM sFee.taccountposting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId
	
	IF EXISTS (SELECT 1 FROM [sAccounting].[tTransaction] WHERE SOURCEID=@lNextNumberPosting)
	BEGIN
		Delete from [sAccounting].[tTransactionDetail] Where TransactionId in (Select Id From sAccounting.tTransaction Where SourceId =@lNextNumberPosting AND SourceTypeId=1)
		Select Id as result From sAccounting.tTransaction Where SourceId =@lNextNumberPosting
		COMMIT TRANSACTION				
		RETURN 
	END
    
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output   
	
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id],
			    [OrgGroupId],
			    [AccountingYearId],
			    [TransactionDate],
			    [Narration],
			    [VoucherNumber],
			    [VoucherTypeId],
			    [IsProfitAndLoss],
			    [RepeatLedger],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [AccountId],
			    [SourceTypeId],
			    [SourceId],
			    [ChequeNo],
			    [BankName],
			    [ChequeDate],
			    [ChequeClearDate],
			    [PayTypeId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rOrgGroupId,
			    @1AccountYearId,
			    @rTransactionDate,
			    @rNarration,
			    @lVoucherNumber,
			    @rVoucherTypeId,
			    @rIsProfitAndLoss,
			    @rRepeatLedger,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @1AccountId,
			    1,
			    @lNextNumberPosting,
			    @rChequeNo,
			    @rBankName,
			    @rChequeDate,
			    @rChequeClearDate,
			    @rPayTypeId
			   )
		    SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAccounting].[pTransactionAdd]...';


GO


ALTER PROCEDURE [sAccounting].[pTransactionAdd]
	 
	        @rId bigint
	       ,@rOrgGroupId int
           ,@rAccountingYearId int
           ,@rTransactionDate date
           ,@rNarration nvarchar(1000)           --Change by dhananjay 150->1000 size for mantis id - 0035082
           ,@rVoucherNumber bigint
           ,@rVoucherTypeId tinyint
           ,@rIsProfitAndLoss int
           ,@rRepeatLedger int
           ,@rCreatedUserId bigint
           ,@rChequeNo nvarchar(10)
           ,@rBankName nvarchar(100)
           ,@rChequeDate datetime
           ,@rTransactionApproveId bigint=null
		   ,@rResult bigint=0 OUT 
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT
	DECLARE @1AccountId int 
	
	IF (@rId = 0)  AND  EXISTS (Select 1 FROM sAccounting.tTransaction where AccountingYearId = @rAccountingYearId AND VoucherNumber = @rVoucherNumber AND VoucherTypeId = @rVoucherTypeId AND OrgGroupId = @rOrgGroupId)
	  BEGIN
	        SELECT -111 AS Result
	  END
  
    ELSE IF(@rId = 0)	
	BEGIN
		
    Select @1AccountId = AccountId from sAccounting.tAccountingYearMaster where Id = @rAccountingYearId 
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output
	--EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sAccounting.tTransaction',@lNextNumber = @lNextNumber output
	
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id]
			   ,OrgGroupId
			   ,[AccountingYearId]
			   ,[TransactionDate]
			   ,[Narration]
			   ,[VoucherNumber]
			   ,[VoucherTypeId]
			   ,[IsProfitAndLoss]
			   ,[RepeatLedger]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,AccountId
			   ,[ChequeNo]
			   ,[BankName]
			   ,[ChequeDate]
			   ,TransactionApproveId
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rOrgGroupId
			   ,@rAccountingYearId
			   ,@rTransactionDate
			   ,@rNarration
			   ,@rVoucherNumber
			   ,@rVoucherTypeId
			   ,@rIsProfitAndLoss
			   ,@rRepeatLedger
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@1AccountId
			   ,@rChequeNo
			   ,@rBankName
			   ,@rChequeDate
			   ,@rTransactionApproveId
			   )
		    SELECT @lNextNumber AS Result
	SET @rResult = @lNextNumber
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sAccounting].[tTransaction]
	    SET
			 
	          AccountingYearId=@rAccountingYearId
	         ,TransactionDate = @rTransactionDate 
             ,Narration = @rNarration
             ,VoucherNumber=@rVoucherNumber
             ,VoucherTypeId=@rVoucherTypeId
             ,IsProfitAndLoss=@rIsProfitAndLoss
             ,RepeatLedger=@rRepeatLedger
             ,UpdatedUserId=@rCreatedUserId
             ,UpdatedDateTime= sCommon.fGetDate() 
             ,ChequeNo = @rChequeNo
             ,ChequeDate = @rChequeDate
             ,BankName = @rBankName         
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
		  SET @rResult = @lNextNumber
	
		--COMMIT TRANSACTION
	 END  	

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


GO

ALTER PROCEDURE [sAccounting].[pTransactionApproveAdd]
	 
	        @rId bigint
	       ,@rOrgGroupId int
           ,@rAccountingYearId int
           ,@rTransactionDate date
           ,@rNarration nvarchar(1000) --Change by dhananjay 150->1000 size for mantis id - 0035082          
           ,@rVoucherNumber bigint
           ,@rVoucherTypeId tinyint
           ,@rIsProfitAndLoss int
           ,@rRepeatLedger int
           ,@rCreatedUserId bigint
           ,@rChequeNo nvarchar(10)
           ,@rBankName nvarchar(100)
           ,@rChequeDate datetime
           
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT
	DECLARE @1AccountId int 
	
	IF (@rId = 0)  AND  EXISTS (Select 1 FROM sAccounting.tTransactionApprove where AccountingYearId = @rAccountingYearId AND VoucherNumber = @rVoucherNumber AND VoucherTypeId = @rVoucherTypeId AND OrgGroupId = @rOrgGroupId)
	  BEGIN
	        SELECT -111 AS Result
	  END
  
    ELSE IF(@rId = 0)	
	BEGIN
		
    Select @1AccountId = AccountId from sAccounting.tAccountingYearMaster where Id = @rAccountingYearId 
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransactionApprove', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAccounting.tTransactionApprove
			   (
			    [Id]
			   ,OrgGroupId
			   ,[AccountingYearId]
			   ,[TransactionDate]
			   ,[Narration]
			   ,[VoucherNumber]
			   ,[VoucherTypeId]
			   ,[IsProfitAndLoss]
			   ,[RepeatLedger]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,AccountId
			   ,[ChequeNo]
			   ,[BankName]
			   ,[ChequeDate]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rOrgGroupId
			   ,@rAccountingYearId
			   ,@rTransactionDate
			   ,@rNarration
			   ,@rVoucherNumber
			   ,@rVoucherTypeId
			   ,@rIsProfitAndLoss
			   ,@rRepeatLedger
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@1AccountId
			   ,@rChequeNo
			   ,@rBankName
			   ,@rChequeDate
			   )
		    SELECT @lNextNumber AS Result
	
	 
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAccounting.tTransactionApprove
	    SET
			 
	          AccountingYearId=@rAccountingYearId
	         ,TransactionDate = @rTransactionDate 
             ,Narration = @rNarration
             ,VoucherNumber=@rVoucherNumber
             ,VoucherTypeId=@rVoucherTypeId
             ,IsProfitAndLoss=@rIsProfitAndLoss
             ,RepeatLedger=@rRepeatLedger
             ,UpdatedUserId=@rCreatedUserId
             ,UpdatedDateTime= sCommon.fGetDate() 
             ,ChequeNo = @rChequeNo
             ,ChequeDate = @rChequeDate
             ,BankName = @rBankName         
             
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	
		
	 END  	

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


GO
 
ALTER PROCEDURE [sFee].[pDepositAddAdd]
	 
	@rId bigint,
	@rDepositHeadId int,
	--@rStudentId bigint,
	@rAmount decimal(12,2),
	@rDepositDate date,
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(20),
	@rBankName nvarchar(200),
	@rRemark nvarchar(200),
	@rCreatedUserId bigint,
	--@rBatchId int,
	@rOrgGroupId smallint,
	@rAcademicId bigint,
	@rNumber int=0,
	@rOrgGroupBatchId int,
	@rReferenceSourceTypeId smallInt = 0,		-- Mantis Id : 0034851	
	@rReferenceSourceId BigInt = 0				-- Mantis Id : 0034851	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lStudentId bigint
DECLARE @lClassId int

BEGIN	
--BEGIN TRY
--BEGIN TRANSACTION	

    SELECT @lStudentId= StudentId From sStudent.vStudentAcademic  Where AcademicId=@rAcademicId 
-- SELECT @lClassId= ClassId From sStudent.vStudentAcademic Where AcademicId=@rStudentId AND OrgGroupBatchId=@rOrgGroupBatchId

	-- AMOUNT VALIDATION
	--If EXISTS
	--(SELECT DB.BalanceAmount FROM sFee.tDepositBalance DB WHERE DB.DepositHeadId = @rDepositHeadId AND DB.ClassId=@lClassId AND BalanceAmount 
	-- < (SELECT  ISNULL(SUM(DA.Amount),0) + @rAmount AS TotalAmount FROM sFee.tDepositAdd DA 
	--	WHERE DepositHeadId = @rDepositHeadId AND StudentId=@lStudentId AND Id <> @rId)) 				
	--BEGIN
	--	SELECT -102 as Result
	--	RETURN
	--END 
	DECLARE @lConfigValue nvarchar(50)

	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 215 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	IF(@lConfigValue='True')
	BEGIN
	 IF EXISTS(SELECT 1 From sStudent.vStudentAcademic VA INNER JOIN  sFee.tDepositAdd  D ON  D.AcademicId=VA.AcademicId  WHERE VA.StudentId=@lStudentId)
	    BEGIN
		SELECT -105 as Result
		RETURN
		END
	END


	
	IF(@rId = 0)	
	BEGIN  
		
		If Exists(select 1 from sFee.tDepositAdd  where OrgGroupBatchId=@rOrgGroupBatchId AND  DepositNumber=@rNumber)
		Begin
			select -102 as Result
			RETURN
		End
			END
	ELSE
	BEGIN
		
		If  Exists(select Id from sFee.tDepositAdd where  OrgGroupBatchId=@rOrgGroupBatchId AND  DepositNumber=@rNumber AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End

	END
	

 DECLARE @lNextNumber bigint 
 IF(@rId = 0)	    
 BEGIN
 
    IF(@rNumber=0 OR @rNumber IS NULL)
	BEGIN
		SELECT @rNumber=DepositNumber FROM sFee.tDepositAdd  WHERE OrgGroupBatchId=@rOrgGroupBatchId
	END 

   
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tDepositAdd', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sFee.tDepositAdd
		(
		Id,
		DepositHeadId,
		--StudentId,
		Amount,
		DepositDate,
		PayTypeId,
		ChequeNo,
		BankName,
		Remark,
		CreatedUserId,
		CreatedDateTime,
		OrgGroupBatchId,
		AcademicId,
		DepositNumber,
		ReferenceSourceTypeId,		-- Mantis Id : 0034851	
		ReferenceSourceId			-- Mantis Id : 0034851	
		
		)
	VALUES
		(
		@lNextNumber,
		@rDepositHeadId,
		--@lStudentId,
		@rAmount,
		@rDepositDate,
		@rPayTypeId,
		@rChequeNo,
		@rBankName,
		@rRemark,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rOrgGroupBatchId,
		@rAcademicId,
		@rNumber,
		@rReferenceSourceTypeId,
		@rReferenceSourceId
		) 
		SELECT @lNextNumber AS Result   
	END	
ELSE

    BEGIN 
    SET @lNextNumber = @rId
	    UPDATE sFee.tDepositAdd
	    SET
	    DepositHeadId=@rDepositHeadId,
	    --StudentId=@lStudentId,
		Amount=@rAmount,
		DepositDate=@rDepositDate,
		PayTypeId=@rPayTypeId,
		ChequeNo=@rChequeNo,
		BankName=@rBankName,
		Remark=@rRemark,
		UpdatedUserId=@rCreatedUserId,
	    UpdatedDateTime=sCommon.fGetDate(),
	    AcademicId=@rAcademicId,
		DepositNumber=@rNumber,
		OrgGroupBatchId=@rOrgGroupBatchId,
		ReferenceSourceTypeId = @rReferenceSourceTypeId,		-- Mantis Id : 0034851	
		ReferenceSourceId = @rReferenceSourceId					-- Mantis Id : 0034851	
	    WHERE Id = @rId 
	    SELECT @lNextNumber AS Result
	 END  
	
--	COMMIT TRANSACTION
		
--END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
--	END CATCH	
	
END
GO
PRINT N'Altering Procedure [sRecruitment].[pCandidateMasterUpdate]...';


GO
ALTER PROCEDURE [sRecruitment].[pCandidateMasterUpdate] 
	
    
	@rVacancyId int, 
	@rId bigint, 
	@rCandidateNumber int, 
	@rFirstName nvarchar(100), 
	@rMiddleName nvarchar(100), 
	@rLastName nvarchar(100), 
	@rDateOfBirth date, 
	@rGenderId smallint, 
	@rReligionId int, 
	@rMaritalStatusId smallint, 
	@rQualification nvarchar(150),
	@rFamilyCast nvarchar(150), 
	@rCastCategoryId int, 
	@rRecruitmentStatusId smallint, 
	@rMobileNo nvarchar(20), 
	@rPersonalEmail nvarchar(100), 	
	@rUpdatedUserId bigint,
	@rLastDrawnSalary decimal(12,2),
	@rExpectedSalary decimal(12,2),
	@rAdditionalRemark nvarchar(500),
	@rReferenceId smallint = 0,
	@rMainSubject nvarchar(100) = '',
	@rOrgId int= 0 	,
	@rBloodGroupId smallint = 0,
	@rWhatsAppContactNo nvarchar(20) = ''	--add for mantis:34273


	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	
	DECLARE @lOrgGroupID int
	
	SELECT @lOrgGroupID = OrgGroupID FROM sRecruitment.tCandidateMaster WHERE Id=@rId

	IF EXISTS(SELECT Id FROM sRecruitment.tCandidateMaster WHERE CandidateNumber=@rCandidateNumber AND OrgGroupID=@lOrgGroupID AND Id<>@rId)
		BEGIN
		SELECT -101 as Result
		RETURN
	END 
			
	 UPDATE sRecruitment.tCandidateMaster
		SET
				VacancyId=@rVacancyId, 			
				CandidateNumber=@rCandidateNumber, 
				FirstName=@rFirstName, 
				MiddleName=@rMiddleName, 
				LastName=@rLastName, 
				DateOfBirth=@rDateOfBirth, 
				GenderId=@rGenderId, 
				ReligionId=@rReligionId, 
				MaritalStatusId=@rMaritalStatusId, 
				Qualification=@rQualification,
				FamilyCast=@rFamilyCast, 
				CastCategoryId=@rCastCategoryId, 
				RecruitmentStatusId=@rRecruitmentStatusId, 
				MobileNo=@rMobileNo, 
				PersonalEmail=@rPersonalEmail, 				
				UpdatedUserId=@rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				LastDrawnSalary=@rLastDrawnSalary,
				ExpectedSalary=@rExpectedSalary,
				AdditionalRemark =@rAdditionalRemark,
				ReferenceId = @rReferenceId ,
				MainSubject = @rMainSubject ,
				OrgId = @rOrgId,
				BloodGroupId = @rBloodGroupId,
				WhatsAppContactNo = @rWhatsAppContactNo	--add for mantis:34273
	  WHERE 
			Id = @rId
	  
	SELECT @rId AS RESULT
	
	--BEGIN 
	--UPDATE sHrm.tEmployeeJobDetail
	--	SET 
	--		EmployeeDesignationId = @rEmployeeDesignationId,	
	--		OrganizationDepartmentId = @rDepartmentId,
	--		DateOfJoining =	@rDateOfJoining,
	--		UpdatedUserId = @rUpdatedUserId,
	--		EmployeeTypeId = @rEmployeeTypeId,
	--		EmployeeGradeId = @rEmployeeGradeId,
	--		EmployeeGroupId = @rEmployeeGroupId
	--	WHERE 
	--		EmployeeId = @rId
	
	--UPDATE sHrm.tEmployeePersonalDetail
	--	SET 
	--		DateOfBirth	=	@rDateOfBirth,
	--		GenderId	=	@rGenderId,
	--		UpdatedUserId = @rUpdatedUserId
	--	WHERE 
	--		EmployeeId = @rId	
	
	--IF @rStatusId = 9
	--BEGIN
	--	UPDATE sSecurity.tUser
	--		SET 
	--			IsObsolete = 1,
	--			UpdatedUserId = @rUpdatedUserId,
	--			UpdatedDateTime = sCommon.fGetDate()
	--		WHERE 
	--			SourceId = @rId AND SourceTypeId = 95
	--END
	--ELSE IF @rStatusId = 7

	--BEGIN
	--	UPDATE sSecurity.tUser
	--		SET 
	--			IsObsolete = 0,
	--			UpdatedUserId = @rUpdatedUserId,
	--			UpdatedDateTime = sCommon.fGetDate()
	--		WHERE 
	--			SourceId = @rId AND SourceTypeId = 95
	--END
	  
	  --BEGIN
	  --   Execute sHrm.pEmployeeJobDetailModify 
	  --     0,@rId,0,@rEmployeeDesignationId,@rLocationId,@rDepartmentId,@rDateOfJoining,'','',0,0,@rUpdatedUserId,
	  --     0,0,@rEmployeeTypeId,@rProcessTypeId,NULL,NULL,NULL,0,0
	     --Execute sHrm.pEmployeePersonalDetailModify
	  
   --  0,@rId,'',@rDateOfBirth,@rGenderId,0,0,'','',0,0,'','','','','',0,'',0,'',0,0,@rUpdatedUserId,@rIsBirthDateUnknown
	     
	  --END
END
GO
PRINT N'Altering Procedure [sAlert].[pOnlineRecruitmentGet]...';


GO
ALTER PROCEDURE [sAlert].[pOnlineRecruitmentGet]
	
	@rCandidateId bigint,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
SELECT 
		
CM.CandidateNumber AS CandidateNumber,
CM.FirstName+' '+CM.MiddleName+' '+CM.LastName AS Name,
CM.ApplicationPassword AS Password,
V.Title AS Vacancy,
CM.MobileNo AS MobileNo,	
CM.PersonalEmail AS EmailId,
REPLACE (
REPLACE (
REPLACE (
REPLACE (
REPLACE(@rTemplate,
		'[Name]',CM.FirstName+' '+CM.MiddleName+' '+CM.LastName),
		'[CandidateNo]',ISNULL(CM.CandidateNumber,'')),
		'[Password]',ISNULL(CM.ApplicationPassword,'')),
		'[Vacancy]',ISNULL(V.Title,0)),
		'[ApplicationNo]',ISNULL(CM.ApplicationNumber,0))		
		AS MsgText,
		
@rSubject AS [Subject],
0 As ReceiverSourceId,
0 As ReceiverSourceTypeId,
ISNULL(CM.CandidateNumber,'') AS CandidateNo,
ISNULL(V.Title,0) AS Vacancy,
ISNULL(CM.ApplicationNumber,0) AS ApplicationNo,
ISNULL(CM.WhatsAppContactNo,'') AS WhatsAppContactNo	--add for mantis:34273

FROM sRecruitment.tCandidateMaster CM
INNER JOIN sRecruitment.tVacancy V ON CM.VacancyId=V.Id AND CM.OrgGroupId=V.OrgGroupId
WHERE	
		
CM.Id = @rCandidateId

END
GO
PRINT N'Altering Procedure [sRecruitment].[pCandidateApplicationAdd]...';


GO
ALTER PROCEDURE [sRecruitment].[pCandidateApplicationAdd]   									
	@rOrgGroupID smallint, 
	@rVacancyId int, 
	@rId bigint, 
	@rApplicationNumber int	,
	@rApplicationPassword nvarchar(100)='',
	@rCandidateNumber int, 
	@rFirstName nvarchar(100), 
	@rMiddleName nvarchar(100), 
	@rLastName nvarchar(100), 
	@rDateOfBirth date, 
	@rGenderId smallint, 
	@rReligionId int, 
	@rMaritalStatusId smallint, 
	@rQualification nvarchar(150),
	@rFamilyCast nvarchar(150), 
	@rCastCategoryId int, 
	@rRecruitmentStatusId smallint, 
	@rMobileNo nvarchar(20), 
	@rPersonalEmail nvarchar(100), 
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint, 	
	@rDataEntryModeId smallint, 
    @rDataEntryStatusId smallint,
    @OutAdmissionFormId BIGINT = NULL OUTPUT,
	@rLastDrawnSalary decimal,
	@rExpectedSalary decimal,
	@rAdditionalRemark nvarchar(500),
	@rReferenceId smallint,
	@rMainSubject nvarchar(100),
	@rOrgId int = 0 ,
	@rBloodGroupId smallint= 0,
	@rWhatsAppContactNo nvarchar(20)=''	--add for mantis:34273
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 IF(@rId = 0)	
 BEGIN
 SELECT  @rCandidateNumber =  ISNULL(MAX(CandidateNumber),0) 
                       FROM  sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupID
                       AND ISNULL(LEN(CandidateNumber),0)=
                       (SELECT ISNULL((MAX(LEN(CandidateNumber))),0) 
                       FROM  sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupID
                       AND Isnumeric(CandidateNumber) = 1)
	
	
	    SET @rCandidateNumber = @rCandidateNumber +1
	
		IF Exists(select ApplicationNumber from sRecruitment.tCandidateMaster where ApplicationNumber=@rApplicationNumber AND OrgGroupID=@rOrgGroupID)
			BEGIN
			select -101 as Result
			RETURN
		END 
 END
 ELSE
 BEGIN
	IF Exists(select @rApplicationNumber from sRecruitment.tCandidateMaster where ApplicationNumber=@rApplicationNumber AND OrgGroupID=@rOrgGroupID And Id <> @rId)
	BEGIN
		select -101 as Result
		RETURN
	END 
 END

	
 BEGIN TRY
 BEGIN TRANSACTION	
 DECLARE @lNextNumber BIGINT
 DECLARE @lBIGID BIGINT
 DECLARE @lSMALLID INT
 
 IF(@rId = 0)	
	BEGIN
	IF(@rApplicationNumber = 0)
	BEGIN
	SELECT @rApplicationNumber = ISNULL(MAX(ApplicationNumber),0) + 1 FROM sRecruitment.tCandidateMaster
	END
	IF(@rApplicationPassword = '')
	BEGIN
	SELECT @rApplicationPassword = @rApplicationNumber
	END
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sRecruitment.tCandidateMaster
		(
				OrgGroupID, 
				VacancyId, 
				Id, 
				ApplicationNumber,	
				ApplicationPassword ,
				CandidateNumber, 
				FirstName, 
				MiddleName, 
				LastName, 
				DateOfBirth, 
				GenderId, 
				ReligionId, 
				MaritalStatusId, 
				Qualification,
				FamilyCast, 
				CastCategoryId, 
				RecruitmentStatusId, 
				MobileNo, 
				PersonalEmail, 
				CreatedUserId, 
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,	
				DataEntryModeId, 
				DataEntryStatusId,
				LastDrawnSalary,
				ExpectedSalary,
				AdditionalRemark,
				ReferenceId,
				MainSubject,
				OrgId,
				BloodGroupId,
				WhatsAppContactNo	--add for mantis:34273
			
		)
	VALUES
		(
			 @rOrgGroupID , 
				@rVacancyId , 
				@lNextNumber , 
				@rApplicationNumber ,	
				@rApplicationPassword ,
				@rCandidateNumber , 
				@rFirstName , 
				@rMiddleName , 
				@rLastName , 
				@rDateOfBirth , 
				@rGenderId , 
				@rReligionId , 
				@rMaritalStatusId , 
				@rQualification ,
				@rFamilyCast, 
				@rCastCategoryId , 
				@rRecruitmentStatusId , 
				@rMobileNo , 
				@rPersonalEmail , 
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rUpdatedUserId,
				sCommon.fGetDate(),	
				@rDataEntryModeId , 
				@rDataEntryStatusId,
				@rLastDrawnSalary,
				@rExpectedSalary,
				@rAdditionalRemark,
				@rReferenceId,
				@rMainSubject,
				@rOrgId,
				@rBloodGroupId,
				@rWhatsAppContactNo	--add for mantis:34273
		)
	INSERT INTO sRecruitment.tRecruitmentStatusLog
		(
		OrgGroupId,
		CandidateId,
		RecruitmentStatusId,
		Remark,
		CreatedUserId,
		CreatedDateTime
			
		)
		VALUES
		(
		@rOrgGroupID , 
		@lNextNumber,
		@rRecruitmentStatusId,
		'',
		@rCreatedUserId,
		sCommon.fGetDate()
		)
	END	 
	ELSE
	BEGIN
	SET @lNextNumber = @rId
	    UPDATE  sRecruitment.tCandidateMaster
	    SET
				VacancyId=@rVacancyId, 	
				--ApplicationNumber=@rApplicationNumber,					
				--CandidateNumber=@rCandidateNumber, 
				FirstName=@rFirstName, 
				MiddleName=@rMiddleName, 
				LastName=@rLastName, 
				DateOfBirth=@rDateOfBirth, 
				GenderId=@rGenderId, 
				ReligionId=@rReligionId, 
				MaritalStatusId=@rMaritalStatusId, 
				Qualification=@rQualification,
				FamilyCast=@rFamilyCast, 
				CastCategoryId=@rCastCategoryId, 
				RecruitmentStatusId=@rRecruitmentStatusId, 
				MobileNo=@rMobileNo, 
				PersonalEmail=@rPersonalEmail, 				
				UpdatedUserId=@rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				LastDrawnSalary=@rLastDrawnSalary,
				ExpectedSalary=@rExpectedSalary,
				AdditionalRemark=@rAdditionalRemark,
				ReferenceId = @rReferenceId,
				MainSubject = @rMainSubject,
				OrgId = @rOrgId,
				BloodGroupId=@rBloodGroupId,
				WhatsAppContactNo = @rWhatsAppContactNo	--add for mantis:34273

	      WHERE Id = @rId 	   
	END  
	SELECT @lNextNumber AS Result
	SET @OutAdmissionFormId=@lNextNumber

	COMMIT TRANSACTION

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


GO
ALTER PROCEDURE [sRecruitment].[pCandidateApplicationConfirmGet]
	 @rCandidateId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
	CM.OrgGroupID,
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				iSNULL(CM.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(CM.DataEntryStatusId,0) as DataEntryStatusId,
			CM.ApplicationNumber,
			CM.ApplicationPassword,
			GM.Title AS Gender,
			RM.Title AS ReligionName,
			CCM.Title AS CastCategoryName,
			CC.PresentStreetOne,
			CC.PresentStreetTwo,
			CC.PresentStreetThree,
			CC.PresentCountry,
			CC.PresentState,
			CC.PresentCity,
			CC.PresentZipCode,
			CC.PresentContactNo,
			CC.PermanentStreetOne,
			CC.PermanentStreetTwo,
			CC.PermanentStreetThree,
			CC.PermanentCountry,
			CC.PermanentState,
			CC.PermanentCity,
			CC.PermanentZipCode,
			CC.PermanentContactNo,
			CI.CandidatePhoto,
			MS.Title AS MaritalStatus,
			CM.LastDrawnSalary,
			CM.ExpectedSalary,
			VM.ConfirmationRemark,
			ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
			ISNULL(DM.Title,'') AS Reference,
			ISNULL(CM.MainSubject,'') AS MainSubject,
			ISNULL(OM.Title,'') AS Organization,
			ISNULL(BG.Title,'') AS BloodGroup,
			ISNULL(CM.WhatsAppContactNo,'') AS WhatsAppContactNo	--add for mantis:34273
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			LEFT JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId 
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId 
			LEFT JOIN sRecruitment.tCandidateCommunications	 CC ON 	CC.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tCandidateImages	CI ON CI.CandidateId=CM.Id	
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id=CM.MaritalStatusId	 		 	
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id  = CM.ReferenceId
			AND DM.DataTypeId = 13
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
			LEFT JOIN sCommon.tBloodGroupMaster BG ON CM.BloodGroupId = BG.Id

  WHERE 
  
      ((CM.Id = @rCandidateId) OR (@rCandidateId = 0))
       
 
END
GO
PRINT N'Altering Procedure [sRecruitment].[pCandidateApplicationGet]...';


GO
ALTER PROCEDURE [sRecruitment].[pCandidateApplicationGet]
	@rCandidateId bigint= 0,
	@rApplicationNumber int	,
	@rOrgGroupID smallint
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
				CM.OrgGroupID,
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				iSNULL(CM.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(CM.DataEntryStatusId,0) as DataEntryStatusId,
			CM.ApplicationNumber,
			CM.ApplicationPassword,
			CM.LastDrawnSalary,
			CM.ExpectedSalary,
			ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
			ISNULL(CM.ReferenceId,0)AS ReferenceId,
			ISNULL(CM.MainSubject,'')AS MainSubject,
			ISNULL(CM.OrgId,0) AS OrgId,
			ISNULL(CM.WhatsAppContactNo,'') AS WhatsAppContactNo	--add for mantis:34273
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId							
		WHERE 
				 CM.OrgGroupID = @rOrgGroupID
		   AND ((CM.Id = @rCandidateId) OR (@rCandidateId = 0))
		   AND ((CM.ApplicationNumber =@rApplicationNumber ) OR (@rApplicationNumber = 0))
		 
 
       
 order by CM.ApplicationNumber
END
GO
PRINT N'Altering Procedure [sRecruitment].[pCandidateDetailExportGet]...';


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

BEGIN
 
 		--SET @rCandidateNumber = ISNULL( sCommon.fSearchStringGet(@rCandidateNumber),0)
		SET @rFirstname = ISNULL( sCommon.fSearchStringGet(@rFirstname),'')
		SET @rLastName = ISNULL( sCommon.fSearchStringGet(@rLastName),'')
		
		IF(@rIsQualificationDetail = 0)
		BEGIN
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				--RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				--RSL.RecruitmentStatusId AS RecruitmentStatusId
				CM.RecruitmentStatusId,
				GM.Title AS Gender,
				ISNULL(MS.Title,'') AS MaritalStatus,
				ISNULL(RM.Title,'') AS Religion,
				ISNULL(CCM.Title,'') AS CastCategory,
				ISNULL(CM.FamilyCast,'') AS FamilyCast,
				ISNULL(CM.Qualification,'')AS Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				CM.LastDrawnSalary,
				CM.ExpectedSalary,
				ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
				ISNULL([PresentStreetOne],'') AS PresentStreetOne,
				ISNULL([PresentStreetTwo],'') AS PresentStreetTwo,
				ISNULL([PresentStreetThree],'') AS PresentStreetThree,
				ISNULL([PresentCountry],'') AS PresentCountry,
				ISNULL([PresentState],'') AS PresentState,
				ISNULL([PresentCity],'') AS PresentCity,
				ISNULL([PresentZipCode],'') AS PresentZipCode,
				ISNULL([PresentContactNo],'') AS PresentContactNo,
				ISNULL([PermanentStreetOne],'') AS PermanentStreetOne,
				ISNULL([PermanentStreetTwo],'') AS PermanentStreetTwo,
				ISNULL([PermanentStreetThree],'') AS PermanentStreetThree,
				ISNULL([PermanentCountry],'') AS PermanentCountry,
				ISNULL([PermanentState],'') AS PermanentState,
				ISNULL([PermanentCity],'') AS PermanentCity,
				ISNULL([PermanentZipCode],'') AS PermanentZipCode,
				ISNULL([PermanentContactNo],'') AS PermanentContactNo,
				CM.CreatedDateTime,
				CM.MainSubject,
				ISNULL(DM.Title,'') AS Reference,
				ISNULL(OM.Title,'') AS Organization,
				ISNULL(BGM.Title ,'') AS BloodGroup,
				ISNULL(CM.WhatsAppContactNo ,'') AS WhatsAppContactNo	--Add for Mantis: 34273
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			
			INNER JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id		
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id = CM.MaritalStatusId	
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId
			LEFT JOIN sRecruitment.tCandidateCommunications CC ON CC.CandidateId = CM.Id
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id = CM.ReferenceId AND DM.DataTypeId = 13 AND DM.IsObsolete = 0
			LEFT JOIN sRecruitment.tAssignOrganization AO ON AO.VacancyId = CM.VacancyId AND AO.OrgId = CM.OrgId
			LEFT JOIN sSetup.tOrganizationMaster OM ON AO.OrgId = OM.Id
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON CM.BloodGroupId = BGM.Id

		WHERE 
		--RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
		--		AND
				((CM.CandidateNumber=@rCandidateNumber ) OR (@rCandidateNumber = 0))
			AND ((CM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((CM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((VM.Id = @rVacancyId) OR (@rVacancyId = 0))	
			AND ((CM.RecruitmentStatusId = @rRecruitmentStatusId) OR (@rRecruitmentStatusId = 0))	
			AND CM.OrgGroupID = @rOrgGroupID
			AND ((CONVERT(date,CM.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,CM.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
			ORDER BY CM.CandidateNumber
		END
		ELSE
		BEGIN
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				--RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				--RSL.RecruitmentStatusId AS RecruitmentStatusId
				CM.RecruitmentStatusId,
				GM.Title AS Gender,
				ISNULL(MS.Title,'') AS MaritalStatus,
				ISNULL(RM.Title,'') AS Religion,
				ISNULL(CCM.Title,'') AS CastCategory,
				ISNULL(CM.FamilyCast,'') AS FamilyCast,
				ISNULL(CM.Qualification,'')AS Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				CM.LastDrawnSalary,
				CM.ExpectedSalary,
				ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
				ISNULL([PresentStreetOne],'') AS PresentStreetOne,
				ISNULL([PresentStreetTwo],'') AS PresentStreetTwo,
				ISNULL([PresentStreetThree],'') AS PresentStreetThree,
				ISNULL([PresentCountry],'') AS PresentCountry,
				ISNULL([PresentState],'') AS PresentState,
				ISNULL([PresentCity],'') AS PresentCity,
				ISNULL([PresentZipCode],'') AS PresentZipCode,
				ISNULL([PresentContactNo],'') AS PresentContactNo,
				ISNULL([PermanentStreetOne],'') AS PermanentStreetOne,
				ISNULL([PermanentStreetTwo],'') AS PermanentStreetTwo,
				ISNULL([PermanentStreetThree],'') AS PermanentStreetThree,
				ISNULL([PermanentCountry],'') AS PermanentCountry,
				ISNULL([PermanentState],'') AS PermanentState,
				ISNULL([PermanentCity],'') AS PermanentCity,
				ISNULL([PermanentZipCode],'') AS PermanentZipCode,
				ISNULL([PermanentContactNo],'') AS PermanentContactNo,
				CM.CreatedDateTime,
				CM.MainSubject,
				ISNULL(DM.Title,'') AS Reference,
				ISNULL(OM.Title,'') AS Organization,
				ISNULL(CQ.ExamPassed,'') AS ExamPassed,
				ISNULL(CQ.PassYear,'') AS PassYear,
				CQ.Percentage,
				ISNULL(CQ.Grade,'') AS Grade,
				ISNULL(CQ.InstituteDetail,'') AS InstituteDetail,
				ISNULL(CQ.BoardDetail,'') AS BoardDetail,
				ISNULL(CQ.Medium,'') AS Medium,
				ISNULL(CQ.Subjects,'') AS Subjects,
				ISNULL(CQ.Remark,'') AS Remark,
				ISNULL(CM.WhatsAppContactNo ,'') AS WhatsAppContactNo	--Add for Mantis: 34273
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			
			INNER JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id		
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id = CM.MaritalStatusId	
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId
			LEFT JOIN sRecruitment.tCandidateCommunications CC ON CC.CandidateId = CM.Id
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id = CM.ReferenceId AND DM.DataTypeId = 13 AND DM.IsObsolete = 0
			LEFT JOIN sRecruitment.tAssignOrganization AO ON AO.VacancyId = CM.VacancyId AND AO.OrgId = CM.OrgId
			LEFT JOIN sSetup.tOrganizationMaster OM ON AO.OrgId = OM.Id
			LEFT JOIN sRecruitment.tCandidateQualification CQ ON CQ.CandidateId = CM.Id

		WHERE 
		--RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
		--		AND
				((CM.CandidateNumber=@rCandidateNumber ) OR (@rCandidateNumber = 0))
			AND ((CM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((CM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((VM.Id = @rVacancyId) OR (@rVacancyId = 0))	
			AND ((CM.RecruitmentStatusId = @rRecruitmentStatusId) OR (@rRecruitmentStatusId = 0))	
			AND CM.OrgGroupID = @rOrgGroupID
			AND ((CONVERT(date,CM.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,CM.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
			ORDER BY CM.CandidateNumber
		END
END
GO
PRINT N'Altering Procedure [sRecruitment].[pCandidateMasterAdd]...';


GO
ALTER PROCEDURE [sRecruitment].[pCandidateMasterAdd]     
	@rOrgGroupID smallint, 
	@rVacancyId int, 
	@rId bigint, 
	@rCandidateNumber int, 
	@rFirstName nvarchar(100), 
	@rMiddleName nvarchar(100), 
	@rLastName nvarchar(100), 
	@rDateOfBirth date, 
	@rGenderId smallint, 
	@rReligionId int, 
	@rMaritalStatusId smallint, 
	@rQualification nvarchar(150),
	@rFamilyCast nvarchar(150), 
	@rCastCategoryId int, 
	@rRecruitmentStatusId smallint, 
	@rMobileNo nvarchar(20), 
	@rPersonalEmail nvarchar(100), 
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint, 	
	@rDataEntryModeId smallint, 
    @rDataEntryStatusId smallint,
	@rLastDrawnSalary decimal(12,2),
	@rExpectedSalary decimal(12,2),
	@rApplicationNumber int,
	@rApplicationPassword int,
	@rAdditionalRemark nvarchar(500),
	@rReferenceId smallint = 0,
	@rMainSubject nvarchar(100) = '',
	@rOrgId int = 0,
	@rBloodGroupId smallint = 0,
	@rWhatsAppContactNo nvarchar(20) = ''	--add for mantis:34273

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber BIGINT
	

    

	IF EXISTS(SELECT Id FROM sRecruitment.tCandidateMaster WHERE CandidateNumber=@rCandidateNumber AND OrgGroupID=@rOrgGroupID)
		BEGIN
		SELECT -101 as Result
		RETURN
	END 
	
    
	BEGIN TRY
 	BEGIN TRANSACTION
	
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				
		INSERT INTO sRecruitment.tCandidateMaster
			(
				OrgGroupID, 
				VacancyId, 
				Id, 
				CandidateNumber, 
				FirstName, 
				MiddleName, 
				LastName, 
				DateOfBirth, 
				GenderId, 
				ReligionId, 
				MaritalStatusId, 
				Qualification,
				FamilyCast, 
				CastCategoryId, 
				RecruitmentStatusId, 
				MobileNo, 
				PersonalEmail, 
				CreatedUserId, 
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,	
				DataEntryModeId, 
				DataEntryStatusId,
				ApplicationNumber,
				ApplicationPassword,
				LastDrawnSalary,
				ExpectedSalary,
				AdditionalRemark,
				ReferenceId,
				MainSubject,
				OrgId,
				BloodGroupId,
				WhatsAppContactNo	--add for mantis:34273
			)
		VALUES
			(
				@rOrgGroupID , 
				@rVacancyId , 
				@lNextNumber , 
				@rCandidateNumber , 
				@rFirstName , 
				@rMiddleName , 
				@rLastName , 
				@rDateOfBirth , 
				@rGenderId , 
				@rReligionId , 
				@rMaritalStatusId , 
				@rQualification ,
				@rFamilyCast, 
				@rCastCategoryId , 
				@rRecruitmentStatusId , 
				@rMobileNo , 
				@rPersonalEmail , 
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rUpdatedUserId,
				sCommon.fGetDate(),	
				@rDataEntryModeId , 
				@rDataEntryStatusId,
				@rApplicationNumber,
				@rApplicationPassword,
				@rLastDrawnSalary,
				@rExpectedSalary,
				@rAdditionalRemark,
				@rReferenceId,
				@rMainSubject,
				@rOrgId,
				@rBloodGroupId,
				@rWhatsAppContactNo	--add for mantis:34273
			)
			INSERT INTO sRecruitment.tRecruitmentStatusLog
			(
			OrgGroupId,
			CandidateId,
			RecruitmentStatusId,
			Remark,
			CreatedUserId,
			CreatedDateTime
			
			)
			VALUES
			(
			@rOrgGroupID , 
			@lNextNumber,
			@rRecruitmentStatusId,
			'',
			@rCreatedUserId,
			sCommon.fGetDate()
			)
			
		SELECT @lNextNumber AS RESULT
		 --@loEmpNumber AS EmpCode FROM sHrm.tEmployeeMaster WHERE  Id = @lNextNumber
		--SET @OutEmployeeId = @lNextNumber -- added for import employee
		
		--BEGIN 
  --      Execute sHrm.pEmployeeJobDetailAdd  
	 --      @rOrgId,@lNextNumber,@rEmployeeDesignationId,@rDepartmentId,@rDateOfJoining,@rCreatedUserId,
	 --      @rEmployeeTypeId,@rEmployeeGradeId,@rEmployeeGroupId,'',@rEmployeeManagerId
	          
	 --    Execute sHrm.pEmployeePersonalDetailAdd @rOrgId,@lNextNumber,'',@rDateOfBirth,@rGenderId,@rReligionId,
	 --    0,'',@rBloodGroupId,@rQualification,@rCreatedUserId,@rFamilyCast,@rCastCategoryId
	     
	      
	     
		--END	

		COMMIT TRANSACTION
	 
		END TRY
		
		BEGIN CATCH
		ROLLBACK TRANSACTION 
 
			--RAISERROR ('Error saving employee Master', -- Message text.
   --            16, -- Severity.
   --            1 -- State.
   --            );           
		 
 
		END CATCH			
 
	
	 
END
GO
PRINT N'Altering Procedure [sRecruitment].[pCandidateMasterGet]...';


GO
ALTER PROCEDURE [sRecruitment].[pCandidateMasterGet]
(
		@rOrgGroupID smallint, 
		@rCandidateNumber int=0,		
	@rId [bigint] = 0,
	@rVacancyId int=0
 )
AS
SET NOCOUNT ON

BEGIN

		
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				CM.LastDrawnSalary,
				CM.ExpectedSalary,
				ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
				ISNULL(CM.ReferenceId,0) AS ReferenceId,
				ISNULL(CM.MainSubject,'')AS MainSubject,
				ISNULL(CM.OrgId,0) AS OrgId,
				ISNULL(CM.BloodGroupId,0)AS BloodGroupId,
				ISNULL(CM.WhatsAppContactNo,'') AS WhatsAppContactNo	--add for mantis:34273
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
						
		WHERE 
				 CM.OrgGroupID = @rOrgGroupID
		   AND ((CM.Id = @rId) OR (@rId = 0))
		   AND ((CM.CandidateNumber =@rCandidateNumber ) OR (@rCandidateNumber = 0))
		   AND ((CM.VacancyId =@rVacancyId ) OR (@rVacancyId = 0))
END
GO
PRINT N'Altering Procedure [sRecruitment].[pRptCandidateApplicationGet]...';


GO
ALTER PROCEDURE [sRecruitment].[pRptCandidateApplicationGet]
	 @rCandidateId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
				convert(nvarchar(20),@rCandidateId) AS CandidateIdText,
				CM.OrgGroupID,
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				iSNULL(CM.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(CM.DataEntryStatusId,0) as DataEntryStatusId,
			CM.ApplicationNumber,
			CM.ApplicationPassword,
			GM.Title AS Gender,
			RM.Title AS ReligionName,
			CCM.Title AS CastCategoryName,
			CC.PresentStreetOne,
			CC.PresentStreetTwo,
			CC.PresentStreetThree,
			CC.PresentCountry,
			CC.PresentState,
			CC.PresentCity,
			CC.PresentZipCode,
			CC.PresentContactNo,
			CC.PermanentStreetOne,
			CC.PermanentStreetTwo,
			CC.PermanentStreetThree,
			CC.PermanentCountry,
			CC.PermanentState,
			CC.PermanentCity,
			CC.PermanentZipCode,
			CC.PermanentContactNo,
			CI.CandidatePhoto,
			MS.Title AS MaritalStatus,
			CM.LastDrawnSalary,
			CM.ExpectedSalary,
			CM.CreatedDateTime,
			ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
			ISNULL(DM.Title,'') AS Reference,
			ISNULL(CM.MainSubject,'') AS MainSubject,
			ISNULL(OM.Title,'') AS Organization,
			ISNULL(BG.Title,'') AS BloodGroup,
			ISNULL(CM.WhatsAppContactNo,'') AS WhatsAppContactNo	--add for mantis:34273
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			LEFT JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId 
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId 
			LEFT JOIN sRecruitment.tCandidateCommunications	 CC ON 	CC.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tCandidateImages	CI ON CI.CandidateId=CM.Id	
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id=CM.MaritalStatusId	 	
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id  = CM.ReferenceId
			AND DM.DataTypeId = 13
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
			LEFT JOIN sCommon.tBloodGroupMaster BG ON CM.BloodGroupId = BG.Id
		
  WHERE 
  
      ((CM.Id = @rCandidateId) OR (@rCandidateId = 0))
       
 
END
GO
PRINT N'Altering Procedure [sTally].[pReceiptTallyPostingAdd]...';


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

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

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

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


GO
ALTER PROCEDURE [sAcademic].[pClassworkStudentWithStatusGet]

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

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

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

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

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsClassworkHomeworkBasedOnApproval = 0
	ELSE
	SET @lIsClassworkHomeworkBasedOnApproval = 1
	
	DECLARE @lIsOptional INT = 0
	SET @lIsOptional =(SELECT TOP 1 1 FROM sAcademic.tClasswork AC 
						INNER Join sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
						INNER Join sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
						INNER Join sSetup.tClassMaster CM On CM.Id = AC.ClassId
						INNER Join sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
						INNER JOIN sStudent.vStudentAcademic SA  ON AC.ClassId=SA.ClassId AND AC.DivisionId=SA.DivisionId
						INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = AC.ClassId AND CS.SubjectId = SM.Id
						where CS.IsOptional=1 AND SA.AcademicId =@lAcademicId)
	
	IF (@lIsOptional=1)
	BEGIN
	SELECT 
			DISTINCT(AC.Id),
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    CASE WHEN AC.ClassworkStatusId != 2 THEN AC.Classwork ELSE 'NA' END AS Classwork,
		    CASE WHEN AC.HomeWorkStatusId != 2 THEN AC.Homework ELSE 'NA' END AS Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    OM.OrgGroupId AS OrgId,
		    ISNULL(HCSM.Title,'Assigned') AS HomeworkStatus,
			AC.ClassWorkDate ,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC			 
			INNER JOIN sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER JOIN sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER JOIN sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER JOIN sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sStudent.tAcademic SA ON SA.ClassId = AC.ClassId AND SA.DivisionId = AC.DivisionId AND SA.BatchId = AC.BatchId
			LEFT JOIN sAcademic.tHomeworkCheck HWC ON HWC.AcademicId = SA.Id AND HWC.ClassworkId = AC.Id
			LEFT JOIN sAcademic.tHomeworkCheckStatusMaster HCSM ON HCSM.Id = HWC.HomeWorkCheckStatusId
			INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = AC.ClassId AND CS.SubjectId = SM.Id
			LEFT JOIN [sAssessment].[tOptionalSubject] OS ON OS.ClassSubjectId = CS.Id AND OS.AcademicId = SA.Id AND OS.AcademicId IS NULL
	WHERE 
			AC.DivisionId = @lDivisionId		 
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (AC.HomeWorkEndDate>=@rHomeWorkEndDate OR ISNULL(@rHomeWorkEndDate,'')='')
			AND AC.BatchId = @rBatchId
			AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			--AND AC.StatusId=550
			--AND SA.Id = @lAcademicId
			--uncomment above AND SA.Id = @lAcademicId because HomeworkStatus not display Studentwise
			--AND OS.AcademicId IS NULL
	ORDER BY  AC.ID DESC
	END

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


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanGet]

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

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

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


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanMobileGet]

	 @rId bigint=0,
	 @rClassId int=0,
	 @rSubjectId int=0,
	 @rDivisionId int=0,
	 @rIsCompleted bit=0,
	 @rBatchId int=0,
	 @rEmployeeId bigint=0,
	 @rDepartmentid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rIsCompletedAPI tinyint=0,
     @rCreatedUserId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
DECLARE @lIsCompleted bit = 0
	
	If(@rIsCompletedAPI=1)
		SET @lIsCompleted = 1
	else If(@rIsCompletedAPI=2)
		SET @lIsCompleted = 0
	
	SELECT 
			LP.Id,
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			DM.Code AS ClassDivisionName,
			SM.Title AS SubjectName,
			--vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			--vTSD.SubjectName,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic ,
			ISNULL(LP.[Session] ,'') As [Session] ,
			ISNULL(LP.TrainingMethod,'') As TrainingMethod,
			ISNULL(LP.PeriodCount,0) As PeriodCount
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sSetup.tDivisionMaster DM ON LP.DivisionId = DM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = DM.ClassId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId   
	WHERE 
		((LP.BatchId = @rBatchId) OR (LP.BatchId = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND((LP.IsCompleted=@lIsCompleted) OR (@rIsCompletedAPI=0))
		--AND (LP.StartDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		--AND (LP.StartDate<=@rToDate OR ISNULL(@rToDate,'')='')
		AND (((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		))
		--AND (LP.CreatedUserId=@rCreatedUserId OR ISNULL(@rCreatedUserId,0)=0) 
		AND  (LP.EmployeeId = @rEmployeeId OR (ISNULL(@rEmployeeId,0)=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
	ORDER BY
		LP.StartDate,LP.EndDate,LP.id 
END
GO
PRINT N'Altering Procedure [sActivity].[pEventAttendanceStudentDetailsGet]...';


GO



ALTER PROCEDURE [sActivity].[pEventAttendanceStudentDetailsGet]
	
	 @rUserTypeId int,
	 @rIsPresentAbsent int,
	 @rOrgId int,
	 @rAcademicId bigint

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	--SET @rUserTypeId = 1 for Student
	--SET @rUserTypeId = 2 for Father
	--SET @rUserTypeId = 3 for Mother
	--SET @rUserTypeId = 4 for Relative

	--SET @rIsPresentAbsent = 1 for All
	--SET @rIsPresentAbsent = 2 for Present
	--SET @rIsPresentAbsent = 3 for Absent


	--for Student
IF(@rUserTypeId = 1 AND @rIsPresentAbsent = 1)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsSelfPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch = 1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsSelfPresent = 0 OR EAT.IsSelfPresent = 1)
END

IF(@rUserTypeId = 1 AND @rIsPresentAbsent = 2)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsSelfPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId		
				AND (EAT.IsSelfPresent = 1)
END

IF(@rUserTypeId = 1 AND @rIsPresentAbsent = 3)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsSelfPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsSelfPresent = 0)
END

--for Father

IF(@rUserTypeId = 2 AND @rIsPresentAbsent = 1)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsFatherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsFatherPresent = 0 OR EAT.IsFatherPresent = 1)
END

IF(@rUserTypeId = 2 AND @rIsPresentAbsent = 2)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsFatherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsFatherPresent = 1)
END

IF(@rUserTypeId = 2 AND @rIsPresentAbsent = 3)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsFatherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsFatherPresent = 0)
END

--for Mother

IF(@rUserTypeId = 3 AND @rIsPresentAbsent = 1)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsMotherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsMotherPresent = 0 OR EAT.IsMotherPresent = 1)
END

IF(@rUserTypeId = 3 AND @rIsPresentAbsent = 2)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsMotherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsMotherPresent = 1)
END

IF(@rUserTypeId = 3 AND @rIsPresentAbsent = 3)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsMotherPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsMotherPresent = 0)
END

--for Relative

IF(@rUserTypeId = 4 AND @rIsPresentAbsent = 1)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsGuardianPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsGuardianPresent = 0 OR EAT.IsGuardianPresent = 1)
END

IF(@rUserTypeId = 4 AND @rIsPresentAbsent = 2)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsGuardianPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsGuardianPresent = 1)
END

IF(@rUserTypeId = 4 AND @rIsPresentAbsent = 3)
BEGIN
SELECT 
ES.Title AS EventName,
(CASE WHEN EAT.IsGuardianPresent = 1 THEN 'PR' ELSE 'AB' END ) AS Status,
ES.FromDate,
ES.ToDate
FROM 
				sStudent.vStudentAcademic vSA
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
				INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
				--AND EA.EventScheduleId=@rEventScheduleId
				INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
				AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
				INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
				INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
				inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
				INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

			WHERE
				--(vSA.ClassId=0 OR 0=0)
				--AND (vSA.DivisionId=0 OR 0=0)
				(vSA.StatusId=1)
				AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
				AND (vSA.IsActiveBatch=1)
				AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
				AND vSA.AcademicId = @rAcademicId	
				AND (EAT.IsGuardianPresent = 0)
END

END
GO
PRINT N'Altering Procedure [sActivity].[pEventAttendanceStudentWiseGet]...';


GO


ALTER PROCEDURE [sActivity].[pEventAttendanceStudentWiseGet]
	
	 @rOrgId smallint,
	 @rAcademicId bigint

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		Select 
		'Student' AS [Events],
		(SELECT COUNT(EAT.IsSelfPresent)
		FROM 
						sStudent.vStudentAcademic vSA
						INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
						INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
						--AND EA.EventScheduleId=@rEventScheduleId
						INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
						AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
						INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
						INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
						inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
						INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

					WHERE
						--(vSA.ClassId=0 OR 0=0)
						--AND (vSA.DivisionId=0 OR 0=0)
						(vSA.StatusId=1)
						AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
						AND (vSA.IsActiveBatch=1)
						AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
						AND vSA.AcademicId = @rAcademicId	
						AND (EAT.IsSelfPresent = 0 OR EAT.IsSelfPresent = 1)
						) AS Total,
			(SELECT COUNT(EAT.IsSelfPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1 )
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsSelfPresent = 1
							) AS Present,

			(SELECT COUNT(EAT.IsSelfPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId
							AND EAT.IsSelfPresent = 0
							) AS Absent

UNION ALL

			Select 
			'Father' AS [Events],
			(SELECT COUNT(EAT.IsFatherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND (EAT.IsFatherPresent = 0 OR EAT.IsFatherPresent = 1)
							) AS Total,
			(SELECT COUNT(EAT.IsFatherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsFatherPresent = 1
							) AS Present,

			(SELECT COUNT(EAT.IsFatherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch=1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsFatherPresent = 0
							) AS Absent

UNION All

			Select 
			'Mother' AS [Events],
			(SELECT COUNT(EAT.IsMotherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND (EAT.IsMotherPresent = 0 OR EAT.IsMotherPresent = 1)
							) AS Total,
			(SELECT COUNT(EAT.IsMotherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsMotherPresent = 1
							) AS Present,

			(SELECT COUNT(EAT.IsMotherPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
						--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsMotherPresent = 0
							) AS Absent


UNION All

			Select 
			'Relative' AS [Events],
			(SELECT COUNT(EAT.IsGuardianPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND (EAT.IsGuardianPresent = 0 OR EAT.IsGuardianPresent = 1)
							) AS Total,
			(SELECT COUNT(EAT.IsGuardianPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0)--Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsGuardianPresent = 1
							) AS Present,

			(SELECT COUNT(EAT.IsGuardianPresent)
			FROM 
							sStudent.vStudentAcademic vSA
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = vSA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
							INNER JOIN sActivity.tEventAssign EA ON EA.SourceId=vSA.DivisionId AND EA.SourceTypeId=2005 
							--AND EA.EventScheduleId=@rEventScheduleId
							INNER JOIN sActivity.tEventAttendance EAT ON EAT.EventScheduleId = EA.EventScheduleId 
							AND EAT.SourceId = vSA.AcademicId AND EAT.SourceTypeId = 2001
							INNER JOIN sActivity.tEventSchedule ES ON ES.Id = EAT.EventScheduleId
							INNER JOiN [sActivity].[tEventTypeMaster] ETM ON ES.EventTypeId=ETM.Id 
							inner Join [sActivity].[tEventMainTypeMaster]  EMTM ON ETM.EventMainTypeId=EMTM.Id --AND EMTM.id=3
							INNER JOIN sSetup.tOrganizationMaster OM ON vSA.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupMaster OGM ON OM.OrgGroupId = OGM.Id

						WHERE
							--(vSA.ClassId=0 OR 0=0)
							--AND (vSA.DivisionId=0 OR 0=0)
							(vSA.StatusId = 1)
							AND (vSA.OrgId = @rOrgId OR @rOrgId = 0)
							AND (vSA.IsActiveBatch = 1)
							AND (OM.Id = @rOrgId OR @rOrgId = 0) --Changed for mantis : 35157 by Nilesh
							AND vSA.AcademicId = @rAcademicId	
							AND EAT.IsGuardianPresent = 0
							) AS Absent


END
GO
PRINT N'Altering Procedure [sActivity].[pPlacementInviteStudentExportGet]...';


GO


--EXEC [sActivity].[pPlacementInviteStudentExportGet] ''

ALTER PROCEDURE [sActivity].[pPlacementInviteStudentExportGet]
	@rStudentId nvarchar(MAX),
	@rBatchId int,
	@rClassId int,
	@rDivisionId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

			DECLARE @StudentIdTable TABLE(StudentId bigint)

			IF (@rStudentId IS NOT NULL AND @rStudentId <> '')
				BEGIN
					INSERT INTO @StudentIdTable 
					SELECT item FROM Scommon.fnSplit(@rStudentId,',')
				END

			SELECT DISTINCT 
				s.StudentId
				,s.Code
				,s.Name
				,b.ClassName +'-'+ d.Title as ClassName
				,d.Title as 'DivisionName'
				,s.RollNo
				--,c.[AdmissionNumber]
				--,c.[IsTransfer]
			   --,c.[TransferFrom]
			   --,c.[PassingYear]
			   --,c.[IsTFWS]
			   --,c.[IsCertificateHolder]
			   --,c.[CertificateName] --Commented for mantis 35404 : by Nilesh
			   ,SA.[CertificateName] --Added for mantis 35404 : by Nilesh
			   ,c.[SSCBoard]
			   ,c.[SSCSchool]
			   ,c.[SSCPassingYear]
			   ,c.[SSCObtainMarks]
			   ,c.[SSCOutOfMarks]
			   ,c.[SSCPercentage]
			   ,c.[SSCMathMarks]
			   ,c.[SSCMathOutOfMarks]
			   ,c.[HSCBoard]
			   ,c.[HSCSchool]
			   ,c.[HSCPassingYear]
			   ,c.[HSCObtainMarks]
			   ,c.[HSCOutOfMarks]
			   ,c.[HSCPercentage]
			   ,c.[HSCPhysicsMarks]
			   ,c.[HSCPhysicsOutOfMarks]
			   ,c.[HSCChemistryMarks]
			   ,c.[HSCChemistryOutOfMarks]
			   ,c.[HSCMathMarks]
			   ,c.[HSCMathOutOfMarks]
			   ,c.[HSCBiologyMarks]
			   ,c.[HSCBiologyOutOfMarks]
			   ,c.[PCMMarks]
			   ,c.[PCBMarks]
			   ,c.[JEERollNo]
			   ,c.[JEEMeritNo]
			   ,c.[JEEMeritMarks]
			   ,c.[JEEOutOfMarks]
			   ,c.[DiplomaBoard]
			   ,c.[DiplomaCollege]
			   ,c.[DiplomaPassingYear]
			   ,c.[DiplomaObtainMarks]
			   ,c.[DiplomaOutOfMarks]
			   ,c.[DiplomaPercentage]
			   --,c.[ApplicationNo]
			   --,c.[AdmissionRound]
			   --,c.[MaritalStatusId]


			FROM sStudent.vStudentName  as s
				LEFT JOIN sStudent.tCollegeDetail as c on s.StudentId=c.StudentId
				LEFT JOIN sSetup.vBatchClass as b on b.ClassId=s.ClassId and b.BatchId=s.BatchId  and s.OrgId=b.OrgId	
				LEFT JOIN sSetup.tDivisionMaster as d on d.Id=s.DivisionId  and d.OrgId=s.OrgId and d.ClassId=s.ClassId
				LEFT JOIN [sStudent].[tStudentAdmission] AS SA ON SA.StudentId = s.StudentId --Added for mantis 35404 : by Nilesh
			WHERE (s.ClassId = @rClassId) 
				AND ((s.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
				AND (s.BatchId = @rBatchId)
				and s.StudentId in (SELECt StudentId FROM @StudentIdTable)

    --ORDER BY 1 DESC --Commented for mantis 35404 : by Nilesh
	ORDER BY s.Code ASC--Added for mantis 35404 : by Nilesh
END
GO
PRINT N'Altering Procedure [sAlert].[pResultGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pResultGet]
	 	 
 	 @rBatchId int,
 	 @rClassId int,
 	 @rDivisionId int,
 	 @rOrgId int,
 	 @rTemplate nvarchar(max),
 	 @rExamId int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ExamName]',ES.Title),
			'[TotalMarks]',CONVERT(int,TotalMarks)),
			'[ObtainMarks]',CONVERT(int,TotalObtain)),
			'[ResultStatus]',R.ResultStatus),
			'[ResultGrade]',R.ResultGrade),
			'[ResultGradePoint]',R.ResultGradePoint),
			'[RankNumber]',R.RankNumber),
			'[Percentage]',R.Percentage),
			'[Percentile]',R.Percentile),
			'[ExamRemark3]',ISNULL(E.Remark3,''))	-- MantisId : 0034978
			 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,
			 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].[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 [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

		

	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(SR.ExamSeatNo,'') AS ExamSeatNo 
	--Mantis End - 35312



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
Order By SF.RollNo,CS.OrderIndex,T.ExamDate Desc



DROP TABLE #tempProgressCard

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


GO

ALTER PROCEDURE [sAssessment].[pRptProgressCardSubjectWiseDetailsGet]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int=0,
	 @rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	--Select
	--	'' AS Builder1,
	--	'' AS Builder2,
	--	'' AS AcademicIdText,
	--	'' Code,
	--	'' AS Name,
	--		0 AS RollNo,
	--	Convert(BigInt,0) AcademicId,			
	--	'' ResultStatus,
	--	'' AS Class,
	--	'' AS Division,
	--  0 AS ExamId,
	--	'' AS ExamName,
	--  Convert(Date,null) AS ExamDate,
	--		Convert(Decimal,0) TotalMark,
	--	Convert(Decimal,0) TotalObtain,
	--	0 AS RankNumber,
	--	Convert(Decimal,0) Percentage,
	--	'' AS ResultGrade,
	--	Convert(Decimal,0) Percentile,
	--	Convert(BigInt,0) ResultDetailId,		
	--	Convert(Bit,0) IsDisplayInMarksheet,
	--	Convert(Bit,0) IsShowSubjectGrade,
	--	Convert(Bit,0) IsIncludeInTotal,
	--	Convert(Decimal,0) AS SubjectObtain,
	--  '' AS SubjectGrade,
	--	Convert(Decimal,0) AS SubjectMinimum,
	--	Convert(Decimal,0) AS SubjectMaximum,
	--		'' AS SubjectCode,
	--	'' AS SubjectName,
	--	0 AS SubjectOrderIndex,
	--	Convert(BigInt,0) AS ResultId,
	--	0 AS SubjectId,			 	
	--	Convert(Bit,0) IsMarksInDecimal,		
	--	'' AS Remark1,
	--	'' AS Remark2,
	--	'' AS Remark3,
	--	'' AS DisplayTitle,
	--	Convert(Bit,0) IsRankNo, 
	--	Convert(Bit,0) IsGrade,
	--	Convert(Bit,0) IsPercentile,
	--	Convert(Bit,0) IsPercentage,
	--	Convert(Bit,0) IsSubjectPercentile,
	--	Convert(Bit,0) IsProcessResult,			 
	--	Convert(Bit,0) IsNegativeMarks,
	--	Convert(Bit,0) IsIncludeCoScholastic,
	--	Convert(Bit,0) IsOnPrePrinted,
	--	Convert(Bit,0) IsDisplayPhoto,
	--	Convert(Bit,0) IsDisplayBirthDate,
	--	Convert(Bit,0) IsLockForEdit,
	--	Convert(Bit,0) IsDisplaySchoolName,			
	--	Convert(Bit,0) IsDisplayAttendance,
	--	Convert(Bit,0) IsDisplayHeightWeight,
	--	Convert(Bit,0) IsResultStatus,
	--  '' AS IsDisplayMonthlyAttendanceText,
	--  Convert(Bit,0) IsDisplayMonthlyAttendance,
	--	'' AS FooterAdjustmentText,
	--	'' AS DetailAdjustmentText,
	--	0 AS FooterAdjustment,
	--	0 AS DetailAdjustment,		 		 		 
	--	Convert(Bit,0) IsPresent,			
	--	'' SmallAddress1,
	--	Convert(Bit,0) IsDisplayParentName,				
	--	Convert(Bit,0) AS IsShowSubjectMark,			
	--	Convert(Bit,0) IsDisplayTeacherSign,
	--	Convert(Bit,0) IsDisplayPrincipalSign,		 			 
	--	Convert(Bit,0) AS IsImageHeader,			 
	--	'' AS DecimalFormat,	 			 
	--	'' AS FatherName,
	--	'' AS MotherName,
	--  0 AS SubjectCount,
	--  Convert(Decimal,0) AS TotalDays,
	--  Convert(Decimal,0) AS PresentDays

CREATE TABLE #TempExam
(
    Id int IDENTITY(1,1) PRIMARY KEY,
    ExamId int,
    Exam nvarchar(100)
)

INSERT INTO #TempExam
(
	 ExamId,
	 Exam 	
)

SELECT 
@rExamId AS ExamId,
ESGM.Title AS Exam
FROM [sAssessment].[tExamMaster] EM 
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId 
WHERE EM.ClassId=@rClassId AND EM.BatchId =@rBatchId AND EM.Id = @rExamId

UNION ALL

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

UNION ALL 

SELECT
EM.Id AS ExamId,
ESGM.Title AS Exam
FROM [sAssessment].[tExamMaster] EM 
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId 
INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId IN (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId)  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId

CREATE TABLE #TempSubjectCount(
ExamId int,
AcademicId BigInt,
SubjectCount int
)
INSERT INTO #TempSubjectCount(ExamId, AcademicId, SubjectCount)
    SELECT R.ExamId, R.AcademicId, COUNT(RD.Id) AS SubjectCount
    FROM sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
    INNER JOIN #TempExam TE ON TE.ExamId = R.ExamId
    GROUP BY R.ExamId,R.AcademicId

--select * from #TempExam
	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			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,
			EC.ExamId,
			EC.Exam AS ExamName,
			ED.ExamDate,
			R.TotalMarks AS TotalMark,
			R.TotalObtain,
			R.RankNumber,
			R.Percentage,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			RD.SubjectGrade,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			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.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,		 		 		 
			RD.IsPresent,	
			OM.SmallAddress1,
			EM.IsDisplayParentName,			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,		 		 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,			 
			EM.DecimalFormat,						 
			SF.FatherName,
			SF.MotherName,
			TSC.SubjectCount AS SubjectCount,
			--start mantis : 0035105
			ISNULL(SR.TotalDays,0) AS TotalDays, 
			ISNULL(SR.PresentDays,0) AS PresentDays
			--end mantis : 0035105
						
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.ExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND  SR.ExamId=EC.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			INNER JOIN #TempSubjectCount TSC ON TSC.ExamId = EM.Id  AND TSC.AcademicId = A.Id 
			
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))

	ORDER BY A.RollNo , EC.Id
		
	 DROP TABLE #TempExam
	 DROP TABLE #TempSubjectCount
	 
END
GO
PRINT N'Altering Procedure [sBiometric].[pBiometricStudentAttendanceGet]...';


GO
ALTER PROCEDURE [sBiometric].[pBiometricStudentAttendanceGet]
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rAttendanceDate date,
		-- @rRepeatCount tinyint,
	 	 @rBatchId int,
	 	 @rOrgId int,
		 @TimeSheetStatusId nvarchar(10) = '0'
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lMonth as nvarchar(3)
DECLARE @lYear as nvarchar(4)
  BEGIN
	Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@rAttendanceDate) AS varchar(2)), 2)
	Select @lMonth = RIGHT('00' + CAST(DATEPART(MM,@rAttendanceDate) AS varchar(2)), 2)
	Select @lYear  = RIGHT('0000' + CAST(DATEPART(yyyy,@rAttendanceDate) AS varchar(4)), 4)

	set @strQuery ='Select SA.AcademicId AS AcademicId,SA.Code AS StudentCode,SA.Name AS StudentName,ISNULL(SA.RollNo,0) as RollNo,ISNULL(SR.IsPresent,''true'') as IsPresent,
					ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,SR.RepeatCount,CASE WHEN SR.CreatedUserId IS NULL THEN cast(0 as bit) ELSE cast(1 as bit) END AS IsDeleted,ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
					ISNULL(D'+convert(nvarchar(15),@lDay)+'_IN,''00:00'') AS FirstIn,ISNULL(D'+convert(nvarchar(15),@lDay)+'_Out,''00:00'') AS LastOut,ISNULL(D'+convert(nvarchar(15),@lDay)+'_L,''00:00'') AS LateBy,
					ISNULL(D'+convert(nvarchar(15),@lDay)+'_E,''00:00'') AS EarlyBy, ISNULL(D'+convert(nvarchar(15),@lDay)+'_T,''00:00'') AS Duration,ISNULL(D'+convert(nvarchar(15),@lDay)+',''XX'') AS PresentStatus 
					From sStudent.vStudentAcademic SA 
					--Mantis:32909, change in below left join, change from SA.StudentId to SA.AcademicId
					LEFT JOIN sBiometric.tMonthTrans T1 ON SA.AcademicId = T1.EmployeeId AND T1.SourceTypeId=2001 AND ATTN_DT = cast(rtrim(YEAR(''' + convert(nvarchar(15),@rAttendanceDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@rAttendanceDate) + ''') *100+ 01


)
 as datetime)
					LEFT JOIN sAttendance.tStudentRegister SR  ON SR.AcademicId=SA.AcademicId AND SR.AttendanceDate ='''+convert(nvarchar(15),@rAttendanceDate)+''' AND  (SR.AttendanceTypeId='+convert(nvarchar(15),@rAttendanceTypeId)+')
					INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
				WHERE 
					((SA.ClassId='+convert(nvarchar(15),@rClassId)+') OR ('+convert(nvarchar(15),@rClassId)+'=0))
					  AND ((SA.DivisionId='+convert(nvarchar(15),@rDivisionId)+') OR ('+convert(nvarchar(15),@rDivisionId)+'=0))
					  AND (SA.OrgId = '+convert(nvarchar(15),@rOrgId)+')
					  AND (SA.BatchId = '+convert(nvarchar(15),@rBatchId)+')
					  AND (SA.StatusId NOT IN (2,3))
					  AND (AD.LeftDate > '''+convert(nvarchar(15),@rAttendanceDate)+''' OR ISNULL(AD.LeftDate,'''')= '''')
					  AND (AD.AdmissionDate <= '''+convert(nvarchar(15),@rAttendanceDate)+''')
					AND  (( '''+convert(nvarchar(15),@TimeSheetStatusId)+''' = ''1'' AND (ISNULL(D'+convert(nvarchar(15),@lDay)+'_T,''00:00'') < ''09:30'')) OR ( '''+convert(nvarchar(15),@TimeSheetStatusId)+'''  != ''1'' AND ((ISNULL(D'+convert(nvarchar(15),@lDay)+',''X



X'') = '''+convert(nvarchar(15),@TimeSheetStatusId)+'''  OR '''+convert(nvarchar(15),@TimeSheetStatusId)+''' =''0''))))
				ORDER BY SA.RollNo'
	execute (@strQuery )
	--print @strQuery
  END
END
GO
PRINT N'Altering Procedure [sCanteen].[pDailyMenuListGet]...';


GO


ALTER PROCEDURE [sCanteen].[pDailyMenuListGet]
		
	 	@rBreakTypeId int,
	 	@rCanteenId int,
	 	@rMenuYear smallint,
	 	@rMenuMonth int,
		@rMenuDate date ='',
		@rClassId int=0

			 		 		 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT 
			DM.Id AS MenuItemId,
			DM.MenuDate,
			Datename(weekday, DM.MenuDate) AS Days,
			Dm.BreakTypeId,
			BTM.Title AS BreakType,
			DM.Title AS Title,
			Dm.MenuItems,
			DM.MenuMonth,
			DM.MenuYear,
			DM.CanteenId,
			ISNULL(CM.Code,'') AS ClassName
	 FROM  
			sCanteen.tDailyMenu DM 
		
		   INNER JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  DM.BreakTypeId 
		   LEFT JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
						    			
  WHERE 
		((DM.BreakTypeId=@rBreakTypeId) OR (@rBreakTypeId=0))
		AND  ((DM.CanteenId=@rCanteenId) OR (@rCanteenId=0))
		AND ((DM.MenuYear = @rMenuYear) OR (@rMenuYear=''))
		AND ((DM.MenuMonth = @rMenuMonth) OR (@rMenuMonth=''))
		AND   ((DM.MenuDate>dateadd(d, - DATEPART(dw, @rMenuDate), @rMenuDate))  OR (@rMenuDate=''))
		AND  ((DM.MenuDate<=dateadd(d, 7-DATEPART(dw, @rMenuDate), @rMenuDate))  OR (@rMenuDate=''))
		AND ((ISNULL(DM.ClassId,0) = @rClassId))
		AND BTM.IsObsolete = 0 --Added for mantis : 35301 by Nilesh
	 	
      ORDER BY DM.MenuDate,BTM.OrderIndex ASC --Added for mantis : 35301 by Nilesh
END
GO
PRINT N'Altering Procedure [sCertificate].[pLeavingGet]...';


GO
 
ALTER PROCEDURE [sCertificate].[pLeavingGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(20),
	 @rName nvarchar(200),
	 @rFromNo int,
	 @rToNo int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromDate date,
	 @rToDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rName = sCommon.fSearchStringGet(@rName)
			
		END
	
	SELECT 
	
			L.Id,
			L.AcademicId,
			SA.Code,
			SA.Name,
			SA.ClassName+'-'+SA.DivisionName as ClassDivision,
			L.LCNumber,
			L.LCDate,
			L.LeftDate,
			L.LCCopy,
			L.LCRemark,
			L.LCProgress,
			L.LCConduct,
			L.LCReason,
			L.LCBookNumber,
			L.ToCollege,
			L.ToCollegeAddress
			,L.LastExamName 
		    ,L.LastExamResult 
		    ,L.RepeatDetail 
		    ,L.SubjectStudied
		    ,L.PromoteToClass 
		    ,L.FeeDetail 
		    ,L.FeeConcessionDetail
		    ,L.ExtraCurricularActivities
		    ,L.NCCScoutDetail 
		    ,L.TermsInInstitute
			,ISNULL(L.TotalDays,0)AS TotalDays
			,ISNULL(L.PresentDays,0) AS PresentDays
			,StuA.ProofOfDOB
			,ISNULL(L.LCCopyRemark,'') AS LCCopyRemark
			--Added by Dhananjay for mantis Start - 0034457
			,ISNULL(CM.ClassNameInWord,'') AS ClassNameInWord 
			, ISNULL(SA.BatchName,'') AS BatchName
			,ISNULL(AD.TotalDaysAnnual,0) As TotalDaysAnnual
			,ISNULL(AD.PresentDaysAnnual,0) As PresentDaysAnnual
			--Added by Dhananjay for mantis End - 0034457
			,SA.StatusId 
			,SA.StatusName  --Added by Nityanand for mantis End- 34985
			
  FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=L.AcademicId
			AND SA.OrgId=@rOrgId AND SA.BatchId=@rBatchId
			LEFT JOIN sStudent.tStudentAdmission StuA ON StuA.StudentId = SA.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId AND CM.OrgId = SA.OrgId   --mantis - 0034457
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = L.AcademicId --mantis - 0034457

			
  WHERE 
			((L.Id = @rId) OR (@rId = 0))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId =@rDivisionId) OR (@rDivisionId = 0))
			AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
			AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((L.LCNumber >= @rFromNo) OR (@rFromNo = 0))
			AND ((L.LCNumber <= @rToNo) OR (@rToNo = 0))
		
			ORDER BY L.LCNumber
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
	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 [sFee].[pFeeConsolidateDashBoardGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeConsolidateDashBoardGet]
		
	@rType nvarchar(100)='',
	@rCount int =0 ,
	@rDivisionId int  =0,
	@rClassId int  =0,
	@rOrgId int  =0,
	@rOrgGroupId int=0,
	@rOrgGroupBatchId int  =0,
	@rCollectionGroupId int =0,
	@rReceiptBookId int =0,
	@rDays int=0,
	@rCommonOrgGroupBatchId int=0,
	@rFromDate varchar(10)='',
	@rToDate varchar(10)='',
	@rMonth int =0,
	@rSyncDate int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

IF(@rType ='FeeStatusOrganization')
	BEGIN 
	IF(@rSyncDate =1)
		BEGIN
			DELETE  sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				
				CREATE TABLE #tempOrganizationSync(
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrgGroupName nvarchar(200),
				OrgGroupId int
				)
				INSERT INTO #tempOrganizationSync
					SELECT 
						SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
						O.Title AS OrgGroupName,
						O.Id AS OrgGroupId
					FROM 
						sStudent.tAcademic SA
						INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
						INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
						INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.ID = SA.OrgId
						
					WHERE	
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  And ISNULL(O.IsObsolete,0) = 0
						  AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
						  --AND SM.StatusId=1
						  -- IsInContext
						  AND BM.IsInContext = 1
					GROUP BY  o.Id,o.Title

					IF EXISTS (SELECT 1 FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId)
						BEGIN							
						IF(@rOrgGroupId !=0)
							INSERT INTO sFee.tTempOrgGroupFeeStatus
							SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
							ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganizationSync T
							SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
						END
					ELSE
						BEGIN						
						INSERT INTO sFee.tTempOrgGroupFeeStatus
							SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
							ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganizationSync T
							SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
						END
				
				DROP TABLE #tempOrganizationSync			
		END
	ELSE
		BEGIN

			IF  Exists(select 1 from sFee.tTempOrgGroupFeeStatus where CONVERT(date,UpdatedDateTime) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))) 
			BEGIN
	
				SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN
			DELETE  sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempOrganization(
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrgGroupName nvarchar(200),
				OrgGroupId int
				)
			INSERT INTO #tempOrganization
					SELECT 
						SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
						O.Title AS OrgGroupName,
						O.Id AS OrgGroupId
					FROM 
						sStudent.tAcademic SA
						INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
						INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
						INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.ID = SA.OrgId
						
					WHERE	
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  And ISNULL(O.IsObsolete,0) = 0
						  AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
						  -- IsInContext
						  AND BM.IsInContext = 1
					GROUP BY  o.Id,o.Title

						
				IF EXISTS (SELECT 1 FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId)
					BEGIN
						
					IF(@rOrgGroupId !=0)
						INSERT INTO sFee.tTempOrgGroupFeeStatus
						SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganization  T
						SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					END
				ELSE
					BEGIN
					
					INSERT INTO sFee.tTempOrgGroupFeeStatus
						SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganization  T
						SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					END 
					
				DROP TABLE #tempOrganization
			END
		END
		
	
	END
ELSE IF(@rType = 'FeeStatusPaid&UnpaidDetilsClassWise')
	BEGIN 
	IF(@rCount = 1)
	BEGIN

	CREATE TABLE #tempPaidDetailsClassWise(
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	ClassId int,
	ClassName nvarchar(50),
	PaidAmount DECIMAL(12,0),
	StudentCount int
	)
  
	INSERT INTO #tempPaidDetailsClassWise
	SELECT 
		 ISNULL(O.Id,0) AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 ISNULL(SA.ClassId,0)AS ClassId,
		 ISNULL(SA.ClassName,'') AS ClassName,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 COUNT(Distinct(SA.AcademicId)) as StudentCount
	FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
	WHERE
		(O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND
		((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0 AND FAS.PaidAmount > 0
		-- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName
	 

		SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount,T.StudentCount
		FROM #tempPaidDetailsClassWise T
		WHERE T.PaidAmount > 0
			 
	DROP TABLE #tempPaidDetailsClassWise
 
	END
	ELSE IF(@rCount = 2)
	BEGIN

	CREATE TABLE #tempPendingDetailsClassWise(
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	ClassId int,
	ClassName nvarchar(50),
	PendingAmount DECIMAL(12,0) 
	)
 
	INSERT INTO #tempPendingDetailsClassWise
	SELECT 
		 ISNULL(SA.AcademicId,0) AS AcademicId,
		 ISNULL(O.Id,0) AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 ISNULL(SA.ClassId,0)AS ClassId,
		 ISNULL(SA.ClassName,'') AS ClassName,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
	FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
	WHERE
		(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0 AND FAS.ToPayAmount > 0.00 --AND SA.StatusId=1
		-- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName,SA.AcademicId

		SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS UnPaidAmount,COUNT(T.PendingAmount)AS StudentCount
		FROM #tempPendingDetailsClassWise T
		--WHERE T.PendingAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.ClassId,T.OrgGroupName
		HAVING ISNULL(SUM(T.PendingAmount),0) > 0
        ORDER BY T.ClassId
	 
	DROP TABLE #tempPendingDetailsClassWise
 
	END
	END
ELSE IF(@rType ='FeeStatusPaid&UnpaidDetils')
BEGIN 

	IF(@rCount = 1)
	BEGIN
		CREATE TABLE #tempPaidDetails(
			SourceId bigint,
			OrgGroupId int,
			ClassName nvarchar(50),
			DivisionId int,
			DivisionName nvarchar(50),
			Code nvarchar(20),
			Name nvarchar(200),
			ParentContactNo nvarchar(50),
			PaidAmount DECIMAL(12,0),
			ClassOrderIndex int,
			DivisionOrder int,
			RollNo int
		)
		INSERT INTO #tempPaidDetails
		SELECT 
				ISNULL(SA.AcademicId,0) AS SourceId,
				ISNULL(O.Id,0) AS OrgGroupId,
				ISNULL(SA.ClassName,'') AS ClassName,
				ISNULL(SA.DivisionId,0) AS DivisionId,
				ISNULL(SA.DivisionName,'') AS DivisionName,
				ISNULL(SA.Code,'') As Code,
				ISNULL(SA.Name,'') AS Name,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
				SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
				 SA.ClassOrderIndex,  
				 SA.DivisionOrder,
				 SA.RollNo 
			FROM 		
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
			    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
		 WHERE
				(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND((SA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				And ISNULL(O.IsObsolete,0) = 0
				AND FAS.PaidAmount > 0
				-- IsInContext
				AND BM.IsInContext = 1
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FAS.PaidAmount,0)) >0
		ORDER BY O.Id,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo

		SELECT T.SourceId, T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,T.DivisionId,
			T.ParentContactNo AS ParentContactNo,T.PaidAmount AS PaidAmount,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
		FROM #tempPaidDetails T
		WHERE T.PaidAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.Name,T.ParentContactNo,T.PaidAmount,T.Code,T.ClassOrderIndex,T.DivisionOrder,T.RollNo,T.DivisionId,T.SourceId
		HAVING T.PaidAmount > 0
		ORDER BY T.OrgGroupId,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
	END
	ELSE IF(@rCount = 2)
	BEGIN
		CREATE TABLE #tempPendingDetails(
			SourceId bigint,
			OrgGroupId int,
			ClassName nvarchar(50),
			DivisionId int,
			DivisionName nvarchar(50),
			Code nvarchar(20),
			Name nvarchar(200),
			ParentContactNo nvarchar(50),
			PendingAmount DECIMAL(12,0),
			ClassOrderIndex int,
			DivisionOrder int,
			RollNo int
		)
		INSERT INTO #tempPendingDetails
		SELECT 
				ISNULL(SA.AcademicId,0) AS SourceId,
				ISNULL(O.Id,0) AS OrgGroupId,
				ISNULL(SA.ClassName,'') AS ClassName,
				ISNULL(SA.DivisionId,0) AS DivisionId,
				ISNULL(SA.DivisionName,'') AS DivisionName,
				ISNULL(SA.Code,'') As Code,
				ISNULL(SA.Name,'') AS Name,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
				SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
				SA.ClassOrderIndex,  
				SA.DivisionOrder,
				SA.RollNo 
			FROM 		
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId
			    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
		 WHERE
				(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND((SA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				And ISNULL(O.IsObsolete,0) = 0 AND FAS.ToPayAmount > 0.00 --AND SA.StatusId=1
				-- IsInContext
				AND BM.IsInContext = 1
				
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		ORDER BY O.Id,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo

		SELECT T.SourceId, T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,T.DivisionId,
			T.ParentContactNo AS ParentContactNo,T.PendingAmount AS UnPaidAmount,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
		FROM #tempPendingDetails T
		WHERE T.PendingAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.Name,T.ParentContactNo,T.PendingAmount,T.Code,T.ClassOrderIndex,T.DivisionOrder,T.RollNo,T.DivisionId,T.SourceId
		HAVING T.PendingAmount > 0
		ORDER BY T.OrgGroupId,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
	END
END

ELSE IF(@rType ='FeeStatusTotalHeadwiseAmount')
BEGIN 
	IF(@rSyncDate =1)
		BEGIN
		DELETE  sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempTotalPaidDetailsSync (
				FeeHeadId bigint,
				FeeHeadName nvarchar(200),
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				ReceiptBookId bigint,
				RecepitTitle nvarchar(100),
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrderIndex int
			)
			 
			INSERT INTO #tempTotalPaidDetailsSync
			SELECT 
				ISNULL(FHM.Id,0) AS FeeHeadId,
				ISNULL(FHM.code,'') AS FeeHeadName,
				ISNULL(CGM.Id,0) AS CollectionGroupId,
				ISNULL(CGM.Code,'') AS CollectionGroup,
				ISNULL(RBM.Id,'')  AS ReceiptBookId,
				ISNULL(RBM.Title,'')  AS ReceiptTitle,
				SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
				SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
				FHM.OrderIndex
			FROM 
				sStudent.tAcademic SA
				INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			 And ISNULL(O.IsObsolete,0) = 0
			 -- IsInContext
				AND BM.IsInContext = 1
			GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Code,RBM.Title,RBM.Id,FHM.OrderIndex

			INSERT INTO sFee.tTempTotalPaidDetails
			SELECT @rOrgGroupId,T.FeeHeadId,ISNULL(T.FeeHeadName,'') AS FeeHeadName,T.CollectionGroupId,
						ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,
						T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
						ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
						T.OrderIndex,@rCommonOrgGroupBatchId,GETDATE() from #tempTotalPaidDetailsSync T
			GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId,T.OrderIndex
			ORDER BY T.OrderIndex

			SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))		

		--New Temp Table Create-------------
			CREATE TABLE #tempTotalStudentCountSync (
			AcademicId bigint,
			CollectionGroupId bigint,
			CollectionGroup nvarchar(200),
			RecepitTitle nvarchar(100),
			ReceiptBookId bigint,
			EndDate date,
			PaidAmount DECIMAL(12,0),
			PendingAmount DECIMAL(12,0)
			)
	
			--Test
	 
			INSERT INTO #tempTotalStudentCountSync
			SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
					INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					 ORDER BY ReceiptDate DESC) EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA
				INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
		        INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id 
				INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 And ISNULL(O.IsObsolete,0) = 0
			 AND COGBM.Id=@rCommonOrgGroupBatchId 
			 -- IsInContext
				AND BM.IsInContext = 1
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	
			INSERT INTO sFee.tTempTotalStudentCount
			SELECT @rOrgGroupId,E.CollectionGroupId,E.CollectionGroup AS CollectionGroup,E.ReceiptBookId AS ReceiptId,E.ReceiptCollection AS ReceiptCollection,
					ISNULL(E.EndDate,'1900-01-01')AS EndDate,
					--E.EndDate AS EndDate,
					SUM(E.TotalStudentCount) AS TotalStudentCount,SUM(E.PaidStudentCount) AS PaidStudentCount,SUM(E.PendingStudentCount) AS PendingStudentCount,@rCommonOrgGroupBatchId,GETDATE() FROM (
			SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(T.CollectionGroup,'') As CollectionGroup,
				ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,T.CollectionGroupId AS CollectionGroupId,
				ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate from #tempTotalStudentCountSync T
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM #tempTotalStudentCountSync --CollectionGroupId,CollectionGroup,
						WHERE PendingAmount  = 0
						GROUP BY CollectionGroupId,ReceiptBookId
					) A ON A.CollectionGroupId = T.CollectionGroupId
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM #tempTotalStudentCountSync
						WHERE PendingAmount !=0
						GROUP BY CollectionGroupId,ReceiptBookId
					)B ON B.CollectionGroupId = T.CollectionGroupId 
					GROUP BY T.CollectionGroupId,T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
					)E
					GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate,E.CollectionGroupId
		
		 SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	


		-------------Create a New Temp Table For Pending date-----------------
			CREATE TABLE #tempPendingCountSync(
			AcademicId bigint,
			CollectionGroupId bigint,
			CollectionGroup nvarchar(200),
			RecepitTitle nvarchar(100),
			ReceiptBookId bigint,
			EndDate date,
			PaidAmount DECIMAL(12,0),
			PendingAmount DECIMAL(12,0)
			)
	 
			DECLARE @lLastReceiptDate datetime
			SET @lLastReceiptDate = (SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
							INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
							INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=R.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id 
							INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE  
							(LEFT(R.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
							AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
							And ISNULL(O.IsObsolete,0) = 0
							-- IsInContext
						AND BM.IsInContext = 1
					ORDER BY ReceiptDate DESC)

			INSERT INTO #tempPendingCountSync
			SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					@lLastReceiptDate AS EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA
				INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 And ISNULL(O.IsObsolete,0) = 0
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
			 -- IsInContext
				AND BM.IsInContext = 1
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate

			INSERT INTO sFee.tTempPendingCount
			SELECT @rOrgGroupId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,T.ReceiptBookId AS ReceiptId,
						T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount,@rCommonOrgGroupBatchId,GETDATE()
			FROM   #tempPendingCountSync T
			WHERE PendingAmount !=0
			 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()- @rDays) AND CONVERT(DATE,GETDATE())
			GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup

			SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	 
			DROP TABLE #tempTotalPaidDetailsSync
			DROP TABLE #tempTotalStudentCountSync
			DROP TABLE #tempPendingCountSync

		END
	ELSE
		BEGIN
		IF  Exists(select 1 from sFee.tTempTotalPaidDetails where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
			BEGIN
	
				SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN

			DELETE  sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			DELETE  sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			DELETE  sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempTotalPaidDetails (
				FeeHeadId bigint,
				FeeHeadName nvarchar(200),
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				ReceiptBookId bigint,
				RecepitTitle nvarchar(100),
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrderIndex int
				)
			
				INSERT INTO #tempTotalPaidDetails
				SELECT 
					ISNULL(FHM.Id,0) AS FeeHeadId,
					ISNULL(FHM.code,'') AS FeeHeadName,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Id,'')  AS ReceiptBookId,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
					FHM.OrderIndex
				FROM 
					sStudent.tAcademic SA
					INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
					INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				 And ISNULL(O.IsObsolete,0) = 0
				 -- IsInContext
				AND BM.IsInContext = 1
				GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Code,RBM.Title,RBM.Id,FHM.OrderIndex

			INSERT INTO sFee.tTempTotalPaidDetails
				SELECT @rOrgGroupId,T.FeeHeadId,ISNULL(T.FeeHeadName,'') AS FeeHeadName,T.CollectionGroupId,
				ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
				ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
				ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
				T.OrderIndex,@rCommonOrgGroupBatchId,GETDATE()from #tempTotalPaidDetails T
				GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId,T.OrderIndex
				ORDER BY T.OrderIndex

			SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	

					--New Temp Table Create-------------
				CREATE TABLE #tempTotalStudentCount (
				AcademicId bigint,
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				RecepitTitle nvarchar(100),
				ReceiptBookId bigint,
				EndDate date,
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0)
				)
	
				--Test
	
				INSERT INTO #tempTotalStudentCount
				SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
					INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					 ORDER BY ReceiptDate DESC) EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
				FROM 
					sStudent.tAcademic SA
					INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id 
					INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				 And ISNULL(O.IsObsolete,0) = 0
				 AND COGBM.Id=@rCommonOrgGroupBatchId 
				 -- IsInContext
				AND BM.IsInContext = 1
				GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	
			INSERT INTO sFee.tTempTotalStudentCount
			SELECT @rOrgGroupId,E.CollectionGroupId,E.CollectionGroup AS CollectionGroup,E.ReceiptBookId AS ReceiptId,E.ReceiptCollection AS ReceiptCollection,
					ISNULL(E.EndDate,'1900-01-01')AS EndDate,
					--E.EndDate AS EndDate,
					SUM(E.TotalStudentCount) AS TotalStudentCount,SUM(E.PaidStudentCount) AS PaidStudentCount,SUM(E.PendingStudentCount) AS PendingStudentCount,@rCommonOrgGroupBatchId,GETDATE() FROM (
			SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(T.CollectionGroup,'') As CollectionGroup,
				ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,T.CollectionGroupId AS CollectionGroupId,
				ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate from #tempTotalStudentCount T
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM #tempTotalStudentCount --CollectionGroupId,CollectionGroup,
						WHERE PendingAmount  = 0
						GROUP BY CollectionGroupId,ReceiptBookId
					) A ON A.CollectionGroupId = T.CollectionGroupId
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM #tempTotalStudentCount
						WHERE PendingAmount !=0
						GROUP BY CollectionGroupId,ReceiptBookId
					)B ON B.CollectionGroupId = T.CollectionGroupId 
					GROUP BY T.CollectionGroupId,T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
					)E
					GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate,E.CollectionGroupId
				 
				 SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

					-------------Create a New Temp Table For Pending date-----------------
				CREATE TABLE #tempPendingCount(
				AcademicId bigint,
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				RecepitTitle nvarchar(100),
				ReceiptBookId bigint,
				EndDate date,
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0)
				)
				
				INSERT INTO #tempPendingCount
				SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
						(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
					INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id 
					INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
			  WHERE  
					(LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
					AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
					And ISNULL(O.IsObsolete,0) = 0
					-- IsInContext
				AND BM.IsInContext = 1
			  ORDER BY ReceiptDate DESC) EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA
				INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 And ISNULL(O.IsObsolete,0) = 0
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
			 -- IsInContext
				AND BM.IsInContext = 1
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
		
		INSERT INTO sFee.tTempPendingCount
				SELECT @rOrgGroupId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,T.ReceiptBookId AS ReceiptId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount,@rCommonOrgGroupBatchId,GETDATE()
				FROM   #tempPendingCount T
				WHERE PendingAmount !=0
				 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()- @rDays) AND CONVERT(DATE,GETDATE())
				 GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup
		SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	
				DROP TABLE #tempTotalPaidDetails
				DROP TABLE #tempTotalStudentCount
				DROP TABLE #tempPendingCount
			END
		END
END

ELSE IF(@rType ='FeeStatusPaidSubPartAmount')
BEGIN 
	CREATE TABLE #tempPaidSubPart (
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	ClassId bigint,
	ClassName nvarchar(50),
	--DivisionId bigint,
	--DivisionName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	ClassOrderIndex int,
	StudentCount int
	--,DivisionOrder int
	)
    
IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPaidSubPart
	SELECT 
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		 ISNULL(CGM.Id,0) AS CollectionGroupId,
		 ISNULL(CGM.Code,'') AS CollectionGroup,
		 ISNULL(RBM.Title,'')  AS ReceiptTitle,
		 ISNULL(RBM.Id,0) As ReceiptBookId,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		 SA.ClassOrderIndex,
		 COUNT(Distinct(FAS.AcademicId)) as StudentCount
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	    	
	WHERE
		(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
		And ISNULL(O.IsObsolete,0) = 0
		AND FAS.PaidAmount > 0
		-- IsInContext
		AND BM.IsInContext = 1
	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.ClassId,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	HAVING ISNULL(SUM(FAS.PaidAmount),0) > 0
	ORDER BY SA.ClassOrderIndex

		select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount, T.StudentCount AS StudentCount,
			ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex,
			'' as MonthName 
		from #tempPaidSubPart T
		 

	END 
	ELSE 
	BEGIN
	INSERT INTO #tempPaidSubPart
		
	SELECT 
		 SA.OrgId AS OrgGroupId,SA.OrganizationName As OrgGroupName,
		 SA.ClassId As ClassId,
		 SA.ClassName AS ClassName,
		 ISNULL(CGM.Id,0) AS CollectionGroupId,
		 ISNULL(CGM.Code,'') AS CollectionGroup,
		 ISNULL(RBM.Title,'')  AS ReceiptTitle,
		 ISNULL(RBM.Id,0) As ReceiptBookId,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		 SA.ClassOrderIndex,
		 COUNT(Distinct(FAS.AcademicId)) as StudentCount
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
		 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
		 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
		 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		 And ISNULL(O.IsObsolete,0) = 0
		 AND FAS.PaidAmount > 0
		 -- IsInContext
		AND BM.IsInContext = 1
    GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.ClassId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	HAVING ISNULL(SUM(FAS.PaidAmount),0) > 0
	ORDER BY SA.ClassOrderIndex

	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount,T.StudentCount As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex,
		'' as MonthName 
		from #tempPaidSubPart T
	END
	
	DROP TABLE #tempPaidSubPart

END

ELSE IF(@rType ='FeeStatusPaidSubPartAmountMonthWise')
BEGIN 
	CREATE TABLE #tempPaidSubPartMonthWise (
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	MonthName nvarchar(15),
	)
   
    CREATE TABLE #tempPFSMonthWise (
       Id INT,
       Amount DECIMAL(12,0),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    
    INSERT INTO #tempPFSMonthWise	
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
	   (FS1.IsOptional=0)
	   --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0
		-- IsInContext
		AND BM.IsInContext = 1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate   
		--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='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		-- IsInContext
		AND BM.IsInContext = 1
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))


     CREATE TABLE #tempPRMonthWise (
         PaidAmount DECIMAL(12,0),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPRMonthWise	
     SELECT 
		  ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 FROM
		  sFee.tReceipt R 
		  INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		  INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		  INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		  INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
		  INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		  INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		  
		  INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		 
	WHERE		
		  (R.SourceTypeId = 2001)
		   AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		   AND (R.IsObsolete = 0) --AND BM.IsActive=1 
		   AND COGBM.Id=@rCommonOrgGroupBatchId 
		   And ISNULL(O.IsObsolete,0) = 0
		   -- IsInContext
		AND BM.IsInContext = 1
		   --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
		   --AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
 

IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPaidSubPartMonthWise
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR.PaidAmount,0.00))AS PendingAmount,
		TPR.ReceiptDate		 
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN #tempPFSMonthWise TPFS ON TPFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=TPFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise TPR ON TPR.FeeSetupId = TPFS.Id AND SA.AcademicId = TPR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN sFee.tReceiptBookMaster RBM ON TPFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON TPFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=TPFS.FeeHeadId	    	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	And ISNULL(O.IsObsolete,0) = 0
	-- IsInContext
	AND BM.IsInContext = 1  
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.PaidAmount,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempPFSMonthWise1 (
       Id INT,
       Amount DECIMAL(12,0),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    INSERT INTO #tempPFSMonthWise1
    SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		 SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		 INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	     INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	     INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	     INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	     INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			 
		 INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		 --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		 AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		 And ISNULL(O.IsObsolete,0) = 0
		 -- IsInContext
	AND BM.IsInContext = 1  
		 --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='')
	UNION ALL
				
	SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		
	WHERE
				
		(FS1.IsOptional=1) AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0
		-- IsInContext
	AND BM.IsInContext = 1  
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
    
    CREATE TABLE #tempPRMonthWise1(
         PaidAmount DECIMAL(12,0),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPRMonthWise1
     SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		

	WHERE		
		(R.SourceTypeId = 2001)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		AND (R.IsObsolete = 0) 
		-- IsInContext
	AND BM.IsInContext = 1  
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate  
   
	
	INSERT INTO #tempPaidSubPartMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,		
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR1.PaidAmount,0.00))AS PendingAmount,
		TPR1.ReceiptDate
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPFSMonthWise1 TPFS1 ON TPFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TPFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise1 TPR1 ON TPR1.FeeSetupId = TPFS1.Id AND SA.AcademicId = TPR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TPFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TPFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TPFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	And ISNULL(O.IsObsolete,0) = 0
	-- IsInContext
		AND BM.IsInContext = 1
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR1.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount,COUNT(T.AcademicId) As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END
	
	DROP TABLE #tempPaidSubPartMonthWise
	DROP TABLE #tempPFSMonthWise
	DROP TABLE #tempPRMonthWise
	DROP TABLE #tempPFSMonthWise1
	DROP TABLE #tempPRMonthWise1
	
END

ELSE IF(@rType ='FeeStatusPendingSubPartAmount')
BEGIN 
CREATE TABLE #tempPendingSubPart(
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(100),
	ClassId bigint ,
	ClassName nvarchar(50),
	--DivisionId bigint,
	--DivisionName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	ClassOrderIndex int
	--,DivisionOrder int
	)

IF(@rCollectionGroupId = 0)
	BEGIN

	INSERT INTO #tempPendingSubPart
    SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId  AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex
	FROM 
		sStudent.vStudentAcademic SA 
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
		(FS.IsOptional=0)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) 
		And ISNULL(O.IsObsolete,0) = 0
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId = 0))
		-- IsInContext
		AND BM.IsInContext = 1
	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassId,SA.ClassName,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	
	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,COUNT(T.AcademicId)AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex from #tempPendingSubPart T
		WHERE T.PendingAmount >0
     group by T.OrgGroupId,T.OrgGroupName,T.ClassName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex
		ORDER BY T.ClassOrderIndex
		
    DROP TABLE #tempPendingSubPart
		
	END 
	ELSE 
	BEGIN
	
	INSERT INTO #tempPendingSubPart
	SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex  
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
		(FS.IsOptional=0)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) 
		And ISNULL(O.IsObsolete,0) = 0
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId = 0))
		-- IsInContext
		AND BM.IsInContext = 1
	 GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	
	SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex from #tempPendingSubPart T
	WHERE T.PendingAmount >0
	GROUP BY T.OrgGroupId,T.ClassName,T.OrgGroupName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex
	--HAVING ISNULL(SUM(T.PendingAmount),0) > 0
	ORDER BY T.ClassOrderIndex	
		
   
	   DROP TABLE #tempPendingSubPart
		
	END
	END

ELSE IF(@rType ='FeeStatusPendingSubPartDetails')
BEGIN 
CREATE TABLE #tempPendingSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
)

IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPendingSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And ISNULL(O.IsObsolete,0) = 0
	 -- IsInContext
		AND BM.IsInContext = 1
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
		select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
			ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPendingSubPartDetails T
		WHERE T.PendingAmount >0
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempPendingSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 And ISNULL(O.IsObsolete,0) = 0
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 -- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

		select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPendingSubPartDetails T
		WHERE T.PendingAmount >0
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.RollNo
		
		 
	END
	
	DROP TABLE #tempPendingSubPartDetails
	 
END	
	
ELSE IF(@rType ='FeeStatusTotalSubPartAmount')
BEGIN 
CREATE TABLE #tempTotalSubPart (
AcademicId bigint,
OrgGroupId int,
OrgGroupName nvarchar(100),
ClassId bigint,
ClassName nvarchar(50),
--DivisionId bigint,
--DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
ClassOrderIndex int
--,DivisionOrder int
)

IF(@rCollectionGroupId = 0)
	BEGIN

	INSERT INTO #tempTotalSubPart
	SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		SA.OrgId AS OrgGroupId,
		SA.OrganizationName AS OrgGroupName,
		SA.ClassId AS ClassId,
		SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE 
		   ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			-- IsInContext
		AND BM.IsInContext = 1
	GROUP by SA.OrgId,SA.OrganizationName, SA.ClassId,SA.ClassName--,SA.DivisionName
		,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex--,SA.DivisionOrder
	

	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from #tempTotalSubPart T
	group by T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName,T.CollectionGroupId,T.ReceiptBookId
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		
	END 
	ELSE 
	BEGIN
	
	INSERT INTO #tempTotalSubPart
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		  SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex--,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE 
		   ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			-- IsInContext
		AND BM.IsInContext = 1

	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassId,SA.ClassName--,SA.DivisionName
		,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex--,SA.DivisionOrder

		 
	SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from #tempTotalSubPart T
	GROUP BY T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName--,T.ClassOrderIndex,T.DivisionOrder
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		--ORDER BY T.ClassOrderIndex,T.DivisionOrder
		
	END
	
	DROP TABLE #tempTotalSubPart
	
  END	
ELSE IF(@rType ='FeeStatusTotalSubPartDetails')
BEGIN 
CREATE TABLE #tempTotalSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
)

 
IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempTotalSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND  ISNULL(CGM.Id,0)=0
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 And ISNULL(O.IsObsolete,0) = 0
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 -- IsInContext
		AND BM.IsInContext = 1
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempTotalSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
	ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempTotalSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And ISNULL(O.IsObsolete,0) = 0
	 -- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempTotalSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId--,T.ClassOrderIndex,T.DivisionOrder 
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
	ORDER BY T.RollNo
		
	 
	END
	
	DROP TABLE #tempTotalSubPartDetails
	
END
  
ELSE IF(@rType ='FeeStatusPaidSubPartDetails')
BEGIN 
CREATE TABLE #tempPaidSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
)

 
IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPaidSubPartDetails
	SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND  ISNULL(CGM.Id,0)=0
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And ISNULL(O.IsObsolete,0) = 0
	 -- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
	HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
	ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempPaidSubPartDetails
	SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 And ISNULL(O.IsObsolete,0) = 0
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 -- IsInContext
		AND BM.IsInContext = 1
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetails T
		
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
		
	END
	
	DROP TABLE #tempPaidSubPartDetails
END

ELSE IF(@rType ='FeeStatusPaidSubPartDetailsMonthWise')
BEGIN 
CREATE TABLE #tempPaidSubPartDetailsMonthWise(
AcademicId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
)

CREATE TABLE #tempDFSMonthWise(
     Id INT,
     Amount DECIMAL(12,0),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

)

INSERT INTO #tempDFSMonthWise
	 SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And ISNULL(O.IsObsolete,0) = 0
		-- IsInContext
		AND BM.IsInContext = 1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=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='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
	   (FS1.IsOptional=1) --AND BM.IsActive=1 
	   AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And ISNULL(O.IsObsolete,0) = 0
	   -- IsInContext
		AND BM.IsInContext = 1
	   --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
	    --AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
	    --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
		


CREATE TABLE #tempDRMonthWise(
       PaidAmount DECIMAL(12,0),
	   FeeSetupId INT,
	   SourceId BIGINT,
	   ReceiptDate DATE
)
INSERT INTO #tempDRMonthWise
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
		,R.ReceiptDate
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
	WHERE		
		(R.SourceTypeId = 2001) 
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And ISNULL(O.IsObsolete,0) = 0
		-- IsInContext
		AND BM.IsInContext = 1
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate     
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate



IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPaidSubPartDetailsMonthWise
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise TDFS ON TDFS.AcademicId=SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDRMonthWise TDR ON TDR.FeeSetupId = TDFS.Id AND SA.AcademicId = TDR.SourceId
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	AND((DATEPART(M, TDR.ReceiptDate)  =@rMonth)OR(@rMonth=0))
	And ISNULL(O.IsObsolete,0) = 0
	-- IsInContext
		AND BM.IsInContext = 1
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetailsMonthWise T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempDFSMonthWise1(
     Id INT,
     Amount DECIMAL(12,0),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT  

    )
    
    INSERT INTO #tempDFSMonthWise1
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And ISNULL(O.IsObsolete,0) = 0
		-- IsInContext
		AND BM.IsInContext = 1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=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='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0
		-- IsInContext
		AND BM.IsInContext = 1
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	
CREATE TABLE #tempDRMonthWise1(
       PaidAmount DECIMAL(12,0),
	   FeeSetupId INT,
	   SourceId BIGINT,
	   ReceiptDate DATE
)
INSERT INTO #tempDRMonthWise1
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId,
		R.ReceiptDate
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		And ISNULL(O.IsObsolete,0) = 0
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId
		-- IsInContext
		AND BM.IsInContext = 1
		 --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
	
	
	
	insert into #tempPaidSubPartDetailsMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR1.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise1 TDFS1 ON TDFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDRMonthWise TDR1 ON TDR1.FeeSetupId = TDFS1.Id AND SA.AcademicId = TDR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND((DATEPART(M, TDR1.ReceiptDate)  =@rMonth)OR(@rMonth=0))
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	And ISNULL(O.IsObsolete,0) = 0
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 -- IsInContext
		AND BM.IsInContext = 1
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetailsMonthWise T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName
		--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
		
		DROP TABLE #tempDFSMonthWise1
	DROP TABLE #tempDRMonthWise1
	END
	
	DROP TABLE #tempPaidSubPartDetailsMonthWise
	DROP TABLE #tempDFSMonthWise
	DROP TABLE #tempDRMonthWise
	
	
	
END

ELSE IF(@rType='ReceiptOrganization')
  BEGIN
	IF(@rSyncDate =1)
		BEGIN
				DELETE  sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				CREATE TABLE #tempReceiptOrganizationSync(
				OrgGroupId int,
				OrgGroupName nvarchar(500),
				ReceiptId bigint,
				TotalReceiptAmount DECIMAL(12,0),
				IsObsolete bit
				)
				INSERT INTO #tempReceiptOrganizationSync
				SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,R.Id AS ReceiptCount,R.ReceiptAmount,R.IsObsolete
				FROM  sFee.tReceipt R
				INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
				INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
				WHERE R.SourceTypeId = 2001
				AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND (COGBM.Id=@rCommonOrgGroupBatchId )
				And ISNULL(O.IsObsolete,0) = 0 
				AND (R.ReceiptDate between @rFromDate and @rToDate)   
				-- IsInContext
				AND BM.IsInContext = 1 
			
			INSERT INTO sFee.tTempReceiptOrganization
				SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate() FROM #tempReceiptOrganizationSync T  
				LEFT JOIN (
				SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganizationSync WHERE IsObsolete = 1
				GROUP BY OrgGroupId,OrgGroupName
				) A ON A.OrgGroupId=t.OrgGroupId
				WHERE IsObsolete = 0
				GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
				ORDER BY OrgGroupId
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				
				DROP TABLE #tempReceiptOrganizationSync
		END 
	ELSE
		BEGIN
			IF  Exists(select 1 from sFee.tTempReceiptOrganization where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND CONVERT(date,ReceiptDate) =@rFromDate AND CONVERT(date,ReceiptDate) =@rToDate )

			BEGIN
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
	ELSE
			BEGIN 
			DELETE  sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				CREATE TABLE #tempReceiptOrganization(
				OrgGroupId int,
				OrgGroupName nvarchar(500),
				ReceiptId bigint,
				TotalReceiptAmount DECIMAL(12,0),
				IsObsolete bit
				)
				INSERT INTO #tempReceiptOrganization
				SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,R.Id AS ReceiptCount,R.TotalReceiptAmount,R.IsObsolete
				FROM  sFee.tReceipt R
				INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
				INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
				WHERE R.SourceTypeId = 2001
				AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND (COGBM.Id=@rCommonOrgGroupBatchId ) 
				AND (R.ReceiptDate between @rFromDate and @rToDate)    
				-- IsInContext
				AND BM.IsInContext = 1
			
				INSERT INTO sFee.tTempReceiptOrganization
				SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate() FROM #tempReceiptOrganization T  
				LEFT JOIN (
				SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganization WHERE IsObsolete = 1
				GROUP BY OrgGroupId,OrgGroupName
				) A ON A.OrgGroupId=t.OrgGroupId
				WHERE IsObsolete = 0
				GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
				ORDER BY OrgGroupId
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DROP TABLE #tempReceiptOrganization
			END
		END
  END
ELSE IF(@rType='ReceiptBookCollectionGroup')
  BEGIN
	CREATE TABLE #tempReceiptBookCollection (
	RecepitTitle nvarchar(200),
	--CollectionTitle nvarchar(200),
	ReceiptCount int,
	ReceiptAmount DECIMAL(12,0),
	ReceiptId bigint,
	--CollectionGroupId bigint,
	IsObsolete bit
)

INSERT INTO #tempReceiptBookCollection
 SELECT ISNULL(RBM.Title,'')  AS RecepitTitle ,
			--ISNULL(CGM.Code,'') AS CollectionTitle,
			ISNULL(COUNT(DISTINCT R.Id),0) AS ReceiptCount,CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
			ISNULL(RBM.Id,0) AS ReceiptId,
			--ISNULL(CGM.Id,0) AS CollectionGroupId,
			R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					
			INNER JOIN  sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id 			
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId 
			AND FS.AdmissionCategoryId=SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			
			--LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id 
			--AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND (R.IsObsolete = 1) 
			--AND(BM.IsActive =1) 
			AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))AND R.ReceiptDate between @rFromDate and @rToDate 
			And ISNULL(O.IsObsolete,0) = 0   
			-- IsInContext
		AND BM.IsInContext = 1
			GROUP BY RBM.Title,RBM.Id,R.ReceiptBookId,R.IsObsolete,R.Id,R.ReceiptAmount
			
			--SELECT  TRC.RecepitTitle +'-'+ TRC.CollectionTitle AS ReceictCollection,TRC.ReceiptId AS ReceiptId,TRC.CollectionGroupId AS CollectionGroupId,ISNULL(COUNT(TRC.ReceiptCount),0) AS ReceiptCount,SUM(ReceiptAmount) AS ReceiptAmount ,
			--ISNULL(A.CancelReceiptCount,0)AS CancelAmount FROM #tempReceiptBookCollection TRC 
			--LEFT JOIN (
			--SELECT ReceiptId,CollectionGroupId,SUM(ReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptBookCollection WHERE IsObsolete = 1
			--GROUP BY ReceiptId,CollectionGroupId
			--) A ON A.ReceiptId=TRC.ReceiptId AND A.CollectionGroupId=TRC.CollectionGroupId
			
			--WHERE IsObsolete = 0
			--GROUP BY TRC.RecepitTitle,TRC.CollectionTitle,A.ReceiptId,A.CancelReceiptCount,TRC.ReceiptId,TRC.CollectionGroupId,TRC.ReceiptCount 

			SELECT  TRC.RecepitTitle AS ReceictCollection,TRC.ReceiptId AS ReceiptId,0 AS CollectionGroupId,ISNULL(COUNT(TRC.ReceiptCount),0) AS ReceiptCount,SUM(ReceiptAmount) AS ReceiptAmount ,
			ISNULL(A.CancelReceiptCount,0)AS CancelAmount FROM #tempReceiptBookCollection TRC 
			LEFT JOIN (
			SELECT ReceiptId,SUM(ReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptBookCollection WHERE IsObsolete = 1
			GROUP BY ReceiptId
			) A ON A.ReceiptId=TRC.ReceiptId
			
			WHERE IsObsolete = 0
			GROUP BY TRC.RecepitTitle,A.ReceiptId,A.CancelReceiptCount,TRC.ReceiptId,TRC.ReceiptCount 
		DROP TABLE #tempReceiptBookCollection
  END
ELSE IF(@rType='ReceiptBookCollectionGroupDetail')
  BEGIN
  CREATE TABLE #tempReceiptBookCollectionDetail(
  SourceId bigint,
Code nvarchar(200),
Name nvarchar(200),
ReceiptNumber bigint,
ReceiptAmount DECIMAL(12,0),
ReceiptId bigint,
IsObsolete bit
)
  
	INSERT INTO #tempReceiptBookCollectionDetail
 SELECT ISNULL(SA.Id,0) AS SourceId,SM.Code AS Code,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) As Name,R.ReceiptNumber AS ReceiptNumber,CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =
1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,R.Id AS ReceiptId,R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
			INNER JOIN sStudent.tStudentMaster SM1 ON SA.StudentId = SM1.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId=SM.Id	
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.AdmissionCategoryId =  SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND (R.IsObsolete = 0) 
			--AND(BM.IsActive =1) 
			And ISNULL(O.IsObsolete,0) = 0			
			AND COGBM.Id=@rCommonOrgGroupBatchId AND R.ReceiptDate between @rFromDate and @rToDate     
			-- IsInContext
			AND BM.IsInContext = 1
			GROUP BY SA.Id,SM.Code,R.ReceiptNumber,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId), R.ReceiptBookId,R.Id,R.IsObsolete,R.ReceiptAmount 
			--ORDER BY 
	 
  SELECT *  FROM #tempReceiptBookCollectionDetail ORDER BY ReceiptNumber
  
  DROP TABLE #tempReceiptBookCollectionDetail
  END
END
GO
PRINT N'Altering Procedure [sFee].[pFeeExportDetailsGet]...';


GO
 


ALTER PROCEDURE [sFee].[pFeeExportDetailsGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(40)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(50) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='',
  @rCancelStatusId int = 0
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
    END 
	
BEGIN       

CREATE Table #FeeReceiptDetail
		(
		StatusId bigint,
		ReceiptId bigint,
		FeeCode nvarchar(100),
		FeeAmount decimal(12,2),
		Organization nvarchar(max),
		Batch nvarchar(100),
		BatchId bigint,
		Code nvarchar(20),
		ClassDiv nvarchar(200),
		Name nvarchar(300),
		ReceiptNumber nvarchar(200),
		ReceiptDate nvarchar(50),
		ReceiptAmount decimal(12,2),
		PayType nvarchar(300),
		ChequeNo nvarchar(40),
		Remark nvarchar(max),
		ChequeDate nvarchar(50),
		InvoiceNumber int,
		ReceiptCreatedDateTime datetime,
		BankName nvarchar(200),
		ReceiptBookName nvarchar(100),
		TotalReceiptAmount decimal(12,2),
		DiscountAmount decimal(12,2),
		VariableAmount decimal(12,2),
		ExemptionAmount decimal(12,2),
		AdditionalAmount decimal(12,2),
		NotApplicableAmount decimal(12,2),
		SUId nvarchar(50),
		CancelRemark nvarchar(500)--Added for mantis : 35507 by Nilesh
		
		)


INSERT INTO #FeeReceiptDetail
 SELECT 
    A.StatusId,    
	R.Id AS ReceiptId,
	FM.Code,
	RD.Amount,
	OM.DisplayTitle AS Organization,  
	BM.Title AS Batch,
	BM.Id AS BatchId,
	A.Code AS Code, 
	CM.Title +' - '+ DM.Title AS ClassDiv,
	A.Name,    
	R.ReceiptNumber,   
	--change by megha for mentis 0027171 start
	--R.ReceiptDate,   
	CONVERT(VARCHAR(10), R.ReceiptDate, 103) AS ReceiptDate, 
   --end
	ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,
	PTM.Title AS PayType,    
	CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
	R.Remark,
	CONVERT(VARCHAR(10), R.ChequeDate, 103)AS ChequeDate, 
	--ISNULL(CAST(R.ChequeDate AS Date),'') AS ChequeDate, 
	ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
	R.CreatedDateTime AS ReceiptCreatedDateTime,
	R.BankName,    
	RBM.Title AS ReceiptBook,    
    ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
    ISNULL(R.DiscountAmount,0)AS DiscountAmount,
	FA.VariableAmount,
	FA.DiscountAmount AS ExemptionAmount,
	FA.AdditionalAmount,
	FA.NotApplicableAmount,
	ISNULL(A.SUId,'') As SUId,
	ISNULL(R.CancelStatusRemark,'')AS CancelRemark --Added for mantis : 35507 by Nilesh
	
  
  FROM     
  
     sFee.tReceipt R    
  INNER JOIN sStudent.vStudentAcademic A    
   ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
   
  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
  INNER JOIN sCommon.tSourceTypeMaster STM    
   ON STM.Id=R.SourceTypeId    
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
   ON PTM.Id=R.PayTypeId    
  INNER JOIN sFee.tReceiptBookMaster RBM    
   ON RBM.Id=R.ReceiptBookId    
  INNER JOIN sSetup.tOrganizationMaster OM    
   ON OM.Id=A.OrgId    
    AND OM.OrgGroupId=@rOrgGroupId    
  INNER JOIN sSetup.tBatchMaster BM    
   ON BM.Id=R.BatchId     
   AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
  LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
  INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
  LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
  
  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
  LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=A.AcademicId
  
WHERE     
 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
 AND (R.SourceTypeId=2001)    
 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
 AND (R.IsObsolete=@rIsObsolete)    
 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
 AND ((R.CancelStatusId = @rCancelStatusId) OR(@rCancelStatusId=0)) ----Added By Dhruv for Issue No.11130    
 ORDER BY R.ReceiptNumber DESC   
 
 --Select * from #FeeReceiptDetail
 DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

    SELECT @cols = STUFF((SELECT  DISTINCT ',' + QUOTENAME(ID.FeeCode)
                       FROM #FeeReceiptDetail ID FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')   
 
    SELECT @query = 
    'SELECT  
			P.*,
            ID.VariableAmount,
            ID.ExemptionAmount,
            ID.AdditionalAmount,
            ID.NotApplicableAmount ,
			ID.DiscountAmount,
			ID.CancelRemark
			
     FROM
    (SELECT  
	
		ReceiptId ,
		Organization ,
		Batch ,
		Code ,
		SUId,
		ClassDiv ,
		Name ,
		ReceiptNumber ,
		ReceiptDate ,
		ReceiptAmount ,
		Remark,
		PayType ,
		ChequeNo ,
		ChequeDate, 
		BankName ,
		ReceiptBookName ,
		InvoiceNumber,    
		ReceiptCreatedDateTime,
		TotalReceiptAmount ,
		FeeCode, 
        FeeAmount
		
				    		
    FROM #FeeReceiptDetail)X
    PIVOT 
    (
         SUM(FeeAmount) 
         FOR [FeeCode] IN (' +  @cols + ')
    ) P
    LEFT JOIN
	(
		SELECT
		    ReceiptId,
			SUM(VariableAmount) AS VariableAmount,
			SUM(ExemptionAmount) AS ExemptionAmount,
			SUM(AdditionalAmount) AS AdditionalAmount,
			SUM(NotApplicableAmount) AS NotApplicableAmount,
			(DiscountAmount) AS DiscountAmount,
			(CancelRemark) AS CancelRemark
			
		FROM  
			#FeeReceiptDetail
			GROUP BY ReceiptId,DiscountAmount,CancelRemark
    ) ID ON ID.ReceiptId = P.ReceiptId
	Order By P.ReceiptNumber DESC
    '
	EXECUTE(@query) 
END
GO
PRINT N'Altering Procedure [sFee].[pFeeReceiptListGet]...';


GO

ALTER PROCEDURE [sFee].[pFeeReceiptListGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(20)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(50) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='',
  @rCancelStatusId int = 0,
  @rFromChequeClearDate date = '',
  @rToChequeClearDate date = ''
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
		SET @rChequeNo = sCommon.fSearchStringGet(@rChequeNo)  
    END 
	
BEGIN       
 SELECT 
  A.StatusId,    
  R.Id AS ReceiptId,    
  R.SourceId AS SourceId,    
  R.SourceTypeId AS SourceTypeId,    
  CASE WHEN R.SourceTypeId=2001 THEN 'Student'    
  ELSE  'Employee' END AS SourceType,    
  --STM.Title     
  A.Code AS Code,    
  A.Name,    
  R.ReceiptNumber,    
  R.ReceiptDate,    
  ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,    
  ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
  ISNULL(R.DiscountAmount,0)AS DiscountAmount,    
  R.PayTypeId,    
  PTM.Title AS PayType,    
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
  --R.ChequeNo,    
  R.BankName,    
  R.ReceiptBookId,    
  RBM.Title AS ReceiptBook,    
  R.IsObsolete,    
  A.OrgId,    
  OM.DisplayTitle AS Organization,    
  R.BatchId,    
  BM.Title AS Batch,    
  R.Remark,    
  ISNULL(R.IsChequeCleared,0) AS IsChequeCleared,    
  ISNULL(R.ChequeClearDate,'') AS ChequeClearDate,    
  ISNULL(R.ChequeDate,'') AS ChequeDate,    
  ISNULL(R.CollectionGroupId,0) AS CollectionGroupId,    
  Cm.title,    
  CM.Id,    
  ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
  CM.Title +' - '+ DM.Title AS Class,    
  A.SUId,    
  ISNULL(R.AmountAfterDiscount,0)AS AmountAfterDiscount,    
  ISNULL(R.CGSTPercentage,0)AS CGSTPercentage,    
  ISNULL(R.SGSTPercentage,0)AS SGSTPercentage,    
  ISNULL(R.CGSTAmount,0)AS CGSTAmount,    
  ISNULL(R.SGSTAmount,0)AS SGSTAmount,    
  ISNULL(R.DepositedLedgerId,0) AS DepositedLedgerId,    
  R.CreatedDateTime AS ReceiptCreatedDateTime,
  ISNULL(R.ReceiptPrintGroupId,'') AS ReceiptPrintGroupId   ,
  R.CancelStatusRemark AS  CancelStatusRemark,
  ISNULL(U.DisplayTitle,'') AS UserName,
  ISNULL(R.CancelStatusRemark,'')AS CancelRemark --Added for mantis : 35507 by Nilesh
  FROM     
   sFee.tReceipt R    
  INNER JOIN sStudent.vStudentAcademic A    
   ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
   
  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
  INNER JOIN sCommon.tSourceTypeMaster STM    
   ON STM.Id=R.SourceTypeId    
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
   ON PTM.Id=R.PayTypeId    
  INNER JOIN sFee.tReceiptBookMaster RBM    
   ON RBM.Id=R.ReceiptBookId    
  INNER JOIN sSetup.tOrganizationMaster OM    
   ON OM.Id=A.OrgId    
    AND OM.OrgGroupId=@rOrgGroupId    
  INNER JOIN sSetup.tBatchMaster BM    
   ON BM.Id=R.BatchId     
   AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
  LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
  INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
  LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
WHERE     
 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
 AND (R.SourceTypeId=2001)    
 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
 AND ((R.ChequeNo like @rChequeNo) OR (CONVERT(nvarchar(20),R.PaymentTransactionId) like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))     
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
 AND (R.IsObsolete=@rIsObsolete)    
 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))
 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))    
 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))    
 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
 AND ((R.CancelStatusId = @rCancelStatusId) OR(@rCancelStatusId=0)) ----Added By Dhruv for Issue No.11130    
ORDER BY R.ReceiptNumber DESC    
END
GO
PRINT N'Altering Procedure [sFee].[pPostDatedPaymentAdd]...';


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

AS
SET NOCOUNT ON
BEGIN
	SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId

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

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

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

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

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

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

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

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


GO
ALTER PROCEDURE [sFee].[pReceiptAddValidate] 
	@rAcademicId BIGINT
	,@rFeeSetupIds NVARCHAR(max) = ''
	,@rReceiptDetailXml [nvarchar] (max)
	,@rPayTypeId TINYINT = 0
	,@rPaymentTransactionId BIGINT = 0
	,@rReceiptBookId INT = 0
	,@rChequeNo nvarchar(40) = '' -- Added for mantis 0035484 by Foram
	,@rIsCreated INT OUTPUT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @loDoc INT

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

	EXEC sp_xml_preparedocument @loDoc OUTPUT,@rReceiptDetailXml

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

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

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

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

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

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

	EXEC sp_xml_removedocument @loDoc
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

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

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


--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
			
	  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
	  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
	  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
	  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
	  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
	  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	
	  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.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SA.MiddleName,'') AS FatherName
	  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


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


GO

 
ALTER PROCEDURE [sFee].[pRptStudentWiseFeeDetailGet]
		
	@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   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN

	SELECT 
			SA.Id AS AcademicId,
			SA.RollNo,
			SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			SM.Code,
			CM.DisplayTitle AS ClassName,
			DM.DisplayTitle AS DivisionName,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
			SUM(ISNULL(FS.Amount,0)+ISNULL(FA.VariableAmount,0)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00))AS Amount,
			ISNULL(SUM(R.PaidAmount),0) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			O.DisplayTitle AS OrgName,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			BM.Title AS BatchName,
			TR.ReceiptNumber,
			TR.ReceiptId AS ReceiptId,  
			TR.PayType,  
			TR.ChequeNo,
			TR.BankName,  
			TR.ReceiptAmount,
			TR.ReceiptDate,  
			TR.FeeDetail,
			TR.ReceiptBookTitle,
			TR.ChequeDate  --added by dhananjay for mantis id - 0035384
	  FROM 
			sStudent.tAcademic SA
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.Id AS AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
				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 ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((BM.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.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.Id AS AcademicId,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
					INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
					INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId
					INNER JOIN sSetup.tBatchMaster BM ON SA1.BatchId = BM.Id
					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 ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((BM.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(BM.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.Id
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
			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.tAcademic SA1 ON SA1.Id=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					INNER JOIN sSetup.tBatchMaster BM ON SA1.BatchId = BM.Id
				WHERE	
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((BM.Title = @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(BM.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 RD.FeeSetupId ,R.SourceId
			) R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
			  LEFT JOIN
				(
					SELECT 
						 R.SourceId
						,R.Id AS ReceiptId,  
						R.ReceiptNumber,  
						PTM.Title AS PayType,  
						CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
						R.BankName,  
						ISNULL(SUM(RD.Amount),0) AS ReceiptAmount,
						R.ReceiptDate,  
						(STUFF((SELECT  ','+FM.Title FROM sFee.tReceiptDetail RD INNER JOIN sFee.tFeeSetup FS ON FS.Id=RD.FeeSetupId INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId WHERE RD.ReceiptId = R.Id FOR XML PATH('')), 1, 1,NULL)) as FeeDetail,
						ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
						ISNULL(RBM.Title,'') AS ReceiptBookTitle,
						R.ChequeDate --added by dhananjay for mantis id - 0035384
					FROM
							sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
						INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
						ON PTM.Id=R.PayTypeId  
						INNER JOIN sFee.tReceiptBookMaster RBM   
						ON RBM.Id=R.ReceiptBookId  
						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 (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					    AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					    AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					    AND ((BM.Title = @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(BM.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  R.SourceId,R.Id,R.ReceiptNumber,PTM.Title,R.ChequeNo,R.PaymentTransactionId,R.BankName,R.ReceiptDate,R.ReceiptBookId,RBM.Title,R.ChequeDate--added (R.ChequeDate) by dhananjay for mantis id - 0035384
				) TR ON SA.Id = TR.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.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 ((BM.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 ((BM.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	((BM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
				AND (SM.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 ((SM.Code=@rCode) OR (@rCode=''))
				AND ((CM.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))  	 	
		Group BY SA.Id,SA.RollNo,SM.FirstName+' '+SM.MiddleName+' '+SM.LastName,SM.Code,CM.DisplayTitle,DM.DisplayTitle,O.DisplayTitle,FHM.Id,FHM.Title,BM.Title,TR.ReceiptNumber,
				 TR.ReceiptId,TR.PayType,TR.ChequeNo,TR.BankName,TR.ReceiptAmount,TR.ReceiptDate,TR.FeeDetail,TR.ReceiptBookTitle,TR.ChequeDate--added (R.ChequeDate)by dhananjay for mantis id - 0035384
		Order by SA.RollNo

END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmployeeIcardGet]...';


GO
ALTER PROCEDURE [sHrm].[pRptEmployeeIcardGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint,
	@rIsShowBarcode bit=0,
	@rStrCode nvarchar(max)='',
	@rBatchName nvarchar(100) = ''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ECD.EmployeeId,
	        ECD.Code,	      	
			ECD.EmployeeName, 	 								 
			ECD.DepartmentId,  			
			ECD.DepartmentName,
		    ECD.MobileNumber,
		    ECD.EmployeeDesignation,
		    ECD.PhoneNoCompany,
		    ECD.BloodGroup,
		    ECD.DateOfBirth,
			EI.EmployeePhoto,
		    OM.Title AS OrgName,
		    OM.PrincipalSignature,
			ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,
			ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,
			ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,
			ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,	
		    OM.OrgLogo AS ICardLogo,
			ICO.ICardBackground,	
			ICO.ICardBackBackground,						
			ISNULL(ICO.LabelColor,'Black') AS LabelColor,
			ISNULL(ICO.DetailColor,'Black') AS DetailColor,
			ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,
			ISNULL(EC.PresentStreetOne,'') AS PresentStreetOne,
			ISNULL(EC.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(EC.PresentStreetThree,'') AS PresentStreetThree,
			ISNULL(EC.PresentCity,'') AS PresentCity,
			ISNULL(EC.PresentState,'') AS PresentState,
			ISNULL(EC.PresentCountry,'') AS PresentCountry,
			ISNULL(EC.PresentZipCode,'') AS PresentZipCode,
			ECD.DateofJoining,
			EI.EmployeeSign,
			@rIsShowBarcode As IsShowBarcode,
			ISNULL(EC.EmergencyStreetOne,'') AS EmergencyStreetOne,
			ISNULL(EC.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
			ISNULL(EC.EmergencyStreetThree,'') AS EmergencyStreetThree,
			ISNULL(EC.EmergencyCity,'') AS EmergencyCity,
			ISNULL(EC.EmergencyState,'') AS EmergencyState,
			ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(PanNumber,'') AS PanNumber,
			EC.EmergencyContactNo AS EmergencyContactNo,
			EPD.Qualification AS Qualification,
			--ISNULL(EM.MiddleName,'')AS FatherName,
			ISNULL(ECD.MiddleName,'')AS FatherName,
			ECD.GenderTitle,
			ISNULL(ECD.FirstName,'')AS FirstName,
			ISNULL(ECD.LastName,'')AS SurName,
			(CASE WHEN RelationshipId = 2 THEN EFD.MobileNo ELSE '' END )AS FatherContactNo,
			ISNULL(@rBatchName,'') AS BatchName,
			ISNULL(EC.PresentContactNo,'') AS PresentContactNo,
			--added by megha for 0027070
			ISNULL(ECD.CompanyEmail,'')AS CompanyEmail,
			ISNULL(EC.PersonalEmail,'')AS PersonalEmail,
			ISNULL(ECD.EmployeeGrade,'')AS EmployeeGrade,
			ISNULL(ECD.Number,0) AS Number --add fro mantis : 0035451

		FROM 
			sHrm.vEmployeeCommonDetail ECD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ECD.OrgID
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeeICardOrg ICO ON ECD.OrgId = ICO.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON ECD.EmployeeId = EC.EmployeeId
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther EO ON EO.EmployeeId = ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EO.EmployeeId
			LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on ECD.EmployeeId=EFD.EmployeeId AND EFD.RelationshipId = 2
			--LEFT JOIN sCommon.tRelationshipMaster RM on EFD.RelationshipId=RM.Id AND RM.Id=2
			--LEFT JOIN sHrm.tEmployeeMaster EM on EM.Id = ECD.EmployeeId
			
		WHERE
		((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ISNULL(ECD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')   
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
	   AND ISNULL(ECD.IsOtherUser,0)=0
	  
END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmployeeLeaveDetailsGet]...';


GO

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

BEGIN 



       SELECT 
				 @rBuilder1 AS Builder1,
				 @rBuilder2 AS Builder2, 
				 EM.Code AS EmployeeCode,
				 EM.EmployeeName,   
				 EM.EmployeeId,
				 EM.DepartmentName,
				 EM.EmployeeGrade,      
				 --ISNULL(AT.LWP,0) AS LWP,
				 --CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
				 --MM.Title AS MonthName,
		   --      (SELECT  t1.MonthTitle FROM (SELECT MonthTitle,MonthNumber FROM [sSetup].[fMonthYearForBatchGet] (100100001))  AS T1
				 --WHERE MonthNumber = 4) AS MonthName,
				 --(SELECT  t2.YearNumber FROM (SELECT YearNumber,MonthNumber FROM [sSetup].[fMonthYearForBatchGet] (100100001))  AS T2
				 --WHERE YearNumber = 2014 AND MonthNumber = 4 ) AS YearName,
				 --AT.ForYear As YearName,
				 L.LeaveReason,
				 L.NoOfLeave,
				 L.ReportDate,
				 L.FromDate,
				 L.ToDate,
				 LPM.Title As LeavePeriod,
				 LTM.Title As LeaveType,
				 LTM.IsCarryForward,
				 LTM.IsLWP,
				 ISNULL(SM.Title,'') AS StatusName,
				 OM.Title AS OrganizationTitle,
				 ISNULL(OM.StreetOne,'') AS StreetOne,
				 ISNULL(OM.StreetTwo,'')AS StreetTwo,
				 ISNULL(OM.StreetThree,'')AS StreetThree,
				 ISNULL(OM.CityName,'')AS CityName,
				 ISNULL(OM.StateName,'')AS StateName,
				 ISNULL(OM.CountryName,'')AS CountryName,
				 ISNULL(OM.ZipCode,'')AS ZipCode,
				 ISNULL(EM.EmployeeDesignation,'')AS EmployeeDesignation ,
				 ISNULL(LM.BalanceLeave,0) AS TotalLeave ,
				 ISNULL(EC.MobileNumber,'')AS MobileNumber,
				 ISNULL((SELECT    
						SUM(NoOfLeave) AS UsedLeave
					FROM 
						sHrm.tLeave L1  
					WHERE 
						(L1.EmployeeId = EM.EmployeeId) 
						AND (L1.LeaveTypeId = L.LeaveTypeId)      
						AND BatchId = @rBatchId AND L.OrgId = @rOrgId 
						AND L1.StatusId = 550 -- apporved
						GROUP BY L1.EmployeeId,L1.LeaveTypeId),0) AS UsedLeave, -- Mantis : 0027600
				L.Id AS LeaveId		-- MantisId : 0035002

        FROM 
				sHrm.vEmployeeCommonDetail EM 
		--LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
		--LEFT JOIN sCommon.tMonthMaster MM ON MM.Id=AT.ForMonth
		INNER JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id=L.LeavePeriodId
		INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id=L.LeaveTypeId
		LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		--INNER JOIN sHrm.tLeaveBalance LM ON LM.EmployeeId = EM.EmployeeId 
		LEFT JOIN sHrm.tLeaveBalance LM ON LM.EmployeeId = EM.EmployeeId AND LM.BatchId = L.BatchId AND LM.LeaveTypeId = L.LeaveTypeId
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
    	WHERE 
    	EM.OrgID = @rOrgId 
    	AND L.BatchId=@rBatchId
    	AND (YEAR(L.FromDate) = @rForYear OR @rForYear='') 
    	AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth='') 
    	AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    	AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    	AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    	AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    	AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    	AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    	AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
    	AND ((L.LeaveReason Like '%'+@rLeaveReson+'%' ) OR (ISNULL(@rLeaveReson,'')=''))
    	AND ((L.StatusId=@rStatusId) OR (@rStatusId=0))
    	AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
		AND ((LM.LeaveTypeId=@rLeaveTypeId) OR (@rLeaveTypeId=0))
END
GO
PRINT N'Altering Procedure [sHrm].[pRptExperienceCertificateGet]...';


GO
ALTER PROCEDURE [sHrm].[pRptExperienceCertificateGet]
	
	 
	 --@rReportId int=0,
	-- @rStrEmployeeId nvarchar(max),
	 --@rEmployeeTypeId [int]= 0,
	@rEmployeeId [bigint]= 0,
	 --@rEmployeeGroupId smallint=0,
	-- @rEmployeeStatusId smallint=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rCode nvarchar(20)='',
	 --@rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rNumber nvarchar(20)='',
	 @rFromDate date='',
     @rToDate date='',
     @rName nvarchar(20)=''
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lConfigValue nvarchar(50)
DECLARE @lIsDisplayImageHeader bit=0

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 182 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
	        EM.Id AS EmployeeId,
	        EM.Code,
	        EM.EmployeeName,
	       	EM.FirstName,
			EM.MiddleName,
			EM.LastName,	
			EM.ShortName,
			EM.OrgID,
			EM.GenderId,
			EM.DateOfJoining,
			EM.StatusId,
			EM.UserId,
			EM.DepartmentId,
			EM.DateOfleaving,
			EM.EmployeeTypeId,
			EM.DesignationId,
			EM.Designation,
			--EM.EmployeeGroup,
			--EM.EmployeeGroupId,
			EM.EmployeePhoto,
			EC.PresentStreetOne,
			EC.PresentStreetTwo,
			EC.PresentStreetThree,
			EC.PresentCity,
			EC.PresentState,
			EC.PresentCountry,
			EC.PresentZipCode,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4 ,
			CE.Remark,
			CE.CertificateReason,
			CE.CertificateDate,
			CE.Number,
			convert(varchar(4),DATEDIFF(MONTH, EM.DateOfJoining, EM.DateOfleaving)/12) +' years '+
			convert(varchar(2),DATEDIFF(MONTH, EM.DateOfJoining, EM.DateOfleaving) % 12)+ ' months' As ExpMonth,
			EM.MaritalStatusId,
			RRG.SchoolRemark1,
			RRG.SchoolRemark2,
			RRG.SchoolRemark3,
			RRG.SchoolRequiredSignature,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			convert(varchar(4),DATEDIFF(MONTH, EM.DateOfJoining, EM.DateOfleaving)/12) AS years,  --Mantis - 35275
			convert(varchar(2),DATEDIFF(MONTH, EM.DateOfJoining, EM.DateOfleaving) % 12) AS months,  --Mantis - 35275
			EM.Qualification	 --Mantis - 35275
			 
			
	FROM 
	        sHrm.tCertificateExperience CE
            INNER JOIN [sHrm].[vExtEmployeeMaster] EM  ON EM.EmployeeId=CE.EmployeeId  
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.EmployeeId=EC.EmployeeId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EM.GenderId
		    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tReportRemarkGroupOrg RRG ON RRG.OrgId = OM.Id AND ReportRemarkGroupId=7
	WHERE
			((EM.Code LIKE @rCode)OR (@rCode = '' ))
	   --AND (ISNULL(EM.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND ((EM.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
	   AND ((EM.EmployeeName like @rName) OR (ISNULL(@rName,'') = ''))
	   AND ((CE.Number=@rNumber) OR (@rNumber=''))
	   AND ((CE.Number >= @rFromNo) OR (@rFromNo=0))
	   AND ((CE.Number <= @rToNo) OR (@rToNo=0))
	   AND ((CE.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	   AND ((CE.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))	   
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  EM.OrgId = @rOrgId
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
     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
     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
    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
     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
      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
      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
       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
       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
	   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
	 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
	 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 [sIp].[pStockItemMasterListGet]...';


GO


ALTER PROCEDURE [sIp].[pStockItemMasterListGet]
	  @rOrgGroupId [int],
	  @rId [int] = 0,
	  @rTitle [nvarchar](100) = '',
	  @rIsWildCardSearch [bit] = 1,
	  @rCode [nvarchar](20) = '',	 
	  @rStoreLocationId [int]=0,
	  @rItemMainGroupId int,
	  @rItemSubGroupId int
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @lSreffered AS BIT
SET @lSreffered = 0
DECLARE @lCount INT
DECLARE @lUpperBound Int
 
 

	IF @rIsWildCardSearch = 1

		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
		 
	IF @rId = 0
		BEGIN	
			SELECT @lcount = COUNT(Id) FROM sIp.tStockItemMaster WHERE ((Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))AND ((Title LIKE @rTitle) OR (ISNULL(@rTitle, '') = '') AND OrgGroupId = @rOrgGroupId AND StoreLocationId = @rStoreLocationId)
			 
			IF @lCount  = 1
				BEGIN
					SELECT @rId = Id FROM sIp.tStockItemMaster WHERE ((Code = @rCode)  OR (ISNULL(@rCode, '') = '')) AND ((Title = @rTitle) OR (ISNULL(@rTitle, '') = '') AND OrgGroupId = @rOrgGroupId AND StoreLocationId = @rStoreLocationId) 
					IF EXISTS(SELECT Id FROM sProcurement.tStockBatch  WHERE StockItemId = @rId  )
						BEGIN
							SET @lSreffered = 1
						END
					ELSE IF EXISTS(SELECT Id FROM sProcurement.tPurchaseOrderDetail WHERE ItemSourceTypeId = 34 AND ItemSourceId = @rId  )
						BEGIN
							SET @lSreffered = 1
							 
						END
				END
		END		
	ELSE IF @rId <> 0 
		BEGIN
			IF EXISTS(SELECT Id FROM sProcurement.tStockBatch  WHERE StockItemId = @rId  )
					BEGIN
						SET @lSreffered = 1
					END
					ELSE IF EXISTS(SELECT Id FROM sProcurement.tPurchaseOrderDetail WHERE ItemSourceTypeId = 34 AND ItemSourceId = @rId  )

					BEGIN
						  SET @lSreffered = 1
					END
		END
	 
 
	 
 
	 SELECT 
			Row_Number() OVER(ORDER BY SIM.Id) AS RowNumber,
	        @lSreffered AS lSreffered,
	        SIM.Id,
			SIM.Code,
			--IMGM.Title AS ItemMainGroup,
			SIM.Title,
			SIM.CreatedUserId,
			SIM.CreatedDateTime,
			SIM.UpdatedUserId,
			SIM.UpdatedDateTime,
			--SIM.StockItemTypeId,
			ISNULL(SIM.StockItemCategoryId,0) AS StockItemCategoryId,			 
			SIM.IsBatchWiseTracking,		 
			--SIM.IsCritical,
			--SIM.IsDangerousDrug,
			--SIM.IsPoison,
			--SIM.IsPsychotropic,
			SIM.IssueStockUomId,
			ISNULL(SIM.ItemSubGroupId,0) AS ItemSubGroupId,
			SIP.MaximumInventory,
			--SIM.PatentDrugName,
			SIP.ReOrderPoint,
			SIP.SafetyStock,
			--SIM.IsNotInStore,
			--SIM.IsAllowDirectIssue,
			--SIM.DrugInstructionId, 	 
			--SIM.StandardPrice,	
			ISNULL(SIM.TaxGroupId,0) AS TaxGroupId,  	 
			ISNULL(SIM.VendorId, '0') VendorId, 
			ISNULL(ven.Title,'') AS VENDORTITLE,			 		 
			SGM.ItemMainGroupId AS MAINID,
		    --SIM.IsDrug,		    
		    ISNULL(CAST(SIP.StandardPrice AS DECIMAL(18, 2)), '0') StandardPrice,
		    ISNULL(CAST(SIP.LastPurchasePrice AS DECIMAL(18, 2)), '0') LastPurchasePrice,
		    ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0') WeightedAverageCost,		    
		    ISNULL(SIM.IsObsolete, '0') IsObsolete,
		    SOM.Title AS IssueStockUOMTitle,
		    SIM.StoreLocationId,
		    SIM.IsBlockedForIssue,
		    --SIM.IsFirstAdd,
		    SIM.Remark AS DrugRemark,
		    ISNULL(SIP.Id,0) AS StockItemPlanningId,
		    --SIM.Reminder,
		    SGM.Title AS SubGroupName,
		    IMGM.Title AS MainGroupName,
		    ISNULl(B.Id,0) as BinId,
		     B.Title As BinTitle,
		     isnull(SIP.ReorderQuantity,0) AS ReorderQuantity
		    --COUNT(*) over() AS TotalRecords		    
		   
						
FROM sIp.tStockItemMaster SIM 
LEFT JOIN sIp.tStockItemPlanning SIP 
ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
INNER JOIN  sIp.tItemSubGroupMaster  SGM 
ON SIM.ItemSubGroupId = SGM.Id 
INNER JOIN  sIp.tItemMainGroupMaster IMGM
ON IMGM.Id=SGM.ItemMainGroupId
LEFT JOIN sFinanceCommon.tStockUomMaster SOM
ON SIM.IssueStockUomId = SOM.Id 
LEFT JOIN sprocurement.vExtVendorMaster ven 
ON SIM.vendorid = ven.Id 
LEFT JOIn sIp.tBinMaster B ON B.ID= SIM.BinID
WHERE
((SIM.Id = @rId) OR (@rId = 0))
AND	((SIM.Code LIKE @rCode) OR (ISNULL(@rCode, '') = ''))
AND ((SIM.Title LIKE @rTitle + '%' ) OR (ISNULL(@rTitle, '') = '')) --add '%' for mantis id - 0035279
AND SIM.OrgGroupId = @rOrgGroupId 
AND ((SIM.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
AND ((SIM.ItemSubGroupId = @rItemSubGroupId) OR (@rItemSubGroupId = 0))
AND ((SGM.ItemMainGroupId = @rItemMainGroupId) OR (@rItemMainGroupId = 0))

 
END 



/****** Object:  StoredProcedure [sIp].[pStockItemPlanningAdd]    Script Date: 07/09/2013 16:12:45 ******/
SET ANSI_NULLS ON
GO
PRINT N'Altering Procedure [sLibrary].[pRptReaderBookListGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptReaderBookListGet]

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

BEGIN
	If(@rReaderSourceTypeId=2003)
	BEGIN
		SELECT

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

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

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


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

BEGIN 
	--Changes for Mantis Id : 0034676
	DECLARE @lConfigValue nvarchar(50) = ''

	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 559 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

	IF(@lConfigValue='True')
	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

	ELSE 
	BEGIN
		SELECT 
			 PPE.PayElementId,
			 PE.Title AS PayElement,
			 CAST(PPE.Amount AS decimal(12,0)) AS 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
	     
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)
	
	--Changes for Mantis Id : 0034676
	DECLARE @lConfigValue nvarchar(50) = ''
	DECLARE @lOrgGroupId int

	select @lOrgGroupId = OrgGroupId From sPayroll.tPayrollYearMaster where Id = @rPayrollYearId

	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 559 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	
	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)

	IF(@lConfigValue = 'False' AND @rReportId = 10197)
	BEGIN
		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,
			CAST(PPE.TotalEarning AS DECIMAL(12,0)) AS TotalEarning,		
			CAST(PPE.TotalDeduction AS DECIMAL(12,0)) AS TotalDeduction,
			CAST(PPE.NetAmount AS DECIMAL(12,0)) AS NetAmount,
			CAST((CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END)AS DECIMAL(12,0)) AS TotalEarningTotal,
			CAST((CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END)AS DECIMAL(12,0)) AS TotalDeductionTotal,
			CAST((CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END)AS DECIMAL(12,0))  AS NetAmountTotal,
			CAST(PE.Amount AS DECIMAL(12,0)) 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
			--LEFT JOIN sHrm.tEmployeeWorkingDays EWD ON tEM.Id = EWD.EmployeeId AND PP.SalaryMonth=EWD.ForMonth AND PP.SalaryYear=EWD.ForYear
		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 ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --		  AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
			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
	ELSE
	BEGIN
		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
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockAdjustmentRegisterGet]...';


GO
 
ALTER PROCEDURE [sProcurement].[pRptStockAdjustmentRegisterGet]
  @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100),
	@rOrgGroupId int,
	@rFromDate date = '',
	@rToDate date = '',
	@rDetail bit =0,
	@rFromRegisterNo int = 0,		-- #Start Mantis Id : 0035096
	@rToRegisterNo int = 0,			
	@rFromRegisterNoYear int = 0,
	@rToRegisterNoYear int = 0		-- #End Mantis Id : 0035096
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
				SIM.Code AS ItemCode,
				SIM.Title AS ItemName,		
				SI.Number AS Billno, 	
				SI.CreatedDateTime AS IssuedDate,
				ID.SystemQuantity,
				ID.PhysicalQuantity,
				 
				SB.ExpiryDate,
				--SB.Price AS Amount,
				SB.Number As BatchNumber,
				SI.Id,
				@rDetail AS Detail,
				@rBuilder1 As Builder1,
				@rBuilder2 AS Builder2,
				SIM.IsObsolete
				
		FROM  sProcurement.tStockAdjustment SI		
		INNER JOIN sProcurement.tStockAdjustmentDetail ID ON SI.Id = ID.StockAdjustmentId 
		INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
	    LEFT JOIN sProcurement.tStockBatch SB ON SB.Id = ID.StockBatchId
	    
	    INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
		INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
		LEFT JOIN sIp.tStockItemCategoryMaster SICM ON SICM.Id=SIM.StockItemCategoryId	
		 
		  WHERE	     
	     --SIM.IsObsolete=0
		  (SB.StoreLocationId= @rStoreLocationId)
		AND (IMGM.Id = @rMainGroupId OR @rMainGroupId=0)
		AND (ISGM.Id = @rSubGroupId OR @rSubGroupId=0)
		AND (SICM.Id = @rStockItemCategoryId OR @rStockItemCategoryId = 0)
		AND (SIM.Code = @rItemCode OR @rItemCode = '')
		AND (SIM.Title = @rItemName OR @rItemName = '')
		AND ((CAST(SI.CreatedDateTime AS DATE) >= CAST(@rFromDate AS DATE)) OR (ISNULL(@rFromDate,'') = '')) 
		AND ((CAST(SI.CreatedDateTime AS DATE) <= CAST(@rToDate AS DATE)) OR (ISNULL(@rToDate,'') = '') )
		AND (SB.OrgGroupId = @rOrgGroupId)
		-- #Start Mantis Id : 0035096
		AND ((SI.Number IS NOT NULL AND LEN(SI.Number) >= 6 AND ISNUMERIC(SUBSTRING(SI.Number, 3, 2)) = 1 AND ISNUMERIC(SUBSTRING(SI.Number, 6, LEN(SI.Number) - 5)) = 1 
			AND (CAST(SUBSTRING(SI.Number, 3, 2) AS INT) > @rFromRegisterNoYear OR (CAST(SUBSTRING(SI.Number, 3, 2) AS INT) = @rFromRegisterNoYear AND CAST(SUBSTRING(SI.Number, 6, LEN(SI.Number) - 5) AS INT) >= @rFromRegisterNo)))
			OR @rFromRegisterNoYear = 0 OR @rFromRegisterNo = 0)
		AND ((SI.Number IS NOT NULL AND LEN(SI.Number) >= 6 AND ISNUMERIC(SUBSTRING(SI.Number, 3, 2)) = 1 AND ISNUMERIC(SUBSTRING(SI.Number, 6, LEN(SI.Number) - 5)) = 1 
			AND (CAST(SUBSTRING(SI.Number, 3, 2) AS INT) < @rToRegisterNoYear OR (CAST(SUBSTRING(SI.Number, 3, 2) AS INT) = @rToRegisterNoYear AND CAST(SUBSTRING(SI.Number, 6, LEN(SI.Number) - 5) AS INT) <= @rToRegisterNo)))
			OR @rToRegisterNoYear = 0 OR @rToRegisterNo = 0)
		-- #End Mantis Id : 0035096
		 
    Order  by SIM.Title	
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockInwardRegisterGet]...';


GO
 
ALTER PROCEDURE [sProcurement].[pRptStockInwardRegisterGet]
   
    @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100),
	@rOrgGroupId int,
	@rFromDate datetime = '',
	@rToDate datetime = '',
	@rDetail bit =0,
	@rVendorID int=0,
	@rFromInwardNo int = 0,		-- #Start Mantis Id : 0035096
	@rToInwardNo int = 0,			
	@rFromInwardNoYear int = 0,
	@rToInwardNoYear int = 0		-- #End Mantis Id : 0035096
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
		SIM.Code AS ItemCode,
		SIM.Title AS ItemName,		
		SI.InwardByName,	
		SI.Number AS Billno, 	
		SI.TransactionDate AS IssuedDate,
		ID.InwardQuantity,
		ID.RequestedQuantity,
		SB.ExpiryDate,
		SIP.WeightedAverageCost AS Amount,
		SB.Number As BatchNumber,
		SI.Id AS  StockInwardId,
		@rDetail AS Detail,
		@rBuilder1 As Builder1,
		@rBuilder2 AS Builder2,
		VM.Code AS VendorCOde,
		VM.Title As VendorTitle,
		SB.StoreLocationId,
		SUOM.Title AS UOM,
		SI.CreatedDateTime AS TransactionDate,
		SIReq.CreatedDateTime AS RequestedDate,
		ID.InwardValue
				
  FROM  sProcurement.tStockInward SI		
		INNER JOIN sProcurement.tStockInwardDetail ID ON SI.Id = ID.StockInwardId
		INNER JOIN sProcurement.tStockInwardBatch SIB ON ID.Id = SIB.StockInwardDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
	    LEFT JOIN sProcurement.tStockBatch SB ON SB.StockItemId = SIM.Id
	    LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id = SI.VendorId
	    INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
		INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
		LEFT JOIN sIp.tStockItemCategoryMaster SICM ON SICM.Id=SIM.StockItemCategoryId	
		INNER JOIN sFinanceCommon.tStockUomMaster SUOM ON SUOM.Id = SIM.IssueStockUomId 
		LEFT JOIN	sProcurement.tStockInwardRequest SIReq ON SIReq.Id = SI.StockInwardRequestId
		 
  WHERE	SIM.IsObsolete=0
		AND(SB.StoreLocationId= @rStoreLocationId)
		AND (IMGM.Id = @rMainGroupId OR @rMainGroupId=0)
		AND (ISGM.Id = @rSubGroupId OR @rSubGroupId=0)
		AND (SICM.Id = @rStockItemCategoryId OR @rStockItemCategoryId = 0)
		AND (SIM.Code = @rItemCode OR @rItemCode = '')
		AND (SIM.Title = @rItemName OR @rItemName = '')
		AND ((CONVERT(DATE,SI.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) 
		AND ((CONVERT(DATE,SI.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = '') )
		AND (SB.OrgGroupId = @rOrgGroupId)
		AND ((SI.VendorId=@rVendorID) OR (@rVendorId=0))
		-- #Start Mantis Id : 0035096
		AND ((SI.Number IS NOT NULL AND LEN(SI.Number) >= 7 AND ISNUMERIC(SUBSTRING(SI.Number, 4, 2)) = 1 AND ISNUMERIC(SUBSTRING(SI.Number, 7, LEN(SI.Number) - 6)) = 1 
			AND (CAST(SUBSTRING(SI.Number, 4, 2) AS INT) > @rFromInwardNoYear OR (CAST(SUBSTRING(SI.Number, 4, 2) AS INT) = @rFromInwardNoYear AND CAST(SUBSTRING(SI.Number, 7, LEN(SI.Number) - 6) AS INT) >= @rFromInwardNo)))
			OR @rFromInwardNoYear = 0 OR @rFromInwardNo = 0)
		AND ((SI.Number IS NOT NULL AND LEN(SI.Number) >= 7 AND ISNUMERIC(SUBSTRING(SI.Number, 4, 2)) = 1 AND ISNUMERIC(SUBSTRING(SI.Number, 7, LEN(SI.Number) - 6)) = 1 
			AND (CAST(SUBSTRING(SI.Number, 4, 2) AS INT) < @rToInwardNoYear OR (CAST(SUBSTRING(SI.Number, 4, 2) AS INT) = @rToInwardNoYear AND CAST(SUBSTRING(SI.Number, 7, LEN(SI.Number) - 6) AS INT) <= @rToInwardNo)))
			OR @rToInwardNoYear = 0 OR @rToInwardNo = 0)
		-- #End Mantis Id : 0035096

    Order  by SIM.Title	
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockIssueReturnRegisterGet]...';


GO
ALTER PROCEDURE [sProcurement].[pRptStockIssueReturnRegisterGet]
  @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rStockItemCategoryId int,
	@rItemCode nvarchar(100),
	@rItemName nvarchar(100),
	@rOrgGroupId int,
	@rFromDate datetime = '',
	@rToDate datetime = '',
	@rDetail bit =0,
	@rFromReturnNo int = 0,		-- #Start Mantis Id : 0035096
	@rToReturnNo int = 0,			
	@rFromReturnNoYear int = 0,
	@rToReturnNoYear int = 0,
	@rFromReturnDate Date = null,
	@rToReturnDate	Date = null	-- #End Mantis Id : 0035096
	
WITH EXECUTE AS CALLER
AS
BEGIN
   SELECT  
				SIM.Code AS ItemCode,
				SIM.Title AS ItemName,		
				SI.ReturnedByName,	
				SI.Number AS Billno, 	
				SI.CreatedDateTime AS IssuedDate,
				SIND.IssuedQuantity, 
				SB.ExpiryDate,
				SB.ItemRate AS Amount,
				--SB.Number As BatchNumber,
				SI.Id, 
				@rDetail AS Detail,
				@rBuilder1 As Builder1,
				@rBuilder2 AS Builder2,
				SIRB.ReturnQuantity,
				PSI.Remark,--mantis - 0032620
				SIP.WeightedAverageCost			-- MantisId : 0034833
				
				
		FROM  sProcurement.tStockIssueReturn SI
		INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SI.Id
		INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id=SIRB.StockIssueBatchId
		INNER JOIN sProcurement.tStockIssueDetail SIND ON SIND.Id=SIB.StockIssueDetailId
		INNER JOIN sIp.tStockItemMaster SIM ON SIND.StockItemId  = SIM.Id 
		LEFT JOIN sProcurement.tStockBatch SB ON SB.Id = SIB.StockBatchId
	     
	    INNER JOIN sIp.tItemSubGroupMaster ISGM ON ISGM.Id=SIM.ItemSubGroupId
		INNER JOIN sIp.tItemMainGroupMaster IMGM ON IMGM.Id=ISGM.ItemMainGroupId
		LEFT JOIN sIp.tStockItemCategoryMaster SICM ON SICM.Id=SIM.StockItemCategoryId	
		LEFT Join sProcurement.tStockIssue PSI on PSI.ID = SI.StockIssueId--mantis - 0032620
		INNER JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId		-- MantisId : 0034833
		 
		  WHERE	     
	     SIM.IsObsolete=0
		--AND(SB.StoreLocationId= @rStoreLocationId)
		AND (IMGM.Id = @rMainGroupId OR @rMainGroupId=0)
		
		AND (ISGM.Id = @rSubGroupId OR @rSubGroupId=0)
		AND (SICM.Id = @rStockItemCategoryId OR @rStockItemCategoryId = 0)
		AND (SIM.Code = @rItemCode OR @rItemCode = '')
		AND (SIM.Title = @rItemName OR @rItemName = '')
		AND ((SI.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) 
		AND ((SI.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'') = '') )
		AND SI.OrgGroupId=@rOrgGroupId
		AND SB.StoreLocationId =@rStoreLocationId
		----AND (SB.OrgId = @rOrgId)
		-- #Start Mantis Id : 0035096
		AND ((SI.Number IS NOT NULL AND LEN(SI.Number) >= 7 AND ISNUMERIC(SUBSTRING(SI.Number, 4, 2)) = 1 AND ISNUMERIC(SUBSTRING(SI.Number, 7, LEN(SI.Number) - 6)) = 1 
			AND (CAST(SUBSTRING(SI.Number, 4, 2) AS INT) > @rFromReturnNoYear OR (CAST(SUBSTRING(SI.Number, 4, 2) AS INT) = @rFromReturnNoYear AND CAST(SUBSTRING(SI.Number, 7, LEN(SI.Number) - 6) AS INT) >= @rFromReturnNo)))
			OR @rFromReturnNoYear = 0 OR @rFromReturnNo = 0)
		AND ((SI.Number IS NOT NULL AND LEN(SI.Number) >= 7 AND ISNUMERIC(SUBSTRING(SI.Number, 4, 2)) = 1 AND ISNUMERIC(SUBSTRING(SI.Number, 7, LEN(SI.Number) - 6)) = 1 
			AND (CAST(SUBSTRING(SI.Number, 4, 2) AS INT) < @rToReturnNoYear OR (CAST(SUBSTRING(SI.Number, 4, 2) AS INT) = @rToReturnNoYear AND CAST(SUBSTRING(SI.Number, 7, LEN(SI.Number) - 6) AS INT) <= @rToReturnNo)))
			OR @rToReturnNoYear = 0 OR @rToReturnNo = 0)
		AND (SI.TransactionDate >= @rFromReturnDate OR @rFromReturnDate IS NULL)
		AND (SI.TransactionDate <= @rToReturnDate OR @rToReturnDate IS NULL)
		-- #End Mantis Id : 0035096
		 
    Order  by SIM.Title	
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockIssueNumberGet]...';


GO

ALTER PROCEDURE [sProcurement].[pStockIssueNumberGet]
	
	
	@rId int,
	@rStorelocationId int,
	@rNumber nvarchar(50) = ''
 			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN


	SELECT
		SI.Id,
		SIM.Code AS StockItemCode,
		SIM.Title AS StockItemName,
		SIND.IssuedQuantity, 
		SIB.Id AS StockIssueBatchId,
		SIB.StockBatchId,
		Sb.Number as 'StockBatchNumber' ,
		SIND.Id AS StockIssueDetailId,
		SIM.Id AS StockItemId,
		ISNULL((SELECT ISNULL(SUM(SIRB.ReturnQuantity),0) FROM sProcurement.tStockIssueReturn SIR 
		INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SIR.Id WHERE SIR.StockIssueId=SI.Id AND SIRB.StockIssueBatchId=SIB.Id),0)
		AS ReturnedQuantity,
		SIND.IssuedQuantity AS IssueQuantity,
		ISNULL(SI.IssueToSourceTypeId,0) IssueToSourceTypeId,	-- MantisId : 0034851	
		ISNULL(SI.IssueToSourceId,0) IssueToSourceId,
		ISNULL(SI.PayTypeId,0) PayTypeId

	FROM 
		sProcurement.tStockIssue SI 
		INNER JOIN sProcurement.tStockIssueDetail SIND ON SIND.StockIssueId=SI.Id
		INNER JOIN sProcurement.tStockIssueBatch  SIB ON SIB.StockIssueDetailId=SIND.Id
		left join sProcurement.tStockBatch Sb on sb.id = SIB.StockBatchId and sb.Number is not null
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId	
			
	WHERE 
		((SI.Id = @rId) OR (@rId = 0))
		AND	((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
		AND SI.FromStoreLocationId=@rStorelocationId
		 			   
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 = 95 then SI.IssueToName ELSE SA.Name 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 = 95 then SI.IssueToName ELSE SA.Name 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 [sRecruitment].[pRecruitmentDocumentGet]...';


GO

ALTER PROCEDURE [sRecruitment].[pRecruitmentDocumentGet]
	 
	@rVacancyId bigint,
	@rDocumentId int,
	@rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
WITH CombinedResults AS ( -- Changed for mantis : 35443 by Nilesh
	SELECT 
		RCD.VacancyId,RCD.SubmitDocumentMasterId AS DocumentId,SDM.DocumentName,ISNULL(RCD.Remark,'') AS Remark,ISNULL(RCD.IsMandatory,0) IsMandatory 
	FROM 
		sRecruitment.tRecruitmentCriteriaDocument RCD
		LEFT JOIN sCommon.tSubmitDocumentMaster SDM ON SDM.Id = RCD.SubmitDocumentMasterId and SDM.OrgId=@rOrgId
	WHERE 
		(RCD.VacancyId = @rVacancyId OR ISNULL(@rVacancyId,0)=0)
		AND (RCD.SubmitDocumentMasterId = @rDocumentId OR ISNULL(@rDocumentId,0)=0)

		UNION
		SELECT 
		0 VacancyId,Id AS DocumentId,DocumentName,'' AS Remark,CAST('FALSE' as bit) IsMandatory
	FROM 
		sCommon.tSubmitDocumentMaster SDM		
		WHERE  SubmitDocumentFunctionalityId=4 AND ID NOT IN(SELECT SubmitDocumentMasterId FROM sRecruitment.tRecruitmentCriteriaDocument WHERE VacancyId = @rVacancyId )
		AND OrgId=@rOrgId
			)

	/******Added for mantis : 35443 by Nilesh******/
	SELECT 
	    VacancyId,
	    DocumentId,
	    DocumentName,
	    Remark,
	    IsMandatory
	FROM 
	    CombinedResults
	ORDER BY 
	    DocumentId ASC;

END
GO
PRINT N'Altering Procedure [sSecurity].[pOrgGroupMobileApiGet]...';


GO
ALTER PROCEDURE [sSecurity].[pOrgGroupMobileApiGet]
	 @rOrgGroupId int
	 
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		 

BEGIN 
	 
	SELECT 
		OGMA.OrgGroupId,
		OGMA.Code,
		OGMA.Title,
		ISNULL(OGMA.ApiUrl,'') AS ApiUrl,
		ISNULL(OGMA.MigrationApiUrl, '') AS ApiUrlMigration    -- For ERP – Add Mingration API URL in Mobile App Registration BY Foram
  FROM 
       sSecurity.tOrgGroupMobileApp OGMA
  WHERE 
      OGMA.OrgGroupId=@rOrgGroupId
END
GO
PRINT N'Altering Procedure [sStudent].[pRptCountCategorywiseStudentGet]...';


GO
ALTER PROCEDURE [sStudent].[pRptCountCategorywiseStudentGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAsOnDate date,
	 @rReportId int,
	 @rDepartmentId int,
	 @rStudentCode varchar(20),
	 @rCasteCategoryIds nvarchar(max) = '',
	 @rReligionIds nvarchar(max) = '',
	 @rGenderIds nvarchar(max) = '',
	 @rAdmissionCatgoryIds nvarchar(max) = '',
	 @rClassGroup bit=0,
	 @rDivisionGroup bit=0,
	 @rTribeIds nvarchar(max) = '',
	 --added by megha for 0027269
	 @rMainCasteCategoryIds nvarchar(max) = '',
	 @rStatusId int = 0,			-- MantisId : 0032948
	 @rClassStatusId smallint=0			-- MantisId : 0032948
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
  
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(GM.Title,'') As Gender,
			A.ClassId,
			A.DivisionId,
			A.Id AS AcademicId,
			A.RollNo,
			SO.DateOfBirth,
			SA.AdmissionDate,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassDivision,
			SM.FirstName +' '+ SM.MiddleName +' '+ SM.LastName AS Name,
			SM.Code,
			CCM.OrderIndex AS CasteNumber,
			CASE WHEN  @rReportId=10135 OR @rReportId=20702-- Caste Category
			THEN ISNULL(CCM.Title,'')
		    WHEN  @rReportId=10136 OR @rReportId=20703 -- Religion
			THEN ISNULL(RM.Title,'') 
			WHEN  @rReportId=20704 -- Gender
			THEN ISNULL(GM.Title,'') 
			WHEN @rReportId=20328 OR @rReportId=20705 -- Admission Catgory 
			THEN ISNULL(SCM.Title,'')
			WHEN  @rReportId=10152 -- BloodGroupwise Summary
			THEN ISNULL(BGM.Title,'') 
			WHEN  @rReportId=20329 OR @rReportId=20706--Agegroupwise
			THEN  ([sStudent].[fStudentAgeGroupGet](SO.DateOfBirth,@rAsOnDate,@rOrgId))
			--WHEN  @rReportId=20426 OR @rReportId=20707  --Age wise
			--THEN  ([sStudent].[fStudentAgeGet](SO.DateOfBirth,@rAsOnDate,@rOrgId) + ' Y')
			WHEN    @rReportId = 20866 OR @rReportId=20426 OR @rReportId=20707
			
			THEN RIGHT('00'+ CAST([sStudent].[fStudentAgeGet](SO.DateOfBirth,@rAsOnDate,@rOrgId) AS VARCHAR(2)), 2)+' Year '
			
			WHen @rReportId=30236
			THEN ISNULL(HM.Title,'')
			WHEN  @rReportId=31039 OR @rReportId=31040 -- Tribe
			THEN ISNULL(TM.Title,'')
			--added by megha for 0027269
			WHEN @rReportId=31266
			THEN  ISNULL(MCM.Title,'')  --MainCasteCategory

			END AS Head,
			DM.OrderIndex AS DivisionOrder,
			@rClassGroup As ClassGroup,
			@rDivisionGroup As DivisionGroup,
			Cm.OrderINdex AS ClassOrderIndex,
			CASE WHEN  @rReportId=10135 OR @rReportId=20702-- Caste Category
			THEN ISNULL(CCM.OrderIndex,'')
		    WHEN  @rReportId=10136 OR @rReportId=20703 -- Religion
			THEN ISNULL(RM.OrderIndex,'')  
			ELSE ''
			END AS OrderIndex,
			A.OrgId
			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 sActivity.tHouseMaster HM ON HM.Id=SO.HouseID
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
			LEFT JOIN sCommon.tTribeMaster TM ON TM.Id=SO.TribeId   -- Tribe
			--added by megha for 0027269
			LEFT JOIN sCommon.tMainCastCategoryMaster MCM ON MCM.Id = CCM.MainCastCategoryId   -- MainCastCategory
	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 OR @rReportId = 20328  OR @rReportId = 10153)	-- MantisId : 0032948, Mantis - 35166(10153 = GenderwiseSummary)
		AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	    AND (ISNULL(CCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rCasteCategoryIds,','))OR @rCasteCategoryIds='')
	    AND (ISNULL(RM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionIds,','))OR @rReligionIds='')
	    AND (ISNULL(GM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderIds,','))OR @rGenderIds='')
	    AND (ISNULL(SCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCatgoryIds,','))OR @rAdmissionCatgoryIds='')
		AND (ISNULL(TM.Id,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rTribeIds,','))OR @rTribeIds='')
	    AND ((SA.AdmissionDate<=@rAsOnDate) OR (ISNULL(@rAsOnDate,'') = ''))
		AND (ISNULL(MCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMainCasteCategoryIds,','))OR @rMainCasteCategoryIds='')
		AND (SM.StatusId = @rStatusId OR @rStatusId = 0)				-- MantisId : 0032948
		AND (A.ClassStatusId = @rClassStatusId OR @rClassStatusId = 0)	-- MantisId : 0032948
END

 
	--Select * from sStudent.tStudentAdmission where AdmissionDate = '2013-05-12'
GO
PRINT N'Altering Procedure [sStudent].[pRptStudentRegisterGet]...';


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

BEGIN 

	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassDivision,
			SD.Code,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,		
			SD.ClassName,
			SD.DivisionName,
			SD.StatusName,
			SD.StatusId,
			SD.LCProgress,
			SD.Religion,
			SD.FamilyCast,
			SD.FamilySubCast,
			SD.LCConduct,
			SD.BirthPlace,
			SD.BirthTaluka,
			SD.BirthDistrict,
			SD.LeftDate,
			SD.PreviousSchool,
			SD.DateOfBirth,
			SD.BirthDateInWord,
			SD.LeftReason,
			SD.AdmissionDate,
			SD.AdmissionStandard,
			SD.LeftStandard,
			SD.LCNumber,
			SD.LCDate,
			SD.StudentPhoto,
			SD.BloodGroup,
			SD.PresentAddress,
			SD.ContactNo,
			SD.Batch,
			SD.InactiveDate,
			OM.Title AS OrgName,
			SF.MotherName,
			SD.DivisionOrder,
			SD.Number AS StudentNumber,
			SF.FatherName,
			SD.Nationality,
			SD.MotherTongue,
			SD.BirthState,
			SD.BirthCountry,
			SD.SUId,
            SD.AdhaarNumber,
            SD.ClassStatusId,
            SD.ClassStatusName,
			SD.UIDNumber,
			SD.Gender,
			SF.FatherOfficeContactNo,
			SF.MotherOfficeContactNo,
			SD.ParentContactNo --mantis id : 0035187
			
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassID AND BC.BatchId = SD.BatchId AND SD.BatchId= @rBatchId
			--LEFT JOIN sStudent.tStudentAdmission SAM ON SD.StudentId=SAM.StudentId				
			--AND ((SAM.AdmissionDate>=@rFromAdmissionDate)OR(ISNULL(@rFromAdmissionDate,'')=''))    
			--AND ((SAM.AdmissionDate<=@rToAdmissionDate)OR(ISNULL(@rToAdmissionDate,'')=''))  
			--AND	SAM.BatchId = @rBatchId   
	WHERE 
		SD.OrgId=@rOrgId
		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.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND ((MONTH(SD.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=0))
	    AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	    AND((SD.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	    AND((SD.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))
		AND((SD.Number>=@rFromNumber) OR (ISNULL(@rFromNumber,0)=0))
	    AND((SD.Number<=@rToNumber) OR (ISNULL(@rToNumber,0)=0))
		AND((SD.AdmissionDate>=@rFromAdmissionDate) OR (ISNULL(@rFromAdmissionDate,'')=''))		
		AND((SD.AdmissionDate<=@rToAdmissionDate) OR (ISNULL(@rToAdmissionDate,'')=''))			
	   
	 Order by
	 SD.RollNo
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentImportGet]...';


GO

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

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


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

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

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

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

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

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

	EXEC sp_xml_removedocument @intDoc

	--select * from  #tempTable

	SELECT @lCount = COUNT(Id) FROM #tempTable

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

		SELECT @lToBatchId = Id from sSetup.tBatchMaster where Title = @lToBatch AND OrgId = @rOrgId AND ISObsolete = 0
		SELECT @lFromClassId = Id from sSetup.tClassMaster where DisplayTitle = @lFromClass AND OrgId = @rOrgId AND ISObsolete = 0
		SELECT @lFromDivisionId = Id from sSetup.tDivisionMaster where Title = @lFromDivision AND ClassId = @lFromClassId AND ISObsolete = 0

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

		IF EXISTS(SELECT Code from sStudent.tStudentMaster SM INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id where SM.Code = @lCode AND A.BatchId = @lToBatchId AND SM.OrgId = @rOrgId)
		BEGIN
			SET @lValidationMsg += 'Student Already Exist,'
		END

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

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

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

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

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

	SELECT * FROM #tempTable
	DROP TABLE #tempTable
    END TRY 

	BEGIN CATCH 
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering Procedure [sTally].[pReceiptPostingGet]...';


GO
ALTER PROCEDURE [sTally].[pReceiptPostingGet] 
	@rOrgGroupBatchId INT
	,@rReceiptBookId INT
	,@rReceiptDate DATE
	,@rToReceiptDate DATE
	,@rPayTypeId INT = 0
	,@rCustomNarration NVARCHAR(max) = ''
	,@rIsCustomNarration BIT = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lTallyPostingType NVARCHAR(100)
	DECLARE @lOrgGroupId INT

	SELECT @lOrgGroupId = OrgGroupId
	FROM sSetup.tOrgGroupBatchMaster
	WHERE Id = @rOrgGroupBatchId

	SELECT @lTallyPostingType = CASE 
			WHEN CS.ItemValue IS NULL
				THEN C.ItemValue
			ELSE CS.ItemValue
			END
	FROM sConfig.tConfigurationMaster C
	INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
	LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id
		AND CS.SOURCEID = @lOrgGroupId
	WHERE C.ItemKey = 'Tally.PostingType'

	IF @lTallyPostingType = 'FeeHeadWise'
	BEGIN
		SELECT ReceiptDate
			,ISNULL(FHM.Title, '') AS FeeName
			,PM.Title AS PayType
			,Sum(FRD.Amount) AS Amount
			,CASE 
				WHEN @rIsCustomNarration = 1
					THEN STUFF((
								SELECT DISTINCT ',' + Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(replace(@rCustomNarration, '[Class]', isnull(SM1.ClassName, '')), '[Division]', Isnull(SM1.DivisionName, '')), '[StudentsName]', isnull(SM1.Name, '')), '[RollNumber]', isnull(convert(NVARCHAR(200), SM1.RollNo), '0')), '[Batch]', isnull(SM1.BatchName, '')), '[ReceiptNumber]', isnull(Convert(NVARCHAR(100), FR1.ReceiptNumber), '')), '[ReceiptDate]', isnull(Convert(NVARCHAR(100), FR1.ReceiptDate), '')), '[ReceiptAmount]', isnull(Convert(NVARCHAR(100), FR1.ReceiptAmount), '')), '[ChequeNo]', isnull(Convert(NVARCHAR(100), FR1.ChequeNo), '')), '[BankName]', isnull(FR1.BankName, '')), '[FeeName]', isnull(FM1.Title, '')), '[FeeAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[FeeHeadName]', ISNULL(FHM.Title, '')), '[FeeHeadAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[CollectionGroupName]', isNull(CGM1.Title, '')), 
											'[ReceiptFromNumber]', isnull(Convert(NVARCHAR(10), (
														SELECT Min(ReceiptNumber)
														FROM sFee.tReceipt
														WHERE FR.ReceiptDate = ReceiptDate
														)), '')), '[ReceiptToNumber]', isnull(Convert(NVARCHAR(10), (
													SELECT Max(ReceiptNumber)
													FROM sFee.tReceipt
													WHERE FR.ReceiptDate = ReceiptDate
													)), ''))
								FROM sFee.tReceipt FR1
								INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
								INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
								INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID
									AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId
								INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
								LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
								INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
									AND FHM1.Id = FHM.Id
								WHERE FR.ReceiptDate = FR1.ReceiptDate
								GROUP BY SM1.ClassName
									,SM1.DivisionName
									,SM1.Name
									,SM1.RollNo
									,SM1.BatchName
									,FR1.ReceiptNumber
									,FR1.ReceiptDate
									,FR1.ReceiptAmount
									,FR1.ChequeNo
									,FR1.PayTypeId
									,FR1.BankName
									,FM1.Title
									,FHM1.Title
									,CGM1.Title -- Added for Fee amount not show proper in narration
								FOR XML PATH('')
								), 1, 1, '')
				ELSE 'Receipt generated for Batch : ' + (
						SELECT Title
						FROM sSetup.tOrgGroupBatchMaster
						WHERE Id = @rOrgGroupBatchId
						) + ' Receipt Date : ' + Convert(NVARCHAR(10), ReceiptDate) + ' and Receipt Number From ' + Convert(NVARCHAR(10), (
							SELECT Min(ReceiptNumber)
							FROM sFee.tReceipt
							WHERE FR.ReceiptDate = ReceiptDate
								AND IsObsolete = 0
							)) + ' -  ' + Convert(NVARCHAR(10), (
							SELECT Max(ReceiptNumber)
							FROM sFee.tReceipt
							WHERE FR.ReceiptDate = ReceiptDate
								AND IsObsolete = 0
							))
				END AS Narration
			,FR.PayTypeId AS PayTypeId
			,FHM.Id AS FeeId
			,0 AS ReceiptId
			,ISNULL(FR.ChequeNo, '') AS ChequeNo -- Added for mantis 0035195 by Foram
		FROM sFee.tReceipt FR
		INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
		WHERE FR.ReceiptBookId = @rReceiptBookId
			AND FR.IsObsolete = 0
			AND FR.OrgGroupBatchId = @rOrgGroupBatchId
			AND FR.ReceiptDate >= @rReceiptDate
			AND FR.ReceiptDate <= @rToReceiptDate
			AND (
				FR.PayTypeId = @rPayTypeId
				OR @rPayTypeId = 0
				)
		GROUP BY ReceiptDate
			,FHM.Title
			,PM.Title
			,FHM.Id
			,FR.PayTypeId
			,FR.ChequeNo
		ORDER BY ReceiptDate DESC
	END
	ELSE IF @lTallyPostingType = 'FeeHeadWiseCustom'
	BEGIN
		SELECT ReceiptDate
			,FR.Id AS FeeName
			,PM.Title AS PayType
			,Sum(FRD.Amount) AS Amount
			,CASE 
				WHEN @rIsCustomNarration = 1
					THEN STUFF((
								SELECT DISTINCT ',' + Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(replace(@rCustomNarration, '[Class]', isnull(SM1.ClassName, '')), '[Division]', Isnull(SM1.DivisionName, '')), '[StudentsName]', isnull(SM1.Name, '')), '[RollNumber]', isnull(convert(NVARCHAR(200), SM1.RollNo), '0')), '[Batch]', isnull(SM1.BatchName, '')), '[ReceiptNumber]', isnull(Convert(NVARCHAR(100), FR1.ReceiptNumber), '')), '[ReceiptDate]', isnull(Convert(NVARCHAR(100), FR1.ReceiptDate), '')), '[ReceiptAmount]', isnull(Convert(NVARCHAR(100), FR1.ReceiptAmount), '')), '[ChequeNo]', isnull(Convert(NVARCHAR(100), FR1.ChequeNo), '')), '[BankName]', isnull(FR1.BankName, '')), '[FeeName]', isnull(FM1.Title, '')), '[FeeAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[FeeHeadName]', ISNULL(FHM1.Title, '')), '[FeeHeadAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[CollectionGroupName]', isNull(CGM1.Title, '')), 
											'[ReceiptFromNumber]', isnull(Convert(NVARCHAR(10), (
														SELECT Min(ReceiptNumber)
														FROM sFee.tReceipt
														WHERE FR.ReceiptDate = ReceiptDate
															AND IsObsolete = 0
														)), '')), '[ReceiptToNumber]', isnull(Convert(NVARCHAR(10), (
													SELECT Max(ReceiptNumber)
													FROM sFee.tReceipt
													WHERE FR.ReceiptDate = ReceiptDate
														AND IsObsolete = 0
													)), ''))
								FROM sFee.tReceipt FR1
								INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
								INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
								INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID
									AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId
								INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
								LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
								INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
								WHERE FR.ReceiptDate = FR1.ReceiptDate
									AND FR.Id = FR1.Id
									AND FR1.IsObsolete = 0
								GROUP BY SM1.ClassName
									,SM1.DivisionName
									,SM1.Name
									,SM1.RollNo
									,SM1.BatchName
									,FR1.ReceiptNumber
									,FR1.ReceiptDate
									,FR1.ReceiptAmount
									,FR1.ChequeNo
									,FR1.PayTypeId
									,FR1.BankName
									,FM1.Title
									,FHM1.Title
									,CGM1.Title -- Added for Fee amount not show proper in narration
								FOR XML PATH('')
								), 1, 1, '')
				ELSE SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
				END AS Narration
			,FR.PayTypeId AS PayTypeId
			,0 AS FeeId
			,FR.Id AS ReceiptId
			,ISNULL(FR.ChequeNo, '') AS ChequeNo -- Added for mantis 0035195 by Foram
		FROM sFee.tReceipt FR
		INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID
			AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
		LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id = OM.OrgSubGroupId
		WHERE FR.ReceiptBookId = @rReceiptBookId
			AND FR.IsObsolete = 0
			AND FR.OrgGroupBatchId = @rOrgGroupBatchId
			AND FR.ReceiptDate >= @rReceiptDate
			AND FR.ReceiptDate <= @rToReceiptDate
			AND (
				FR.PayTypeId = @rPayTypeId
				OR @rPayTypeId = 0
				)
		GROUP BY ReceiptDate
			,PM.Title
			,FR.PayTypeId
			,FR.Id
			,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
			,FR.ChequeNo
		ORDER BY FR.Id
			,ReceiptDate DESC
	END
	ELSE IF @lTallyPostingType = 'OrgMainGroupWise'
	BEGIN
		SELECT ReceiptDate
			,SM.AcademicId AS FeeName
			,PM.Title AS PayType
			,Sum(FRD.Amount) AS Amount
			,CASE 
				WHEN @rIsCustomNarration = 1
					THEN STUFF((
								SELECT DISTINCT ',' + Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(replace(@rCustomNarration, '[Class]', isnull(SM1.ClassName, '')), '[Division]', Isnull(SM1.DivisionName, '')), '[StudentsName]', isnull(SM1.Name, '')), '[RollNumber]', isnull(convert(NVARCHAR(200), SM1.RollNo), '0')), '[Batch]', isnull(SM1.BatchName, '')), '[ReceiptNumber]', isnull(Convert(NVARCHAR(100), FR1.ReceiptNumber), '')), '[ReceiptDate]', isnull(Convert(NVARCHAR(100), FR1.ReceiptDate), '')), '[ReceiptAmount]', isnull(Convert(NVARCHAR(100), FR1.ReceiptAmount), '')), '[ChequeNo]', isnull(Convert(NVARCHAR(100), FR1.ChequeNo), '')), '[BankName]', isnull(FR1.BankName, '')), '[FeeName]', isnull(FM1.Title, '')), '[FeeAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[FeeHeadName]', ISNULL(FHM1.Title, '')), '[FeeHeadAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[CollectionGroupName]', isNull(CGM1.Title, '')), 
											'[ReceiptFromNumber]', isnull(Convert(NVARCHAR(10), FR1.ReceiptNumber), '')), '[ReceiptToNumber]', isnull(Convert(NVARCHAR(10), FR1.ReceiptNumber), ''))
								FROM sFee.tReceipt FR1
								INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
								INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
								INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID
									AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId
								INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
								LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
								INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
								INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
								WHERE FR.ReceiptDate = FR1.ReceiptDate
									AND PM.Title = PM1.Title
									AND SM.AcademicId = SM1.AcademicId
									AND FR.PayTypeId = FR1.PayTypeId
									AND FR1.IsObsolete = 0
								GROUP BY SM1.ClassName
									,SM1.DivisionName
									,SM1.Name
									,SM1.RollNo
									,SM1.BatchName
									,FR1.ReceiptNumber
									,FR1.ReceiptDate
									,FR1.ReceiptAmount
									,FR1.ChequeNo
									,FR1.PayTypeId
									,FR1.BankName
									,FM1.Title
									,FHM1.Title
									,CGM1.Title -- Added for Fee amount not show proper in narration
								FOR XML PATH('')
								), 1, 1, '')
				ELSE SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
				END AS Narration
			,FR.PayTypeId AS PayTypeId
			,FR.Id AS FeeId
			,SM.AcademicId AS ReceiptId
			,ISNULL(FR.ChequeNo, '') AS ChequeNo -- Added for mantis 0035195 by Foram
		FROM sFee.tReceipt FR
		INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID
			AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
		INNER JOIN sSEtup.tOrganizationMaster OM ON OM.OrgSubGRoupID = @rReceiptBookId
			AND OM.ID = SM.OrgId
		WHERE FR.IsObsolete = 0
			AND FR.OrgGroupBatchId = @rOrgGroupBatchId
			AND FR.ReceiptDate >= @rReceiptDate
			AND FR.ReceiptDate <= @rToReceiptDate
			AND FR.PayTypeID = 2
			AND (
				FR.PayTypeId = @rPayTypeId
				OR @rPayTypeId = 0
				)
		GROUP BY ReceiptDate
			,PM.Title
			,SM.AcademicId
			,FR.PayTypeId
			,FR.Id
			,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
			,FR.ChequeNo
		ORDER BY FR.Id
			,ReceiptDate DESC
	END
	ELSE IF @lTallyPostingType = 'ReceiptWise'
	BEGIN
		SELECT ReceiptDate
			,ISNULL(SLM.LedgerName, '') AS FeeName
			,PM.Title AS PayType
			,FR.ReceiptAmount AS Amount
			,CASE 
				WHEN @rIsCustomNarration = 1
					THEN STUFF((
								SELECT DISTINCT ',' + + Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(replace(@rCustomNarration, '[Class]', isnull(SM1.ClassName, '')), '[Division]', Isnull(SM1.DivisionName, '')), '[StudentsName]', isnull(SM1.Name, '')), '[RollNumber]', isnull(convert(NVARCHAR(200), SM1.RollNo), '0')), '[Batch]', isnull(SM1.BatchName, '')), '[ReceiptNumber]', isnull(Convert(NVARCHAR(100), FR1.ReceiptNumber), '')), '[ReceiptDate]', isnull(Convert(NVARCHAR(100), FR1.ReceiptDate), '')), '[ReceiptAmount]', isnull(Convert(NVARCHAR(100), FR1.ReceiptAmount), '')), '[ChequeNo]', isnull(Convert(NVARCHAR(100), FR1.ChequeNo), '')), '[BankName]', isnull(FR1.BankName, '')), '[FeeName]', isnull(FM1.Title, '')), '[FeeAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[FeeHeadName]', ISNULL(FHM1.Title, '')), '[FeeHeadAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[CollectionGroupName]', isNull(CGM1.Title, '')), 
											'[ReceiptFromNumber]', isnull(Convert(NVARCHAR(10), FR1.ReceiptNumber), '')), '[ReceiptToNumber]', isnull(Convert(NVARCHAR(10), FR1.ReceiptNumber), ''))
								FROM sFee.tReceipt FR1
								INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
								INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
								INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID
									AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId
								INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
								LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
								INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
								INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
								LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId
									AND SLM1.ReceiptBookid = FR1.ReceiptBookId
									AND SLM.LedgerName = SLM1.LedgerName
								WHERE FR1.ReceiptDate = FR.ReceiptDate
									AND FR1.PayTypeId = FR.PayTypeId
									AND A.StudentId = SM1.StudentId
									AND FR.ReceiptAmount = FR1.ReceiptAmount
									AND FR1.IsObsolete = 0
								GROUP BY SM1.ClassName
									,SM1.DivisionName
									,SM1.Name
									,SM1.RollNo
									,SM1.BatchName
									,FR1.ReceiptNumber
									,FR1.ReceiptDate
									,FR1.ReceiptAmount
									,FR1.ChequeNo
									,FR1.PayTypeId
									,FR1.BankName
									,FM1.Title
									,FHM1.Title
									,CGM1.Title -- Added for Fee amount not show proper in narration
								FOR XML PATH('')
								), 1, 1, '')
				ELSE CASE 
						WHEN FR.PayTypeId = 1
							THEN 'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(NVARCHAR(20), RollNo) + ' ' + BatchName + '-->' + STUFF((
										SELECT ',' + convert(NVARCHAR(20), isnull(FRD1.Amount, '')) + '-' + isnull(FM1.Title, '')
										FROM sFee.tReceipt FR1
										INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
										INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
										INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId
											AND FRD.ReceiptId = FRD1.ReceiptId
										FOR XML PATH('')
										), 1, 1, '')
						WHEN FR.PayTypeId <> 1
							THEN 'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(NVARCHAR(20), RollNo) + ' ' + BatchName + '-->' + STUFF((
										SELECT ',' + convert(NVARCHAR(20), isnull(FRD1.Amount, '')) + '-' + isnull(FM1.Title, '')
										FROM sFee.tReceipt FR1
										INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
										INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
										INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId
											AND FRD.ReceiptId = FRD1.ReceiptId
										FOR XML PATH('')
										), 1, 1, '') + '  Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
						END
				END AS Narration
			,
			--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')'
			--AS Narration,					
			FR.PayTypeId AS PayTypeId
			,A.StudentId AS FeeId
			,FRD.ReceiptId
			,ISNULL(FR.ChequeNo, '') AS ChequeNo -- Added for mantis 0035195 by Foram
		FROM sFee.tReceipt FR
		INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
		INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId
			AND A.OrgGRoupBatchId = FR.OrgGRoupBatchId
		LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId
			AND SLM.ReceiptBookid = FR.ReceiptBookId
		WHERE FR.ReceiptBookId = @rReceiptBookId
			AND FR.IsObsolete = 0
			AND FR.OrgGroupBatchId = @rOrgGroupBatchId
			AND FR.ReceiptDate >= @rReceiptDate
			AND FR.ReceiptDate <= @rToReceiptDate
			AND (
				FR.PayTypeId = @rPayTypeId
				OR @rPayTypeId = 0
				)
		GROUP BY ReceiptDate
			,PM.Title
			,SLM.LedgerName
			,FR.PayTypeId
			,A.StudentId
			,FRD.ReceiptId
			,Isnull(FR.ChequeNo, '')
			,ISNull(FR.BankName, '')
			,--A.Name+', '+ClassName + '-' + DivisionName+', '+A.OrganizationName+', ('+BatchName+')',
			'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(NVARCHAR(20), RollNo) + ' ' + BatchName
			,FR.ReceiptAmount
		ORDER BY ReceiptDate DESC
	END
	ELSE IF @lTallyPostingType = 'FeeHeadAndReceiptBookWise'
	BEGIN
		SELECT ReceiptDate
			,ISNULL(FHM.Title, '') AS FeeName
			,PM.Title AS PayType
			,Sum(FRD.Amount) AS Amount
			,CASE 
				WHEN @rIsCustomNarration = 1
					THEN STUFF((
								SELECT DISTINCT ',' + Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(replace(@rCustomNarration, '[Class]', isnull(SM1.ClassName, '')), '[Division]', Isnull(SM1.DivisionName, '')), '[StudentsName]', isnull(SM1.Name, '')), '[RollNumber]', isnull(convert(NVARCHAR(200), SM1.RollNo), '0')), '[Batch]', isnull(SM1.BatchName, '')), '[ReceiptNumber]', isnull(Convert(NVARCHAR(100), FR1.ReceiptNumber), '')), '[ReceiptDate]', isnull(Convert(NVARCHAR(100), FR1.ReceiptDate), '')), '[ReceiptAmount]', isnull(Convert(NVARCHAR(100), FR1.ReceiptAmount), '')), '[ChequeNo]', isnull(Convert(NVARCHAR(100), FR1.ChequeNo), '')), '[BankName]', isnull(FR1.BankName, '')), '[FeeName]', isnull(FM1.Title, '')), '[FeeAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[FeeHeadName]', ISNULL(FHM1.Title, '')), '[FeeHeadAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[CollectionGroupName]', isNull(CGM1.Title, '')), 
											'[ReceiptFromNumber]', isnull(Convert(NVARCHAR(10), FR1.ReceiptNumber), '')), '[ReceiptToNumber]', isnull(Convert(NVARCHAR(10), FR1.ReceiptNumber), ''))
								FROM sFee.tReceipt FR1
								INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
								INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
								INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID
									AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId
								INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
								LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
								INNER JOIN sFinanceCommon.tPayTypeMaster PM1 ON PM1.Id = FR1.PayTypeId
								INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
								LEFT JOIN sTally.tStudentLedgerMapping SLM1 ON SLM1.StudentId = SM1.StudentId
									AND SLM1.ReceiptBookid = FR1.ReceiptBookId
								WHERE FR1.ReceiptDate = FR.ReceiptDate
									AND PM1.Title = PM.Title
									AND FR1.PayTypeId = FR.PayTypeId
									AND FR1.IsObsolete = 0
								GROUP BY SM1.ClassName
									,SM1.DivisionName
									,SM1.Name
									,SM1.RollNo
									,SM1.BatchName
									,FR1.ReceiptNumber
									,FR1.ReceiptDate
									,FR1.ReceiptAmount
									,FR1.ChequeNo
									,FR1.PayTypeId
									,FR1.BankName
									,FM1.Title
									,FHM1.Title
									,CGM1.Title -- Added for Fee amount not show proper in narration
								FOR XML PATH('')
								), 1, 1, '')
				ELSE CASE 
						WHEN FR.PayTypeId = 1
							THEN 'Receiptno-' + CONVERT(NVARCHAR, isnull(FR.ReceiptNumber, '')) + STUFF((
										SELECT ',' + convert(NVARCHAR(20), isnull(FM1.title, ''))
										FROM sFee.tReceipt FR1
										INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
											AND FRD1.ReceiptId = FRD.ReceiptId
										INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
										INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId
											AND FRD.ReceiptId = FRD1.ReceiptId
										FOR XML PATH('')
										), 1, 1, '')
						WHEN FR.PayTypeId <> 1
							THEN 'Receiptno-' + CONVERT(NVARCHAR, isnull(FR.ReceiptNumber, '')) + STUFF((
										SELECT ',' + convert(NVARCHAR(20), isnull(FM1.title, ''))
										FROM sFee.tReceipt FR1
										INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
											AND FRD1.ReceiptId = FRD.ReceiptId
										INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
										INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId
											AND FRD.ReceiptId = FRD1.ReceiptId
										FOR XML PATH('')
										), 1, 1, '') + '  Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
						END
				END AS Narration
			,FR.PayTypeId AS PayTypeId
			,FHM.Id AS FeeId
			,0 AS ReceiptId
			,ISNULL(FR.ChequeNo, '') AS ChequeNo -- Added for mantis 0035195 by Foram
		FROM sFee.tReceipt FR
		INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
		WHERE FR.ReceiptBookId = @rReceiptBookId
			AND FR.IsObsolete = 0
			AND FR.OrgGroupBatchId = @rOrgGroupBatchId
			AND FR.ReceiptDate >= @rReceiptDate
			AND FR.ReceiptDate <= @rToReceiptDate
			AND (
				FR.PayTypeId = @rPayTypeId
				OR @rPayTypeId = 0
				)
		GROUP BY PM.Title
			,FRD.ReceiptId
			,FR.BankName
			,FR.ChequeNo
			,FM.Title
			,ReceiptDate
			,FHM.Title
			,PM.Title
			,FHM.Id
			,FR.PayTypeId
			,FR.ReceiptNumber
			,FRD.ReceiptId
			,Isnull(FR.ChequeNo, '')
			,ISNull(FR.BankName, '')
			,FM.Title
		--,FHM.Title
		ORDER BY ReceiptDate DESC
	END
	ELSE IF @lTallyPostingType = 'FeeHeadWiseReceipt_AllDetail'
	BEGIN
		SELECT ReceiptDate
			,FR.Id AS FeeName
			,PM.Title AS PayType
			,Sum(FRD.Amount) AS Amount
			,CASE 
				WHEN @rIsCustomNarration = 1
					THEN STUFF((
								SELECT DISTINCT ',' + Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(Replace(replace(replace(replace(replace(@rCustomNarration, '[Class]', isnull(SM1.ClassName, '')), '[Division]', Isnull(SM1.DivisionName, '')), '[StudentsName]', isnull(SM1.Name, '')), '[RollNumber]', isnull(convert(NVARCHAR(200), SM1.RollNo), '0')), '[Batch]', isnull(SM1.BatchName, '')), '[ReceiptNumber]', isnull(Convert(NVARCHAR(100), FR1.ReceiptNumber), '')), '[ReceiptDate]', isnull(Convert(NVARCHAR(100), FR1.ReceiptDate), '')), '[ReceiptAmount]', isnull(Convert(NVARCHAR(100), FR1.ReceiptAmount), '')), 'Cheque No. :[ChequeNo]', CASE 
																					WHEN FR1.PayTypeId = 1
																						THEN ''
																					ELSE 'Cheque No. :[ChequeNo]'
																					END), '[ChequeNo]', isnull(Convert(NVARCHAR(100), FR1.ChequeNo), '')), 'BankName :[BankName]', CASE 
																			WHEN FR1.PayTypeId = 1
																				THEN ''
																			ELSE 'BankName :[BankName]'
																			END), '[BankName]', isnull(FR1.BankName, '')), '[FeeName]', isnull(FM1.Title, '')), '[FeeAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[FeeHeadName]', ISNULL(FHM1.Title, '')), '[FeeHeadAmount]', isnull(Convert(NVARCHAR(100), Sum(FRD1.Amount)), '0.00')), '[CollectionGroupName]', isNull(CGM1.Title, '')), '[ReceiptFromNumber]', isnull(Convert(NVARCHAR(10), (
														SELECT Min(ReceiptNumber)
														FROM sFee.tReceipt
														WHERE FR.ReceiptDate = ReceiptDate
															AND IsObsolete = 0
														)), '')), '[ReceiptToNumber]', isnull(Convert(NVARCHAR(10), (
													SELECT Max(ReceiptNumber)
													FROM sFee.tReceipt
													WHERE FR.ReceiptDate = ReceiptDate
														AND IsObsolete = 0
													)), ''))
								FROM sFee.tReceipt FR1
								INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
								INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId
								INNER JOIN sStudent.vStudentAcademic SM1 ON SM1.ACademicId = FR1.SourceID
									AND SM1.OrgGRoupBatchId = FR1.OrgGRoupBatchId
								INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId --AND FRD.ReceiptId=FRD1.ReceiptId
								LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON CGM1.Id = FS1.CollectionGroupId
								INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id = FM1.FeeHeadId
								WHERE FR.ReceiptDate = FR1.ReceiptDate
									AND FR.Id = FR1.Id
									AND FR1.IsObsolete = 0
								GROUP BY SM1.ClassName
									,SM1.DivisionName
									,SM1.Name
									,SM1.RollNo
									,SM1.BatchName
									,FR1.ReceiptNumber
									,FR1.ReceiptDate
									,FR1.ReceiptAmount
									,FR1.ChequeNo
									,FR1.PayTypeId
									,FR1.BankName
									,FM1.Title
									,FHM1.Title
									,CGM1.Title -- Added for Fee amount not show proper in narration
								FOR XML PATH('')
								), 1, 1, '')
				ELSE CASE 
						WHEN FR.PayTypeId = 1
							THEN 'ReceiptNo-' + CONVERT(NVARCHAR, isnull(FR.ReceiptNumber, '')) + '(' + BatchName + ')'
						WHEN FR.PayTypeId <> 1
							THEN 'Receiptno-' + CONVERT(NVARCHAR, isnull(FR.ReceiptNumber, '')) + '(' + BatchName + ')' + '  Cheque No. :' + ISNULL(FR.ChequeNo, '') + ' BankName :' + ISNULL(FR.BankName, '')
						END
				END AS Narration
			,FR.PayTypeId AS PayTypeId
			,FR.Id AS FeeId
			,FR.Id AS ReceiptId
			,ISNULL(FR.ChequeNo, '') AS ChequeNo -- Added for mantis 0035195 by Foram
		FROM sFee.tReceipt FR
		INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
		INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID
			AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
		LEFT JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id = OM.OrgSubGroupId
		WHERE FR.ReceiptBookId = @rReceiptBookId
			AND FR.IsObsolete = 0
			AND FR.OrgGroupBatchId = @rOrgGroupBatchId
			AND FR.ReceiptDate >= @rReceiptDate
			AND FR.ReceiptDate <= @rToReceiptDate
			AND (
				FR.PayTypeId = @rPayTypeId
				OR @rPayTypeId = 0
				)
		GROUP BY ReceiptDate
			,PM.Title
			,FR.PayTypeId
			,FR.Id
			,isnull(FR.ReceiptNumber, '')
			,BatchName
			,ISNULL(FR.BankName, '')
			,ISNULL(FR.ChequeNo, '')
		ORDER BY FR.Id
			,ReceiptDate DESC
	END
END
GO
PRINT N'Altering Procedure [sTimetable].[pRptFreeLectureListGet]...';


GO
ALTER PROCEDURE [sTimetable].[pRptFreeLectureListGet]
	  @rBatchId int,
	  @rClassID int,
	  @rDivisionId int,
	  @rEmployeeId bigint,
	  @rTimeTableSchemaId int,	
	  @rReportId int,
	  @rOrgId int = 0	  
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN   
	

CREATE TABLE #Temp (Id int identity, LectureNumber int,TimeTableSchemaId int)
DECLARE @lMaxLecture int = (SELECT MAX(NoOfPeriod) FROM sTimeTable.tTimeSetup WHERE TimeTableSchemaId = @rTimeTableSchemaId)
DECLARE @lCount int = 1

WHILE @lCount <= @lMaxLecture
BEGIN
INSERT INTO #Temp VALUES (@lCount, @rTimeTableSchemaId)

SET @lCount = @lCount + 1
END

--SELECT * FROM #Temp


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


--SELECT 
--		0 AS DayId, 
--		'' AS DayNames,
--		'' AS Code,
--		0 AS EmployeeId,
--		'' AS EmployeeName,
--		'' AS Employee,
--		0 AS TimeTableId,
--		0 AS LectureNumber,
--		--ISNULL(TT.LectureNumber,0) AS LectureNumber,
--		0 AS TimeTableDayId,
--		--ISNULL(TT.DayId,0) AS TimeTableDayId,		
--		0 AS Lecture,
--		0 AS SubjectId,
--		'' AS SubjectName,
--		'' AS LectureTime,
--		0 AS DivisionId,
--		'' AS DivisionTitle,
--		0 AS ClassId,
--		'' AS ClassTitle,
--		'' AS ClassDivisionName,
--		0 AS IsDisplayPeriodTime,
--		'' AS OrganizationName,
--		'' AS  ClassSubject

END
GO
PRINT N'Altering Procedure [sTimetable].[pRptFreeLectureListGet_L]...';


GO
ALTER PROCEDURE [sTimetable].[pRptFreeLectureListGet_L]
    @rBatchId INT,
    @rClassID INT,
    @rDivisionId INT,
    @rEmployeeId BIGINT,
    @rTimeTableSchemaId INT,    
    @rReportId INT,
    @rOrgId INT  
AS
BEGIN   
    CREATE TABLE #Temp (Id INT IDENTITY, LectureNumber INT, TimeTableSchemaId INT, DayId INT);
    
    -- Determine the number of days dynamically
    DECLARE @lDayId INT = 1;
    DECLARE @lMaxDayId INT = (SELECT MAX(DayId) FROM sTimeTable.tTimeSetup WHERE TimeTableSchemaId = @rTimeTableSchemaId);

    WHILE @lDayId <= @lMaxDayId
    BEGIN
        DECLARE @lMaxLecture INT = (SELECT ISNULL(MAX(NoOfPeriod), 0) 
                                    FROM sTimeTable.tTimeSetup 
                                    WHERE TimeTableSchemaId = @rTimeTableSchemaId AND DayId = @lDayId);
        
        DECLARE @lCount INT = 1;
        WHILE @lCount <= @lMaxLecture
        BEGIN
            INSERT INTO #Temp (LectureNumber, TimeTableSchemaId, DayId) VALUES (@lCount, @rTimeTableSchemaId, @lDayId);
            SET @lCount = @lCount + 1;
        END
        
        SET @lDayId = @lDayId + 1;
    END

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

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

    -- Clean-up
    DROP TABLE #Temp;
    DROP TABLE #TempTimeTable;

	--	 SELECT 
--		0 AS DayId, 
--		'' AS DayNames,
--		0 AS LectureNumber,
--		0 AS TimeTableDayId,
--		0 AS Lecture,
--		--ISNULL(TT.LectureNumber,0) AS LectureNumber,
--		'' AS LectureTime,
--		'' AS OrganizationName,
--		'' AS EmployeeNames
END;
GO
PRINT N'Creating Procedure [sAccounting].[pRptAllVoucherEntryGet]...';


GO



CREATE PROCEDURE [sAccounting].[pRptAllVoucherEntryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAccountingYearId int,
	 @rTransactionDate date,
	 @rTransactionDateTo Date,
	 @rVoucherNumber int,
	 @rVoucherNumberTo int,
	 @rNarration nvarchar(1000),  
	 @rAmount Decimal(20,5),
	 @rVoucherTypeId int = 0,
	 @rIsApproved bit=0




	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
	  BEGIN
			SET @rNarration = sAccounting.fNarrationSearchStringGet(@rNarration) --added New function by dhananjay for mantis id - 0035082
	  END	 
BEGIN  
Declare @DecimalCount INT , @lOrgGroupId Int


	 SELECT @lOrgGroupId = OrgGroupId FROM sAccounting.tTransaction T WHERE AccountingYearId = @rAccountingYearId

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


	
	 
  SELECT    
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		T.Id AS TransactionId,
		T.Narration,
		T.TransactionDate,
		T.VoucherNumber,
		TD.Amount,
		TD.Id as TransactionDetailId,
		LM.Title AS Ledger,
		VTM.Title AS VoucherType,
		TD.TransactionTypeId ,
		([sAccounting].[fDecimalValueGet] ((CASE WHEN TD.Amount > 0 THEN TD.Amount
		ELSE 0 END), @DecimalCount)) DebitAmount, --Added for mantis : 32211
		([sAccounting].[fDecimalValueGet] ((CASE WHEN TD.Amount < 0 THEN  -1 * TD.Amount
		ELSE 0 END), @DecimalCount)) CreditAmount, --Added for mantis : 32211
		AM.ReportOrgTitle As OrgTitle,
		AM.SmallAddress1 AS SmallAddress1,
		AM.SmallAddress2 AS SmallAddress2,
		T.ChequeNo,
		T.ChequeDate,
		AM.Title as AccountTitle,
		U.DisplayTitle As CreatedUserName,
		T.TransactionDate

		--sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(TD.Amount,0.00),1,2,@rOrgGroupId) AS AmountInWords
			  
  FROM 
       sAccounting.tTransaction T
       INNER JOIN sAccounting.tTransactionDetail TD ON T.Id=TD.TransactionId
       LEFT JOIN sAccounting.tLedgerMaster LM On LM.Id=TD.LedgerId
       LEFT JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
       LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	   LEFT JOIN sSecurity.tUser U ON U.Id = T.CreatedUserId
      
  WHERE 
	(T.VoucherTypeId=@rVoucherTypeId OR @rVoucherTypeId = 0)
		AND (T.AccountingYearId=@rAccountingYearId)  AND LM.AccountingYearId = @rAccountingYearId
		AND (T.TransactionDate >= @rTransactionDate OR ISNULL(@rTransactionDate,'') = '') 
		And (T.TransactionDate <= @rTransactionDateTo OR ISNULL(@rTransactionDateTo,'') = '')
		AND (T.VoucherNumber >= @rVoucherNumber OR @rVoucherNumber=0) 
		AND (T.VoucherNumber <=@rVoucherNumberTo OR @rVoucherNumberTo=0)
		AND ((T.Narration like @rNarration) OR (ISNULL(@rNarration,'') = '')) 
		AND (TD.Amount = @rAmount OR ISNULL(@rAmount,0) = 0)
		AND ((@rIsApproved=1 AND  ISNULL(T.TransactionApproveId,0) !=0) OR (@rIsApproved = 0) )

		order by T.TransactionDate,T.VoucherNumber, LM.Id 

END
GO
PRINT N'Creating Procedure [sAttendance].[pAttendanceFollowupPortalGet]...';


GO
Create Procedure sAttendance.pAttendanceFollowupPortalGet
	 	 @rClassId int=0,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rFollowupDate date,
	 	 @rBatchId int,
	 	 @rOrgId int,
		 @rPresentStatus int,
		 @rCode nvarchar(20)='',
		 @rIsEditMode bit = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	SELECT
		SA.AcademicId, 
		SA.ClassName +'-' + SA.DivisionName AS ClassDivision,
		SA.Code,
		SA.RollNo,
		SA.Name,
		SC.PresentContactNo,
		SC.PermanentContactNo,
		SC.EmergencyContactNo,
		SC.ParentContactNo,
		SC.StudentContactNo,
		--AF.Remark,
		CASE WHEN (ISNULL((SELECT 1 FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate),0)
		= 1 AND (AF.Remark IS NULL OR AF.Remark = '')) THEN (SELECT LeaveReason FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate)
		ELSE (
		replace (
		replace (
		replace (
		replace (
		replace (
		replace(AF.Remark,'\n','<br />'),
		'#amp;','&'),
		'#gt;','>'),
		'#quot;','\"'),
		'#lt;','<'),
		'#39;','''')) END AS Remark,
		ISNULL((SELECT 1 FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId 
		AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate),0) AS IsOnLeave
		,ISNULL(SA.StudentId, 0) AS StudentId
	FROM
		sStudent.vStudentAcademic SA
		INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
		LEFT JOIN sAttendance.tAttendanceFollowup AF ON AF.AcademicId = SA.AcademicId 
		AND SR.AttendanceTypeId = AF.AttendanceTypeId AND SR.AttendanceDate  = AF.FollowupDate
		LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
 
	WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
		  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		  AND (SA.OrgId = @rOrgId)
		  AND (SA.BatchId = @rBatchId)
		  AND (SA.StatusId NOT IN(2,3))
		  AND ((@rIsEditMode = 1 AND AF.IsPresent = @rPresentStatus) OR (@rIsEditMode = 0 AND SR.IsPresent = @rPresentStatus))
		  AND (AD.AdmissionDate <= @rFollowupDate)
		  AND ((SA.Code=@rCode)OR (ISNULL(@rCode,'')=''))
		  AND (SR.AttendanceTypeId = @rAttendanceTypeId)
		  AND (SR.AttendanceDate = @rFollowupDate)
	ORDER BY SA.RollNo
	
END
GO
PRINT N'Creating Procedure [sFee].[pRptRoutewiseTransportFeeWithDetailGet]...';


GO


 
CREATE PROCEDURE [sFee].[pRptRoutewiseTransportFeeWithDetailGet] 
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rUptoDate date='',
		@rBatchId int=0,
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		@rStatusId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rRouteId int=0,
		@rDestinationId int = 0,
		@rTransportId int =0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	


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

 
	--CREATE TYPE  TempPendingFee AS TABLE
	--(
	--AcademicId bigint
	--,
	--RollNo int,
	--Name nvarchar(200),
	--Code nvarchar(20),
	--ClassId int,
	--DivisionId int,
	--ClassName nvarchar(100),
	--DivisionName nvarchar(100),
	--ClassDivision nvarchar(100),
	--FeeSetupId int,
	--IsVariable int,
	--Amount Decimal(12,2),
	--StartDate date,
	--EndDate date,
	--FAAmount Decimal(12,2),
	--DiscountAmount Decimal(12,2),
	--AdditionalAmount Decimal(12,2),
	--PaidAmount Decimal(12,2),
	--PendingAmount Decimal(12,2),
	--Remark nvarchar(200),
	--ReceiptBookId int,
	--FeeName nvarchar(100),
	--FeeCode nvarchar(100),
	--OrgId int,
	--OrgName nvarchar(200),
	--OrgOrderIndex int,
	--ReceiptBookTitle nvarchar(200),
	--ReceiptOrderIndex int 
	--)
	 
	DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId
		,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName, 
		'' AS Pickup,
		'' AS DRoppoint,
		'' AS PresentContactNo,
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex,
		'' AS FatherContactNo,
		'' AS MotherContactNo
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				SA1.StudentId AS StudentId,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
			--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
				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,
				SA1.StudentId AS StudentId,
				FM.OrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId AND FH.Number = 1001
		--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				
		) 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 FS.Id = RD.FeeSetupId 
				INNER JOIN sfEe.tFeeMaster FM ON FM.Id = FS.FeeId 
				INNER JOIN sFee.tFeeHeadMaster FH ON FM.FeeHeadId = FH.Id AND FH.Number = 1001
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				--INNER JOIN sTransport.tAssignRoute AR oN SA1.AcademicId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tAssignRoute AR oN SA1.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id = AR.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
				AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
				AND ((BRM.TransportId=@rTransportId) OR (@rTransportId=0))
				AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
				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 sTransport.tAssignRoute AR 
			ON  SA.StudentId = AR.SourceId AND AR.SourceTypeId = 2003	
		INNER JOIN sTransport.tBusRouteDestinationMaster BRDM 
			ON BRDM.Id = AR.PickupDestinationId
	 INNER JOIN sTransport.tBusRouteMaster BRM ON BRDM.BusRouteId = BRM.Id
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND ((BRDM.BusRouteId=@rRouteId) OR (@rRouteId=0))
			AND ((BRDM.Id=@rDestinationId) OR (@rDestinationId=0))
			AND (BRM.OrgGroupBatchId = @rOrgGroupBatchId)
			Order by SA.RollNo

			SELECT
			P.OrgId,			 
			P.ReceiptBookId,
			P.AcademicId,
			P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,ReceiptBookTitle,OrgName,
			SUM(P.PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](P.AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			P.ReceiptOrderIndex,
			BR.Id AS BusRouteId,
			BR.Title AS BusRoute,
			BD.Title AS BusDestination,
			isnull(SC.ParentContactNo,'') AS ParentContactNo,
			P.SUID,
			P.ClassOrderIndex,
			P.DivisionOrderIndex,
			'' AS FatherContactNo,
		    '' AS MotherContactNo,
			--Added by dhananjay for mantis id Start - 35419
			ISNULL(P.PaidAmount,0) AS PaidAmount
			--ISNULL(P.Amount,0) AS Amount	 ,
			--Added by dhananjay for mantis id End - 35419
			FROM @p P INNER JOIN sStudent.vStudentAcademic VA ON p.AcademicId=VA.AcademicId
			INNER JOIN sTransport.tAssignRoute AR oN VA.StudentId = AR.SourceId AND SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BD ON BD.Id = AR.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster BR ON BR.Id = BD.BusRouteId 
			AND BR.OrgGroupBatchId = @rOrgGroupBatchId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =  VA.StudentId
			GROUP By P.ReceiptBookId,P.OrgId,P.AcademicId,P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,
			P.ReceiptBookTitle,P.OrgName,P.ReceiptOrderIndex,BR.Title,BD.Title,BR.Id,SC.ParentContactNo	,P.SUID,P.ClassOrderIndex,P.DivisionOrderIndex ,P.PaidAmount --Added by dhananjay(P.PaidAmount,P.Amount) for mantis id - 35419
			ORDER BY P.AcademicId
 
END
GO
PRINT N'Creating Procedure [sProcurement].[pRptStockInwardRequestDetail]...';


GO
CREATE PROCEDURE [sProcurement].[pRptStockInwardRequestDetail]
	@rOrgGroupId int,
	@rStockInwardRequestId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT SIRD.Id,
			SIRD.StockInwardRequestId,
			SIRD.StockItemId,
			SIRD.RequestedQuantity,
			SIRD.Remark,
			SIRD.UpdatedUserID,
			SIRD.UpdatedDateTime,
			SIM.Code ItemCode,
			SIM.Title ItemTitle,
			SU.Code UomCode,
			SU.Title UomTitle,
			SU.Id IssueStockUomId,
			SIM.IsBatchWiseTracking,
			SIM.Code StockItemCode,
			SIM.Title StockItemName,
			SU.Title Uom,
		    '' as Number,
			SIRD.InwardQuantity,
			'' ExpiryDate,
			'' As InwardValue,
			SB.AvailableQuantity AS AvailableQuantity
	   FROM 
			sProcurement.tStockInwardRequestDetail SIRD
		    INNER JOIN sIP.tStockItemMaster SIM ON SIM.Id = SIRD.StockItemId
		    INNER JOIN sFinanceCommon.tStockUomMaster  SU ON SU.Id = SIM.IssueStockUomId
		    LEFT JOIN sProcurement.tStockBatch SB ON SB.StockItemId=SIm.Id
	   WHERE 
		    ((SIRD.StockInwardRequestId = @rStockInwardRequestId) OR (@rStockInwardRequestId = 0))
		    AND SIRD.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Creating Procedure [sStudent].[pStudentCustomFieldImport]...';


GO
CREATE PROCEDURE [sStudent].[pStudentCustomFieldImport]
	  
	@rStrXml nvarchar(max) 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN
	BEGIN TRY
		
		--DELETE FROM sStudent.tStudentCustomFieldData WHERE StudentId=@rStudentId
	
	
	UPDATE sStudent.tStudentCustomFieldData
			SET 
				StudentCustomFieldId=A.StudentCustomFieldId,
				FieldData=[sSetup].[fPortalXMLTagsReplaceReverse](A.FieldData),				
				UpdatedUserId=A.UpdatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
			FROM (
			SELECT
				StudentCustomFieldId,FieldData,UpdatedUserId,StudentId	
				FROM OPENXML (@loDoc, '/Table/StudentCustomField', 1)
			WITH
			(
				StudentId Bigint '@StudentId',
				StudentCustomFieldId INT '@StudentCustomFieldId',
				FieldData nvarchar(max) '@FieldData',
				CreatedUserId bigint,
				UpdatedUserId bigint
			))A 
			INNER JOIN sStudent.tStudentCustomFieldData SCM ON  SCM.StudentId=A.StudentId AND SCM.StudentCustomFieldId=A.StudentCustomFieldId
	
	
	  INSERT INTO sStudent.tStudentCustomFieldData
		(
			StudentId,
			StudentCustomFieldId,
			FieldData,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
		SELECT
				A.StudentId,A.StudentCustomFieldId,[sSetup].[fPortalXMLTagsReplaceReverse](A.FieldData),A.CreatedUserId,sCommon.fGetDate(),A.UpdatedUserId,sCommon.fGetDate()	
				FROM OPENXML (@loDoc, '/Table/StudentCustomField', 1)
			WITH
			(
				StudentId Bigint '@StudentId',
				StudentCustomFieldId INT '@StudentCustomFieldId',
				FieldData nvarchar(max) '@FieldData',
				CreatedUserId bigint,
				UpdatedUserId bigint
			)A 
			LEFT JOIN sStudent.tStudentCustomFieldData SCM ON SCM.StudentId=A.StudentId AND SCM.StudentCustomFieldId=A.StudentCustomFieldId
			WHERE SCM.StudentId IS NULL 
			
	
		
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating Procedure [sStudent].[pValidateCommunicationDetailsImport]...';


GO
CREATE PROCEDURE [sStudent].[pValidateCommunicationDetailsImport]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,
			@intDoc INT,
	        @lCode nvarchar(50),
	        @1ExistStudentCode nvarchar(max) = '',
	        @1DuplicateStudentCode nvarchar(max) = '' 
	DECLARE @lValidationMsg  nvarchar(max) = ''      
	       
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	 
	CREATE TABLE #tTable1 
	(
		Id bigint identity,
	    Code nvarchar(50) 
	)

	INSERT INTO #tTable1
		(
		    Code 
	  ) 
	 SELECT
	      Code 
	 
	 FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
	 With
	 (
	      Code nvarchar(50) '@Code' 
	 )   
	EXEC sp_xml_removedocument @intDoc
			
	IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
	BEGIN
		SET @lValidationMsg = 'ID No Should not be empty'
	END
	
	SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'')	+ Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
					
	IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SET @lValidationMsg = 'Duplicate Code ' + @1DuplicateStudentCode
	END
			
	SELECT @lValidationMsg AS Validation
END
GO
PRINT N'Creating Procedure [sStudent].[pValidateFamilyDetailsImport]...';


GO
CREATE PROCEDURE [sStudent].[pValidateFamilyDetailsImport]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,
			@intDoc INT,
	        @lCode nvarchar(50),
	        @1ExistStudentCode nvarchar(max) = '',
	        @1DuplicateStudentCode nvarchar(max) = '' 
	        
	       
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	 
	CREATE TABLE #tTable1 
	(
		Id bigint identity,
	    Code nvarchar(50) 
	)
	  
	  
	INSERT INTO #tTable1
	(
	    Code 
	) 
	SELECT
        Code 
   
	FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
	With
	(	
	     Code nvarchar(50) '@Code' 
	)   
	EXEC sp_xml_removedocument @intDoc
	 
	declare @lValidationMsg nvarchar(max)	=''
	IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
	BEGIN
		SET @lValidationMsg = 'ID No Should not be empty' 
	END
	
	SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'') + Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
					
	IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
	BEGIN
		SET @lValidationMsg += 'Duplicate Code ' + @1DuplicateStudentCode				
	END	
	
	select @lValidationMsg as Validation
END
GO
PRINT N'Creating Procedure [sStudent].[pValidateStudentImport]...';


GO
CREATE PROCEDURE [sStudent].[pValidateStudentImport]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rOperation int=0,
	@rBatchId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lSUIdActivate nvarchar(50)=''
	DECLARE @lPENNumberActive nvarchar(50)='' 
	DECLARE @lIsActivateUniquePENNumber bit = 0 
	DECLARE @lIsSurnameAndFatherNameMandatory nvarchar(50)=''
	DECLARE @lIsActivateUniqueId bit = 0
	DECLARE @lOrgGroupId int = 0
	DECLARE @lIsStudentUIDNumberUnique nvarchar(50)=''
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	SELECT @lSUIdActivate = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 167 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	SELECT @lPENNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 544 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId --Mantis- 0031338	
	SELECT @lIsSurnameAndFatherNameMandatory =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 415 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId	
	SELECT @lIsStudentUIDNumberUnique = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 534 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId		--add
	IF (@lSUIdActivate = '') OR (@lSUIdActivate = 'False')
		SET @lIsActivateUniqueId = 0
	ELSE
		SET @lIsActivateUniqueId = 1	

	IF (ISNULL(@lPENNumberActive, '') = '') OR (@lPENNumberActive = 'False')
		SET @lIsActivateUniquePENNumber = 0
	ELSE
		SET @lIsActivateUniquePENNumber = 1	
	
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),
        @lClass nvarchar(100),
        @lDivision nvarchar(100),        
        @lRegistrationNumber nvarchar(20),  
        @lAdmissionDate nvarchar(15),        
        @lDOB nvarchar(15),             
        @1ReturnCode int = 1,
        @1ExistStudentCode nvarchar(max) = '',
        @1NotExistStudentCode nvarchar(max) = '',
        @1ExistStudentRegistrationNumber nvarchar(max) = '',
        @1ValidAdmissionDate nvarchar(max) = '',
        @1ValidDOB nvarchar(max) = '',
        @1DuplicateStudentCode nvarchar(max) = '',
        @1DuplicateStudentRegistrationNumber nvarchar(max) = '',
        @lSUId nvarchar(50),
        @1ExistStudentSUId nvarchar(max) = '',
        @1DuplicateStudentSUId nvarchar(max) = '',
        @lLeftDate nvarchar(15),
        @lLCDate nvarchar(15),
        @1ValidLeftDate nvarchar(max) = '',
        @1ValidLCDate nvarchar(max) = '',
        @lStatusId smallint,        
        @lAdhaarNumber nvarchar(50),  
        @1DuplicateAdhaarNumber nvarchar(max) = '',        
        @lUIDNumber nvarchar(50),  
        @1DuplicateUIDNumber nvarchar(max) = '',        
        @1StudentId BIGINT = 0,
		@lPENNumber BIGINT = 0,
		@1ExistPENNumber nvarchar(max) = '',
		@1DuplicatePENNumber nvarchar(max) = '' 

	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
	CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(50),
        RegistrationNumber nvarchar(20),
        FirstName nvarchar(100),
		MiddleName nvarchar(100),
        LastName nvarchar(100),
		Class nvarchar(100),
		Division nvarchar(100),
		AdmissionStandard nvarchar(100),
		AdmissionDate nvarchar(15),
        DOB nvarchar(15),
        Gender nvarchar(10),
		Religion nvarchar(100),
		CastCategory nvarchar(100),
        SUId nvarchar(50),
        LeftDate nvarchar(15),
        LCDate nvarchar(15),
        LeftStandard nvarchar(100),
        StatusId smallint,
        AdhaarNumber varchar(100),
        UIDNumber varchar(100),
		PENNumber BIGINT 
 
  )
	INSERT INTO #tTable1
	(
	    Code,
	    RegistrationNumber, 
	    FirstName,
		MiddleName,
	    LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    Religion,
	    CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber,
		PENNumber 
    ) 
   SELECT
        Code,
	    RegistrationNumber, 
	    sSetup.fPortalXMLTagsReplaceReverse(FirstName) AS FirstName,
		sSetup.fPortalXMLTagsReplaceReverse(MiddleName) AS MiddleName,
	    sSetup.fPortalXMLTagsReplaceReverse(LastName) AS LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    sSetup.fPortalXMLTagsReplaceReverse(Religion) AS Religion,
	    sSetup.fPortalXMLTagsReplaceReverse(CastCategory) AS CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber,
		PENNumber 
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        Code nvarchar(50) '@Code',
        RegistrationNumber nvarchar(20) '@RegistrationNumber',
        FirstName nvarchar(100) '@FirstName',
		MiddleName nvarchar(100) '@MiddleName',
        LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		Division nvarchar(100) '@Division',
		AdmissionStandard nvarchar(100) '@AdmissionStandard',
		AdmissionDate nvarchar(15) '@AdmissionDate',
		DOB nvarchar(15) '@DOB',
		Gender nvarchar(10) '@Gender',
		Religion nvarchar(100) '@Religion',
		CastCategory nvarchar(100) '@CastCategory',
		SUId nvarchar(50) '@SUId',
		LeftDate nvarchar(15) '@LeftDate',
		LCDate nvarchar(15) '@LCDate',
		LeftStandard nvarchar(100) '@LeftStandard',
		StatusId smallint '@StatusId',
		AdhaarNumber varchar(100) '@AdhaarNumber',
		UIDNumber varchar(100) '@UIDNumber',
		PENNumber BIGINT '@PENNumber'
   )   
	EXEC sp_xml_removedocument @intDoc
		
	SELECT @lCount =  COUNT(Id) FROM #tTable1
	DECLARE @lValidationMsg nvarchar(max) = ''
	WHILE @lCount > 0 
	BEGIN	
    SELECT
         @lCode = Code, 
         @lRegistrationNumber = RegistrationNumber,
         @lAdmissionDate = AdmissionDate,
         @lDOB=DOB,
         @lSUId = SUId,
         @lLeftDate = LeftDate,
         @lLCDate = LCDate,
         @lStatusId = StatusId,
         @lAdhaarNumber = AdhaarNumber,
         @lUIDNumber = UIDNumber,
		 @lPENNumber = PENNumber 
        FROM #tTable1 WHERE Id = @lCount 

	IF(@rOperation=2)
	BEGIN   
		IF Exists(SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId)    
		 SET @1StudentId = (SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId)
		ELSE
		  SET @1NotExistStudentCode = @1NotExistStudentCode + @lCode + ','    
   END     
        
	IF(@rOperation=1 OR @rOperation=0)     
	BEGIN    
		IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
		  BEGIN
 			 SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
		  END	  
		IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId))         
		BEGIN
  		    SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
		END	 
 
		IF(@lPENNumber > 0)
	BEGIN
		IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where CAST(SM.PENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT = CAST(@lPENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId))         
        BEGIN
  		    SET @1ExistPENNumber = @1ExistPENNumber + CAST(@lPENNumber AS NVARCHAR(200)) + ','
	    END	       
	END
		        
		IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
	BEGIN
		IF(ISNULL(@lRegistrationNumber,'')!='')
		BEGIN
			SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
		END
	END
		
		IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lAdhaarNumber COLLATE DATABASE_DEFAULT))         
    BEGIN
		IF(ISNULL(@lAdhaarNumber,'')!='')
		BEGIN
  		    SET @1DuplicateAdhaarNumber = @1DuplicateAdhaarNumber + @lAdhaarNumber + ','
	 	END
	END	
		     
		IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lUIDNumber COLLATE DATABASE_DEFAULT))         
	BEGIN
		IF(@lIsStudentUIDNumberUnique='True')	--add
		BEGIN
			IF(ISNULL(@lUIDNumber,'')!='')
			BEGIN
                
  				SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
  			                 
			END 
		END
	END	
	END

	ELSE
	BEGIN    
    IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId AND Id<>@1StudentId))         
    BEGIN
  		SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
	END	  
	IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId AND SM.Id<>@1StudentId))         

    BEGIN
  		SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
	END	

	IF(@lPENNumber > 0)
	BEGIN 
		IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where CAST(SM.PENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT = CAST(@lPENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId AND SM.Id<>@1StudentId))         
        BEGIN
  		    SET @1ExistPENNumber = @1ExistPENNumber + CAST(@lPENNumber AS NVARCHAR(200)) + ','
	    END	       
	END
          
	IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId AND Id<>@1StudentId))         
          BEGIN
				IF(ISNULL(@lRegistrationNumber,'')!='')
				BEGIN
  					SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
				END
	       END
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lAdhaarNumber COLLATE DATABASE_DEFAULT AND SM.Id<>@1StudentId))         
          BEGIN
          
                IF(ISNULL(@lAdhaarNumber,'')!='')
                BEGIN
  			        SET @1DuplicateAdhaarNumber = @1DuplicateAdhaarNumber + @lAdhaarNumber + ','
  			    END
	       END	
	     
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lUIDNumber COLLATE DATABASE_DEFAULT AND SM.Id<>@1StudentId))         
	BEGIN
		IF(@lIsStudentUIDNumberUnique='True')		--add
		BEGIN  
			IF(ISNULL(@lUIDNumber,'')!='')
			BEGIN
  				SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
			END 
		END   
	END	
END       
	
	IF(ISDATE(@lAdmissionDate) = 0 AND @lAdmissionDate!='')
	BEGIN
		SET @1ValidAdmissionDate=@1ValidAdmissionDate + @lCode + '-' + @lAdmissionDate+','
	END
	
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB + @lCode + '-' + @lDOB+','
	END
	
	IF(ISDATE(@lLeftDate) = 0 AND @lLeftDate!='')
	BEGIN
		SET @1ValidLeftDate=@1ValidLeftDate + @lCode + '-' + @lLeftDate+','
	END
	
	IF(ISDATE(@lLCDate) = 0 AND @lLCDate!='')
	BEGIN
		SET @1ValidLCDate=@1ValidLCDate + @lCode + '-' + @lLCDate+','
	END
	
     SET @lCount = @lCount - 1	
   END	
   
	SELECT @lCount =  COUNT(Id) FROM #tTable1
 	WHILE @lCount > 0 		
	BEGIN
		SELECT @lClass = Class, @lDivision = Division FROM #tTable1 WHERE Id = @lCount
		
		IF NOT EXISTS (SELECT 1 FROM sSetup.tDivisionMaster DM INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId 
					WHERE CM.Title COLLATE DATABASE_DEFAULT =@lClass COLLATE DATABASE_DEFAULT AND DM.Title COLLATE DATABASE_DEFAULT =@lDivision COLLATE DATABASE_DEFAULT AND DM.OrgId=@rOrgId)	
		BEGIN
			SET @lValidationMsg = 'Enter proper value for Division ' + @lClass + ' ' + @lDivision +','
		END

		If(@rOperation=2)
   	    BEGIN
   			DECLARE @lExistingClassId int
   			DECLARE @lExcelClassId int
   			SET @lExistingClassId=(SELECT ClassId From sStudent.tAcademic WHERE StudentId=@1StudentId AND BatchId=@rBatchId)
	   		
   			SET @lExcelClassId=(select Id from sSetup.tClassMaster where Title=@lClass and OrgId=@rOrgId)
	   		
   			IF(@lExcelClassId<>@lExistingClassId)
   			BEGIN
				SET @lValidationMsg+='Class Id not match/update,'
			END   			
   	    END

		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='ID No Should not be empty,'
		END
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='First Name Should not be empty,'			
		END

		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SET @lValidationMsg+='Class Should not be empty,'
		END
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Division IS NULL OR Division COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SET @lValidationMsg+='Division Should not be empty,'
		END
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender='')
		BEGIN
			SET @lValidationMsg+='Gender Should not be empty,'
		END
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionDate IS NULL OR AdmissionDate COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SET @lValidationMsg+='Admission Date Should not be empty or check the date format,'
		END
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId)) AND (@rOperation=1)
		BEGIN
			SET @lValidationMsg+='Enter proper value for Class as per Institute Setup > Class Master,'
		END
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard  COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND AdmissionStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId)) AND (@rOperation=1)
		BEGIN
			SET @lValidationMsg+='Enter proper value for Admission Class as per Admin Tool > Institute Setup > Class Master,'
		END
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Religion COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Religion COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tReligionMaster WHERE OrgGroupId=@rOrgGroupId))
		BEGIN
			SET @lValidationMsg+='Enter proper value / Check spelling for Religion per Admin Tool > Master > Religion Master,'
		END
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tGenderMaster))
		BEGIN
			SET @lValidationMsg+='Enter proper value / Check spelling for gender ( Male / Female ),'
		END
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE CastCategory COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND CastCategory COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tCastCategoryMaster))
		BEGIN
			SET @lValidationMsg+='Enter proper value for Cast Category (OBC,SC,ST,GENERAL),'
		END
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1) AND (@rOperation=1)
		BEGIN
			SET @lValidationMsg+='Left Date Should not be empty or check the date format,'
		END	
		
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LCDate IS NULL OR LCDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1)
		BEGIN
			SET @lValidationMsg+='LC Date Should not be empty or check the date format,'
		END
		
		IF (@1NotExistStudentCode IS NOT NULL AND @1NotExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='Not Exist Code ' + @1NotExistStudentCode+','
		END	
		
		SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'') + Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
		
		SELECT @1DuplicateStudentSUId=COALESCE(@1DuplicateStudentSUId ,'') + SUId + ',' FROM #tTable1 GROUP BY SUId HAVING ( COUNT(SUId) > 1 )	
		IF(@1DuplicateStudentSUId IS NOT NULL AND @1DuplicateStudentSUId != '' AND @lIsActivateUniqueId=1)
		BEGIN
			SET @lValidationMsg+='Duplicate SUId ' + @1DuplicateStudentSUId +','
		END						

		SELECT @1DuplicatePENNumber=COALESCE(@1DuplicatePENNumber ,'') + CAST(PENNumber AS nvarchar(30))+ ',' FROM #tTable1 GROUP BY PENNumber HAVING ( COUNT(PENNumber) > 1 )	
		IF(@1DuplicatePENNumber IS NOT NULL AND @1DuplicatePENNumber != '' AND @lIsActivateUniquePENNumber=1)
		BEGIN
			SET @lValidationMsg+='Duplicate PENNumber ' + @1DuplicatePENNumber +','
		END

		IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='Duplicate Code ' + @1DuplicateStudentCode +','
		END

		SELECT @1DuplicateStudentRegistrationNumber=COALESCE(@1DuplicateStudentRegistrationNumber ,'') + CONVERT(VARCHAR(20),RegistrationNumber) + ',' FROM #tTable1 GROUP BY RegistrationNumber HAVING ( COUNT(RegistrationNumber) > 1 AND ISNULL(RegistrationNumber
,'')!='')	
		IF(@1DuplicateStudentRegistrationNumber IS NOT NULL AND @1DuplicateStudentRegistrationNumber  COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='Duplicate Registration Number ' + @1DuplicateStudentRegistrationNumber +','
		END

		IF (@1DuplicateAdhaarNumber IS NOT NULL AND @1DuplicateAdhaarNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='Exist Adhaar Number ' + @1DuplicateAdhaarNumber +','
		END

		IF (@1DuplicateUIDNumber IS NOT NULL AND @1DuplicateUIDNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT AND @lIsStudentUIDNumberUnique='True') --add
		BEGIN
			SET @lValidationMsg+='Exist UID Number ' + @1DuplicateUIDNumber +','
		END

		IF (@1ExistPENNumber IS NOT NULL AND @1ExistPENNumber != '' AND @lIsActivateUniquePENNumber=1)
		BEGIN
			SET @lValidationMsg+='Exist PENNumber ' + @1ExistPENNumber +','
		END

		IF((@1ExistStudentSUId IS NULL OR @1ExistStudentSUId = '' OR @lIsActivateUniqueId=0) AND (@1ExistStudentCode IS NULL OR @1ExistStudentCode = '') AND (@1ExistStudentRegistrationNumber IS NULL OR @1ExistStudentRegistrationNumber = '')
		AND (@1ValidAdmissionDate IS NULL OR @1ValidAdmissionDate = '') AND (@1ValidDOB IS NULL OR @1ValidDOB = ''))
		BEGIN
			SET @lValidationMsg +=''
		END

		IF (@1ExistStudentSUId IS NOT NULL AND @1ExistStudentSUId != '' AND @lIsActivateUniqueId=1)
		BEGIN
			SET @lValidationMsg+='Exist SUId ' + @1ExistStudentSUId +','
		END

		IF (@1ExistStudentCode IS NOT NULL AND @1ExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='Exist Code ' + @1ExistStudentCode +','
		END

		IF (@1ExistStudentRegistrationNumber IS NOT NULL AND @1ExistStudentRegistrationNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @lValidationMsg+='Exist Registration Number ' + @1ExistStudentRegistrationNumber +','
		END

		IF (@1ValidAdmissionDate IS NOT NULL AND @1ValidAdmissionDate != '')
		BEGIN
			SET @lValidationMsg+= 'Wrong Admission Date ' + @1ValidAdmissionDate +','
		END

		IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
		BEGIN
			SET @lValidationMsg+= 'Wrong DOB ' + @1ValidDOB +','
		END

		IF (@1ValidLeftDate IS NOT NULL AND @1ValidLeftDate != '' AND @lLCDate!='')
		BEGIN
			SET @lValidationMsg+= 'Wrong LeftDate ' + @1ValidLeftDate +','
		END

		IF (@1ValidLCDate IS NOT NULL AND @1ValidLCDate != '' AND @lLCDate!='')
		BEGIN
			SET @lValidationMsg+= 'Wrong LCDate ' + @1ValidLCDate +','
		END

		IF (@lIsSurnameAndFatherNameMandatory = 'True' )
		BEGIN
			IF EXISTS(SELECT 1 fROM #tTable1 WHERE MiddleName IS NULL OR MiddleName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SET @lValidationMsg+= 'FatherName Should not be empty,'
			END

			IF EXISTS(SELECT 1 fROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SET @lValidationMsg+= 'Surname Should not be empty,'
			END
		END

		SET @lCount = @lCount - 1			  
	END
	SELECT @lValidationMsg AS Validate
END
GO
PRINT N'Altering Procedure [sAccounting].[pAccountwiseBalanceGet]...';


GO
ALTER PROCEDURE [sAccounting].[pAccountwiseBalanceGet]
	@rOrgGroupId int,
	@rAccountId int,
	@rAccountYearTitle nvarchar(100)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

Declare @LedgerId int 
Declare @LOpeningBalance Decimal (25,5)
Declare @OpeningBalance Decimal (25,5)
Declare @lClOsingBalance Decimal (25,5)
Declare @CreditBalance Decimal (25,5)
Declare @DebitBalance Decimal (25,5)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @LedgerName Nvarchar(150)
Declare @LedgerGroupId int
declare @lAccountYearId int
Declare @DecimalCount INT
declare @lStartDate Date,@lEndDate Date

	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548
	
	IF OBJECT_ID('tempdb..#tempAccountYearMaster') IS NOT NULL DROP TABLE #tempAccountYearMaster

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

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

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

	CREATE TABLE #tempAccountYearMaster
	(	
 		Id INT IDENTITY (1, 1),
		AccountYearId int,
		AccountId int,
 		AccountYearName nvarchar(100),
	)

	INSERT INTO #tempAccountYearMaster
	select Id,AccountId,Code from sAccounting.tAccountingYearMaster where OrgGroupId = @rOrgGroupId AND AccountId = @rAccountId 
		AND IsLocked = 0 AND Title = @rAccountYearTitle
		
   CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(25,5), 
		Closing_Balance decimal(25,5),
		Transaction_Balance decimal(25,5) 
	) 
 	
	CREATE TABLE #tCashBankBookTemp
 	(	Id INT IDENTITY (1, 1),
 		LedgerId int,
 		LedgerName nvarchar(150),
 		OpBalance Decimal(25,5), 
 		CrBalance Decimal(25,5),
 		DrBalance Decimal(25,5),
 		ClBalance Decimal(25,5),
 		LedgerGroupId int
 	) 
	
	CREATE TABLE #tCashBankBook
 	(	Id INT IDENTITY (1, 1),
 		LedgerId int,
 		LedgerName nvarchar(150),
 		OpBalance Decimal(25,5),
 		LedgerTypeId int,
 		LedgerGroupId int,
		AccountYearId int
 	) 
	
	declare @lCount1 int
	SELECT @lCount1 =  COUNT(Id) FROM #tempAccountYearMaster
	
	WHILE (@lCount1 > 0)
	BEGIN	
		select @lAccountYearId= AccountYearId FROM #tempAccountYearMaster where Id = @lCount1 

		INSERT INTO #tCashBankBook
		select L.Id,L.Title,L.OpeningBalance,LedgerTypeId,L.LedgerGroupId,@lAccountYearId from sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		where LG.OrgGroupId = L.OrgGroupId AND L.IsObsolete=0 AND L.IsShowInDashBoard = 1  -- Mantis Id : 0035149	
		AND LG.OrgGroupId = @rOrgGroupId and L.AccountingYearId = @lAccountYearId AND LG.AccountingYearId = @lAccountYearId
		ORDER BY L.Id Asc

		SET @lCount1 = @lCount1 - 1
	END	 
	
	SELECT @lCount =  COUNT(Id) FROM #tCashBankBook    
	WHILE (@lCount > 0)
	BEGIN		
		SELECT @LedgerId =LedgerId,@LedgerName= LedgerName,@OpeningBalance=ISNULL(OpBalance,0),@LedgerGroupId = LedgerGroupId, 
		@lLedgerTypeId=LedgerTypeId, @lAccountYearId = AccountYearId FROM #tCashBankBook WHERE Id = @lCount				

		SELECT  @lStartDate = FromDate, @lEndDate = ToDate from sAccounting.tAccountingYearMaster where OrgGroupId = @rOrgGroupId AND Id = @lAccountYearId
		
		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @lStartDate,@lEndDate,@rOrgGroupId,@lAccountYearId,@LedgerId,''

		 SELECT @LOpeningBalance=ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId And TD.LedgerId=@LedgerId
			AND T.AccountingYearId = @lAccountYearId 
			AND T.TransactionDate < @lStartDate

		SELECT @CreditBalance= -1 * ISNULL(SUM(AMOUNT), 0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 		 
			AND T.AccountingYearId = @lAccountYearId 
			AND T.TransactionDate >= @lStartDate AND T.TransactionDate <= @lEndDate
			AND TD.TransactionTypeId = 1 And TD.LedgerId=@LedgerId

		 SELECT @DebitBalance=  ISNULL(Sum(TD.Amount) ,0)
		 FROM  sAccounting.tTransaction T INNER JOIN sAccounting.tTransactionDetail TD
		 ON T.Id=TD.TransactionId 
			AND T.AccountingYearId = @lAccountYearId 
			AND T.TransactionDate >= @lStartDate AND T.TransactionDate <= @lEndDate
			AND TD.TransactionTypeId = 2 And TD.LedgerId=@LedgerId

		SET @LOpeningBalance = @LOpeningBalance  +  @OpeningBalance

		SELECT  @lClOsingBalance = Closing_Balance FROM #tempUpdateClosingBalance WHERE LedgerId=@LedgerId

		INSERT INTO #tCashBankBookTemp  (LedgerId,LedgerName,OpBalance,CrBalance,DrBalance,ClBalance,LedgerGroupId)
		VALUES 	(@LedgerId,@LedgerName,@LOpeningBalance,@CreditBalance,@DebitBalance,@lClOsingBalance,@LedgerGroupId)
		
		SET @lCount = @lCount - 1
	END

		SELECT LedgerId,LedgerName, ([sAccounting].[fDecimalValueGet] (OpBalance, @DecimalCount)) AS OpBalance,
		  ([sAccounting].[fDecimalValueGet] (ISNULL(CrBalance,0), @DecimalCount)) AS CrBalance
		  ,([sAccounting].[fDecimalValueGet] (ISNULL(DrBalance,0), @DecimalCount)) AS DrBalance
		  ,([sAccounting].[fDecimalValueGet] (ClBalance, @DecimalCount)) AS ClBalance 
		FROM #tCashBankBookTemp

	DROP TABLE #tCashBankBook
	DROP TABLE #tCashBankBookTemp
	DROP TABLE #tempUpdateClosingBalance
	DROP TABLE #tempAccountYearMaster
END
GO
PRINT N'Altering Procedure [sAccounting].[pDashboardLedgerwiseClosingBalanceGet]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
Declare @OpeningBalance decimal(25,5)
Declare @AccOpBalance decimal(25,5) = 0
Declare @ClosingBalance decimal(25,5)
Declare @TransactionBalance decimal(25,5)
Declare @LedgerId int 
Declare @lCount int
Declare @LedgerTypeId int,@lAccountYearId int,@lAccountId int
declare @lStartDate Date,	@lEndDate Date
	
	Declare @DecimalCount INT
	SELECT @DecimalCount = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
						  FROM sConfig.tConfigurationMaster CM
						  LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
						  AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId WHERE CM.Id = 548

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

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

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

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

		SET @lCount = @lCount - 1
	END
	
	DECLARE  @columns NVARCHAR(MAX) = '', @sql     NVARCHAR(MAX) = '';	
	SET @columns =(SELECT STUFF(
    ( SELECT  distinct ',' +  QUOTENAME(title) FROM sAccounting.tLedgerMaster where OrgGroupId = @rOrgGroupId AND IsObsolete = 0 AND IsShowInDashBoard = 1
					AND AccountingYearId IN (select Id from sAccounting.tAccountingYearMaster where Title = @rAccountYearTitle AND OrgGroupId = @rOrgGroupId)		-- Mantis Id : 0035149	
	FOR XML PATH('')), 1, 1, '') AS Ledgers)

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

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


GO

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

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

DECLARE @lCount int = 0, @lResult bigint = 0
DECLARE @lOrgGroupId bigint = 0,
		@lAccountingYearId int = 0,
		@lVoucherDate date = '',
		@lNarration nvarchar(1000) = '',--Change by dhananjay 150->1000 size for mantis id - 0035082
		@lVoucherNumber bigint = 0,
		@lVoucherType nvarchar(50) = '',
		@lVoucherTypeId tinyint = 0,		 
		@lCreatedUserId bigint = 0,
		@lCreatedDateTime datetime = '',
		@lAccountId int = 0,
		@lChequeNo nvarchar(20) = '',		
		@lChequeDate date = '',
		@lTransactionApproveId bigint = NULL,
		@lCreditAmount decimal(12,2) = 0,
		@lDebitAmount decimal(12,2) = 0,
		@lToLedger nvarchar(50) = '',
		@lByLedger nvarchar(50) = '',
		@lToLedgerId bigint = 0,
		@lByLedgerId bigint = 0

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


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

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

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

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

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


	SET @lCount = @lCount - 1		
END

SELECT 1
	
	COMMIT TRANSACTION	

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


GO
ALTER PROCEDURE [sStudent].[pStudentDetailFormGet]
	@rBatchId int = 0,
	@rStudentId bigint = 0,
	@rOrgGroupBatchId int = 0,
	@rOrgId int = 0,
	@Tab nvarchar(20) = '',
	@rAttendanceTypeId smallint = 0,
	@rDepositHeadId int = 0,
	@rAlertModeId smallint = 0,
	@rIsMobileApp bit = 0,
	@rExamId int = 0

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @lSUIdBarcode nvarchar(50)
	DECLARE @lAcademicId bigint = 0, @lClassId int  = 0, @lAdmissionCategoryId int = 0,@lCode nvarchar(20) = '',@lEmail nvarchar(50) = '',@lContactNo nvarchar(50) ='',@lDate datetime = (SELECT sCommon.fGetDate()),@lOrgGroupId int = 0,
	@lDepartmentId int = 0, @lDivisionId int = 0
	SELECT @lAcademicId = Id,@lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId,@lDivisionId = DivisionId from sStudent.tAcademic
	Where StudentId = @rStudentId AND BatchId = @rBatchId
	SELECT @lCode = Code FROM sStudent.tStudentMaster WHERE Id = @rStudentId
	SELECT @lEmail = ParentEmail, @lContactNo = ParentContactNo FROM sStudent.tStudentCommunication WHERE StudentId = @rStudentId
	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId	
	SELECT @lDepartmentId = DepartmentId FROM sSetup.tClassMaster WHERE Id = @lClassId
	SELECT @lSUIdBarcode = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 168 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId



	IF(LOWER(@Tab) = 'overview')
	BEGIN
		SELECT
			SA.StudentId AS Id,			
			SA.Name AS StudentName,
			SA.FirstName as FirstName,
			SA.MiddleName as MiddleName,
			SA.LastName as LastName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,' - ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			SA.RollNo,
			ISNULL(SM.Title,'-') AS House,
			--Other
			ISNULL(SA.DateOfBirth,'0001/01/01') AS DateOfBirth,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			SA.GenderId,
			ISNULL(SA.Religion,'') AS Religion,
			--Admission			
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,			
			ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,	
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
			ISNULL(SA.LeftDate,'0001/01/01') AS LeftDate,						 
			ISNULL(SA.LeftStandard,'') AS LeftStandard,			
			ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,		
			ISNULL(SA.LCNumber,'') AS LCNumber,			
			ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			--Communication
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			
			--Parent Information
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			ISNULL(SF.FatherDesignation,'') AS FatherDesignation,
			ISNULL(SF.FatherOrganization,'') AS FatherOrganization,
			ISNULL(SF.FatherIncome,'') AS FatherIncome,

			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			ISNULL(SF.MotherDesignation,'') AS MotherDesignation,
			ISNULL(SF.MotherOrganization,'') AS MotherOrganization,
			ISNULL(SF.MotherIncome,'') AS MotherIncome,

			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			ISNULL(SF.RelativeDesignation,'') AS RelativeDesignation,
			ISNULL(SF.RelativeOrganization,'') AS RelativeOrganization,
			ISNULL(SF.RelativeIncome,'') AS RelativeIncome,
			
			--Health Information
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			
			ISNULL(SH.IsPysicalDeformity,0) AS IsPysicalDeformity,
			ISNULL(SH.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			ISNULL(SH.IsMajorIllness,0) AS IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			ISNULL(SH.IsAllergy,0) AS IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			ISNULL(SH.IsPastHistory,0) As IsPastHistory ,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			--Hostel
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,

			-- Photos		
	   	    ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentPhoto,
	   	    ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
	   	    ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
	   	    ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
			
		   -- Transport Details
		    A.VehicleName AS VehicleName,
		    A.VehicleRegistrationNumber AS VehicleRegistrationNumber,
		    A.TypeOfVehicle AS TypeOfVehicle,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    A.DriverName,
		    A.DriverMobileNo,
		    A.ConductorName,
		    A.ConductorMobileNo,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,		    
		    A.DropVehicleName AS DropVehicleName,
		    A.DropVehicleRegistrationNumber AS DropVehicleRegistrationNumber,
		    A.DropTypeOfVehicle AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    A.DropRouteDriverName AS DropRouteDriverName,
		    A.DropRouteDriverMobileNo AS DropRouteDriverMobileNo,
		    A.DropRouteConductorName AS DropRouteConductorName,
		    A.DropRouteConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		    
		    --ClassTeacher Details
		    ISNULL(EMT.Id,0) AS TeacherId,
		    EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName AS TeacherFullName,
		    EDM.Title AS TeacherDesignation,
		    EPD.Qualification AS TeacherQualification,
			ISNULL(FED.PaidAmount,0) AS FeePaidAmount,
			ISNULL(FED.PendingAmount,0) AS FeePendingAmount,
			ISNULL(FED.PaidAmount,0) + ISNULL(FED.PendingAmount,0) AS FeeTotalAmount,
			(SELECT COUNT(AcademicId) FROM sAttendance.tStudentRegister WHERE AcademicId = @lAcademicId AND IsPresent = 0) AS AbsentCount,
			(SELECT COUNT(AcademicId) FROM sAttendance.tStudentRegister WHERE AcademicId = @lAcademicId AND IsPresent = 1) AS PresentCount,

			--TecherSubjectDivision
			--EM.FirstName + ' ' + EM.LastName AS DivisionTeacherName,
			--SM.Title AS DivisionSubjectName,

			-- Today's Lectures

			ISNULL(STUFF((
			SELECT ',' + OnlineLearningTitle FROM 
			(SELECT OL.Title AS OnlineLearningTitle FROM sAcademic.tOnlineLearning OL INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
				WHERE (
				( 
				(OLS.SourceTypeId = 2021 AND OLS.SourceId =SA.OrgId) 
				OR
				(OLS.SourceTypeId = 2017 AND OLS.SourceId =SA.DepartmentId) OR
				(OLS.SourceTypeId = 2016 AND OLS.SourceId =SA.ClassId) OR
				(OLS.SourceTypeId = 2005 AND OLS.SourceId =SA.DivisionId) OR
				(OLS.SourceTypeId = 2003 AND OLS.SourceId =SA.StudentId) OR
				(OLS.SourceTypeId = 2001 AND OLS.SourceId =SA.AcademicId)
				 ))
				) D
				ON D.OnlineLearningId= OL.Id WHERE OL.StartDate >= CAST(sCommon.fGetDate() AS DATE) AND OL.EndDate <= CAST(sCommon.fGetDate() AS DATE)) OL FOR XML PATH('')),1,1,''),'') AS OnlineLearningLectures,

			ISNULL(STUFF((
				SELECT ',' + ExamName + ' (' + CAST([Percentage] AS NVARCHAR(20)) + ')' FROM (
				SELECT AD.Id AS AcademicId,E.[Name] AS ExamName, R.[Percentage] FROM
				sStudent.tAcademic AD 
				INNER JOIN  sAssessment.vExamMaster E ON E.BatchId = AD.BatchId AND E.ClassId = AD.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON E.BatchId = BM.Id 
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=AD.DivisionId
				INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = E.Id
 
				 WHERE ((AD.Id=@lAcademicId) OR (@lAcademicId=0))	
					AND IsProcessResult=1 ) E
				FOR XML PATH('')),1,1,''),'') AS ExamPercentage,
				
			(SELECT SUM(Amount) FROM sFee.tDepositAdd WHERE AcademicId = @lAcademicId) AS DepositCreditAmount,
			(SELECT SUM(Amount) FROM sFee.tDepositAdjustment WHERE AcademicId = @lAcademicId) + (SELECT SUM(RefundAmount) FROM sFee.tDepositRefund WHERE AcademicId = @lAcademicId) AS DepositDebitAmount,
			ISNULL(SI.QRCode,0x) AS QRCode,
			CASE WHEN @lSUIdBarcode = 'True' THEN SA.SUId  ELSE SA.Code END AS BarcodeNumber,
			SA.StatusName AS [Status]--Added for mantis : 35424 by Nilesh

			FROM 
			sStudent.vStudentAllDetail SA          
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId           
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId  
		   LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId
		   --LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = SA.DivisionId
		   --LEFT JOIN sSetup.tSubjectMaster SBM ON SBM.Id = TSD.SubjectId
		   --LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD.EmployeeId
            LEFT JOIN --HostelDetails
            (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 		   
		 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1           
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id AND  ISNULL(EMW.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id AND  ISNULL(EMA.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN -- Transport Details
           ( SElect AR1.SourceId,
           VM.Title AS VehicleName,
		    VM.RegistrationNumber AS VehicleRegistrationNumber,
		    TV.Title AS TypeOfVehicle,
		    ISNULL(BRM.Title,'') AS BusRoute,
		    BRM.DriverName,
		    BRM.DriverMobileNo,
		    BRM.ConductorName,
		    BRM.ConductorMobileNo,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    VM.Title AS DropVehicleName,
		    VM.RegistrationNumber AS DropVehicleRegistrationNumber,
		    TV1.Title AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		    BRM1.DriverName AS DropRouteDriverName,
		    BRM1.DriverMobileNo AS DropRouteDriverMobileNo,
		    BRM1.ConductorName AS DropRouteConductorName,
		    BRM1.ConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination
		      FROM
             sTransport.tAssignRoute AR1   
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId) A ON A.SourceId=SA.StudentId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId AND  ISNULL(EMT.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
           INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
           LEFT JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = SA.StudentId AND CGM.SourceTypeId = 2003
           LEFT JOIN sCommunication.tCustomGroup CGG ON CGG.Id = CGM.CustomGroupId
           LEFT JOIN sStudent.tStudentMaster SMM ON SMM.Id = SA.StudentId
           LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SMM.StudentGroupId
           LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id = SMM.StudentOtherGroupId
		   LEFT JOIN sStudent.tStudentAdmission SAM ON SAM.StudentId = SA.StudentId
		   LEFT JOIN -- Fee Details
		   (
				SELECT 
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount,
			FS.BatchId
			  FROM 
						sFee.tFeeMaster FM
					INNER JOIN 
					(
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
				 
						FROM sFee.tFeeSetup FS1
			   
							WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
							AND FS1.BatchId = @rBatchId
							UNION ALL
				
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId 
				 
						FROM sFee.tFeeSetup FS1
			 
					INNER JOIN sFee.tFeeOptional FO
						ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lAcademicId) AND(FO.SourceTypeId=2001)
						WHERE
						 FS1.BatchId = @rBatchId
						AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
					) FS ON FS.FeeId=FM.Id
					LEFT JOIN sFee.tFeeAllocation FA
						ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lAcademicId) AND(FA.SourceTypeId=2001)
					LEFT JOIN
					(
						SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
						FROM
						sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
						WHERE						
						 R.SourceId= @lAcademicId
						AND ((R.SourceTypeId = 2001))
						AND R.IsObsolete = 0 
						AND R.BatchId = @rBatchId
						 GROUP BY FeeSetupId
					) R ON R.FeeSetupId = FS.Id	
			WHERE 
				FS.BatchId=@rBatchId
				GROUP BY FS.BatchId
		   ) FED ON FED.BatchId = SA.BatchId			  		  

  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.BatchId=@rBatchId) OR(@rBatchId=0))			
			AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))			
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))			
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId = 0))
	END
	ELSE IF(LOWER(@Tab) = 'studentdetails')
	BEGIN
		exec sStudent.pStudentFullProfileGet @rBatchId=@rBatchId,@rStudentId=@rStudentId,@rOrgGroupBatchId=@rOrgGroupBatchId,@rOrgId=@rOrgId
	END	
	ELSE IF(LOWER(@Tab) = 'feedetails')
	BEGIN
		IF(@rIsMobileApp = 0)
		BEGIN
			exec [sFee].[pFeeAllocationViewGet] @rSourceId=@lAcademicId,@rSourceTypeId=2001,@rBatchId=@rBatchId
		
			DECLARE @Receiptgrid NVARCHAR(max)=''
			SELECT  @Receiptgrid = @Receiptgrid + '<tr>		
			<td align="left" scope="col">' + ISNULL(RBM.Title,'') + '</td>
			<td style="color:Black;overflow-wrap:anywhere;"><a style="color: #03afc5 !important;" onclick="FeeReceiptEdit(' + convert(nvarchar,R.ReceiptBookId) + ',' + convert(nvarchar,R.PayTypeId) + ',' + convert(nvarchar,R.ReceiptNumber) + ')">' + convert(varchar,isnull(R.ReceiptNumber,'')) + '</a></td>		
			<td align="left" scope="col">' +  convert(varchar,isnull(R.ReceiptDate,'01/01/0001'),103) + '</td>
			<td align="left" scope="col">' +  ISNULL(PTM.Title,'') + '</td>
			<td align="left" scope="col">' +  isnull(R.ChequeNo,'') + '</td>
			<td align="left" scope="col">' + isnull(R.BankName,'') + '</td>
			<td align="left" scope="col">' +  ISNULL([sFee].[fReceiptFeeDetailGet](R.Id),'') + '</td>
			<td align="left" scope="col">' +  convert(varchar,isnull(R.ReceiptAmount,0)) + '</td>
			<td><input type="button" id="' + convert(varchar,R.Id) + '" value="&#xf02f; Print Fee Receipt" onclick="PrintFeeReceipt(this, ' + convert(varchar,R.Id) + ', ' + convert(varchar,RBM.Id) + ');" class="fas btn btn-report " /></td>
			</tr>'	
			
		  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
				LEFT JOIN sSecurity.tUser U
					ON U.Id=R.CreatedUserId
				INNER JOIN sFee.tReceiptBookMaster RBM 
					ON RBM.Id=R.ReceiptBookId
			
		WHERE 
			R.SourceTypeId = 2001
			AND SA.AcademicId=@lAcademicId		
			ORDER BY R.ReceiptNumber
			
			
		select isnull(@Receiptgrid,'') as Receiptgrid

			--exec [sFee].[pFeeReceiptListViewGet] @rAcademicId=@lAcademicId,@rOrgId=@rOrgId
			exec [sFee].[pFeecancelReceiptListviewGet] @rBatchId=@rBatchId,@rOrgId=@rOrgId,@rAcademicId=@lAcademicId		
			exec [sFee].[pRptFeePendingAllBatchGet] @rOrgGroupBatchId=0,@rOrgId=@rOrgId,@rBatchId=0,@rCode=@lCode,@rUserId=0

			--exec [sFee].[pFeeAllocationViewGet] @rSourceId=@lAcademicId,@rSourceTypeId=2001,@rBatchId=@rBatchId
		END
		ELSE
		BEGIN
			exec [sFee].[pFeeAllocationViewGet] @rSourceId=@lAcademicId,@rSourceTypeId=2001,@rBatchId=@rBatchId

			SELECT  
			ISNULL(RBM.Title,'') AS ReceiptBook,
			convert(varchar,isnull(R.ReceiptNumber,'')) AS ReceiptNumber,
			convert(varchar,isnull(R.ReceiptDate,'01/01/0001'),103) AS ReceiptDate,
			ISNULL(PTM.Title,'') AS PayType,
			isnull(R.ChequeNo,'') AS ChequeNo,
			isnull(R.BankName,'') AS BankName,
			ISNULL([sFee].[fReceiptFeeDetailGet](R.Id),'') AS FeeDetail,
			convert(varchar,isnull(R.ReceiptAmount,0)) AS ReceiptAmount						
			  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
					LEFT JOIN sSecurity.tUser U
						ON U.Id=R.CreatedUserId
					INNER JOIN sFee.tReceiptBookMaster RBM 
						ON RBM.Id=R.ReceiptBookId			
			WHERE 
				R.SourceTypeId = 2001
				AND SA.AcademicId=@lAcademicId		
				ORDER BY R.ReceiptNumber


			SELECT convert(varchar,Isnull(R.ReceiptNumber,0)) AS ReceiptNumber,
			convert(varchar,ISNULL(R.ReceiptDate,'01/01/0001'),103) AS ReceiptDate,
			Convert(varchar,ISNULL(R.ReceiptAmount,0)) AS ReceiptAmount,
			ISNULL(PTM.Title,'') AS PayType,
			ISNULL(R.ChequeNo,'') AS ChequeNo,
			ISNULL(R.BankName,'') AS BankName,
			ISNULL(RBM.Title,'') AS ReceiptBook,
			convert(varchar,ISNULL(FI.InvoiceNumber,0)) AS InvoiceNumber,
			 convert(varchar,ISNULL(R.Remark,'')) AS Remark			
		  FROM 
				sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic A
					ON A.AcademicId=R.SourceId
				INNER JOIN sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=R.PayTypeId
				INNER JOIN sFee.tReceiptBookMaster RBM
					ON RBM.Id=R.ReceiptBookId
				LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId
		WHERE 
				R.SourceTypeId=2001 AND R.IsObsolete=1
				AND A.OrgId=@rOrgId AND R.BatchId=@rBatchId
				AND A.AcademicId=@lAcademicId
			   ORDER BY R.ReceiptNumber DESC


            /**** Changes done for mantis : 28925 ****/
		
		SELECT 
			ISNULL(OM.DisplayTitle,'') AS OrganizationName,
			SA.FirstName+' '+SA.LastName as StudentName,
			convert(varchar,Isnull(CR.ReceiptNumber,0)) AS ReceiptNumber,
			convert(varchar,ISNULL(CR.ReceiptDate,'01/01/0001'),103) AS ReceiptDate,
			ISNULL(RBM.Title,'') AS ReceiptBook,
			ISNULL(CCM.Title,'') AS ChargeCategory,
			convert(varchar,ISNULL(SUM(CRD.Amount),0)) AS Amount
			
		    FROM 
            sFee.tChargeReceipt CR
		    INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id	
		    INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		    INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001
		    INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		    INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		    WHERE 
			CR.SourceTypeId=2001 AND CR.IsObsolete=0
			AND SA.OrgId=@rOrgId AND CR.BatchId=@rBatchId
			AND SA.AcademicId=@lAcademicId
			GROUP BY
            OM.DisplayTitle,
            SA.FirstName,
            SA.LastName,
            CR.ReceiptNumber,
            CR.ReceiptDate,
            RBM.Title,
            CCM.Title
            ORDER BY CR.ReceiptNumber DESC

		SELECT 
		    ISNULL(DHM.Title,'') AS DepositHeadName,
		    ISNULL(vSA.Name,'') AS StudentName, 
		    ISNULL(vSA.Code,'') AS GrNo,
		    vSA.ClassName AS Class,
		    ISNULL(EM.Title,'') As ExpenseType,
		    Convert(varchar,ISNULL(DA.Amount,0)) AS Amount,
		    convert(varchar,ISNULL(DA.AdjustmentDate,'01/01/0001'),103) AS AdjustmentDate
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdjustment DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
		LEFT JOIN  sFee.tFeeDepositExpenseTypeMaster EM ON EM.Id=DA.FeeDepositExpenseTypeId
  WHERE 				
		vSA.OrgId=@rOrgId AND vSA.BatchId=@rBatchId
		AND vSA.AcademicId=@lAcademicId
		ORDER BY vSA.Name DESC

		SELECT 
		ISNULL(DHM.Title,'') AS DepositHeadName,
		ISNULL(vSA.Name,'') AS StudentName,
		ISNULL(vSA.Code,'') AS GrNo, 
		ISNULL(vSA.ClassName,'') AS Class,
		convert(varchar,(CASE  WHEN ISNULL(DR.RefundAmount,0) <> 0 THEN ISNULL(DR.RefundAmount,0) ELSE
        (SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D 
        INNER JOIN sFee.tDepositRefund DR1 ON DR1.DepositHeadId=D.DepositHeadId AND DR1.AcademicId=D.AcademicId AND D.AcademicId = DR.AcademicId
        WHERE D.DepositHeadId = DR1.DepositHeadId AND D.AcademicId=DR1.AcademicId )         
		 - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sFee.tDepositAdjustment DA 
		 INNER JOIN sFee.tDepositRefund DR2 ON DR2.DepositHeadId=DA.DepositHeadId AND DR2.AcademicId=DA.AcademicId AND DA.AcademicId= DR.AcademicId
		 WHERE DA.DepositHeadId = DR2.DepositHeadId AND DA.AcademicId=DR2.AcademicId ) END)) AS RefundAmount,
		 convert(varchar,ISNULL(DR.RefundDate,'01/01/0001'),103) AS RefundDate
		
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DR.DepositHeadId

  WHERE 				
		vSA.OrgId=@rOrgId AND vSA.BatchId=@rBatchId
		AND vSA.AcademicId=@lAcademicId
		--AND DR.DepositHeadId=@rDepositHeadId
		ORDER BY vSA.Name DESC

		/**** Changes done for mantis : 28925 ****/

		END
	END	
	ELSE IF(LOWER(@Tab) = 'attendance')
	BEGIN
		IF(@rIsMobileApp = 0)
		BEGIN
			IF(@rAttendanceTypeId = 5)
			BEGIN
			exec [sAttendance].[pSubjectRegisterStudentViewGet] @rAcademicId = @lAcademicId,@rBatchId = @rBatchId, @rAttendanceTypeId = @rAttendanceTypeId		
			END
			ELSE 
			BEGIN
			exec [sAttendance].[pMonthlyRegisterStudentviewGet] @rAttendanceTypeId = @rAttendanceTypeId, @rAcademicId = @lAcademicId,@rBatchId = @rBatchId
			END
		END
		ELSE
		BEGIN	
			IF(@rAttendanceTypeId <> 5)
			BEGIN
			SELECT 
				Isnull(MY.MonthTitle,'') AS ForMonth,
				CAST(isnull(MY.YearNumber,0) AS NVARCHAR(20)) AS ForYear,
				CAST(isnull(MR.AttendanceCount,0) AS NVARCHAR(20)) AS AttendanceCount,
				CAST(isnull(MR.PresentCount,0) AS NVARCHAR(20)) AS PresentDays,
				CAST(isnull(MR.AbsentCount,0) AS NVARCHAR(20)) AS AbsentDays,
				CAST(isnull(MR.AveragePresence,0) AS NVARCHAR(20)) AS AveragePresence,
				CAST(isnull(MR.AbsentDays,0) AS NVARCHAR(20)) AS AbsentDate					
			FROM sStudent.vStudentName SN 
			INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@lAcademicId 
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
				AND MR.AttendanceTypeId=@rAttendanceTypeId
				AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
			WHERE
				SN.AcademicId=@lAcademicId	
			ORDER BY MY.YearNumber,MY.MonthNumber
			END
			ELSE
			BEGIN
			Select 
				isnull(SM.Title,'') AS [Subject],
				(SELECT convert(varchar,ISNULL(count(1),0) )FROM sAttendance.tStudentRegister SR  WHERE  SR.AttendanceTypeId = 5 AND SR.IsPresent = 1 AND SR.AcademicId = SN.AcademicId  AND SR.SubjectId = CS.SubjectId) AS PresentCount,
				(SELECT convert(varchar,ISNULL(count(1),0)) FROM sAttendance.tStudentRegister SR WHERE SR.AttendanceTypeId = 5 AND SR.IsPresent = 0 AND SR.AcademicId = SN.AcademicId AND SR.SubjectId = CS.SubjectId) AS AbsentCount	
				From sStudent.vStudentName SN
				INNER JOIN sSetup.tClassSubject CS
				ON SN.ClassId = CS.ClassId
				INNER JOIN sSetup.tSubjectMaster SM
				ON CS.SubjectId = SM.Id 
				WHERE
					(SN.AcademicId=@lAcademicId)
					AND SN.BatchId = @rBatchId
			END
		END
	END
	ELSE IF(LOWER(@Tab) = 'assessment')
	BEGIN
		IF (@rIsMobileApp = 0) 
		BEGIN
			exec [sAssessment].[pExamListGet] @rAcademicId = @lAcademicId, @rBatchId = @rBatchId
		END
		ELSE
		BEGIN
			SELECT  ISNULL(Cm.DisplayTitle,'')+' - '+isnull(Dm.DisplayTitle,'')+' : '+isnull(E.Name,'') AS ExamName,
			isnull(BM.Title,'') AS [Year],
			convert(varchar,isnull(R.TotalMarks,0)) AS TotalMarks,
			convert(varchar,isnull(R.TotalObtain,'')) AS TotalObtain,
			isnull(R.ResultStatus,'') AS Result,
			isnull(R.ResultGrade,'') AS Grade,
			convert(varchar,isnull(R.RankNumber,0)) AS [Rank],
			convert(varchar,isnull(R.Percentage,0)) AS [Percentage],
			convert(varchar,isnull(R.Percentile,0)) AS Percentile,
			@lAcademicId AS AcademicId,
			convert(varchar,E.Id) AS ExamId
			 From
			 sStudent.tAcademic AD 
			 INNER JOIN  sAssessment.vExamMaster E ON E.BatchId = AD.BatchId AND E.ClassId = AD.ClassId
			 INNER JOIN sSetup.tBatchMaster BM ON E.BatchId = BM.Id 
			 INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
			 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=AD.DivisionId
			 INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = E.Id
 
			 WHERE ((AD.Id=@lAcademicId) OR (@lAcademicId=0))	
			 AND IsProcessResult=1
			 ORDER BY DM.OrderIndex DESC


			 SELECT isnull(ESGM.Title,'') AS ExamName,
			 isnull(SBM.Title,'') AS [Subject],
			convert(varchar,isnull(ED.Maximum,0)) AS Maximum,
			convert(varchar,isnull(ED.Minimum,0)) AS Minimum,
			convert(varchar,isnull(RD.Obtain,0)) As Obtain,
			convert(varchar,isnull(RD.GraceMark,0)) AS GraceMark,
			isnull(RD.Remark,'') AS Remark			
    	
		   FROM sStudent.tAcademic AD
			INNER JOIN sAssessment.tExamMaster EM ON EM.BatchId = AD.BatchId AND EM.ClassId = AD.ClassId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
			INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = EM.Id
			INNER JOIN sAssessment.tResultDetail RD ON RD.ExamDetailId = ED.Id AND R.Id = RD.ResultId
			INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SBM ON SBM.Id = CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			Where
			((AD.Id=@lAcademicId) OR (@lAcademicId=0))
			AND ((AD.BatchId =  @rBatchId) OR (@rBatchId=0))
		   AND ((EM.Id=@rExamId) OR (@rExamId=0))
		END
	END
	ELSE IF(LOWER(@Tab) = 'certificate')
	BEGIN
		SELECT 'Bonafied' AS CertificateName,CreatedDateTime,Number AS CertificateNumber,Id FROM [sCertificate].[tBonafide] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId
		UNION ALL
		SELECT 'Character' AS CertificateName,CreatedDateTime,Number AS CertificateNumber,Id FROM [sCertificate].[tCharacter] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId		
		UNION ALL
		SELECT 'Leaving' AS CertificateName,CreatedDateTime,LCNumber AS CertificateNumber,Id FROM [sCertificate].[tLeaving] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId
		UNION ALL
		SELECT 'FirstTrial' AS CertificateName,CreatedDateTime,Number AS CertificateNumber,Id FROM [sCertificate].[tFirstTrial] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId		
		UNION ALL
		SELECT 'Transfer' AS CertificateName,CreatedDateTime,Number AS CertificateNumber,Id FROM [sCertificate].[tTransfer] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId
	END
	ELSE IF(LOWER(@Tab) = 'deposit')
	BEGIN
		exec sFee.pStudentLedgerGet @rAcademicId=@rStudentId,@rDepositHeadId=@rDepositHeadId,@rCode=@lCode,@rSUId=N'',@rOrgId=@rOrgId
	END
	ELSE IF(LOWER(@Tab) = 'alert')
	BEGIN				
		IF(@rIsMobileApp = 1)
		BEGIN
			SELECT 
				'Notification' AS SourceEvent,EM.Title AS EventName,AL.MessageTitle AS AlertSubject,[sCommon].[fXMLTagsReplace](AL.NotificationMessage) as AlertMessage,CONVERT(VARCHAR(10),AL.CreatedDateTime,103) AS CreatedDate,'3' AS AlertModeId			
			FROM
				sAlert.tNotificationLog AL
				INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			WHERE  
				AL.SourceId = @lAcademicId AND AL.SourceTypeId = 2001				

				UNION ALL

			SELECT 
				AL.SourceEvent,EM.Title AS EventName,AL.AlertSubject,[sCommon].[fXMLTagsReplace](AL.AlertMessage) as AlertMessage,CONVERT(VARCHAR(10),AL.CreatedDateTime,103) AS CreatedDate,CAST(AL.AlertModeId AS NVARCHAR(10)) AS AlertModeId
			FROM
				sAlert.tAlertLog AL
				INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			WHERE  
				((AL.ContactId = @lContactNo) OR (AL.ContactId = @lEmail))
				And AL.OrgId=@rOrgId				
		END
		ELSE 
		BEGIN
			IF(@rAlertModeId = 3)
			BEGIN
				exec sAlert.pNotificationViewGet @rSourceId = @lAcademicId, @rSourceTypeId = 2001, @rIsFlag = 1
			END
			ELSE
			BEGIN
				exec [sAlert].[pSMSViewGet] @rMobileNumber = @lContactNo,@rEmail = @lEmail, @rOrgId = @rOrgId, @rIsFlag = 1, @rAlertModeId = @rAlertModeId		
			END
		END
	END
	ELSE IF(LOWER(@Tab) = 'library')
	BEGIN
		IF(@rIsMobileApp = 1)
		BEGIN
			SELECT
				Isnull(LM.Title,'') AS [Library],
				ISNULL(BM.Code,'') AS BookCode,
				isnull(BM.Title,'') AS BookTitle,
				convert(varchar,isnull(BL.LogDate,''),103) AS LogDate,
				convert(varchar,isnull(BL.DueDate,''),103) AS DueDate,
				CASE WHEN SM.Title = 'Available' THEN  'Returned' ELSE ISNULL(SM.Title,'') END AS [Status]		
			FROM 
				sLibrary.tBookLog BL
				INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
				INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId
				INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005 AND BL.LibraryId = IS1.LibraryId
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId AND SM.IsObsolete = 0 AND SM.StatusTypeId=106
				INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
			WHERE 
				(BL.ReaderSourceTypeId=2003)
				AND BL.IsCurrentStatus=1
				AND ((BL.StatusId=521) OR (BL.StatusId=523))
				AND (BL.OrgId=@rOrgId)
				AND (BL.BatchId=@rBatchId)
				AND SA.AcademicId=@lAcademicId
		END
		ELSE BEGIN
		exec [sLibrary].[pBookLogListViewGet] @rAcademicId = @lAcademicId, @rOrgId = @rOrgId,@rBatchId = @rBatchId
		END
	END
	ELSE IF(LOWER(@Tab) = 'paymentdetails')
	BEGIN
		exec sOp.pPaymentTransactionGet @rId=@lAcademicId,@rFromDate=NULL,@rToDate=@lDate,@rTransactionStatusId=0,@rFunctionalityId=0,
		@rFirstName=NULL,@rOrgGroupId=@lOrgGroupId,@rOrgId=@rOrgId,
		@rBatchId=@rBatchId,@rReceiptBookId=0,@rOSTypeId=0,@rFormNo=0,@rReferenceNo=0,@rPaymentGatewayId=0
	END
	ELSE IF(LOWER(@Tab) = 'onlinelearning')
	BEGIN
	SELECT OL.Title AS OLTitle,  OL.StartTime, OL.EndTime, SM.Title AS [Subject], EM.FirstName + ' ' + Em.LastName AS EmployeeName, DM.Title AS LearningType FROM sAcademic.tOnlineLearningScope OLS
	INNER JOIN sAcademic.tOnlineLearning OL ON OL.Id = OLS.OnlineLearningId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TeacherEmployeeId
	INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
	WHERE (
	( 
	(OLS.SourceTypeId = 2021 AND OLS.SourceId = @rOrgId) 
	OR
	(OLS.SourceTypeId = 2017 AND OLS.SourceId = @lDepartmentId) OR
	(OLS.SourceTypeId = 2016 AND OLS.SourceId = @lClassId) OR
	(OLS.SourceTypeId = 2005 AND OLS.SourceId = @lDivisionId) OR
	(OLS.SourceTypeId = 2003 AND OLS.SourceId = @rStudentId) OR
	(OLS.SourceTypeId = 2001 AND OLS.SourceId = @lAcademicId)
		))

	AND OL.StartDate = CAST(sCommon.fGetDate() AS DATE)

	SELECT
		ISNULL((SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 1 And AcademicId = @lAcademicId),0) AS PresentCount,
		ISNULL((SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 0 And AcademicId = @lAcademicId),0) AS AbsentCount,
		CAST(ISNULL((((SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 1 And AcademicId = @lAcademicId) / 
		(SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 0 And AcademicId = @lAcademicId)) * 100 ),0) AS DECIMAL(10,2)) AS PresentPercentage
	
	END
	ELSE IF(LOWER(@Tab) = 'charge')
	BEGIN
		exec sFee.pChargeReceiptListGet @rSourceTypeId=0,@rGuestName=N'*',@rSourceCode=@lCode,@rFromDate=NULL,@rToDate=NULL,@rReceiptBookId=0,@rChargeCategoryId=0,@rOrgId=@rOrgId,@rBatchId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromNo=0,@rToNo=0,@rOrgGroupId=@lOrgGroupId
	END
	ELSE IF(LOWER(@Tab) = 'siblingdetails')
	BEGIN
		exec sStudent.pSiblingLinkListGet @rStudentId=@rStudentId
	END
	ELSE IF (LOWER(@Tab) = 'teachersubject')
	BEGIN
		SELECT DISTINCT SM.Title AS SubjectName,
		(SELECT Stuff (( select ',' + Convert(nvarchar(MAX),EM.FirstName + ' ' + EM.LastName)
			FROM 
			sAcademic.tTeacherSubjectDivision TSD1
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD1.EmployeeId AND EM.StatusId = 7
			WHERE 
			TSD1.SubjectId = TSD.SubjectId AND TSD1.DivisionId = @lDivisionId
			  FOR XML PATH('')  
			 ),1,1,'')) TeacherName

		FROM 
		sAcademic.tTeacherSubjectDivision TSD
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TSD.SubjectId
		WHERE TSD.DivisionId = @lDivisionId
	END
	ELSE IF (LOWER(@Tab) = 'activitybehaviour')
	BEGIN		
		SELECT
			convert(varchar,isnull(A.FromDate,''),103) AS FromDate,
			convert(varchar,isnull(A.ToDate,''),103) AS ToDate,
			isnull (A.Title,'') AS Title,
			isnull( A.Remark,'') AS Remark				
		FROM 
			sActivity.tActivity A 
			INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id=A.ActivityTypeId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=@rStudentId AND SA.BatchId = @rBatchId
			INNER JOIN sActivity.tActivityParticipant AP ON AP.ActivityId=A.Id AND AP.SourceTypeId=2003
		WHERE 
			AP.SourceTypeId = 2003 AND AP.SourceId = @rStudentId  AND A.BatchId=@rBatchId
					
		SELECT 
			convert(varchar,isnull(B.BehaviourDate,''),103) AS BehaviourDate,
			isnull (BTM.Title,'') AS BehaviourType,
			isnull( B.Title,'') AS BehaviourDetails,
			isnull(B.Remark,'') AS Remark
		FROM 
			sCommunication.tBehaviour B
			 INNER JOIN sCommunication.tBehaviourTypeMaster BTM
			 ON B.BehaviourTypeId=BTM.Id
			 INNER JOIN sStudent.vStudentAcademic SA
			 ON SA.AcademicId=B.AcademicId      
		WHERE 
			SA.OrgGroupBatchId=@rOrgGroupBatchId AND SA.AcademicId=@lAcademicId

		SELECT  CONVERT(VARCHAR,ISNULL(ES.FromDate,''),103) AS FromDate, CONVERT(VARCHAR,ISNULL(ES.ToDate,''),103) AS ToDate
			,ISNULL(ES.Title,'') AS EventName, (CASE WHEN EA.IsSelfPresent = 1 then 'Yes' ELSE 'No' END) AS StudentAttendance
			,(CASE WHEN EA.IsFatherPresent = 1 then 'Yes' ELSE 'No' END) AS FatherAttendance
			,(CASE WHEN EA.IsMotherPresent = 1 then 'Yes' ELSE 'No' END) AS MotherAttendance
			,ISNULL(EA.ParentFeedBack,'') AS ParentFeedBack, ISNULL(EA.SchoolFeedback,'') AS SchoolFeedback
		FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sActivity.tEventAttendance EA ON  SA.AcademicId = EA.SourceId AND EA.SourceTypeId = 2001
			INNER JOIN sActivity.tEventSchedule ES ON EA.EventScheduleId=ES.Id 
			INNER JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
  WHERE 
			(SA.OrgId=@rOrgId)
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			AND((SA.AcademicId=@lAcademicId)OR(@lAcademicId=0)) 
			ORDER BY SA.ClassId,SA.DivisionId
	END
END
GO
PRINT N'Altering Procedure [sFee].[pFeeReceiptImportValidate]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

BEGIN

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

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

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


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

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

	BEGIN
	BEGIN TRY

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

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

	EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rPayTypeId,@rPaymentTransactionId,@rReceiptBookId,@rChequeNo,@rIsCreated = @lIsCreated OUTPUT 
	-- Added @rChequeNo for mantis 0035484 By Foram
 	
	IF(@lIsCreated = 1)
 	BEGIN
		SELECT -501 AS Result
		RETURN
	END
	
	IF(@lIsCreated = -1)	-- For Mantis 0032370 by Foram
 	BEGIN
		SELECT -502 AS Result
		RETURN
	END
	IF(@lIsCreated = -2)	-- For Mantis 0035484 by Foram
 	BEGIN
		SELECT -503 AS Result
		RETURN
	END
 
	 BEGIN TRANSACTION	
	 IF(@rId = 0)	
	 BEGIN

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


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

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

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


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


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

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

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

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

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

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

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

	IF(@lIsCreated = 1)
 	BEGIN
		SELECT -501 AS Result
		RETURN
	END
	IF(@lIsCreated = -1)	-- For Mantis 0032370 by Foram
 	BEGIN
		SELECT -502 AS Result
		RETURN
	END
	IF(@lIsCreated = -2)	-- For Mantis 0035484 by Foram
 	BEGIN
		SELECT -503 AS Result
		RETURN
	END
 
	BEGIN TRANSACTION	
	IF(@rId = 0)	
	BEGIN

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

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

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

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

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

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

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

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


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

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

PRINT N'Update complete.';


GO


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

