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

GO
PRINT N'Altering Table [sAdmission].[tAdmissionForm]...';


GO
ALTER TABLE [sAdmission].[tAdmissionForm]
    ADD [PENNumber]     BIGINT        NULL,
        [ApaarIdNumber] NVARCHAR (50) NULL;


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


GO
ALTER TABLE [sSecurity].[tOrgGroupMobileApp]
    ADD [IsRestrictOtherAppLogin] BIT NULL;


GO
PRINT N'Creating Table [dbo].[ListofClubData]...';


GO
CREATE TABLE [dbo].[ListofClubData] (
    [AutoId]        BIGINT         IDENTITY (1, 1) NOT NULL,
    [AcademicId]    BIGINT         NULL,
    [StudentId]     BIGINT         NULL,
    [SubCategory]   NVARCHAR (150) NULL,
    [UpdatedUserId] BIGINT         NULL
);


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


GO
CREATE TABLE [sFee].[tDepositDefaultSetup] (
    [DepositHeadId] INT             NOT NULL,
    [OrgId]         INT             NOT NULL,
    [BatchId]       INT             NOT NULL,
    [Amount]        DECIMAL (12, 2) NOT NULL
);


GO
PRINT N'Creating Table [sSystem].[tTraceLog]...';


GO
CREATE TABLE [sSystem].[tTraceLog] (
    [Id]                 BIGINT          IDENTITY (1, 1) NOT NULL,
    [LogMessage]         NVARCHAR (MAX)  NULL,
    [ExtraLogMessage]    NVARCHAR (MAX)  NULL,
    [ExceptionLog]       NVARCHAR (MAX)  NULL,
    [ExceptionDetailLog] NVARCHAR (MAX)  NULL,
    [CreatedDateTime]    DATETIME        NOT NULL,
    [PagePath]           NVARCHAR (1000) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC) WITH (FILLFACTOR = 85)
);


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


GO

ALTER VIEW [sHrm].[vPrintTemplateJoiningCertificateGet]  

 AS
   
 SELECT   
   EM.Id AS EmployeeId,
   CJ.Number,
   EM.EmployeeName,
   EM.FirstName,  
   EM.MiddleName,  
   EM.LastName,      
   EM.Code,    
   EM.ShortName,  
   EM.OrgID,  
   EM.DepartmentId,  
   EM.DepartmentName,  
   EM.DesignationId,  
   EM.Designation,  
   EM.EmployeePhoto, 
   EM.DateOfJoining,    
   OI.CertificateHeaderA4 ,  
   CJ.Remark,  
   ISNULL(CJ.CertificateDate,'') AS CertificateDate,  
   EM.MaritalStatusId,  
   CJ.PayScale,  
   CJ.AgreementPeriod,
   CJ.CertificateRemark,
   OM.Title As OrgTitle,
   CJ.CreatedDateTime As CreatedDateTime,
   U.DisplayTitle As UserDisplayName,
   EDM.Title AS EmployeeDesignation,
   OM.DisplayTitle As ShortTitle,
   DM.Title AS DepartmentName1,
   EM.MobileNumber,
    EC.PresentStreetOne  
	,EC.PresentStreetTwo 
	,EC.PresentStreetThree 
   ,EC.PresentCity
   ,EC.PresentState
   ,EC.PresentZipCode
   ,EC.PresentContactNo 	
   ,ISNULL(EDM1.Title,'Admin') AS UserDesignation,   
	ISNULL(CJ.DateOfJoining,'') As CertificateDateOfJoining,
	EM.GenderId
	,'[Number],[EmployeeName],[FirstName],[LastName],[Code],[ShortName],[DepartmentName],[Designation],[EmployeePhoto],[DateOfJoining],[CertificateHeaderA4]
	,[Remark],[CertificateDate],[PayScale],[AgreementPeriod],[CertificateRemark],[OrgTitle],[CreatedDateTime],[UserDisplayName]
	,[EmployeeDesignation],[ShortTitle],[DepartmentName1],[MobileNumber],[PresentStreetOne],[PresentStreetTwo],[PresentStreetThree]
	,[PresentCity],[PresentState],[PresentZipCode],[PresentContactNo],[UserDesignation],[CertificateDateOfJoining]
	,[MiddleName]' AS ColumnList --MiddleName add for mantis : 0043976

 FROM   
	  sHrm.tCertificateJoining CJ   
      INNER JOIN [sHrm].[vExtEmployeeMaster] EM  ON EM.EmployeeId=CJ.EmployeeId 
      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId   
      INNER JOIN  sSecurity.tUser U ON U.Id=CJ.CreatedUserId 
	  --AND U.SourceTypeId = 95
      INNER JOIN  sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.Id
	  INNER JOIN  sSetup.tDepartmentMaster DM ON DM.Id=CJ.DepartmentId
	  LEFT JOIN  sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId  --added
	  LEFT JOIN  sHrm.tEmployeeCommunications EC ON EC.EmployeeId=CJ.EmployeeId  --added
	  LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id 
      LEFT JOIN  sHrm.tEmployeeJobDetail EJD1 ON EJD1.EmployeeId=U.SourceId
	  LEFT JOIN  sHrm.tEmployeeDesignationMaster EDM1 ON EDM1.Id=EJD1.EmployeeDesignationId
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
		 -- added by dhananjay for Mantis - 39234
		ISNULL(SF.FatherAdhaarNumber,'') AS FatherAdhaarNumber,
		ISNULL(SF.MotherAdhaarNumber,'') AS MotherAdhaarNumber,
		-- added by dhananjay for Mantis - 39234
		ISNULL(SA.ApaarIdNumber, '') AS ApaarIdNumber, -- add for mantis : 0040679
		ISNULL(SAD.PreviousLCResult,'') AS PreviousResult		-- Mantis Id : 0043737
  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.PresentCity, ''), '') + -- changed sorting order for mantis : 40447
           COALESCE(',' + NULLIF(SC.PresentState, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentCountry, ''), '') +
            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.PermanentCity, ''), '') + -- changed sorting order for mantis : 40447
           COALESCE(',' + NULLIF(SC.PermanentState, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentCountry, ''), '') +
            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.EmergencyCity, ''), '') + -- changed sorting order for mantis : 40447
           COALESCE(',' + NULLIF(SC.EmergencyState, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyCountry, ''), '') +
            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
		 -- added by dhananjay for Mantis - 39234
		ISNULL(SF.FatherAdhaarNumber,'') AS FatherAdhaarNumber,
		ISNULL(SF.MotherAdhaarNumber,'') AS MotherAdhaarNumber,
		-- added by dhananjay for Mantis - 39234
		ISNULL(SA.ApaarIdNumber, '') AS ApaarIdNumber, -- add for mantis : 0040679
		ISNULL(SAD.PreviousLCResult,'') AS PreviousResult			-- Mantis Id : 0043737

  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'Creating Function [sPayroll].[fGetPayElementNetAmount]...';


GO



CREATE FUNCTION [sPayroll].[fGetPayElementNetAmount] (
	@rPayElementId INT
	,@rEmployeeId BIGINT
	,@rPayrollGroupId INT
	,@rPayrollYearId INT
	,@rIsEmployeeSpecific BIT
	)
RETURNS DECIMAL(12, 2)
AS
BEGIN
	DECLARE @lPaySetupId INT;

	SELECT @lPaySetupId = Id
	FROM sPayroll.tPaySetup PS
	WHERE PS.PayElementId = @rPayElementId
		AND PS.SourceId = CASE 
			WHEN ISNULL(@rIsEmployeeSpecific, 0) = 1
				THEN @rEmployeeId
			ELSE @rPayrollGroupId
			END
		AND PS.SourceTypeId = CASE 
			WHEN ISNULL(@rIsEmployeeSpecific, 0) = 1
				THEN 95
			ELSE 2020
			END

	DECLARE @lReturnAmount DECIMAL(12, 2) = 0

	SELECT @lReturnAmount = SUM(CASE 
				WHEN Am.IsDeduct = 0
					THEN Am.Amount
				WHEN Am.IsDeduct = 1
					THEN - Am.Amount
				ELSE 0
				END) * ISNULL(PS.Percentage, 0) / 100
	FROM sPayroll.tPaySetup PS
	INNER JOIN (
		SELECT PSD.PaySetupId
			,PSD.IsDeduct
			,CASE 
				WHEN PE.IsDepend = 0
					THEN ISNULL((
								SELECT TOP 1 PS.Amount
								FROM sPayroll.tPaySetup PS
								WHERE PS.PayElementId = PE.Id
									AND PS.SourceId = CASE 
										WHEN ISNULL(PE.IsEmployeeSpecific, 0) = 1
											THEN @rEmployeeId
										ELSE @rPayrollGroupId
										END
									AND PS.SourceTypeId = CASE 
										WHEN ISNULL(PE.IsEmployeeSpecific, 0) = 1
											THEN 95
										ELSE 2020
										END
									AND PS.PayrollYearId = @rPayrollYearId
								), 0)
				ELSE sPayroll.fGetPayElementNetAmount(PE.Id, @rEmployeeId, @rPayrollGroupId, @rPayrollYearId, PE.IsEmployeeSpecific)
				END AS Amount
		FROM sPayroll.tPaySetupDependent PSD
		INNER JOIN sPayroll.tPayElement PE ON PE.Id = PSD.DependentPayElementId
		WHERE PSD.PaySetupId = @lPaySetupId
		) AS Am ON PS.Id = @lPaySetupId
	GROUP BY PS.Id
		,PS.Percentage

	RETURN @lReturnAmount
END
GO
PRINT N'Creating Function [sStudent].[fAssignedBulkClubGet]...';


GO

CREATE FUNCTION [sStudent].[fAssignedBulkClubGet](@rAcademicId bigint)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	 
	  DECLARE @lTempClub TABLE(ClubName nvarchar(100))
	  INSERT INTO @lTempClub(ClubName)
	  SELECT CM.Title AS ClubName FROM sActivity.tClubMaster CM
	  LEFT JOIN sActivity.tAssignClub AC ON AC.ClubId = CM.Id
	  WHERE AC.AcademicId = @rAcademicId
	  
	  DECLARE @rAttClub nvarchar(500)
	  SELECT @rAttClub= coalesce(@rAttClub+',','')+convert(nvarchar(500),ClubName )
	  FROM @lTempClub
		
      RETURN  ISNULL(@rAttClub,'')

END
GO
PRINT N'Altering Procedure [sAdmission].[pRptAdmissionFormGet]...';


GO

ALTER PROCEDURE [sAdmission].[pRptAdmissionFormGet]
 
	
	@rId bigint = 0,
	@rRelationShipId int=0,
	@rClassId int = 0,	 	
	@rFromDate date = '',
	@rToDate date = '',
	@rOrgId int = 0,
	@rDepartmentId int = 0,
	@rFromMeritMarks int = 0,
	@rToMeritMarks int = 0,
	@rBatchId int = 0

AS
 SET NOCOUNT ON

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 Convert(nvarchar(20),@rRelationShipId) AS RelationShipIdText,
	 ISNULL(AF.Id,0) AS AdmissionFromId,
	 ISNULL(AF.FormNo,0) AS FormNo,
	 [sStudent].[fStudentNameGet](AF.FirstName , ISNULL(AF.MiddleName,'') , AF.LastName,OM.StudentNameFormatId ) AS Name,
	 ISNULL(AF.FirstName,'')AS FirstName,
	 ISNULL(AF.ForClassId,0) AS ForClassId,
	 ISNULL(AF.DateOfBirth,'') AS DateOfBirth,
	 ISNULL(AF.BatchId,0)AS BatchId,
	 ISNULL(CM.Title,'') AS ClassName,
	 ISNULL(AF.OrgId,0)AS OrgId,
	 ISNULL(AF.StreetOne,'')AS StreetOne,
	 ISNULL(AF.StreetTwo,'')AS StreetTwo,
	 ISNULL(AF.StreetThree,'')AS StreetThree,
	 ISNULL(AF.Country,'')AS Country,
	 ISNULL(AF.City,'')AS City,
	 ISNULL(AF.State,'')AS State,
	 ISNULL(AF.ZipCode,'') AS ZipCode,
	 ISNULL(AF.ContactEmail,'')AS ContactEmail,
	 ISNULL(AF.ContactNo,'') AS ContactNo,
	 ISNULL(AF.PreviousSchool,'')AS PreviousSchool,
	 ISNULL(AF.StudentPhoto,0x) As StudentPhoto,
	 ISNULL(AF.ReligionId,0) AS ReligionId,
	 IsNULL(RM.Title,'') AS ReligionName,
	 ISNULL(AF.MeritGrade,'')AS MeritGrade,
	 ISNULL(AF.MeritMarks,0) AS MeritMarks,
	 ISNULL(AF.GenderId,0) AS GenderId,
	 ISNULL(GM.Title,'') AS Gender,
	 ISNULL(AF.FamilyCast,'')AS FamilyCast,
	 ISNULL(AF.FamilySubCast,'')AS FamilySubCast,
	 ISNULL(AF.CastCategoryId,0) AS CastCategoryId,
	 ISNULL(CCM.Title,'') AS CastCategory ,
	 ISNULL(OM.DisplayTitle,'')AS DisplayTitle ,
	 ISNULL(BM.Title,'') As Batch,
	 ISNULL(AFM.FatherName,'') AS FatherName ,
	 ISNULL(AFM.FatherDateOfBirth,'')As FatherDateOfBirth,
	 ISNULL(AFM.FatherOccupation,'') AS FatherOccupation,
	 ISNULL(AFM.FatherOfficeAddress,'') AS FatherOfficeAddress,
	 ISNULL(AFM.FatherIncome,0) AS FatherIncome,
	 ISNULL(AFM.FatherQualification,'') AS FatherQualification,
	 ISNULL(AFM.FatherContactNo,'') AS FatherContactNo ,
	 ISNULL(AFM.FatherMail,'') AS FatherMail,
	 ISNULL(AFM.FatherOrganization,'') AS FatherOrganization,
	 ISNULL(AFM.MotherName,'') AS MotherName,
	 IsNull(AFM.MotherDateOfBirth,'')As MotherDateOfBirth,
	 ISNULL(AFM.MotherIncome,0) AS MotherIncome,
	 ISNULL(AFM.MotherOccupation,'') AS MotherOccupation,
	 ISNULL(AFM.MotherOfficeAddress,'') AS MotherOfficeAddress,
	 ISNULL(AFM.MotherQualification,'') AS MotherQualification,
	 ISNULL(AFM.MotherContactNo,'') AS MotherContactNo,
	 ISNULL(AFM.MotherMail,'') AS MotherMail,
	 ISNULL(AFM.MotherOrganization,'') AS MotherOrganization,
	 isnull(AFM.RelativeName,'') AS RelativeName ,
	 ISNULL(AFM.RelativeDateOfBirth,'') AS RelativeDateOfBirth,
	 ISNULL(AFM.RelativeOccupation,'') AS RelativeOccupation,
	 ISNULL(AFM.RelativeContactNo,'') AS RelativeContactNo,
	 ISNULL(AFM.RelativeMail,'') AS RelativeMail,
	 ISNULL(AFM.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
	 ISNULL(AFM.RelativeIncome,0) AS RelativeIncome,
	 ISNULL(AFM.RelativeQualification,'') AS RelativeQualification,
	 ISNULL(AFM.RelationshipName,'') AS RelationshipName ,
	 ISNULL(AC.IsFixParentAcademic,0) AS IsParentAcademicRequired ,
	 ISNULL (AC.IsStudentAcademicRequired,0) AS IsStudentAcademicRequired ,
	 ISNULL(AC.IsSiblingDetailRequired,0) AS IsSiblingDetailRequired,
	 ISNULL(AC.IsReferenceDetailRequired,0) AS IsReferenceDetailRequired ,
	 ISNULL(AC.IsFamilyDetailRequired,0) AS IsFamilyDetailRequired ,
	 ISNULL(AC.IsFixStudentAcademic,0) AS IsFixStudentAcademic,
	 ISNULL(AC.ConfirmationRemark,'') AS ConfirmationRemark,
	 ISNULL(AC.IsHostelDetailRequired,0) AS IsHostelDetailRequired ,
	 ISNULL (AC.IsTransportDetailRequired,0) AS IsTransportDetailRequired ,
	 ISNULL(AC.IsHealthDetailRequired,0) AS IsHealthDetailRequired,
	 ISNULL(AC.IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired ,
	 ISNULL(AC.IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired ,
	 ISNULL(AC.IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
	
	 ISNULL(AF.IsPysicalDeformity,0) AS IsPysicalDeformity,
	 ISNULL(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
	 ISNULL(AF.IsMajorIllness,0) AS IsMajorIllness,
	 ISNULL(AF.MajorIllnessRemark, '') As MajorIllnessRemark,
	 ISNULL(AF.IsAllergy,0)AS IsAllergy,
	 ISNULL(AF.AllergyRemark,'') As AllergyRemark,
	 ISNULL(AF.BirthPlace,'') As BirthPlace,
	 ISNULL(AF.BirthTaluka,'') As BirthTaluka,
	 ISNULL(AF.BirthDistrict,'') As BirthDistrict,
	 Isnull(BGM.Title,'') As BloodGroupName,
	 ISNULL(AF.AdhaarNumber,'') AS AdhaarNumber,
	 ISNULL(AF.IsHostelRequired,0)AS IsHostelRequired,
	 ISNULL(AF.IsTransportRequired,0)AS IsTransportRequired,
	 ISNULL(AFM.FatherPhoto,0x)As FatherPhoto,
	  ISNULL(AFM.MotherPhoto,0x) As MotherPhoto,
	 ISNULL(AFM.RelativePhoto,0x) As RelativePhoto,
	 ISNULL(AF.BirthState,'')AS BirthState,
	 ISNULL(AF.BirthCountry,'') AS BirthCountry,
	 ISNULL(AC.CustomField1Remark,'') AS CustomField1Remark,
	 ISNULL(AC.CustomField2Remark,'') AS CustomField2Remark,
	 ISNULL(AC.CustomField3Remark,'') AS CustomField3Remark,
	 ISNULL(AF.CustomField1Answer,'')As CustomField1Answer,
	 ISNULL(AF.CustomField2Answer,'')As CustomField2Answer,
	 ISNULL(AF.CustomField3Answer,'')As CustomField3Answer,
	 ISNULL(AF.Nationality,'') AS Nationality,
	 ISNULL(AF.MotherTongue,'') AS MotherTongue,
	 ISNULL(AF.OtherInformation,'') AS OtherInformation,
	 ISNULL(LWM.Title,'') AS LiveWith,
	 ISNULL(AC.AgeCutOffDate,'') AS AgeCutOffDate,
	 ISNULL(AC.Remark1,'') AS ExtraRemark1,
	 ISNULL(AC.Remark2,'') AS ExtraRemark2,
	 ISNULL(AC.Remark3,'') AS ExtraRemark3,
	 ISNULL(AF.DateOfBirthInWord,'') AS DOBInWords,
	 ISNULL(AF.CreatedDateTime,'') As FormDate,
	  ISNULL(AC.IsFatherDetail,0) AS IsFatherDetail,
	 ISNULL(AC.IsFatherFullDetail,0) AS IsFatherFullDetail,
	 ISNULL (AC.IsFatherAcademic,0) As IsFatherAcademic,
	 ISNULL (AC.IsMotherDetail,0) As IsMotherDetail,
	 ISNULL (AC.IsMotherFullDetail,0)As IsMotherFullDetail,
	 ISNULL (AC.IsMotherAcademic,0)As IsMotherAcademic,
	 ISNULL (AC.IsGuardianDetail,0)As IsGuardianDetail,
	 ISNULL (AC.IsGuardianFullDetail,0)As IsGuardianFullDetail,
	 ISNULL (AC.IsGuardianAcademic,0)As IsGuardianAcademic,
	 ISNULL (AC.IsOtherInformationRequired,0)As IsOtherInformationRequired,
	 ISNULL (AC.IsHealthDetailRequired,0) As IsHealthDetailRequired,
	 ISNULL (AC.IsCustomField1Required,0) As IsCustomField1Required,
	 ISNULL (AC.IsCustomField2Required,0) As IsCustomField2Required,
	 ISNULL (AC.IsCustomField3Required,0) As IsCustomField3Required,
	 ISNULL (AFM.FatherAdhaarNumber,'') AS FatherAadhaarNumber,
	 ISNULL (AFM.MotherAadhaarNumber,'') AS MotherAadhaarNumber,
	 ISNULL (AFM.RelativeAadhaarNumber,'') AS RelativeAadhaarNumber,
	 ISNULL( (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=324
	 ),0)AS IsOtherDetailsLiveWith,
	 ISNULL( (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=323
	 ),0)AS IsOtherDetailsOtherInformation,
	 ISNULL(AF.MiddleName,'') AS MiddleName,
	 ISNULL(AF.LastName,'')AS LastName,
	 ISNULL(PT.Id,0) AS PaymentTransactionId,
	 ISNULL(PT.PayAmount,0.00) AS PayAmount,
	 ISNULL(PT.TransactionStatusId,0) AS TransactionStatusId,
	 ISNULL(PT.PayDateTime,'') AS PayDateTime,
	 ISNULL(AFM.IsFatherExStudent,0) AS IsFatherExStudent,
	 ISNULL(AFM.IsMotherExStudent,0) AS IsMotherExStudent,
	 ISNULL(AFM.IsRelativeExStudent,0)AS IsRelativeExStudent,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](302,OM.Id) AS IsBirthPlace,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](303,OM.Id) AS IsBirthTaluka,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](304,OM.Id) AS IsBirthDistrict,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](305,OM.Id) AS IsBirthState,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](306,OM.Id) AS IsBirthCountry,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](307,OM.Id) AS IsPreviousSchool,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](308,OM.Id) AS IsStudentPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](316,OM.Id) AS IsContactEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](317,OM.Id) AS IsReligion,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](318,OM.Id) AS IsFamilyCaste,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](319,OM.Id) AS IsNationality,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](320,OM.Id) AS IsCasteCategory,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](388,OM.Id) AS IsFamilySubCaste,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](321,OM.Id) AS IsMotherTongue,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](322,OM.Id) AS IsAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](323,OM.Id) AS IsOtherInformation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](324,OM.Id) AS IsLiveWith,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](325,OM.Id) AS IsHotelRequired,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](326,OM.Id) AS IsTransportRequired,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](327,OM.Id) AS IsMotherFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](328,OM.Id) AS IsMotherMobilNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](329,OM.Id) AS IsMotherQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](330,OM.Id) AS IsMotherOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](331,OM.Id) AS IsMotherEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](332,OM.Id) AS IsMotherIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](333,OM.Id) AS IsMotherOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](334,OM.Id) AS IsMotherDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](337,OM.Id) AS IsMotherOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](338,OM.Id) AS IsMotherPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](410,OM.Id) AS IsMotherAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](349,OM.Id) AS IsFatherFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](350,OM.Id) AS IsFatherMobileNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](351,OM.Id) AS IsFatherQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](352,OM.Id) AS IsFatherOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](353,OM.Id) AS IsFatherEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](354,OM.Id) AS IsFatherIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](355,OM.Id) AS IsFatherOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](356,OM.Id) AS IsFatherDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](359,OM.Id) AS IsFatherOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](360,OM.Id) AS IsFatherPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](409,OM.Id) AS IsFatherAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](361,OM.Id) AS IsGuardianFullName,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](362,OM.Id) AS IsGuardianMobileNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](363,OM.Id) AS IsGuardianPhoto,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](396,OM.Id) AS IsGuardianQualification,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](397,OM.Id) AS IsGuardianOccupation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](398,OM.Id) AS IsGuardianEmail,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](399,OM.Id) AS IsGuardianIncome,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](400,OM.Id) AS IsGuardianOrganization,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](401,OM.Id) AS IsGuardianDesignation,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](403,OM.Id) AS IsGuardianRelationship,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](405,OM.Id) AS IsGuardianOfficeAddress,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](411,OM.Id) AS IsGuardianAadhaarNo,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](369,OM.Id) AS IsPhysicalDeformity,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](370,OM.Id) AS IsPhysicalDeformityRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](371,OM.Id) AS IsMajorIllness,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](372,OM.Id) AS IsMajorIllnessRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](373,OM.Id) AS IsAllergy,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](374,OM.Id) AS IsAllergyRemark,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](407,OM.Id) AS IsMeritMarks,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](408,OM.Id) AS IsMeritGrade,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](395,OM.Id) AS IsBloodGroup,
	 [sAdmission].[fAdmissionFormDisplayFieldGet](309,OM.Id) AS IsStreetOneAddress ,

	  ISNULL(AFM.FatherDesignation,'') AS FatherDesignation ,
	  ISNULL(AFM.FatherPassOutYear,'') AS FatherPassOutYear ,
	  ISNULL(AFM.MotherDesignation,'') AS MotherDesignation ,
	  ISNULL(AFM.MotherPassOutYear,'') AS MotherPassOutYear ,
	  AF.AdmissionDate, --add for Mentis : 0034078
	  ISNULL(AC.AdmissionConfirmationRemark,'') AS AdmissionConfirmationRemark			-- MantisId : 0038036
	  ,[sAdmission].[fAdmissionFormDisplayFieldGet](1233,OM.Id) AS IsPENNumber
	  ,[sAdmission].[fAdmissionFormDisplayFieldGet](1234,OM.Id) AS IsApaarIdNumber
	  ,ISNULL(AF.PENNumber,0) AS PENNumber --Mantis -0043425
	  ,ISNULL(AF.ApaarIdNumber,'') AS ApaarIdNumber --Mantis -0043425

  FROM  
		    sAdmission.tAdmissionForm AF 
		     
			--INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AF.OrgId
			INNER JOIN sSetup.tBatchMaster BM  ON  BM.Id=AF.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JoIN sCommon.tReligionMaster RM ON RM.Id=AF.ReligionId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=AF.BloodGroupId
			--LEFT JOIN sAdmission.tAdmissionFormParentAcademic PA ON PA.AdmissionFormId=AF.Id
			--INNER JOIN sCommon.tRelationshipMaster RSM ON RSM.Id=PA.RelationshipId
			LEFT JOIN sCommon.tCastCategoryMaster CCM  ON CCM.Id=AF.CastCategoryId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFM ON AFM.AdmissionFormId=AF.Id
			LEFT JOIN sCommon.tLiveWithMaster LWM ON LWM.Id = AFM.LiveWithId
			LEFT JOIN  sAdmission.tAdmissionCriteria AC ON AC.ClassId=CM.Id  AND AC.BatchId=AF.BatchId		
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.PayerSourceId = AF.Id AND PT.PayerSourceTypeId = 2027 AND (PT.TransactionStatusId = 2 OR PT.TransactionStatusId = 4)
 WHERE 	
  (AF.Id = @rId OR @rId = 0)
  AND ((AF.ForClassId=@rClassId) OR (@rClassId=0))	
  AND ((AF.BatchId = @rBatchId) OR (@rBatchId = 0))
	AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
	AND ((AF.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	AND ((AF.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))		
	AND ((CONVERT(DATE,AF.CreatedDateTime) >= @rFromDate) OR (isnull(@rFromDate,'')=''))
	AND ((CONVERT(DATE,AF.CreatedDateTime) <= @rToDate) OR (isnull(@rToDate,'')=''))
 

				
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionFormGet]...';


GO

ALTER PROCEDURE [sAdmission].[pAdmissionFormGet]

	 @rAdmissionFormId bigint = 0,
	 @rFormNo int,
	 @rForClassId int,
	 @rBatchId int=0,
	 @rStatusId smallint='',
	 @rOrgId int,
	 @rFirstName nvarchar(100),
	 @rLastName nvarchar(100),
	 @rMeritMarks decimal(10,2),
	 @rFromDate datetime= '1900-01-01',
	 @rToDate datetime = '9990-12-31',
	 @rDepartmentId int=0,
	 @rIsTransportFilter int=2,
	 @rIsHostelFilter int=2,
	 @rDataEntryStatusId smallint=0,
	 @rIsCommonSearch bit=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	SET @rToDate = DATEADD(d,1,@rToDate)		 

BEGIN 
		--IF @rIsSearch = 1
		BEGIN
		SET @rFirstName = ISNULL(@rFirstName,'')
		SET @rLastName = ISNULL(@rLastName,'')
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
		--- Mantis : 0038918 As per To Date Filter Changes to as required. chnages to <= to < sign in filter : By Krunal K Patel.
	SELECT 
			 AF.Id
			,AF.FormNo
			,AF.FirstName
			,AF.MiddleName
			,AF.LastName

			--,AF.FirstName+' '+AF.LastName as Name
			,[sStudent].[fStudentNameGet](AF.FirstName , ISNULL(AF.MiddleName,'') , AF.LastName,OM.StudentNameFormatId ) AS Name

			,AF.ForClassId
			,AF.BatchId
			,CM.Title AS ClassName
			,AF.ForBatch
			,ISNULL(AF.DateOfBirth,'') AS DateOfBirth
			,AF.DateOfBirthInWord
			,AF.StatusId
			,SM.Title as StatusName
			,ISNULL(ASM.Title,'') AS FormStatus
			,AF.StreetOne
			,AF.StreetTwo
			,AF.StreetThree
			,AF.Country
			,AF.State
			,AF.City
			,AF.ZipCode
			,AF.ContactNo
			,AF.ContactEmail
			,AF.Remark
			,AF.PreviousSchool
			,AF.MeritMarks
			,AF.MeritGrade
			,AF.GenderId
			,ISNULL(GM.Title,'') AS Gender
			,ISNULL(AF.ReligionId,0) AS ReligionId
			,AF.FamilyCast
			,AF.FamilySubCast
			,ISNULL(AF.CastCategoryId,0) AS CastCategoryId
			,AF.CreatedDateTime AS AdmissionFormDate
			,ISNULL(AF.StudentId,0) AS StudentId
			,ISNULL(AF.AdmissionDate,'') AS AdmissionDate
			--,AF.StudentPhoto,
			,(CASE WHEN @rIsCommonSearch=0 THEN ISNULL(AF.StudentPhoto,0) ELSE NULL END) AS StudentPhoto
			
			,ISNULL(AFFD.FatherName,'') AS FatherName,
			Isnull(AFFD.FatherDateOfBirth,'') AS FatherDateOfBirth,
			Isnull(AFFD.FatherOccupation,'') AS FatherOccupation,
			Isnull(AFFD.FatherQualification,'') AS FatherQualification,
			Isnull(AFFD.FatherContactNo,'') AS FatherContactNo,
			Isnull(AFFD.FatherMail,'') AS FatherMail,
			Isnull(AFFD.FatherOfficeAddress,'') As FatherOfficeAddress,
			isnull(AFFD.FatherOrganization,'') as FatherOrganization,
			isnull(AFFD.FatherDesignation,'') as FatherDesignation,
			Isnull(AFFD.FatherIncome,'') as FatherIncome,
			Isnull(AFFD.MotherName,'') AS MotherName,
			iSNULL(AFFD.MotherDateOfBirth,'')AS MotherDateOfBirth,
			isnull(AFFD.MotherOccupation,'') AS MotherOccupation,
			isnull(AFFD.MotherQualification,'') AS MotherQualification,
			isnull(AFFD.MotherContactNo,'') as MotherContactNo,
			isnull(AFFD.MotherMail,'') As MotherMail,
			isnull(AFFD.MotherOfficeAddress,'') as MotherOfficeAddress,
			isnull(AFFD.MotherOrganization,'') as MotherOrganization,
			isnull(AFFD.MotherDesignation,'') as MotherDesignation,
			isnull(AFFD.MotherIncome,'') as MotherIncome,
			AF.MotherTongue AS MotherTongue,
		 
			isnull(AFFD.RelationshipName,'') as RelationshipName,
			isnull(AFFD.RelativeName,'')  AS GuardianName ,
			isnull(AFFD.RelativeDateOfBirth ,'')AS GuardianDateOfBirth,
			isnull(AFFD.RelativeOccupation,'') AS GuardianOccupation,
			isnull(AFFD.RelativeQualification,'') AS GuardianQualification,
			isnull(AFFD.RelativeContactNo,'') AS GuardianContactNo,
			isnull(AFFD.RelativeMail,'')  AS GuardianMail,
			isnull(AFFD.RelativeOfficeAddress,'') AS GuardianOfficeAddress,
			isnull(AFFD.RelativeOrganization,'') as RelativeOrganization,
			isnull(AFFD.RelativeDesignation,'') as RelativeDesignation,
			isnull(AFFD.RelativeIncome,'') AS GuardianIncome  ,
			isnull(AF.IsHostelRequired,0) AS IsHostelRequired  ,
			isnull(AF.IsTransportRequired,0) AS IsTransportRequired,
			isnull(AF.BirthPlace,'') AS BirthPlace,
			isnull(AF.BirthTaluka,'') AS BirthTaluka,
			isnull(AF.BirthDistrict,'') AS BirthDistrict,
			isnull(AF.BloodGroupId,0) AS BloodGroupId,
			isnull(AF.AdhaarNumber,'') AS AdhaarNumber,
			isnull(AF.IsPysicalDeformity,0) AS IsPysicalDeformity,
			isnull(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			isnull(AF.IsMajorIllness,0) AS IsMajorIllness,
			isnull(AF.MajorIllnessRemark,'') AS MajorIllnessRemark,
			isnull(AF.IsAllergy,0) AS IsAllergy,
			isnull(AF.AllergyRemark,'') AS AllergyRemark,
			isnull(AF.BirthState,'') AS BirthState,
			isnull(AF.BirthCountry,'') AS BirthCountry,
			isnull(SA.PreviousStandard,'') As PreviousStandard,
	        isnull(AFFD.LiveWithId,0) AS LiveWithId,
			--isnull(ASB.SiblingName,'') AS SiblingName,
			--isnull(ASB.SiblingRelation,'')AS SiblingRelation,
			
			--isnull(ASB.SiblingStandard,'') AS SiblingStandard,
			--isnull(ASB.SiblingSchool,'')AS SiblingSchool
			
			 ISNULL(AF.CustomField1Answer,'') AS CustomField1Answer,
			 ISNULL(AF.CustomField2Answer,'') AS CustomField2Answer,
			 ISNULL(AF.CustomField3Answer,'') AS CustomField3Answer,
			 SM1.Title AS DataEntryStatus,
			 AF.Nationality,
			 ISNULL(AFFD.FatherAdhaarNumber,'') AS FatherAdhaarNumber,
			 AF.CreatedDateTime AS AdmissionFormDate,
			 ISNULL(AFFD.MotherAadhaarNumber,'') AS MotherAadhaarNumber,
			 ISNULL(AFFD.RelativeAadhaarNumber,'') AS RelativeAadhaarNumber,
			 ISNULL(AFFD.FatherOfficePhone,'') AS FatherOfficePhone,
			 ISNULL(AFFD.MotherOfficePhone,'') AS MotherOfficePhone,
			 CASE WHEN AF.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode,
			 ISNULL(AF.WhatsappContactNo,'') AS WhatsappContactNo		--add for 29511 mantis
			 ,ISNULL(AF.PENNumber,0) AS PENNumber --0043425	
			 ,ISNULL(AF.ApaarIdNumber,'') AS ApaarIdNumber --0043425	
  FROM 
            sAdmission.tAdmissionForm AF
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sCommon.tStatusMaster SM1 ON SM1.Id=AF.DataEntryStatusId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFFD ON AFFD.AdmissionFormId = AF.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = AF.StudentId
			 --LEFT JOIN sAdmission.tAdmissionFormSibling ASB ON ASB.AdmissionFormId = AF.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentID=AF.StudentID
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
		AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))
		AND ((AF.FirstName like @rFirstName) OR (@rFirstName=''))
		AND ((AF.LastName like @rLastName) OR (@rLastName=''))
		--AND ((AF.CreatedDateTime>= @rFromDate) OR (@rFromDate=''))
		AND ((Cast(AF.AdmissionDate as datetime)>= @rFromDate) OR (@rFromDate=''))
		--AND ((AF.AdmissionDate is not null AND Cast(AF.AdmissionDate as datetime)>= @rFromDate) or (AF.AdmissionDate is null AND AF.CreatedDateTime>= @rFromDate) or (@rFromDate=''))
		--AND ((AF.CreatedDateTime < @rToDate) OR (@rToDate=''))
		AND ((Cast(AF.AdmissionDate as datetime)< @rToDate) OR (@rToDate=''))
		--AND ((AF.AdmissionDate is not null AND Cast(AF.AdmissionDate as datetime)< @rToDate) or (AF.AdmissionDate is null AND AF.CreatedDateTime< @rToDate) or (@rToDate=''))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0)) 
		AND ((AF.BatchId=@rBatchId) OR (@rBatchId=0)) 
		--AND ((AF.MeritMarks=@rMeritMarks) OR (@rMeritMarks=0))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId = ''))
		AND ((AF.DataEntryStatusId=@rDataEntryStatusId) OR (@rDataEntryStatusId = 0))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND AF.OrgId=@rOrgId
        AND ((ISnull(AF.IsHostelRequired,0)=@rIsHostelFilter ) OR   (ISNULL(@rIsHostelFilter,2)=2) )
	   AND ((ISNUll(AF.IsTransportRequired,0)=@rIsTransportFilter) OR (isnull(@rIsTransportFilter,0) = 2))
	  
 order by AF.FormNo
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionFormConfirmGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionFormConfirmGet]
	 @rAdmissionFormId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
			iSNULL(AF.Id,0) as Id,
			AF.FormNo,
			AF.FirstName,
			AF.MiddleName,
			AF.LastName,
			AF.ForClassId,
			iSNULL(AF.ForBatchId, 0) as ForBatchId,
			AF.ForBatch,
			AF.DateOfBirth,
			AF.DateOfBirthInWord,
			AF.OrgId,
			AF.BatchId,
			AF.StatusId,
			AF.StreetOne,
			AF.StreetTwo,
			AF.StreetThree,
			AF.Country,
			AF.State,
			AF.City,
			AF.ZipCode,
			AF.ContactNo,
			AF.ContactEmail,
			AF.Remark,
			AF.PreviousSchool,
			AF.MeritMarks,
			AF.MeritGrade,
			iSNULL(AF.GenderId,0) as GenderId,
			iSNULL(AF.ReligionId,0) as ReligionId ,
			AF.FamilyCast,
			AF.FamilySubCast,
			iSNULL(AF.CastCategoryId,0) as CastCategoryId,
			AF.CreatedUserId,
			AF.CreatedDateTime,
			iSNULL(AF.UpdatedUserId,0) aS UpdatedUserId,
			AF.UpdatedDateTime,
			iSNULL(AF.StudentId,0) as StudentId,
			AF.FormPassword,
			iSNULL(AF.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(AF.DataEntryStatusId,0) as DataEntryStatusId,
			AF.StudentPhoto,
			iSNULL(AF.AdmissionCategoryId,0) AS AdmissionCategoryId,
			AF.Nationality,
			AF.MotherTongue,
			AF.OtherInformation,
			iSNULL(AF.IsPysicalDeformity,0) aS IsPysicalDeformity ,
			AF.PysicalDeformityRemark,
			iSNULL(AF.IsMajorIllness,0) aS IsMajorIllness ,
			AF.MajorIllnessRemark,
			iSNULL(AF.IsAllergy,0) aS IsAllergy,
			AF.AllergyRemark,
			AF.BirthPlace,
			AF.BirthTaluka,
			AF.BirthDistrict,
			iSNULL(AF.BloodGroupId,0) AS  BloodGroupId,
			AF.AdhaarNumber,
			iSNULL(AF.IsHostelRequired,0) as IsHostelRequired,
			iSNULL(AF.IsTransportRequired,0) as IsTransportRequired,
			AF.BirthState,
			AF.BirthCountry,
			OM.Title AS SchoolName,
			BM.Title AS BatchName,
			CM.Title AS ClassName,
			GM.Title AS Gender,
			RM.Title AS ReligionName,
			CCM.Title AS CastCategoryName,
			BGM.Title AS BloodGroup,
			ISNULL(AF.CustomField1Answer,'') AS CustomField1Answer,
			ISNULL(AF.CustomField2Answer,'') AS CustomField2Answer,
			ISNULL(AF.CustomField3Answer,'') AS CustomField3Answer,
			AF.WhatsappContactNo -- Change done for mantis 29772
			,ISNULL(AF.PENNumber,0) AS PENNumber  --mantis : 0043425
			,ISNULL(AF.ApaarIdNumber,'') AS ApaarIdNumber  --mantis : 0043425
  FROM
   sAdmission.tAdmissionForm AF
   LEFT JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 
   LEFT JOIN sSetup.tBatchMaster BM ON AF.BatchId=BM.Id 
   LEFT JOIN sSetup.tClassMaster CM ON AF.ForClassId = CM.Id 
   LEFT JOIN sCommon.tGenderMaster GM ON AF.GenderId = GM.Id
    LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = AF.ReligionId 
    LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = AF.CastCategoryId 
    LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = AF.BloodGroupId
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
       
 
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionFormOnlineGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionFormOnlineGet]  
  @rAdmissionFormId bigint = 0,  
  @rFormNo int,  
  @rOrgId int  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
    
 SELECT   
   iSNULL(Id,0) as id,  
   FormNo,  
   FirstName,  
   MiddleName,  
   LastName,  
   ForClassId,  
   iSNULL(ForBatchId, 0) as ForBatchId,  
   ForBatch,  
   DateOfBirth,  
   DateOfBirthInWord,  
   OrgId,  
   BatchId,  
   StatusId,  
   StreetOne,  
   StreetTwo,  
   StreetThree,  
   Country,  
   State,  
   City,  
   ZipCode,  
   ContactNo,  
   ContactEmail,  
   Remark,  
   PreviousSchool,  
   MeritMarks,  
   MeritGrade,  
   iSNULL(GenderId,0) as GenderId,  
   iSNULL(ReligionId,0) as ReligionId ,  
   FamilyCast,  
   FamilySubCast,  
   iSNULL(CastCategoryId,0) as CastCategoryId,  
   CreatedUserId,  
   CreatedDateTime,  
   iSNULL(UpdatedUserId,0) aS UpdatedUserId,  
   UpdatedDateTime,  
   iSNULL(StudentId,0) as StudentId,  
   FormPassword,  
   iSNULL(DataEntryModeId,0) as DataEntryModeId,  
   iSNULL(DataEntryStatusId,0) as DataEntryStatusId,  
   StudentPhoto,  
   iSNULL(AdmissionCategoryId,0) AS AdmissionCategoryId,  
   Nationality,  
   MotherTongue,  
   OtherInformation,  
   iSNULL(IsPysicalDeformity,0) aS IsPysicalDeformity ,  
   PysicalDeformityRemark,  
   iSNULL(IsMajorIllness,0) aS IsMajorIllness ,  
   MajorIllnessRemark,  
   iSNULL(IsAllergy,0) aS IsAllergy,  
   AllergyRemark,  
   BirthPlace,  
   BirthTaluka,  
   BirthDistrict,  
   iSNULL(BloodGroupId,0) AS  BloodGroupId,  
   AdhaarNumber,  
   iSNULL(IsHostelRequired,0) as IsHostelRequired,  
   iSNULL(IsTransportRequired,0) as IsTransportRequired,  
   BirthState,  
   BirthCountry,  
   ISNULL(AF.CustomField1Answer,'') AS CustomField1Answer,  
   ISNULL(AF.CustomField2Answer,'') AS CustomField2Answer,  
   ISNULL(AF.CustomField3Answer,'') AS CustomField3Answer,
   WhatsappContactNo -- Change done for mantis 29772
   	,ISNULL(AF.PENNumber,0) AS PENNumber --mantis : 0043425
	,ISNULL(AF.ApaarIdNumber,'') AS ApaarIdNumber --mantis : 0043425
  FROM   
           sAdmission.tAdmissionForm AF  
  WHERE   
    
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))  
  AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))  
  AND AF.OrgId=@rOrgId  
         
 order by AF.FormNo  
END
GO
PRINT N'Altering Procedure [sAdmission].[pExportAllAdmissionFormDetail]...';


GO
ALTER PROCEDURE [sAdmission].[pExportAllAdmissionFormDetail]
	 @rAdmissionFormId bigint = 0,
	 @rFormNo int=0,
	 @rForClassId int=0,
	 @rBatchId int=0,
	 @rStatusId smallint='',
	 @rOrgId int,
	 @rFirstName nvarchar(200)='',
	 @rLastName nvarchar(200)='',
 
	 @rFromDate datetime= '1900-01-01',
	 @rToDate datetime = '9990-12-31',
	 @rDepartmentId int=0,
	 @rDataEntryStatusId smallint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	SET @rToDate = DATEADD(d,1,@rToDate)		 

BEGIN 
		--IF @rIsSearch = 1
		--BEGIN
		--SET @rFirstName = ISNULL(@rFirstName,'')
		--SET @rLastName = ISNULL(@rLastName,'')
		--	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		--	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		--END
	CREATE Table #tempAdmissionForm
	(
		AdmissionFormId bigint,
		FormNo int,
		FirstName nvarchar(500),
		MiddleName nvarchar(500),
		LastName nvarchar(500),
		Name nvarchar(500),
		ClassId int,
		ClassName nvarchar(500),
		ForBatch nvarchar(500),
		DateOfBirth date,
		--StatusName nvarchar(200),
		ProcessStatus nvarchar(100),
		FormStatus nvarchar(500),
		StreetOne nvarchar(500),
		StreetTwo nvarchar(500),
		StreetThree nvarchar(500),
		Country nvarchar(500),
		State nvarchar(500),
		City nvarchar(500),
		ZipCode nvarchar(500),
		ContactNo nvarchar(500),
		ContactEmail nvarchar(500),
		Religion nvarchar(500),
		Nationality nvarchar(500),
		MotherTongue nvarchar(500),
		OtherInformation nvarchar(500),
		IsPysicalDeformity	bit	,
		PysicalDeformityRemark	nvarchar(500)	,
		IsMajorIllness	bit	,
		MajorIllnessRemark	nvarchar(500)	,
		IsAllergy	bit	,
		AllergyRemark	nvarchar(500)	,
		BirthPlace	nvarchar(500)	,
		BirthTaluka	nvarchar(500)	,
		BirthDistrict	nvarchar(500),
		BloodGroupName	nvarchar(500)	,
		AdhaarNumber	nvarchar(500)	,
		IsHostelRequired	nvarchar(500)	,
		IsTransportRequired	nvarchar(500)	,
		Remark nvarchar(500),
		PreviousSchool nvarchar(500),
		MeritMarks decimal(6,2),
		MeritGrade nvarchar(500),
		Gender nvarchar(500),
		
		FamilyCast nvarchar(500),
		FamilySubCast nvarchar(500),
		 
		AdmissionFormDate datetime,
		FatherName nvarchar(500),
		--FatherDateOfBirth date,
		FatherOccupation nvarchar(500),
		FatherQualification nvarchar(500),
		FatherDesignation  nvarchar(500),
		FatherOrganization nvarchar(500),
		FatherOfficePhone nvarchar(500),
		FatherContactNo nvarchar(500),
		FatherMail nvarchar(500),
		FatherOfficeAddress nvarchar(500),
		FatherIncome int	,
		FatherAadharNo nvarchar(20),
		MotherName nvarchar(500),
		--MotherDateOfBirth date ,
		MotherOccupation nvarchar(500),
		MotherQualification nvarchar(500),
		MotherDesignation nvarchar(500),
		MotherOrganization nvarchar(500),
		MotherOfficePhone nvarchar(500),
		MotherContactNo nvarchar(500),
		MotherMail nvarchar(500),
		MotherOfficeAddress nvarchar(500), 
		MotherIncome int,
		RelationshipName nvarchar(500),
		GuardianName nvarchar(500),
		--GuardianDateOfBirth date,
		GuardianOccupation nvarchar(500),
		GuardianQualification nvarchar(500),
		GuardianOrganization nvarchar(500),
		GuardianDesignation nvarchar(500),
		GuardianOfficePhone nvarchar(500),
		GuardianContactNo nvarchar(500),
		GuardianMail nvarchar(500),
		GuardianOfficeAddress nvarchar(500),
		GuardianIncome int,
		FatherPassOutYear nvarchar(500),
		MotherPassOutYear nvarchar(500),
		RelativePassOutYear nvarchar(500),
		CustomField1Answer  nvarchar(500),
		CustomField2Answer  nvarchar(500),
		CustomField3Answer  nvarchar(500),
		CastCategory nvarchar(50),
		DataEntryMode nvarchar(20),
		StatusName nvarchar(200) -- Added for mantis : 34323 by Nilesh
		,PENNumber bigint -- Added for mantis : 43425 by Vishruti
		,ApaarIdNumber nvarchar(100) -- Added for mantis : 43425 by Vishruti
		
	)
	Insert into #tempAdmissionForm
	(
		AdmissionFormId,
		FormNo ,
		FirstName ,
		MiddleName ,
		LastName ,
		Name ,
		ClassId,
		ClassName ,
		ForBatch ,
		DateOfBirth ,
		--StatusName ,
		ProcessStatus ,
		FormStatus ,
		StreetOne ,
		StreetTwo ,
		StreetThree,
		Country,
		State ,
		City ,
		ZipCode ,
		ContactNo ,
		ContactEmail,
		Religion,
		Nationality,
		MotherTongue,
		OtherInformation,
		IsPysicalDeformity,
		PysicalDeformityRemark,
		IsMajorIllness,
		MajorIllnessRemark,
		IsAllergy,
		AllergyRemark,
		BirthPlace,
		BirthTaluka,
		BirthDistrict,
		BloodGroupName,
		AdhaarNumber,
		IsHostelRequired,
		IsTransportRequired,
		Remark ,
		PreviousSchool,
		MeritMarks ,
		MeritGrade,
		Gender,
		
		FamilyCast ,
		FamilySubCast,
		 
		AdmissionFormDate,
		FatherName ,
		--FatherDateOfBirth ,
		FatherOccupation,
		FatherQualification ,
		FatherDesignation,
		FatherOrganization,
		FatherOfficePhone,
		FatherContactNo  ,
		FatherMail  ,
		FatherOfficeAddress   ,
		FatherIncome  	,
		FatherAadharNo,
		MotherName  ,
		--MotherDateOfBirth   ,
		MotherOccupation  ,
		MotherQualification  ,
		MotherDesignation,
		MotherOrganization,
		MotherOfficePhone,
		MotherContactNo  ,
		MotherMail  ,
		MotherOfficeAddress  , 
		MotherIncome  ,
		RelationshipName  ,
		GuardianName  ,
		--GuardianDateOfBirth  ,
		GuardianOccupation  ,
		GuardianQualification  ,
		GuardianDesignation,
		GuardianOrganization,
		GuardianOfficePhone,
		GuardianContactNo  ,
		GuardianMail  ,
		GuardianOfficeAddress   ,
		GuardianIncome  ,
		FatherPassOutYear,
		MotherPassOutYear,
		RelativePassOutYear,
		CustomField1Answer,
		CustomField2Answer,
		CustomField3Answer,
		CastCategory,
		DataEntryMode,
		StatusName -- Added for mantis : 34323 by Nilesh
		,PENNumber
		,ApaarIdNumber
	)
	SELECT 
			  AF.Id
			,AF.FormNo
			,AF.FirstName
			,AF.MiddleName
			,AF.LastName
			,AF.FirstName+' '+AF.LastName as Name
			--,AF.ForClassId
			--,AF.BatchId
			,CM.Id AS ClassId
			,CM.Title AS ClassName
			,AF.ForBatch
			,ISNULL(AF.DateOfBirth,'') AS DateOfBirth
			--,AF.DateOfBirthInWord
			--,AF.StatusId
			--,SM.Title as StatusName
			,SM1.Title AS DataEntryStatus
			,ISNULL(ASM.Title,'') AS FormStatus
			,AF.StreetOne
			,AF.StreetTwo
			,AF.StreetThree
			,AF.Country
			,AF.State
			,AF.City
			,AF.ZipCode
			,AF.ContactNo
			,AF.ContactEmail,
			RM.Title AS Religion,
			AF.Nationality,
			AF.MotherTongue,
			AF.OtherInformation,
			AF.IsPysicalDeformity,
			AF.PysicalDeformityRemark,
			AF.IsMajorIllness,
			AF.MajorIllnessRemark,
			AF.IsAllergy,
			AF.AllergyRemark,
			AF.BirthPlace,
			AF.BirthTaluka,
			AF.BirthDistrict,
			BGm.Title,
			AF.AdhaarNumber,
			CAse WHEn ISnull(AF.IsHostelRequired,0)=0 THEN 'No' Else 'Yes' END AS IsHostelRequired,
			CAse WHEn ISnull(AF.IsTransportRequired,0)=0 THEN 'No' Else 'Yes' END AS IsTransportRequired
			
			,AF.Remark
			,AF.PreviousSchool
			,AF.MeritMarks
			,AF.MeritGrade
			--,AF.GenderId
			,ISNULL(GM.Title,'') AS Gender
			--,ISNULL(AF.ReligionId,0) AS ReligionId
			,AF.FamilyCast
			,AF.FamilySubCast
			--,ISNULL(AF.CastCategoryId,0) AS CastCategoryId
			,AF.CreatedDateTime AS AdmissionFormDate,
			--,ISNULL(AF.StudentId,0) AS StudentId
			--,AF.StudentPhoto,
			ISNULL(AFFD.FatherName,'') AS FatherName,
			--Isnull(AFFD.FatherDateOfBirth,'') AS FatherDateOfBirth,
			Isnull(AFFD.FatherOccupation,'') AS FatherOccupation,
			Isnull(AFFD.FatherQualification,'') AS FatherQualification,
			Isnull(AFFD.FatherDesignation,'') AS FatherDesignation,
			Isnull(AFFD.FatherOrganization,'') AS FatherOrganization,
			Isnull(AFFD.FatherOfficePhone,'') AS FatherOfficePhone,
			Isnull(AFFD.FatherContactNo,'') AS FatherContactNo,
			Isnull(AFFD.FatherMail,'') AS FatherMail,
			Isnull(AFFD.FatherOfficeAddress,'') As FatherOfficeAddress,
			Isnull(AFFD.FatherIncome,'') as FatherIncome,
			Isnull(AFFD.FatherAdhaarNumber,'') as FatherAadharNo,
			Isnull(AFFD.MotherName,'') AS MotherName,
			--iSNULL(AFFD.MotherDateOfBirth,'')AS MotherDateOfBirth,
			isnull(AFFD.MotherOccupation,'') AS MotherOccupation,
			isnull(AFFD.MotherQualification,'') AS MotherQualification,
			
			Isnull(AFFD.MotherDesignation,'') AS MotherDesignation,
			Isnull(AFFD.MotherOrganization,'') AS MotherOrganization,
			Isnull(AFFD.MotherOfficePhone,'') AS MotherOfficePhone,
			
			isnull(AFFD.MotherContactNo,'') as MotherContactNo,
			isnull(AFFD.MotherMail,'') As MotherMail,
			isnull(AFFD.MotherOfficeAddress,'') as MotherOfficeAddress,
			isnull(AFFD.MotherIncome,'') as MotherIncome,
		 
			isnull(AFFD.RelationshipName,'') as RelationshipName,
			isnull(AFFD.RelativeName,'')  AS GuardianName ,
			--isnull(AFFD.RelativeDateOfBirth ,'')AS GuardianDateOfBirth,
			isnull(AFFD.RelativeOccupation,'') AS GuardianOccupation,
			isnull(AFFD.RelativeQualification,'') AS GuardianQualification,
			
			Isnull(AFFD.RelativeDesignation,'') AS GuardianDesignation,
			Isnull(AFFD.RelativeOrganization,'') AS GuardianOrganization,
			Isnull(AFFD.RelativeOfficePhone,'') AS GuardianOfficePhone,
			
			isnull(AFFD.RelativeContactNo,'') AS GuardianContactNo,
			isnull(AFFD.RelativeMail,'')  AS GuardianMail,
			isnull(AFFD.RelativeOfficeAddress,'') AS GuardianOfficeAddress,
			isnull(AFFD.RelativeIncome,'') AS GuardianIncome  ,
			isnull(AFFD.FatherPassOutYear,'') AS FatherPassOutYear,
			isnull(AFFD.MotherPassOutYear,'')As MotherPassOutYear,
			isnull(AFFD.RelativePassOutYear,'') As RelativePassOutYear,
			isnull(AF.CustomField1Answer,'') AS CustomField1Answer,
			isnull(AF.CustomField2Answer,'')As CustomField2Answer,
			isnull(AF.CustomField3Answer,'') As CustomField3Answer,
   			ISNULL(CCM.Title,'') AS CastCategory,
			CASE WHEN AF.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END AS DataEntryMode,
			SM.Title as StatusName -- Added for mantis : 34323 by Nilesh
			,ISNULL(PENNumber,0) AS PENNumber -- Added for mantis : 43425 by Vishruti
			,ISNULL(ApaarIdNumber,'') AS ApaarIdNumber -- Added for mantis : 43425 by Vishruti
  FROM 
            sAdmission.tAdmissionForm AF
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sCommon.tStatusMaster SM1 ON SM1.Id=AF.DataEntryStatusId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId			
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFFD ON AFFD.AdmissionFormId = AF.Id
			LEFT JOIN sCommon.tReligionMaster RM on RM.Id= AF.religionId
			LEFT JOIN sCommon.tBloodGroupMaster BGM on BGM.Id= AF.BloodGroupId
			--LEFT JOIN sAdmission.tAdmissionFormSibling ASB ON ASB.AdmissionFormId = AF.Id
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=AF.CastCategoryId
			 
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
		AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))
		AND ((AF.FirstName like @rFirstName) OR (@rFirstName=''))
		AND ((AF.LastName like @rLastName) OR (@rLastName=''))
		AND ((AF.CreatedDateTime>= @rFromDate) OR (@rFromDate=''))
		AND ((AF.CreatedDateTime < @rToDate) OR (@rToDate=''))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0)) 
		AND ((AF.BatchId=@rBatchId) OR (@rBatchId=0)) 
		--AND ((AF.MeritMarks=@rMeritMarks) OR (@rMeritMarks=0))
		
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId = ''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND AF.OrgId=@rOrgId
		AND ((AF.DataEntryStatusId=@rDataEntryStatusId) OR (@rDataEntryStatusId = 0))
 
 create table #tempStudentAcademic
(
	AdmissionFormId bigint,
	StudentAcademicYear1 nvarchar(500),	StudentAdmissionClass1 nvarchar(500),	StudentInstituteName1 nvarchar(500),	StudentInstituteCity1 nvarchar(500),			StudentInstituteAffiliaton1 nvarchar(500),	StudentLanguage1 nvarchar(500),	StudentResult1 Nvarchar(500),
	StudentAcademicYear2 nvarchar(500),	StudentAdmissionClass2 nvarchar(500),	StudentInstituteName2 nvarchar(500),	StudentInstituteCity2 nvarchar(500),	StudentInstituteAffiliaton2 nvarchar(500),	StudentLanguage2 nvarchar(500),	StudentResult2 Nvarchar(500),
	StudentAcademicYear3 nvarchar(500),	StudentAdmissionClass3 nvarchar(500),	StudentInstituteName3 nvarchar(500),	StudentInstituteCity3 nvarchar(500),	StudentInstituteAffiliaton3 nvarchar(500),	StudentLanguage3 nvarchar(500),	StudentResult3 Nvarchar(500),
	StudentAcademicYear4 nvarchar(500),	StudentAdmissionClass4 nvarchar(500),	StudentInstituteName4 nvarchar(500),	StudentInstituteCity4 nvarchar(500),	StudentInstituteAffiliaton4 nvarchar(500),	StudentLanguage4 nvarchar(500),	StudentResult4 Nvarchar(500),
	StudentAcademicYear5 nvarchar(500),	StudentAdmissionClass5 nvarchar(500),	StudentInstituteName5 nvarchar(500),	StudentInstituteCity5 nvarchar(500),	StudentInstituteAffiliaton5 nvarchar(500),	StudentLanguage5 nvarchar(500),	StudentResult5 Nvarchar(500),
	StudentAcademicYear6 nvarchar(500),	StudentAdmissionClass6 nvarchar(500),	StudentInstituteName6 nvarchar(500),	StudentInstituteCity6 nvarchar(500),	StudentInstituteAffiliaton6 nvarchar(500),	StudentLanguage6 nvarchar(500),	StudentResult6 Nvarchar(500),
	StudentAcademicYear7 nvarchar(500),	StudentAdmissionClass7 nvarchar(500),	StudentInstituteName7 nvarchar(500),	StudentInstituteCity7 nvarchar(500),	StudentInstituteAffiliaton7 nvarchar(500),	StudentLanguage7 nvarchar(500),	StudentResult7 Nvarchar(500),
	StudentAcademicYear8 nvarchar(500),	StudentAdmissionClass8 nvarchar(500),	StudentInstituteName8 nvarchar(500),	StudentInstituteCity8 nvarchar(500),	StudentInstituteAffiliaton8 nvarchar(500),	StudentLanguage8 nvarchar(500),	StudentResult8 Nvarchar(500),
	StudentAcademicYear9 nvarchar(500),	StudentAdmissionClass9 nvarchar(500),	StudentInstituteName9 nvarchar(500),	StudentInstituteCity9 nvarchar(500),	StudentInstituteAffiliaton9 nvarchar(500),	StudentLanguage9 nvarchar(500),	StudentResult9 Nvarchar(500),
	StudentAcademicYear10 nvarchar(500),	StudentAdmissionClass10 nvarchar(500),	StudentInstituteName10 nvarchar(500),	StudentInstituteCity10 nvarchar(500),	StudentInstituteAffiliaton10 nvarchar(500),	StudentLanguage10 nvarchar(500),	StudentResult10 Nvarchar(500) )
INsert into #tempStudentAcademic
(AdmissionFormId, 
StudentAcademicYear1  ,	StudentAdmissionClass1  ,	StudentInstituteName1  ,	StudentInstituteCity1  ,	StudentInstituteAffiliaton1   ,	StudentLanguage1  ,	StudentResult1  ,
	StudentAcademicYear2  ,	StudentAdmissionClass2  ,	StudentInstituteName2  ,	StudentInstituteCity2  ,	StudentInstituteAffiliaton2  ,	StudentLanguage2  ,	StudentResult2   ,
	StudentAcademicYear3   ,	StudentAdmissionClass3  ,	StudentInstituteName3  ,	StudentInstituteCity3  ,	StudentInstituteAffiliaton3  ,	StudentLanguage3  ,	StudentResult3  ,
	StudentAcademicYear4  ,	StudentAdmissionClass4  ,	StudentInstituteName4  ,	StudentInstituteCity4  ,	StudentInstituteAffiliaton4  ,	StudentLanguage4   ,	StudentResult4  ,
	StudentAcademicYear5  ,	StudentAdmissionClass5  ,	StudentInstituteName5  ,	StudentInstituteCity5  ,	StudentInstituteAffiliaton5  ,	StudentLanguage5  ,	StudentResult5  ,
	StudentAcademicYear6  ,	StudentAdmissionClass6  ,	StudentInstituteName6  ,	StudentInstituteCity6  ,	StudentInstituteAffiliaton6  ,	StudentLanguage6  ,	StudentResult6  ,
	StudentAcademicYear7  ,	StudentAdmissionClass7  ,	StudentInstituteName7  ,	StudentInstituteCity7  ,	StudentInstituteAffiliaton7  ,	StudentLanguage7   ,	StudentResult7  ,
	StudentAcademicYear8  ,	StudentAdmissionClass8  ,	StudentInstituteName8  ,	StudentInstituteCity8  ,	StudentInstituteAffiliaton8  ,	StudentLanguage8  ,	StudentResult8  ,
	StudentAcademicYear9  ,	StudentAdmissionClass9  ,	StudentInstituteName9  ,	StudentInstituteCity9  ,	StudentInstituteAffiliaton9  ,	StudentLanguage9  ,	StudentResult9  ,
	StudentAcademicYear10  ,	StudentAdmissionClass10  ,	StudentInstituteName10  ,	StudentInstituteCity10  ,	StudentInstituteAffiliaton10  ,	StudentLanguage10  ,	StudentResult10  
)

SELECT AdmissionFormId,
  ISNULL(max(case when    rn = 1  then  AcademicYear  end),'') StudentAcademicYear1,
  ISNULL(max(case when    rn = 1  then  AdmissionClass  end),'') StudentAdmissionClass1,
   ISNULL(max(case when    rn = 1  then  InstituteName  end),'') StudentInstituteName1,
  ISNULL(max(case when    rn = 1  then  InstituteCity  end),'') StudentInstituteCity1,
  ISNULL(max(case when    rn = 1  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton1,
  ISNULL(max(case when    rn = 1  then  Language  end),'') StudentLanguage1,
    ISNULL(max(case when    rn = 1  then  Result  end),'') StudentResult1,
     
  ISNULL(max(case when    rn = 2 then  AcademicYear  end),'') StudentAcademicYear2,
  ISNULL(max(case when    rn = 2  then  AdmissionClass  end),'') StudentAdmissionClass2,
   ISNULL(max(case when    rn = 2  then  InstituteName  end),'') StudentInstituteName2,
  ISNULL(max(case when    rn = 2  then  InstituteCity  end),'') StudentInstituteCity2,
  ISNULL(max(case when    rn = 2  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton2,
  ISNULL(max(case when    rn = 2  then  Language  end),'') StudentLanguage2,
    ISNULL(max(case when    rn = 2  then  Result  end),'') StudentResult2,

     
  ISNULL(max(case when    rn = 3  then  AcademicYear  end),'') StudentAcademicYear3,
  ISNULL(max(case when    rn = 3  then  AdmissionClass  end),'') StudentAdmissionClass3,
   ISNULL(max(case when    rn = 3  then  InstituteName  end),'') StudentInstituteName3,
  ISNULL(max(case when    rn = 3  then  InstituteCity  end),'') StudentInstituteCity3,
  ISNULL(max(case when    rn = 3  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton3,
  ISNULL(max(case when    rn = 3  then  Language  end),'') StudentLanguage3,
  ISNULL(max(case when    rn = 3  then  Result  end),'') StudentResult3,
     
  ISNULL(max(case when    rn = 4  then  AcademicYear  end),'') StudentAcademicYear4,
  ISNULL(max(case when    rn = 4  then  AdmissionClass  end),'') StudentAdmissionClass4,
   ISNULL(max(case when    rn = 4  then  InstituteName  end),'') StudentInstituteName4,
  ISNULL(max(case when    rn = 4  then  InstituteCity  end),'') StudentInstituteCity4,
  ISNULL(max(case when    rn = 4  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton4,
  ISNULL(max(case when    rn = 4  then  Language  end),'') StudentLanguage4,
  ISNULL(max(case when    rn = 4  then  Result  end),'') StudentResult4,
           
  ISNULL(max(case when    rn = 5  then  AcademicYear  end),'') StudentAcademicYear5,
  ISNULL(max(case when    rn = 5  then  AdmissionClass  end),'') StudentAdmissionClass5,
   ISNULL(max(case when    rn = 5  then  InstituteName  end),'') StudentInstituteName5,
  ISNULL(max(case when    rn = 5  then  InstituteCity  end),'') StudentInstituteCity5,
  ISNULL(max(case when    rn = 5  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton5,
  ISNULL(max(case when    rn = 5  then  Language  end),'') StudentLanguage5,
    ISNULL(max(case when    rn = 5  then  Result  end),'') StudentResult5,
   
  ISNULL(max(case when    rn = 6  then  AcademicYear  end),'') StudentAcademicYear6,
  ISNULL(max(case when    rn = 6  then  AdmissionClass  end),'') StudentAdmissionClass6,
   ISNULL(max(case when    rn = 6  then  InstituteName  end),'') StudentInstituteName6,
  ISNULL(max(case when    rn = 6  then  InstituteCity  end),'') StudentInstituteCity6,
  ISNULL(max(case when    rn = 6  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton6,
  ISNULL(max(case when    rn = 6  then  Language  end),'') StudentLanguage6,
  ISNULL(max(case when    rn = 6  then  Result  end),'') StudentResult6,
     
  ISNULL(max(case when    rn = 7  then  AcademicYear  end),'') StudentAcademicYear7,
  ISNULL(max(case when    rn = 7  then  AdmissionClass  end),'') StudentAdmissionClass7,
  ISNULL(max(case when    rn = 7  then  InstituteName  end),'') StudentInstituteName7,
  ISNULL(max(case when    rn = 7  then  InstituteCity  end),'') StudentInstituteCity7,
  ISNULL(max(case when    rn = 7  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton7,
  ISNULL(max(case when    rn = 7  then  Language  end),'') StudentLanguage7,
   ISNULL(max(case when    rn = 7  then  Result  end),'') StudentResult7,
  
  ISNULL(max(case when    rn = 8  then  AcademicYear  end),'') StudentAcademicYear8,
  ISNULL(max(case when    rn = 8  then  AdmissionClass  end),'') StudentAdmissionClass8,
   ISNULL(max(case when    rn = 8  then  InstituteName  end),'') StudentInstituteName8,
  ISNULL(max(case when    rn = 8  then  InstituteCity  end),'') StudentInstituteCity8,
  ISNULL(max(case when    rn = 8  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton8,
  ISNULL(max(case when    rn = 8  then  Language  end),'') StudentLanguage8,
  ISNULL(max(case when    rn = 8  then  Result  end),'') StudentResult8,
     
  ISNULL(max(case when    rn = 9  then  AcademicYear  end),'') StudentAcademicYear9,
  ISNULL(max(case when    rn = 9  then  AdmissionClass  end),'') StudentAdmissionClass9,
   ISNULL(max(case when    rn = 9  then  InstituteName  end),'') StudentInstituteName9,
  ISNULL(max(case when    rn = 9  then  InstituteCity  end),'') StudentInstituteCity9,
  ISNULL(max(case when    rn = 9  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton9,
  ISNULL(max(case when    rn = 9  then  Language  end),'') StudentLanguage9,
   ISNULL(max(case when    rn = 9  then  Result  end),'') StudentResult9,
     
  ISNULL(max(case when    rn = 10  then  AcademicYear  end),'') StudentAcademicYear10,
  ISNULL(max(case when    rn = 10 then  AdmissionClass  end),'') StudentAdmissionClass10,
   ISNULL(max(case when    rn = 10 then  InstituteName  end),'') StudentInstituteName10,
  ISNULL(max(case when    rn = 10  then  InstituteCity  end),'') StudentInstituteCity10,
  ISNULL(max(case when    rn = 10  then  InstituteAffiliaton  end),'') StudentInstituteAffiliaton10,
  ISNULL(max(case when    rn = 10  then  Language  end),'') StudentLanguage10,
    ISNULL(max(case when    rn = 10  then  Result  end),'') StudentResult10
                     
from
(
  select AP.AdmissionFormId,  AcademicYear, AdmissionClass, InstituteName, InstituteCity,InstituteAffiliaton,Language,Result
      , row_number() over(partition by AP.AdmissionFormId 
                          Order by AP.AdmissionFormId) rn
  from sAdmission.tAdmissionFormStudentAcademic AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
  
) d
group by AdmissionFormId order by AdmissionFormId 

Create Table #tempFatherAcademic
(
	AdmissionFormId bigint,
	FatherAcademicYear1 nvarchar(500),
	FatherInstituteName1 nvarchar(500),
	FatherInstituteCity1 nvarchar(500),
	FatherInstituteAffilation1 nvarchar(500),
	FatherAdmissionClass1 nvarchar(500),
	FatherMediumStudy1 nvarchar(500),
	
	FatherAcademicYear2 nvarchar(500),
	FatherInstituteName2 nvarchar(500),
	FatherInstituteCity2 nvarchar(500),
	FatherInstituteAffilation2 nvarchar(500),
	FatherAdmissionClass2 nvarchar(500),
	FatherMediumStudy2 nvarchar(500),
	
	
	FatherAcademicYear3 nvarchar(500),
	FatherInstituteName3 nvarchar(500),
	FatherInstituteCity3 nvarchar(500),
	FatherInstituteAffilation3 nvarchar(500),
	FatherAdmissionClass3 nvarchar(500),
	FatherMediumStudy3 nvarchar(500),
	
	
	
	FatherAcademicYear4 nvarchar(500),
	FatherInstituteName4 nvarchar(500),
	FatherInstituteCity4 nvarchar(500),
	FatherInstituteAffilation4 nvarchar(500),
	FatherAdmissionClass4 nvarchar(500),
	FatherMediumStudy4 nvarchar(500),
	
	FatherAcademicYear5 nvarchar(500), 
	FatherInstituteName5 nvarchar(500), 
	FatherInstituteCity5 nvarchar(500),
    FatherInstituteAffilation5 nvarchar(500),
    FatherAdmissionClass5 nvarchar(500),
    FatherMediumStudy5 nvarchar(500),
	
	MotherAcademicYear1 nvarchar(500),
	MotherInstituteName1 nvarchar(500),
	MotherInstituteCity1 nvarchar(500),
	MotherInstituteAffilation1 nvarchar(500),
	MotherMediumStudy1 nvarchar(500),
	MotherAdmissionClass1 nvarchar(500),
	
	MotherAcademicYear2 nvarchar(500),
	MotherInstituteName2 nvarchar(500),
	MotherInstituteCity2 nvarchar(500),
	MotherInstituteAffilation2 nvarchar(500),
	MotherMediumStudy2 nvarchar(500),
	MotherAdmissionClass2 nvarchar(500),
	
	MotherAcademicYear3 nvarchar(500),
	MotherInstituteName3 nvarchar(500),
	MotherInstituteCity3 nvarchar(500),
	MotherInstituteAffilation3 nvarchar(500),
	MotherMediumStudy3 nvarchar(500),
	MotherAdmissionClass3 nvarchar(500),
	
	
	MotherAcademicYear4 nvarchar(500),
	MotherInstituteName4 nvarchar(500),
	MotherInstituteCity4 nvarchar(500),
	MotherInstituteAffilation4 nvarchar(500),
	MotherMediumStudy4 nvarchar(500),
	MotherAdmissionClass4 nvarchar(500),
	
	MotherAcademicYear5 nvarchar(500), 
	MotherInstituteName5 nvarchar(500), 
	MotherInstituteCity5 nvarchar(500), 
	MotherInstituteAffilation5 nvarchar(500), 
	MotherMediumStudy5 nvarchar(500), 
	MotherAdmissionClass5 nvarchar(500) ,
	
	GuardianAcademicYear1 nvarchar(500),
	GuardianInstituteName1 nvarchar(500),
	GuardianInstituteCity1 nvarchar(500),
	GuardianInstituteAffilation1 nvarchar(500),
	GuardianAdmissionClass1 nvarchar(500),
	GuardianMediumStudy1 nvarchar(500),
	
	
	GuardianAcademicYear2 nvarchar(500),
	GuardianInstituteName2 nvarchar(500),
	GuardianInstituteCity2 nvarchar(500),
	GuardianInstituteAffilation2 nvarchar(500),
	GuardianAdmissionClass2 nvarchar(500),
	GuardianMediumStudy2 nvarchar(500),
	
	
	GuardianAcademicYear3 nvarchar(500),
	GuardianInstituteName3 nvarchar(500),
	GuardianInstituteCity3 nvarchar(500),
	GuardianInstituteAffilation3 nvarchar(500),
	GuardianAdmissionClass3 nvarchar(500),
	GuardianMediumStudy3 nvarchar(500),
	
	
	GuardianAcademicYear4 nvarchar(500),
	GuardianInstituteName4 nvarchar(500),
	GuardianInstituteCity4 nvarchar(500),
	GuardianInstituteAffilation4 nvarchar(500),
	GuardianAdmissionClass4 nvarchar(500),
	GuardianMediumStudy4 nvarchar(500),
	
	GuardianAcademicYear5 nvarchar(500),
	GuardianInstituteName5 nvarchar(500),
	GuardianInstituteCity5 nvarchar(500),
	GuardianInstituteAffilation5 nvarchar(500),
	 GuardianAdmissionClass5 nvarchar(500),
	 GuardianMediumStudy5 nvarchar(500)
	
)	
Insert into #tempFatherAcademic
(
	AdmissionFormId, 
	FatherAcademicYear1,FatherInstituteName1,FatherInstituteCity1,FatherInstituteAffilation1,FatherMediumStudy1,FatherAdmissionClass1,
	FatherAcademicYear2,FatherInstituteName2,FatherInstituteCity2,FatherInstituteAffilation2,FatherMediumStudy2,FatherAdmissionClass2,
	FatherAcademicYear3,FatherInstituteName3,FatherInstituteCity3,FatherInstituteAffilation3,FatherMediumStudy3,FatherAdmissionClass3,
	FatherAcademicYear4,FatherInstituteName4,FatherInstituteCity4,FatherInstituteAffilation4,FatherMediumStudy4,FatherAdmissionClass4,
	FatherAcademicYear5,FatherInstituteName5,FatherInstituteCity5,FatherInstituteAffilation5,FatherMediumStudy5,FatherAdmissionClass5,
	
	 
	MotherAcademicYear1,MotherInstituteName1,MotherInstituteCity1,MotherInstituteAffilation1,MotherMediumStudy1,MotherAdmissionClass1,
	MotherAcademicYear2,MotherInstituteName2,MotherInstituteCity2,MotherInstituteAffilation2,MotherMediumStudy2,MotherAdmissionClass2,
	MotherAcademicYear3,MotherInstituteName3,MotherInstituteCity3,MotherInstituteAffilation3,MotherMediumStudy3,MotherAdmissionClass3,
	MotherAcademicYear4,MotherInstituteName4,MotherInstituteCity4,MotherInstituteAffilation4,MotherMediumStudy4,MotherAdmissionClass4,
	MotherAcademicYear5,MotherInstituteName5,MotherInstituteCity5,MotherInstituteAffilation5,MotherMediumStudy5,MotherAdmissionClass5,
	    
	GuardianAcademicYear1,GuardianInstituteName1, GuardianInstituteCity1,GuardianInstituteAffilation1,GuardianMediumStudy1,GuardianAdmissionClass1,
	GuardianAcademicYear2,GuardianInstituteName2,GuardianInstituteCity2,GuardianInstituteAffilation2,GuardianMediumStudy2,GuardianAdmissionClass2,
	GuardianAcademicYear3,GuardianInstituteName3,GuardianInstituteCity3,GuardianInstituteAffilation3,GuardianMediumStudy3,GuardianAdmissionClass3,
	GuardianAcademicYear4,GuardianInstituteName4,GuardianInstituteCity4,GuardianInstituteAffilation4,GuardianMediumStudy4,GuardianAdmissionClass4,
	GuardianAcademicYear5,GuardianInstituteName5,GuardianInstituteCity5,GuardianInstituteAffilation5,GuardianMediumStudy5,GuardianAdmissionClass5
	
	 
)
SELECT AdmissionFormId,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  AcademicYear  end),'') FatherAcademicYear1,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteName  end),'') FatherInstituteName1, 
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteCity  end),'') FatherInstituteCity1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteAffiliaton  end),'') FatherInstituteAffilation1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  Language  end),'') FatherMediumStudy1,
     ISNULL(max(case when  relationshipId =2 and rn = 1  then  AdmissionClass  end),'') FatherAdmissionClass1,
     
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AcademicYear  end),'') FatherAcademicYear2,
    ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteName  end),'') FatherInstituteName2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteCity  end),'') FatherInstituteCity2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteAffiliaton  end),'') FatherInstituteAffilation2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  Language  end),'') FatherMediumStudy2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  AdmissionClass  end),'') FatherAdmissionClass2,


  ISNULL(max(case when  relationshipId =2 and rn = 3  then  AcademicYear  end),'') FatherAcademicYear3,
 ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteName  end),'') FatherInstituteName3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteCity  end),'') FatherInstituteCity3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteAffiliaton  end),'') FatherInstituteAffilation3,
    ISNULL(max(case when  relationshipId =2 and rn = 3  then  Language  end),'') FatherMediumStudy3,
    ISNULL(max(case when  relationshipId =2 and rn = 3  then  AdmissionClass  end),'') FatherAdmissionClass3,

  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AcademicYear  end),'') FatherAcademicYear4,
      ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteName  end),'') FatherInstituteName4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteCity  end),'') FatherInstituteCity4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteAffiliaton  end),'') FatherInstituteAffilation4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  Language  end),'') FatherMediumStudy4,
    ISNULL(max(case when  relationshipId =2 and rn = 4  then  AdmissionClass  end),'') FatherAdmissionClass4,

  ISNULL(max(case when  relationshipId =2 and rn = 5  then  AcademicYear  end),'') FatherAcademicYear5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteName  end),'') FatherInstituteName5,
    ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteCity  end),'') FatherInstituteCity5,
    ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteAffiliaton  end),'') FatherInstituteAffilation5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  Language  end),'') FatherMediumStudy5,
    ISNULL(max(case when  relationshipId =2 and rn = 5  then  AdmissionClass  end),'') FatherAdmissionClass5,
   
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  AcademicYear  end),'') MotherAcademicYear1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteName  end),'') MotherInstituteName1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteCity  end),'') MotherInstituteCity1,
   ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteAffiliaton  end),'') MotherInstituteAffilation1,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  Language  end),'') MotherMediumStudy1,
  ISNULL(max(case when  relationshipId =2 and rn = 1  then  AdmissionClass  end),'') MotherAdmissionClass1,

  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AcademicYear  end),'') MotherAcademicYear2,
   ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteName  end),'') MotherInstituteName2,
    ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteCity  end),'') MotherInstituteCity2,
     ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteAffiliaton  end),'') MotherInstituteAffilation2,
       ISNULL(max(case when  relationshipId =2 and rn = 2  then  Language  end),'') MotherMediumStudy2,
       ISNULL(max(case when  relationshipId =2 and rn = 2  then  AdmissionClass  end),'') MotherAdmissionClass2,
    
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  AcademicYear  end),'') MotherAcademicYear3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteName  end),'') MotherInstituteName3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteCity  end),'') MotherInstituteCity3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteAffiliaton  end),'') MotherInstituteAffilation3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  Language  end),'') MotherMediumStudy3,
ISNULL(max(case when  relationshipId =2 and rn = 3  then  AdmissionClass  end),'') MotherAdmissionClass3,
  
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AcademicYear  end),'') MotherAcademicYear4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteName  end),'') MotherInstituteName4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteCity  end),'') MotherInstituteCity4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteAffiliaton  end),'') MotherInstituteAffilation4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  Language  end),'') MotherMediumStudy4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AdmissionClass  end),'') MotherAdmissionClass4,
  
  ISNULL(max(case when  relationshipId =2 and rn = 5  then  AcademicYear  end),'') MotherAcademicYear5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteName  end),'') MotherInstituteName5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteCity  end),'') MotherInstituteCity5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteAffiliaton  end),'') MotherInstituteAffilation5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  Language  end),'') MotherMediumStudy5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  AdmissionClass  end),'') MotherAdmissionClass5,
   
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  AcademicYear  end),'') GuardianAcademicYear1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteName  end),'') GuardianInstituteName1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteCity  end),'') GuardianInstituteCity1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation1,
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  Language  end),'') GuardianMediumStudy1, 
    ISNULL(max(case when  relationshipId =2 and rn = 1  then  AdmissionClass  end),'') GuardianAdmissionClass1,
    
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AcademicYear  end),'') GuardianAcademicYear2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteName  end),'') GuardianInstituteName2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteCity  end),'') GuardianInstituteCity2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  Language  end),'') GuardianMediumStudy2,
  ISNULL(max(case when  relationshipId =2 and rn = 2  then  AdmissionClass  end),'') GuardianAdmissionClass2,
  
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  AcademicYear  end),'') GuardianAcademicYear3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteName  end),'') GuardianInstituteName3,
  ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteCity  end),'') GuardianInstituteCity3,
   ISNULL(max(case when  relationshipId =2 and rn = 3  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation3,
   ISNULL(max(case when  relationshipId =2 and rn = 3  then  Language  end),'') GuardianMediumStudy3,
   ISNULL(max(case when  relationshipId =2 and rn = 3  then  AdmissionClass  end),'') GuardianAdmissionClass3,
   
   
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AcademicYear  end),'') GuardianAcademicYear4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteName  end),'') GuardianInstituteName4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteCity  end),'') GuardianInstituteCity4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  Language  end),'') GuardianMediumStudy4,
  ISNULL(max(case when  relationshipId =2 and rn = 4  then  AdmissionClass  end),'') GuardianAdmissionClass4,
  
  ISNULL(max(case when  relationshipId =2 and rn = 5  then  AcademicYear  end),'') GuardianAcademicYear5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteName  end),'') GuardianInstituteName5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteCity  end),'') GuardianInstituteCity5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  InstituteAffiliaton  end),'') GuardianInstituteAffilation5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  Language  end),'') GuardianMediumStudy5,
   ISNULL(max(case when  relationshipId =2 and rn = 5  then  AdmissionClass  end),'') GuardianAdmissionClass5  
   
from
(
  select AP.AdmissionFormId, RelationshipId, AcademicYear, AdmissionClass, InstituteName, InstituteCity,InstituteAffiliaton,Language
      , row_number() over(partition by AP.AdmissionFormId, RelationshipId
                          order by RelationshipId) rn
  from sAdmission.tAdmissionFormParentAcademic AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
) d
group by AdmissionFormId order by AdmissionFormId 


 

create table #tempReference
(
	AdmissionFormId bigint ,
	ReferenceDetail1 nvarchar(500),
	ReferenceName1 nvarchar(500),
	ReferenceRelation1 nvarchar(500),
	ReferenceContactNo1 nvarchar(500),
	ReferenceDetail2 nvarchar(500),
	ReferenceName2 nvarchar(500),
	ReferenceRelation2 nvarchar(500),
	ReferenceContactNo2 nvarchar(500)
)
INsert Into  #tempReference
 (
	AdmissionFormId,
	ReferenceDetail1,
	ReferenceName1,
	ReferenceRelation1,
	ReferenceContactNo1,
	ReferenceDetail2,
	ReferenceName2,
	ReferenceRelation2,
	ReferenceContactNo2
 )
SELECT AdmissionFormId,
  ISNULL(max(case when    rn = 1  then  ReferenceDetail  end),'') ReferenceDetail1,
  ISNULL(max(case when   rn = 1  then  ReferenceName  end),'') ReferenceName1,
  ISNULL(max(case when    rn = 1  then  ReferenceRelation  end),'') ReferenceRelation1,
  ISNULL(max(case when    rn = 1  then  ReferenceContactNo  end),'') ReferenceContactNo1,
  
  ISNULL(max(case when  rn = 2  then  ReferenceDetail  end),'') ReferenceDetail2,
  ISNULL(max(case when   rn = 2  then  ReferenceName  end),'') ReferenceName2,
  ISNULL(max(case when   rn = 2  then  ReferenceRelation  end),'') ReferenceRelation2,
  ISNULL(max(case when  rn = 2 then  ReferenceContactNo  end),'') ReferenceContactNo2
   
from
(
  select AP.AdmissionFormId,ReferenceDetail, ReferenceName, ReferenceRelation, ReferenceContactNo 
      , row_number() over(partition by AP.AdmissionFormId 
                           order by AP.AdmissionFormId ) rn
  from sAdmission.tAdmissionFormReference AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
) d
group by AdmissionFormId order by AdmissionFormId 

Create table #TempSibling
(
	AdmissionFormId bigint,
	Code1 nvarchar(500),
	SiblingName1 nvarchar(500),
	SiblingRelation1 nvarchar(500),
	SiblingStandard1 nvarchar(500),
	SiblingSchool1 nvarchar(500),
	Code2 nvarchar(500),
	SiblingName2 nvarchar(500),
	SiblingRelation2 nvarchar(500),
	SiblingStandard2 nvarchar(500),
	SiblingSchool2 nvarchar(500),
	Code3 nvarchar(500),
	SiblingName3 nvarchar(500),
	SiblingRelation3 nvarchar(500),
	SiblingStandard3 nvarchar(500),
	SiblingSchool3 nvarchar(500),
	Code4 nvarchar(500),
	SiblingName4 nvarchar(500),
	SiblingRelation4 nvarchar(500),
	SiblingStandard4 nvarchar(500),
	SiblingSchool4 nvarchar(500)
)
Insert Into #TempSibling
(AdmissionFormId,
Code1,	
SiblingName1,
	SiblingRelation1,
	SiblingStandard1,
	SiblingSchool1,
	Code2,	
	SiblingName2,
	SiblingRelation2,
	SiblingStandard2,
	SiblingSchool2,
	Code3,	
	SiblingName3,
	SiblingRelation3,
	SiblingStandard3,
	SiblingSchool3,
	Code4,	
	SiblingName4,
	SiblingRelation4,
	SiblingStandard4,
	SiblingSchool4
)
SELECT AdmissionFormId,
  ISNULL(max(case when    rn = 1  then  Code  end),'') Code1,
  ISNULL(max(case when    rn = 1  then  SiblingName  end),'') SiblingName1,
  ISNULL(max(case when    rn = 1  then  SiblingRelation  end),'') SiblingRelation1,
   ISNULL(max(case when    rn = 1  then  SiblingStandard  end),'') SiblingStandard1,
    ISNULL(max(case when    rn = 1  then  SiblingSchool  end),'') SiblingSchool1,
  
  ISNULL(max(case when    rn = 2  then  Code  end),'') Code2,
  ISNULL(max(case when    rn = 2  then  SiblingName  end),'') SiblingName2,
  ISNULL(max(case when    rn = 2  then  SiblingRelation  end),'') SiblingRelation2,
  ISNULL(max(case when    rn = 2  then  SiblingStandard  end),'') SiblingStandard2,
  ISNULL(max(case when    rn = 2 then  SiblingSchool  end),'') SiblingSchool2,
  
  ISNULL(max(case when    rn = 2  then  Code  end),'') Code3,
   ISNULL(max(case when    rn = 2  then  SiblingName  end),'') SiblingName3,
  ISNULL(max(case when    rn = 2  then  SiblingRelation  end),'') SiblingRelation3,
  ISNULL(max(case when    rn = 2  then  SiblingStandard  end),'') SiblingStandard3,
  ISNULL(max(case when    rn = 2 then  SiblingSchool  end),'') SiblingSchool3,
  
  ISNULL(max(case when    rn = 2  then  Code  end),'') Code4,
   ISNULL(max(case when    rn = 2  then  SiblingName  end),'') SiblingName4,
  ISNULL(max(case when    rn = 2  then  SiblingRelation  end),'') SiblingRelation4,
  ISNULL(max(case when    rn = 2  then  SiblingStandard  end),'') SiblingStandard4,
  ISNULL(max(case when    rn = 2 then  SiblingSchool  end),'') SiblingSchool4
   
from
(
  select AP.AdmissionFormId,    SiblingName, SiblingRelation, SiblingStandard,SiblingSchool,Code  
      , row_number() over(partition by AP.AdmissionFormId 
                          order by AP.AdmissionFormId) rn
  from sAdmission.tAdmissionFormSibling AP
  INNER JOIN #tempAdmissionForm TAF ON TAF.AdmissionFormId = Ap.AdmissionFormId
) d
group by AdmissionFormId order by AdmissionFormId 

 
DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

-- CTE for Admission Form Field
;WITH AdmissionCriteriaFormCTE AS (SELECT  DISTINCT FieldRemark FROM sAdmission.tAdmissionCriteriaForm ACF
INNER JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
WHERE ACF.BatchId = @rBatchId
GROUP BY Id,FieldRemark,ClassId,BatchId
)

SELECT @cols = STUFF((SELECT  ',' + QUOTENAME(FieldRemark) FROM AdmissionCriteriaFormCTE
GROUP BY FieldRemark
ORDER BY FieldRemark FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')

IF object_id('tempdb..##tempAdmissionCriteriaForm') IS NOT NULL 
BEGIN
   DROP TABLE ##tempAdmissionCriteriaForm 
END

IF(@cols IS NOT NULL)
BEGIN 
	SET @query = N'SELECT DISTINCT AdmissionFormId,' + @cols + N' INTO ##tempAdmissionCriteriaForm FROM 
				 (
					SELECT DISTINCT  AFF.AdmissionFormId,AdmissionFormFieldResponse, FieldRemark
					FROM 
					sAdmission.tAdmissionCriteriaForm ACF
					INNER JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
					WHERE ACF.BatchId = '+CONVERT(nvarchar(10),@rBatchId)+'
				) x
				PIVOT
				(
					MAX(AdmissionFormFieldResponse)
					FOR FieldRemark IN (' + @cols + N')
				) p '
			
	exec sp_executesql @query
	
	SELECT * from #tempAdmissionForm tempAF
	LEFT JOIN #tempStudentAcademic tempSA ON tempSA.AdmissionFormId = tempAF.AdmissionFormId
	LEFT JOIN #tempFatherAcademic tempFA ON tempFA.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #tempReference tempRF on tempRF.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #TempSibling tempSB ON tempSB.AdmissionFormId = tempAF.AdmissionFormId
	LEFT JOIN ##tempAdmissionCriteriaForm tempACF ON tempACF.AdmissionFormId = tempAF.AdmissionFormId
	Order by tempAF.Formno

END
ELSE 
BEGIN 
	SELECT * from #tempAdmissionForm tempAF
	LEFT JOIN #tempStudentAcademic tempSA ON tempSA.AdmissionFormId = tempAF.AdmissionFormId
	LEFT JOIN #tempFatherAcademic tempFA ON tempFA.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #tempReference tempRF on tempRF.AdmissionFormId=tempAF.AdmissionFormId
	LEFT JOIN #TempSibling tempSB ON tempSB.AdmissionFormId = tempAF.AdmissionFormId
	Order by tempAF.Formno
END
END
GO
PRINT N'Altering Procedure [sAdmission].[pValidateImportAdmissionForm]...';


GO
ALTER PROCEDURE [sAdmission].[pValidateImportAdmissionForm]
    @rOrgId smallint,
	@rBatchId int,
	@rOrgGroupId int,
	@rXmldoc [nvarchar](max)


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,@lCode nvarchar(20),
		@lFormNo int,@lStudentName nvarchar(100),@lSurName nvarchar(100),@lForClass nvarchar(100),@lDateOfBirth nvarchar(max) = '' ,
        @lGender nvarchar(100),@lReligion nvarchar(100),@lCastCategory nvarchar(20),@lSetClass nvarchar(max)='',@lDuplicateFormNo  nvarchar(max) = '' ,
		@lHostelRequired nvarchar(20) ,@lTransportRequired nvarchar(20),@1ExistFormNo nvarchar(MAX)='',
		@lCastCategoryId int=0,@1ValidDOB nvarchar(max) = '' ,@lSETReligion nvarchar(max)='',@lSETCastCategory nvarchar(MAX)='',@lContactNo nvarchar(20)=''
		,@lFatherContactNo nvarchar(20)='',@lMotherContactNo nvarchar(20)='' --mantis: 0041560
		,@lPENNumber nvarchar(100)='',
		@1ExistPENNumber nvarchar(max) = '',
		@1DuplicatePENNumber nvarchar(max) = '',
		@lDuplicatePENNumber nvarchar(max) = '',
		@lApaarIdNumber nvarchar(50) = '',            
		@1ExistApaarIdNumber nvarchar(max) = '',
		@1DuplicateApaarIdNumber nvarchar(max) = ''
		,@lDuplicateApaarIdNumber nvarchar(max) = ''

			
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
--mantis: 0041560 : Krunal Patel Added valdiation ContactNoDigit
DECLARE @lConfigValueAdmissionContactNoDigitVal nvarchar(50)=''
DECLARE @lPENNumberActive nvarchar(50)='' 
DECLARE @lApaarIdNumberActive nvarchar(50)=''
DECLARE @lIsActivateUniquePENNumber bit = 0 
DECLARE @lIsActivateUniqueApaarIdNumber bit = 0 

SELECT @lConfigValueAdmissionContactNoDigitVal = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 599 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
--add for mantis : 0043425
SELECT @lPENNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 544 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId 
SELECT @lApaarIdNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 587 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
 
	IF (ISNULL(@lPENNumberActive, '') = '') OR (@lPENNumberActive = 'False')
		SET @lIsActivateUniquePENNumber = 0
	ELSE
		SET @lIsActivateUniquePENNumber = 1	

	IF (ISNULL(@lApaarIdNumberActive, '') = '') OR (@lApaarIdNumberActive = 'False')
		SET @lIsActivateUniqueApaarIdNumber = 0
	ELSE
		SET @lIsActivateUniqueApaarIdNumber = 1	
 --add for mantis : 0043425
	CREATE TABLE #tTable  
	(
		Id bigint identity,
		FormNo int,
		ForClass nvarchar(100),
		StudentName nvarchar(100), 
		SurName nvarchar(100),
		DateOfBirth date ,
	    Gender nvarchar(100), 
	    Religion nvarchar(100), 
	    CastCategory nvarchar(100),
	    HostelRequired nvarchar(20), 
	    TransportRequired nvarchar(20),
		ContactNo nvarchar(20), --mantis: 0041560  FatherContactNo ,MotherContactNo             
        FatherContactNo nvarchar(20), 
        MotherContactNo nvarchar(20) 
		,PENNumber nvarchar(100) --add for mantis : 0043425
		,ApaarIdNumber nvarchar(50) --add for mantis : 0043425
	)
	INSERT INTO #tTable
	(   FormNo,ForClass,StudentName,SurName,DateOfBirth, Gender, 
	    Religion,CastCategory,HostelRequired,TransportRequired,ContactNo,FatherContactNo,MotherContactNo  --mantis: 0041560
		,PENNumber,ApaarIdNumber --add for mantis : 0043425
	)
	SELECT
		FormNo,ForClass,StudentName,SurName,DateOfBirth, Gender, 
	    Religion,CastCategory,HostelRequired,TransportRequired,ContactNo,FatherContactNo,MotherContactNo   --mantis: 0041560
		,PENNumber,ApaarIdNumber --add for mantis : 0043425
	FROM OPENXML (@intDoc, '/Table/ImportAdmissionForm', 1)
	WITH
	( 	
	    FormNo int  '@FormNo',
		ForClass nvarchar(100) '@ForClass',
		StudentName nvarchar(100) '@StudentName', 
		SurName nvarchar(100) '@SurName',
		DateOfBirth date  '@DateOfBirth',
	    Gender nvarchar(100) '@Gender', 
	    Religion nvarchar(100) '@Religion',
	    CastCategory nvarchar(100) '@CastCategory',
	    HostelRequired nvarchar(20) '@HostelRequired', 
	    TransportRequired nvarchar(20) '@TransportRequired',
		ContactNo nvarchar(20) '@ContactNo', --mantis: 0041560
        FatherContactNo nvarchar(20) '@FatherContactNo', --mantis: 0041560
        MotherContactNo nvarchar(20) '@MotherContactNo' --mantis: 0041560
		,PENNumber nvarchar(100) '@PENNumber'
		,ApaarIdNumber nvarchar(50) '@ApaarIdNumber'
	    )

EXEC sp_xml_removedocument @intDoc


   IF EXISTS(SELECT 1 fROM #tTable WHERE FormNo=null OR FormNo ='')
BEGIN
	SELECT 'FormNo Should not be empty' AS FormNo
END
 ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE ForClass IS NULL OR ForClass COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'ForClass Should not be empty' AS ForClass
END
ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE StudentName IS NULL OR StudentName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'StudentName Should not be empty' AS StudentName
END
ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE SurName IS NULL OR SurName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'SurName Should not be empty' AS SurName
END
ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE DateOfBirth IS NULL OR DateOfBirth ='' )
BEGIN
	SELECT 'DateOfBirth Should not be empty' AS DateOfBirth
END
ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE Gender IS NULL OR Gender COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'Gender Should not be empty' AS Gender
END
ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE HostelRequired IS NULL OR HostelRequired COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'HostelRequired Should not be empty' AS HostelRequired
END
ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE TransportRequired IS NULL OR TransportRequired COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
BEGIN
	SELECT 'TransportRequired Should not be empty' AS TransportRequired
END
ELSE
SELECT @lCount =  COUNT(Id) FROM #tTable
WHILE @lCount > 0 
BEGIN	
  SELECT @lFormNo = FormNo,
  @lForClass=ForClass,@lReligion=Religion,@lGender=Gender,@lCastCategory=CastCategory,@lHostelRequired=HostelRequired,
  @lTransportRequired=TransportRequired,@lContactNo=ContactNo,@lFatherContactNo=FatherContactNo,
  @lMotherContactNo=MotherContactNo
  ,@lPENNumber = PENNumber,@lApaarIdNumber = ApaarIdNumber --add for mantis : 0043425
FROM #tTable WHERE Id = @lCount 
IF NOT EXISTS(SELECT  1 FROM sSetup.tClassMaster WHERE OrgId=@rOrgId AND Title=@lForClass)
	BEGIN
 SET @lSetClass=@lSetClass+',' + @lForClass
	END		
 ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender NOT IN('Male','Female'))
		BEGIN
			SELECT 'Enter proper value / Check spelling for gender ( Male / Female )' AS gender
			RETURN
		END
 ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE HostelRequired COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND HostelRequired NOT IN('Yes','NO'))
		BEGIN
			SELECT 'Enter proper value / Check spelling for Hostel ( Yes / No )' AS Hostel
			RETURN
	END
	ELSE IF EXISTS(SELECT 1 fROM #tTable WHERE TransportRequired COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND TransportRequired NOT IN('Yes','NO'))
		BEGIN
			SELECT 'Enter proper value / Check spelling for Transport ( Yes / No )' AS Transport
			RETURN
	END
	--mantis: 0041560 : Krunal Patel Added valdiation ContactNoDigit
	IF(@lConfigValueAdmissionContactNoDigitVal is not null OR @lConfigValueAdmissionContactNoDigitVal !='') --mantis: 0041560
        BEGIN                
            IF(@lContactNo != '' AND LEN(@lContactNo) > 0)
            BEGIN  
					declare @lContactNotmp nvarchar(20) 
                    set @lContactNotmp = LEN(@lContactNo)
					IF(@lContactNotmp != @lConfigValueAdmissionContactNoDigitVal)
                    BEGIN 
                            SELECT 'Contact No should be atleast of '+ @lConfigValueAdmissionContactNoDigitVal +' digits' AS StudentCode
                            RETURN
                    END
            END        
   END     
   IF(@lConfigValueAdmissionContactNoDigitVal is not null OR @lConfigValueAdmissionContactNoDigitVal !='') 
    BEGIN               
            IF(@lFatherContactNo != '' AND LEN(@lFatherContactNo) > 0)
            BEGIN  
                    declare @lFatherContactNotmp nvarchar(20)
                    set @lFatherContactNotmp = LEN(@lFatherContactNo)
                    IF(@lFatherContactNotmp != @lConfigValueAdmissionContactNoDigitVal)
                    BEGIN
                            SELECT 'Father Contact No should be atleast of '+ @lConfigValueAdmissionContactNoDigitVal +' digits' AS StudentCode
                            RETURN
                    END                
            END            
   END    

   IF(@lConfigValueAdmissionContactNoDigitVal is not null OR @lConfigValueAdmissionContactNoDigitVal !='') --mantis: 0041560
    BEGIN           
            IF(@lMotherContactNo != '' AND LEN(@lMotherContactNo) > 0)
            BEGIN  
                                        declare @lMotherContactNotmp nvarchar(20)
                    set @lMotherContactNotmp = LEN(@lMotherContactNo)
                    IF(@lMotherContactNotmp != @lConfigValueAdmissionContactNoDigitVal)
                    BEGIN
                            SELECT 'Mother Contact No should be atleast of '+ @lConfigValueAdmissionContactNoDigitVal +' digits' AS StudentCode
                   RETURN
                    END
            END
   END

   
    --End Code :   mantis: 0041560 : Krunal Patel Added valdiation ContactNoDigit
	IF (@lIsActivateUniquePENNumber = 1 AND @lPENNumber != '')
	BEGIN
		IF (ISNUMERIC(@lPENNumber) = 0)
		BEGIN
			SELECT 'PENNumber must be numeric' AS PENNumberErrorMessage;
			RETURN;
		END
		IF (LEN(@lPENNumber) > 12)
		BEGIN
			SELECT 'PENNumber ID Number must be  12 digits' AS ErrorMessage
			RETURN
		END
	END
	IF (@lIsActivateUniqueApaarIdNumber = 1 AND LEN(@lApaarIdNumber) > 0)
	BEGIN
		IF ISNUMERIC(@lApaarIdNumber) = 0
		BEGIN
			SELECT 'Apaar ID Number must be numeric' AS ApaarIdNumberErrorMessage
			RETURN
		END
		IF LEN(@lApaarIdNumber) != 12
		BEGIN
			SELECT 'Apaar ID Number must be exactly 12 digits' AS ErrorMessage
			RETURN
		END
	END
   
	IF(@lReligion!='' OR @lReligion!=null )
	BEGIN
	IF NOT EXISTS(SELECT 1 FROM sCommon.tReligionMaster WHERE  OrgGroupId=@rOrgGroupId AND IsObsolete=0 AND Title=@lReligion)
	BEGIN
	SET @lSETReligion=@lSETReligion++','+@lReligion 
	END
	END
	IF(@lCastCategory!='' OR @lCastCategory!=null )
	BEGIN
	IF NOt EXISTS(SELECT 1 FROM sCommon.tCastCategoryMaster WHERE  OrgGroupId=@rOrgGroupId AND IsObsolete=0 AND Title=@lCastCategory )
	BEGIN
	SET @lSETCastCategory=@lSETCastCategory+@lCastCategory  +','
	END
	END
	IF ((@lDateOfBirth) IS NOT NULL AND @lDateOfBirth != '')
		BEGIN
			SET @lDateOfBirth = 'Wrong DOB ' + @lDateOfBirth
		END
	IF Exists ((select 1 from sAdmission.tAdmissionForm where BatchId=@rBatchId AND FormNo=  @lFormNo  ))               
    BEGIN
		SET @1ExistFormNo =@1ExistFormNo+ convert(varchar,@lFormNo )+ ','
    END	
	
	--IF (@lIsActivateUniquePENNumber = 1)
	--BEGIN
	--	IF(convert(bigint,@lPENNumber) > 0)
	--	BEGIN 		
	--		 IF Exists ((select 1 from sAdmission.tAdmissionForm AF INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =AF.OrgId 
	--			where AF.PENNumber = convert(bigint,@lPENNumber)
	--		)) 		
	--		BEGIN
 -- 				SET @1ExistPENNumber = @1ExistPENNumber + CAST(@lPENNumber AS NVARCHAR(200)) + ','
	--		END	       
	--	END
	--END
	--IF(@lIsActivateUniqueApaarIdNumber=1)
 --   BEGIN
	--	IF(convert(bigint,@lApaarIdNumber) > 0)
	--	BEGIN 		
	--		 IF Exists ((select 1 from sAdmission.tAdmissionForm AF INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =AF.OrgId 
	--			where AF.ApaarIdNumber = @lApaarIdNumber
	--		)) 		
	--		BEGIN
 -- 				SET @1ExistApaarIdNumber = @1ExistApaarIdNumber + CAST(@lApaarIdNumber AS NVARCHAR(200)) + ','
	--		END	       
	--	END
	--END

  SET @lCount = @lCount - 1	
END

SELECT @lDuplicateFormNo=COALESCE(@lDuplicateFormNo ,'') + convert(varchar,FormNo) + ',' FROM #tTable GROUP BY FormNo HAVING ( COUNT(FormNo) > 1 )	

--SELECT  @lDuplicatePENNumber = COALESCE(@lDuplicatePENNumber, '') + PENNumber + ',' FROM #tTable GROUP BY PENNumber HAVING COUNT(*) > 1

 IF(@lDuplicateFormNo IS NOT NULL AND @lDuplicateFormNo != '')
	BEGIN
		SET @lDuplicateFormNo = 'Duplicate Form No : ' + convert(varchar,@lDuplicateFormNo)
	END
	--add for mantis : 0043425
	IF @lIsActivateUniqueApaarIdNumber = 1
	BEGIN
		SELECT  @lDuplicateApaarIdNumber = COALESCE(@lDuplicateApaarIdNumber, '') + ApaarIdNumber + ',' FROM #tTable GROUP BY ApaarIdNumber HAVING COUNT(ApaarIdNumber) > 1
		IF (@lDuplicateApaarIdNumber =',')
		BEGIN
			SET @lDuplicateApaarIdNumber =''
		END
		IF @lDuplicateApaarIdNumber IS NOT NULL AND @lDuplicateApaarIdNumber <> '' 
		BEGIN
			SET @lDuplicateApaarIdNumber = 'Duplicate Apaar Id Number : ' + @lDuplicateApaarIdNumber;
		END
	END
	
	IF @lIsActivateUniquePENNumber = 1
	BEGIN
		SELECT  @lDuplicatePENNumber = COALESCE(@lDuplicatePENNumber, '') + PENNumber + ',' FROM #tTable GROUP BY PENNumber HAVING COUNT(*) > 1
		IF (@lDuplicatePENNumber =',')
		BEGIN
			SET @lDuplicatePENNumber =''
		END
		IF @lDuplicatePENNumber IS NOT NULL AND @lDuplicatePENNumber <> ''
		BEGIN
			SET @lDuplicatePENNumber = 'Duplicate PEN Number : ' +convert(varchar,@lDuplicatePENNumber);
		END
	END
	--add for mantis : 0043425
   If(@1ExistFormNo!='' AND @1ExistFormNo IS NOT NULL)

   BEGIN

   SET @1ExistFormNo=' Already Exists  Form No: ' +@1ExistFormNo
   END
    If(@lSetClass!='' AND @lSetClass IS NOT NULL)
   BEGIN
   SET @lSetClass=' Enter proper value for Class as per Institute Setup > Class Master  :' +@lSetClass
   END
    If(@lSETReligion!='' AND @lSETReligion IS NOT NULL)
   BEGIN
   SET @lSETReligion= ' Enter proper value / Check spelling for Religion :'  +@lSETReligion
   END
      If(@lSETCastCategory!='' AND @lSETCastCategory IS NOT NULL)
   BEGIN
   SET @lSETCastCategory= 'Enter proper value / Check spelling for CastCategory :'  +@lSETCastCategory
   END
	 ----   IF (@lIsActivateUniquePENNumber = 1)
		----BEGIN
	 --  If(@1ExistPENNumber!='' AND @1ExistPENNumber IS NOT NULL)
	 --  BEGIN
	 --  SET @1ExistPENNumber=' Already Exists  PEN Number: ' +@1ExistPENNumber
	 --  END
	 --  --END
	 --  --IF(@lIsActivateUniqueApaarIdNumber=1)
	 --  --BEGIN
	 --  If(@1ExistApaarIdNumber!='' AND @1ExistApaarIdNumber IS NOT NULL)
	 --  BEGIN
	 --  SET @1ExistApaarIdNumber=' Already Exists  ApaarIdNumber: ' +@1ExistApaarIdNumber
	 --  END
	 --  --END
   
	SELECT	@lDuplicateFormNo+Isnull(@lSetClass,'')+ISNULL(@lSETCastCategory,'')+ISNULL(@lSETReligion,'')+ISNULL(@lDateOfBirth,'')+ISNULL(@1ExistFormNo,'')
	--+ ISNULL(@1ExistPENNumber,'') + ISNULL(@1ExistApaarIdNumber,'') 
	+ @lDuplicateApaarIdNumber+Isnull(@lSetClass,'') + @lDuplicatePENNumber+Isnull(@lSetClass,'')
END
--END
GO
PRINT N'Altering Procedure [sCommon].[pOrganizationSetupRemove]...';


GO
ALTER PROCEDURE [sCommon].[pOrganizationSetupRemove]
	 
	 @rOrgId bigint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
  --  BEGIN TRY
	
	 --BEGIN TRANSACTION
	 
	 --EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    
DELETE FROM sAccounting.tExpense WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tExpenseGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursementDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursementTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tActivity WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tActivityParticipant WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tAssignClub WHERE CAST(LEFT(ClubId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tEventAssign WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tEventEnrollment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tEventSchedule WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupAssign WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupDetail WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupParameter WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupStudent WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterList WHERE CAST(LEFT(HealthParameterId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthTrack WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tHouseMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tPlacement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tPlacementInvite WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tStudentImmunizationStatus WHERE CAST(LEFT(ImmunizationChartId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionForm WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormIssue WHERE OrgId = @rOrgId
DELETE FROM sAdmission.tAdmissionInquiry WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tAlertConfiguration WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tAlertLog WHERE OrgId = @rOrgId
DELETE FROM sAlert.tAlertQueue WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tAlertQueueDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tCustomTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tDepartmentRecipient WHERE CAST(LEFT(DepartmentId, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tEmailConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tEventTemplate WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tExternalRecipientMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tSMSConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSClass WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSIndicatorGrade WHERE CAST(LEFT(CCECSId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSScore WHERE CAST(LEFT(CCECSId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamMapping WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamSetting WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEFAGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAScore WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCEFASubject WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEResult WHERE AcademicId = @rOrgId
DELETE FROM sAssessment.tCCEResultDetail WHERE AcademicId = @rOrgId
DELETE FROM sAssessment.tExamCombine WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamStatus WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tExamsubgroupmaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tGeneralExamCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tGradeSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tGradeSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tLevelSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tLevelSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tOptionalSubject WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tRankSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tRankSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tResult WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAudit WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAuditDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tDepartmentLocation WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMaintenence WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMovement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMovementDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tRecordManualEvent WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tApplicableAttendanceType WHERE OrgId = @rOrgId
DELETE FROM sAttendance.tMonthlyRegister WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tMonthlySetup WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tStudentRegister WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tStudentSetup WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tSubjectBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tSubjectBatchStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAudit WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAuditLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAuditLogTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTable WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTableField WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAction WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tActionStatusMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tActionTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAudit WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tAuditLocation WHERE CAST(LEFT(AuditId, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tAuditReasonMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAuditStatusMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAuditTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tDocument WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tDocumentTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tFinding WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tFindingTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tInspection WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tQuestionAnswerMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionAnswerTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionMainGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionnairesMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionResponse WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tQuestionSubGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tSeverityMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBiometric.tPunchMaster WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sCertificate.tBonafide WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCertificate.tCharacter WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tFirstTrial WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCertificate.tLeaving WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tAgeGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tClinicMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId


DELETE FROM sCommon.tDurationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tExceptions WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sCommon.tFileUpload WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tFirstAidMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tFunctionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tLocationMaster WHERE OrgId = @rOrgId
DELETE FROM sCommon.tOrganizationDepartmentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPrefixSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPublicHolidayMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPublicHolidayTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tReasonMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tReportFormatGroupOrg WHERE OrgId = @rOrgId
 
DELETE FROM sCommunication.tAssignment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignmentScope WHERE CAST(LEFT(AssignmentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignmentView WHERE CAST(LEFT(AssignmentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignTask WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tBehaviour WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussion WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionComment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionGroup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionGroupMember WHERE CAST(LEFT(DiscussionGroupId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tPhotoCategoryOrg WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tQueryCategoryOrg WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tUploadBookLog WHERE CAST(LEFT(BookLogId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tUploadResult WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tColorLegendDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tConfigurationSetup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId AND SourceTypeId <> 2010
DELETE FROM sConfig.tCultureConfiguration WHERE OrgId = @rOrgId
DELETE FROM sConfig.tImport WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sConfig.tLocalDeviceSetting WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tMachineMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tMachinePrinterMapping WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tPrinterMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sEExam.tTestAssign WHERE CAST(LEFT(TestId, 4) AS int) = @rOrgId
DELETE FROM sEExam.tTestMaster WHERE OrgId = @rOrgId
DELETE FROM sEExam.tTestParticipant WHERE CAST(LEFT(TestId, 4) AS BIGINT) = @rOrgId
DELETE FROM sEExam.tTestParticipantAnswer WHERE CAST(LEFT(TestId, 4) AS INT) = @rOrgId
DELETE FROM sEExam.tTestQuestion WHERE CAST(LEFT(TestId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tChargeReceipt WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tChargeReceiptDetail WHERE CAST(LEFT(ChargeReceiptId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeAllocation WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeOptional WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tReceipt WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tReceiptDetail WHERE CAST(LEFT(ReceiptId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFixedAsset.tCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFixedAsset.tLocationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFrontOffice.tVisitorLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tActivityIndicatorScore WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tAnusuchiB WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tClassActivity WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tExamSetting WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tGSEBExamMapping WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tHetuMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tAnusuchiB WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResult WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResultDetail WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResultDetailOptional WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tSubjectIndicatorMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tAssignRoom WHERE CAST(LEFT(RoomId, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tHostelWarden WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeAttendance WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeCommunications WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeDesignationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeFamilyDetails WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeGradeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeImages WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeJobDetail WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeePersonalDetail WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeePreviousEmployment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeStatutoryAndOther WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tGuestMaster WHERE OrgId = @rOrgId
DELETE FROM sHrm.tLeave WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tLeaveTypeGradeSettings WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sHrm.tLeaveTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tWorkingDays WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sIp.tBinMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tItemStandardPriceLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tStockItemBin WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tStockItemPlanning WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tStockItemPurchaseUom WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tWeightedAverageCostLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tAssignOrganization WHERE OrgId = @rOrgId
DELETE FROM sLibrary.tBookLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tBookLogPenalty WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tBooksForClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sLibrary.tIssueSetting WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sOmr.tAnswerKeySetup WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tExamSetup WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tScanHistory WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sOmr.tSetting WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sOmr.tSheetCallibration WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tTempAnsKeyAnalysis WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tIssueReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tIssueReturnDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tOrderEntry WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sOrderEntry.tOrderEntryBatch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sOrderEntry.tServiceItemTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tFirstAidEmoloyee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidEmployeeDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidInspection WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidInspectionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNote WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturnBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturnDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tPurchaseOrder WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tPurchaseOrderDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustmentBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAudit WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAuditDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockFreezeAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockFreezeAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInward WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardReturnBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssue WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockItemFreeze WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockTransfer WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockVerification WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockVerificationApproval WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSecurity.tDivisionPermission WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tLdapUser WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUser WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserAccess  WHERE CAST(LEFT(UserId, 4) AS int) = @rOrgId
DELETE FROM sSecurity.tUserFavoriteScreen WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserLocation WHERE CAST(LEFT(StoreLocationId, 4) AS INT) = @rOrgId
DELETE FROM sSecurity.tUserLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserOrganization WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSecurity.tUserPreference WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserProfile WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserRole WHERE CAST(LEFT(UserId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId
DELETE FROM sSetup.tClassMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tClassSubject WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDepartmentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDivisionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
 
DELETE FROM sSetup.tReportConfiguration WHERE OrgId = @rOrgId
DELETE FROM sSetup.tReportSetting WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSetup.tSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tTermMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tAcademic WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tAcademicDetail WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentAdmission WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentCommunication WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentFamily WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentHealth WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentImages WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentOther WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tContactMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tContactTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tImageMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tImageTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tLinkMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tVideoMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tVideoTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTax.tTaxRateSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tDivisionWorkLoad WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tProxySetting WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTeacherWorkLoad WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeSetup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeTable WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeTableSchema WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTransport.tAssignRoute WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCECSExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEFAExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamCombineTerm WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tGradeSujbectExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tStudentRemark WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tSubjectIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tTempAllExam
DELETE FROM sAssessment.tTempCoScholasticExam

DELETE FROM sFee.tAccountMapping WHERE CAST(LEFT(FeeSetupId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tDepositAdd WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tDepositAdjustment WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tDepositBalance WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tDepositRefund WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipEligibleStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipMaster WHERE CAST(LEFT(BatchId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipReceive WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipStudentPaid WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSetup.tYearChangeDivisionMapping WHERE CAST(LEFT(OldDivisionId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tClasswork WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tLessonPlan WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tLessonPlanResource WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tTopicMaster WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tPrintTemplate WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tPrintTemplateStudent WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tStudentGatePass WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tFeeHeadOrgwise WHERE OrgId = @rOrgId
DELETE FROM sFee.tReceiptBookOrgwise WHERE OrgId = @rOrgId

DELETE FROM sAcademic.tTeacherSubject WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tTeacherSubjectDivision WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionCriteriaMaster WHERE OrgId = @rOrgId
--DELETE FROM sAdmission.tAdmissionCriteriaStudent WHERE CAST(LEFT(AdmissionSetupId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormSelected WHERE CAST(LEFT(AdmissionFormId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionSetup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tFilterCriteria WHERE OrgId = @rOrgId
DELETE FROM sAttendance.tFilterCriteriaDetail WHERE CAST(LEFT(FilterCriteriaId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tYearlyRegister WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tWinfeeDetail WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeAttendanceRegister WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeICardOrg WHERE OrgId = @rOrgId
DELETE FROM sSecurity.tUserDashlet WHERE CAST(LEFT(UserId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tICardOrg WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionSetupStudent WHERE CAST(LEFT(AdmissionSetupId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSForClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tActivityLog WHERE CAST(LEFT(OrgId, 4) AS INT)  = @rOrgId
DELETE FROM sAudit.tReceiptDelete WHERE BatchId = @rOrgId
DELETE FROM sAudit.tReceiptDetailDelete WHERE CAST(LEFT(ReceiptId, 4) AS INT) = @rOrgId

DELETE FROM sCommunication.tViewResult WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tViewResultDetail WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrgInfo WHERE OrgId = @rOrgId

DELETE FROM sStudent.tStudentCustomTag WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionCriteria WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormFamilyDetail WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormParentAcademic WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormReference WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormSibling WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormStudentAcademic WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCESubjectActivityMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCESubjectSubActivityExamScore WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCESubjectSubActivityMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tResultAnalysis WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDetail WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tReportOrg WHERE ScopeSourceId = @rOrgId AND ScopeSourceTypeId = 2021
DELETE FROM sAssessment.tCCESubjectSubActivityIndicatorMaster WHERE  OrgId = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDivision WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDivisionDetail WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFrontOffice.tStudentGatePass WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgCalander WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgDrive WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgYouTube WHERE OrgId = @rOrgId
DELETE FROM sHrm.tLeaveBalance WHERE CAST(LEFT(BatchId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceAdd WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sTimetable.tAssignTeacher WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sTimetable.tDivision WHERE CAST(LEFT(OrgId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tSubject WHERE CAST(LEFT(OrgId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tSubjectTimeOff WHERE CAST(LEFT(SubjectId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTeacher WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeQualification WHERE OrgId = @rOrgId
DELETE FROM sSecurity.tUserDashboardNotification WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sTransport.tAssignTransportOrg WHERE OrgId = @rOrgId

--DELETE FROM sFee.tOnlinePayment WHERE  CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
--DELETE FROM sFee.tOnlinePaymentDetail WHERE  CAST(LEFT(OnlinePaymentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tReceiptRefund WHERE  CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tReceiptRefundDetail WHERE  CAST(LEFT(ReceiptRefundId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformIssue WHERE  CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformIssue WHERE  CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformItemForClass WHERE  CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sIp.tUniformOrder WHERE  CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformOrderDetail WHERE  CAST(LEFT(UniformOrderId, 4) AS BIGINT) = @rOrgId
 
DELETE FROM sFee.tFeeInvoice WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tFeeInvoiceDetail WHERE CAST(LEFT(FeeInvoiceId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFee WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeDetail WHERE CAST(LEFT(OnlineFeeId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tCertificateEmployment WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sOp.tPaymentTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrgImages WHERE OrgId = @rOrgId
DELETE FROM sStudent.tStudentadditional WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tStudentBatchStatus WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId

DELETE FROM sCommon.tPrefixConfig WHERE OrgId = @rOrgId
DELETE FROM sConfig.tDisplayFieldOrg WHERE OrgId = @rOrgId
DELETE FROM sHrm.tCertificateExperience WHERE OrgId = @rOrgId
DELETE FROM sHrm.tCertificateRelieving WHERE OrgId = @rOrgId
DELETE FROM sRFID.tAttendance WHERE OrgId = @rOrgId
DELETE FROM sRFID.tRegistration WHERE CAST(LEFT(RegistrtionId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchClassLecture WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tStudentSibling WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tTranscriptAssessment WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sTally.tStudentLedgerMapping WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

/* -- Date : 13/06/2016 -- */
DELETE FROM sActivity.tEventAttendance WHERE CAST(LEFT(SourceId, 4) AS INT) = @rOrgId
DELETE FROM sCanteen.tAssignOrganization WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tRegisteredUsers WHERE OrgId = @rOrgId
DELETE FROM sStudent.tCollegeDetail WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

-- 15.7.2016
DELETE FROM sFrontOffice.tInwardRegister WHERE OrgId = @rOrgId
DELETE FROM sFrontOffice.tOutwardRegister WHERE OrgId = @rOrgId
DELETE FROM sSetup.tSubjectGroupMaster WHERE OrgId = @rOrgId

/* -- Date : 12/08/2016 -- */
DELETE FROM sAssessment.tExamCombineSubject WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tResultDetailOther WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDivisionInchargeEmployee WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tEnrollmentStatusOrg WHERE OrgId = @rOrgId
DELETE FROM sStudent.tEnrollmentStatusStudent WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tLinkSibling WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

/* -- Date : 17/09/2016 -- */

DELETE FROM sAssessment.tTempAllExamSubjectActivity WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tTempAttendance WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId

/* -- Date : 05/10/2016 -- */

DELETE FROM sAdmission.tAdmissionInquiryFollowup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
--DELETE FROM sAssessment.tStaticCCECSGroupMaster WHERE OrgId = @rOrgId
--DELETE FROM sAssessment.tStaticCCECSMaster WHERE OrgId = @rOrgId

/* -- Date : 20/10/2016 -- */

DELETE FROM sAssessment.tOptionalCCECS WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId

/* -- Date : 24/11/2016 -- */
DELETE FROM sBiometric.tMonthTrans WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId

/* -- Date : 23/12/2016 -- */
DELETE FROM sAdmission.tAdmissionFormReceipt WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamStatus WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tAttendanceGroup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tAttendanceGroupStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tAccountPosting WHERE CAST(LEFT(AccountId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceAddRequest WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId

/* -- Date : 14/02/2017 -- */

DELETE FROM sCRM.tChannelPartnerMaster WHERE OrgId = @rOrgId
DELETE FROM sCRM.tInstituteGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sCRM.tInstituteMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrganizationOtherDetail WHERE OrgId = @rOrgId

DELETE FROM sAppraisal.tConduct WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tAllBatchClassGroup WHERE OrgId= @rOrgId
DELETE FROM sAssessment.tAllBatchResult WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tAllBatchSubject WHERE OrgId= @rOrgId
DELETE FROM sHrm.tEmployeeTravel WHERE OrgId= @rOrgId


DELETE FROM sLoan.tLoanDetail WHERE OrgId= @rOrgId
DELETE FROM sLoan.tLoanEMI WHERE CAST(LEFT(LoanDetailId, 4) AS BIGINT) = @rOrgId
DELETE FROM sLoan.tLoanPayrollMapping WHERE OrgId= @rOrgId
DELETE FROM sLoan.tLoanTypeMaster WHERE OrgId= @rOrgId
DELETE FROM sPayroll.tPayrollCustomSearch WHERE OrgId= @rOrgId
DELETE FROM sErp.tChannelMaster WHERE OrgId = @rOrgId

DELETE FROM sAccounting.tExpenseDetail WHERE CAST(LEFT(ExpenseId, 4) AS int) = @rOrgId
DELETE FROM sAccounting.tExpenseSubGroupMaster WHERE OrgId= @rOrgId
DELETE FROM sAppraisal.tAppraisalTypeMaster WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tBusinessHeadsRatingStatus WHERE CAST(LEFT(AppraisalTypeId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployee WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeDetail WHERE CAST(LEFT(KPAEmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeRating WHERE CAST(LEFT(KPAEmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeRatingDetail WHERE CAST(LEFT(KPAEmployeeRatingId, 4) AS bigint) = @rOrgId
DELETE FROM sPoliciesForms.tFolderFile WHERE OrgId = @rOrgId
DELETE FROM sPoliciesForms.tFolderFilePermission WHERE CAST(LEFT(FolderFileId, 4) AS int) = @rOrgId


DELETE FROM sFee.tFeeMainGroupOptionalFee WHERE OrgId = @rOrgId
DELETE FROM sFee.tFeeStructureDetail WHERE CAST(LEFT(FeeStructureId, 4) AS int) = @rOrgId
DELETE FROM sFee.tFeeStructureMaster WHERE OrgId = @rOrgId
DELETE FROM sFrontOffice.tEmployeeGatePass WHERE OrgId = @rOrgId
DELETE FROM sHostel.tHostelStudentGatePass WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sTransport.tAttendanceRegister WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAssessment.tCCESubjectActivityExamScore WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tTempAll_Exam WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sCanteen.tAttendanceForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCanteen.tRegisterForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCertificate.tTransfer WHERE OrgId = @rOrgId
DELETE FROM sCanteen.tRegisterForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sErp.tLeadFollowup WHERE CAST(LEFT(LeadId, 4) AS int) = @rOrgId
DELETE FROM sErp.tLeadMaster WHERE OrgId = @rOrgId


DELETE FROM sAdmission.tAdmissionHSCDetail WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sBiometric.tEmployeeCheckIn WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId

DELETE FROM sBiometric.tEmployeeLateStatus WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId

DELETE FROM sCommon.tSubmitDocumentMaster WHERE OrgId = @rOrgId
DELETE FROM sStudent.tStudentDocument WHERE CAST(LEFT(SubmitDocumentMasterId, 4) AS int) = @rOrgId
DELETE FROM sTimetable.tAnnualSubjectWorkLoad WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId

DELETE FROM sFee.tReceiptDeleted WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sFee.tReceiptDetailDeleted WHERE CAST(LEFT(ReceiptId, 4) AS bigint) = @rOrgId

DELETE FROM sAttendance.tStudentLeaveRequest WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sInfrastructure.tResourceMaster WHERE CAST(LEFT(Id, 4) AS int) = @rOrgId
DELETE FROM sInfrastructure.tResourceRequest WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgId

DELETE FROM sAlumni.tRegistration WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tMonthlyStatusUpdate WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tDSR WHERE OrgId = @rOrgId
DELETE FROM sErp.tDSRWorkTypeMaster WHERE OrgId = @rOrgId
DELETE FROM sErp.tProjectMaster WHERE OrgId = @rOrgId
DELETE FROM sFee.tFeeFollowup WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
 
DELETE FROM sActivity.tWeekOffSetting WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tAllBatchResultCoScholestic WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tEmployeeDocument WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tChangeIdLog WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sAlert.tAssociateRecipient WHERE CAST(LEFT(ForUserId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tPreLessonPlan WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAssessment.tAllBatchResultGrade WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId

DELETE FROM sVts.tvtsClassMaster WHERE CAST(LEFT(ClassId, 4) AS int) = @rOrgId
DELETE FROM sVts.tvtsOrganizationMaster WHERE OrgId = @rOrgId
DELETE FROM sVts.tvtsStudent WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tLeadChannelPartnerMaster WHERE  OrgId = @rOrgId


DELETE FROM sAlumni.tStudentMapping WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tUserFeedback WHERE CAST(LEFT(UserId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeExpense WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId


DELETE FROM sAdmission.tAdmissionCriteriaForm WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormField WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tGradeSetClassSubjectDetail WHERE CAST(LEFT(Id, 4) AS int) = @rOrgId
DELETE FROM sAssessment.tGradeSetClassSubjectMaster WHERE OrgId = @rOrgId
DELETE FROM sBiometric.BioDetailMapping WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tLog WHERE OrgId = @rOrgId

DELETE FROM sCertificate.tOtherCertificate WHERE OrgId = @rOrgId
DELETE FROM sWorkflow.tApprovalAction WHERE CAST(LEFT(ActionUserId, 4) AS bigint) = @rOrgId
DELETE FROM sWorkflow.tApprovalRequest WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sWorkflow.tFunctionalityApprovingAuthority WHERE OrgId = @rOrgId
DELETE FROM sWorkflow.tFunctionalityApprovingDepartment WHERE OrgId = @rOrgId

DELETE FROM sBiometric.tProcess WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tConfiguration WHERE OrgId = @rOrgId

DELETE FROM sAcademic.tHomeworkCheck WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId

DELETE FROM sAdmission.tAdmissionCriteriaFee WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormFee WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId


DELETE FROM sFee.tFeeOpening WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sTransport.tChangeRouteLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tClassworkConfig WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tPunchData WHERE CAST(LEFT(StudentID, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tCallLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tMarketingActivityPlan WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
--DELETE FROM tMarketingActivityStatus WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tTripLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId


DELETE FROM sAudit.HistoryLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAudit.tOperationLog WHERE CAST(LEFT(SourceId, 4) AS int) = @rOrgId

--DELETE FROM sErp.tCustomerTicket WHERE OrgId= @rOrgId
DELETE FROM sPayroll.tPayProcessEmployeeRemark WHERE CAST(LEFT(EmployeeId, 4) AS int) = @rOrgId


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

DELETE FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgId


DELETE FROM sAlert.tAlertLogHistory WHERE OrgId= @rOrgId
DELETE FROM sAlert.tNotificationLogHistory WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeCommunications WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeFamilyDetails WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeJobDetail WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeeMaster WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeePersonalDetail WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeeStatutoryAndOther WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sSecurity.tUserLogHistory WHERE OrgId= @rOrgId
DELETE FROM sStudent.tAcademicStudent WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentAdditional WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentCommunication WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentFamily WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentHealth WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentOther WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tStudentCustomFieldData WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tStudentMasterDelete WHERE OrgId= @rOrgId

DELETE FROM sAudit.ChangeLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tCertificateIncrement WHERE OrgId= @rOrgId
DELETE FROM sAudit.ChangeLog WHERE CAST(LEFT(ScreenId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tClassworkView WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sBiometric.tPunchCount WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sFrontOffice.tOTPLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tLeaveDeduction WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId


DELETE FROM sAdmission.tAdmissionCriteriaDocument WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionStudentDocument WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sTimetable.tTimeTableTime WHERE CAST(LEFT(DivisionId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeWorkingDays WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId

DELETE FROM sErp.tContactBookMaster WHERE OrgId= @rOrgId
DELETE FROM sErp.tEmployeeERPDetail WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sFrontOffice.tLostFoundRegisterScope WHERE CAST(LEFT(SourceId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeChangeHistory WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sCommon.tReportTemplate WHERE OrgId= @rOrgId
DELETE FROM sTransport.tBusRouteAssignedTo WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sWorkflow.tStudentDataChange WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tOnlineLearning WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAssignment WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAssignmentSubmit WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAttendance WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAttendanceLog WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningReference WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningResource WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningScope WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tTempOnlineLearningScope WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tChat WHERE CAST(LEFT(FromSourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tTempChatGroupScope WHERE CAST(LEFT(MemberSourceId, 4) AS bigint) = @rOrgId


DELETE FROM sAcademic.tOnlineMeetingSettings WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tDigitalForm WHERE OrgId= @rOrgId
DELETE FROM sStudent.tDigitalFormScope WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId
DELETE FROM sStudent.tDigitalFormField WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId
DELETE FROM sStudent.tDigitalFormStudent WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningView WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId

DELETE FROM sOp.tPaymentTransactionHistory WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeHistory WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeDetailHistory WHERE CAST(LEFT(OnlineFeeId, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tStudentDocumentUpload WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId

DELETE FROM sFee.tFeeAllocationHistory WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sCommon.tUploadDocument WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId

DELETE FROM sFee.tFeeAllocationStudent WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeClassBatchStatus WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeBatch WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tEmployeeDocumentUpload WHERE OrgId = @rOrgId

DELETE FROM [sHrm].[tEmployeeCustomFieldData] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId

DELETE FROM [sCommunication].[tDailyThoughtAssign] WHERE OrgId= @rOrgId
DELETE FROM [sFee].[tEMandate] WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgId

DELETE FROM [sAdmission].[tAdmissionInquiryCriteria] WHERE CAST(LEFT([ClassId], 4) AS int) = @rOrgId
DELETE FROM [sCommon].[tSubmitDocumentScope] WHERE CAST(LEFT([SubmitDocumentId], 4) AS int) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningRecording WHERE CAST(LEFT([OnlineLearningId], 4) AS bigint) = @rOrgId

DELETE FROM [sCommon].[tUserToken] WHERE CAST(LEFT([UserId], 4) AS bigint) = @rOrgId

DELETE FROM [sBiometric].[tEmployeeConfiguration] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM sAlert.tWhatsAppConfiguration WHERE OrgId= @rOrgId
DELETE FROM sFee.tDepositSetup WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sAlert].[tWhatsAppLog] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningHistoryLog WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId

DELETE FROM [sAlert].[tAlertTrack] WHERE OrgId = @rOrgId
DELETE FROM sTally.tJVPosting WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId

DELETE FROM [sHrm].[tLeavePeriod] WHERE OrgId = @rOrgId
DELETE FROM [sRecruitment].[tAssignOrganization] WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionCustomSearch WHERE OrgId = @rOrgId

DELETE FROM[sCommunication].[tTempQueryCategoryScope] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId


DELETE FROM [sStudent].[tOnlineRegistrationStudentAdmission] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentCommunication] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentCustomFieldData] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentDocument] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentFamily] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentImages] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentOther] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCollegeDetail] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationDisplayField]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaDocument]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaForm]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentMaster] WHERE OrgId = @rOrgId

DELETE FROM [sBiometric].[tShiftAllocationCloud] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sBiometric].[tCloudTransactionData] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM [sTransport].[tAssignRouteLog] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sAttendance].[tAttendanceFollowup] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId

DELETE FROM sAssessment.tAssessmentLabelSetup WHERE OrgId = @rOrgId
DELETE FROM [sAssessment].[tStudentExamRemark] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId
DELETE FROM [sBiometric].[tDeviceMasterCloud] WHERE OrgId = @rOrgId

DELETE FROM [sHrm].[tDigitalForm] WHERE OrgId = @rOrgId
DELETE FROM [sHrm].[tDigitalFormField] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sHrm].[tDigitalFormScope] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sHrm].[tDigitalFormEmployee] WHERE CAST(LEFT([DigitalFormId], 4) AS int) = @rOrgId
DELETE FROM [sAdmission].[tAdmissionOptionalSubject] WHERE CAST(LEFT([AdmissionFormId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentOptionalSubject] WHERE CAST(LEFT([OnlineRegistrationStudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteria] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaOptionalSubject] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sAdmission].[tAdmissionCriteriaOptionalSubject] WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId

DELETE FROM [sAlert].[tAlertTrackHistory] WHERE OrgId = @rOrgId
DELETE FROM [sActivity].[tEventInchargeAssign] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sLibrary].[tNewspaperLog] WHERE CAST(LEFT([NewspaperId], 4) AS int) = @rOrgId
DELETE FROM sSetup.tClassContentSetup WHERE CAST(LEFT([ClassId], 4) AS int) = @rOrgId

DELETE FROM[sHrm].[tCertificateJoining] WHERE [OrgId] = @rOrgId
DELETE FROM[sCommunication].[tTempMultiPhotoCategoryScope] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM[sStudent].[tDigitalFormStudentStatus] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId
DELETE FROM[sHrm].[tDigitalFormEmployeeStatus] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM[sHrm].[tLeaveHierarchyLevel] WHERE CAST(LEFT([LeaveId], 4) AS bigint) = @rOrgId

DELETE FROM [sAudit].[tChargeDeleted] WHERE [OrgId] = @rOrgId
DELETE FROM [sAudit].[tChargeDetailDelete] WHERE CAST(LEFT([ChargeReceiptId], 4) AS bigint) = @rOrgId

DELETE FROM sFee.tLateFeeRuleMaster WHERE OrgId = @rOrgId
DELETE FROM sAlert.tAlertQueueLog WHERE OrgId = @rOrgId

DELETE FROM sFee.tDepositDefaultSetup WHERE OrgId = @rOrgId

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

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


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

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

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


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

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

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

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



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


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

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

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

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

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

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

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

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



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


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


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

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

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

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

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

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

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

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

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


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

		

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

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

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


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

		

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


GO
ALTER PROCEDURE [sAlert].[pViewQueryGet]

	 	 @rQueryId bigint,
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rFromSourceTypeId smallint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--mantis: 44100, start
	IF(@rFromSourceTypeId=0)
	BEGIN
		SELECT @rFromSourceTypeId=FromSourceTypeId FROM sCommunication.tQuery WHERE Id=@rQueryId
	END
	--mantis: 44100, end

	IF(@rFromSourceTypeId=2003)
	BEGIN
		SELECT
			QM.Id AS QueryId,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			--'mohit.patel@vidyalayaschoolsoftware.com' AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			replace (
				replace (
					replace(
						@rTemplate,'[Name]',SC.Name),
						'[Status]',CASE WHEN QM.StatusId = 209 THEN 'Open'
										WHEN QM.StatusId = 210 THEN 'Closed'
										WHEN QM.StatusId = 709 THEN 'Hold' ELSE '' END),
						'[QueryNo]',QM.number)
					AS MsgText,

			@rSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			SC.Name AS Name,
			(CASE WHEN QM.StatusId = 209 THEN 'Open' 
				WHEN QM.StatusId = 210 THEN 'Closed' 
				WHEN QM.StatusId = 709 THEN 'Hold' ELSE '' END) [Status1],	--mantis: 44100, change column name Status => Stauts1
			QM.number AS QueryNo,
			SC.WhatsAppContactNo
		FROM
			sCommunication.tQuery QM
			INNER JOIN [sStudent].[vStudentCommunication] SC ON QM.FromSourceId=SC.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId
		WHERE
			QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId AND BM.IsActive=1 AND SC.IsBlockAllAlert=0
	END
	IF(@rFromSourceTypeId=95)
	BEGIN
		SELECT
			QM.Id AS QueryId,
			ISNULL(EM.CompanyEmail,'') AS EmailId,
			ISNULL(EM.MobileNumber,'') AS MobileNo,
			replace(
				replace(
					replace(
						@rTemplate,'[Name]',EM.EmployeeName),
						'[Status]',CASE WHEN QM.StatusId = 209 THEN 'Open'
										WHEN QM.StatusId = 210 THEN 'Closed'
										WHEN QM.StatusId = 709 THEN 'Hold' ELSE '' END),
						'[QueryNo]',QM.number)
					AS MsgText,

			@rSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EM.EmployeeId AS ReceiverSourceId
		FROM
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId
		WHERE
			QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId
	END
END
GO
PRINT N'Altering Procedure [sAssessment].[pImportExamSetupGet]...';


GO
ALTER PROCEDURE [sAssessment].[pImportExamSetupGet]
	 @rClassId int,
	 @rFromBatchId int,
	 @rToBatchId int,
	 @rExamGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

SELECT 
		ESGM.Id AS ExamSubGroupId, 
		ESGM.Title AS ExamName,

		(Select (Select ESGM1.Title +','  from sAssessment.tExamMaster EM1 INNER JOIN sAssessment.tExamSubGroupMaster ESGM1 ON ESGM1.ID = EM1.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC  ON EC.SubExamId=EM1.Id AND EC.ExamId = (SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId 
		AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id ) where (EM1.Id <> (SELECT Id FROM sAssessment.tExamMaster  WHERE ClassId = @rClassId 
		AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id )) AND (EM1.ClassId = @rClassId ) AND EM1.BatchId = @rFromBatchId FOR XML PATH('')) ) AS FromBatchCombine,

		(Select (Select CONVERT(VARCHAR(15), ESGM1.Id) +','  from sAssessment.tExamMaster EM1 INNER JOIN sAssessment.tExamSubGroupMaster ESGM1 ON ESGM1.ID = EM1.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC  ON EC.SubExamId=EM1.Id AND EC.ExamId = (SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId 
		AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id ) where (EM1.Id <> (SELECT Id FROM sAssessment.tExamMaster  WHERE ClassId = @rClassId 
		AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id )) AND (EM1.ClassId = @rClassId ) AND EM1.BatchId = @rFromBatchId FOR XML PATH('')) ) AS FromBatchCombineIds,

		ISNULL((SELECT COUNT(ESGM1.Title) FROM sAssessment.tExamMaster EM1 INNER JOIN sAssessment.tExamSubGroupMaster ESGM1 ON ESGM1.ID = EM1.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId = EM1.Id AND EC.ExamId = (SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId 
		AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id) WHERE EM1.Id <> (SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId 
		AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id) AND EM1.ClassId = @rClassId AND EM1.BatchId = @rFromBatchId),0) AS FromBatchCombineCount,

		(Select (Select ESGM2.Title +','  from sAssessment.tExamMaster EM2 INNER JOIN sAssessment.tExamSubGroupMaster ESGM2 ON ESGM2.ID = EM2.ExamSubGroupId  
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM2.Id AND EC.ExamId in (select SubExamId  from sAssessment.tExamCombine 
		where examid=(SELECT Id FROM sAssessment.tExamMaster  WHERE ClassId = @rClassId AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id )) 
		where (EM2.ClassId = @rClassId ) AND EM2.BatchId = @rFromBatchId FOR XML PATH(''))  From sAssessment.tExamMaster EM3  where EM3.Id = 
		(SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id ) AND EM3.IsIncludeSubExam = 1 ) AS FromBatchSubCombine,
		
		(Select (Select CONVERT(VARCHAR(15), ESGM2.Id) +','  from sAssessment.tExamMaster EM2 INNER JOIN sAssessment.tExamSubGroupMaster ESGM2 ON ESGM2.ID = EM2.ExamSubGroupId  
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM2.Id AND EC.ExamId in (select SubExamId  from sAssessment.tExamCombine 
		where examid=(SELECT Id FROM sAssessment.tExamMaster  WHERE ClassId = @rClassId AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id )) 
		where (EM2.ClassId = @rClassId ) AND EM2.BatchId = @rFromBatchId FOR XML PATH(''))  From sAssessment.tExamMaster EM3  where EM3.Id = 
		(SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id ) AND EM3.IsIncludeSubExam = 1 ) AS FromBatchSubCombineIds,

		ISNULL((SELECT (SELECT COUNT(ESGM2.Id) FROM sAssessment.tExamMaster EM2 INNER JOIN sAssessment.tExamSubGroupMaster ESGM2 ON ESGM2.ID = EM2.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId = EM2.Id AND EC.ExamId IN (SELECT SubExamId FROM sAssessment.tExamCombine WHERE 
		examid = (SELECT Id FROM sAssessment.tExamMaster WHERE ClassId = @rClassId AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id)) 
		WHERE EM2.ClassId = @rClassId AND EM2.BatchId = @rFromBatchId) FROM sAssessment.tExamMaster EM3 WHERE EM3.Id = (SELECT Id FROM sAssessment.tExamMaster 
		WHERE ClassId = @rClassId AND BatchId = @rFromBatchId AND ExamSubGroupId = ESGM.Id) AND EM3.IsIncludeSubExam = 1),0) AS FromBatchSubCombineCount
		
	FROM 
	sAssessment.tExamMaster EM 
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	INNER JOIN sAssessment.tExamGroupMaster EGM ON ESGM.ExamGroupId = EGM.Id

	WHERE 
	EM.BatchId = @rFromBatchId 
	AND EM.ClassId = @rClassId
	AND (EGM.Id = @rExamGroupId  OR @rExamGroupId = 0)

END
GO
PRINT N'Altering Procedure [sAssetManagement].[pAssetCustomFieldsUpdateGet]...';


GO
ALTER PROCEDURE [sAssetManagement].[pAssetCustomFieldsUpdateGet]
	 		
	 @rOrgId int,
	 @rDepartmentId int,
	 @rLocationId int,
	 @rSubCategoryId int
	 
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=FieldTypeId FROM sAssetManagement.tAssetCustomFieldMaster WHERE Id=@rSubCategoryId
		
		 Declare @Sql nvarchar(max)
		 Declare @Sql1 nvarchar(max)
		  ----0038705 : By Krunal K Patel -- Added FieldTypeId=5 for Date.
		 --IF(@lDataTypeId=3)   --For Free Text and Numeric
		 --BEGIN
	SET @Sql = 'select * from (
				Select Row_Number() OVER (PARTITION BY AM.Id ORDER BY CASE WHEN ACF.FieldTypeId IS NOT NULL THEN ACF.FieldTypeId END Desc) as RowNumber
				,AM.Id AS AssetId, AM.Title,CM.Title AS Category, AM.Code AS AssetCode,
				CASE WHEN ACF.FieldTypeId=3 OR ACF.FieldTypeId=4 THEN
				ISNULL(AC.FieldData,'''') 
				WHEN ACF.FieldTypeId=2 THEN
				ISNULL(AC.FieldData,''0'')
				WHEN ACF.FieldTypeId=1 THEN
				ISNULL(AC.FieldData,''False'')
				WHEN ACF.FieldTypeId=5 THEN
				ISNULL(AC.FieldData,'''') 				
				END AS SubCategory
			FROM 
		         sAssetManagement.tAssetMaster AM
				 INNER JOIN sFixedAsset.tCategoryMaster CM ON AM.CategoryId = CM.Id
		         LEFT JOIN sAssetManagement.tAssetCustomFieldData AC ON AC.AssetId=AM.Id
		         LEFT JOIN sAssetManagement.tAssetCustomFieldMaster ACF ON ACF.Id=AC.AssetCustomFieldId AND ACF.FieldTypeId='''+@lDataTypeId+'''  AND ACF.Id= '''+CAST(@rSubCategoryId AS nvarchar(15))+''' AND ACF.IsObsolete=0 
		         
		    Where AM.OrgId='+CAST(@rOrgId AS nvarchar(15))
				+'AND (AM.DepartmentId='+CAST(@rDepartmentId AS nvarchar(15))+ 'OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
				AND (AM.LocationId='+CAST(@rLocationId AS nvarchar(15))+ 'OR '+CAST(@rLocationId AS nvarchar(15))+'=0))AS a where RowNumber =1'     
		 			
		  print @Sql		
		   		
			EXECUTE  sp_executesql @Sql		
	   
END
GO
PRINT N'Altering Procedure [sAttendance].[pStudentAttendaceDashboardGet]...';


GO
ALTER PROCEDURE [sAttendance].[pStudentAttendaceDashboardGet]
	 @rTypeId smallint,
	 @rUptoDate date='',
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDivisionId int=0,
	 @rClassId int =0,
	 @rGenderType int=0,
	 @rCommonOrgGroupBatchId int=0,
	 @rSyncDate int =0,
	 @rUserId Bigint,
	 @rAttendanceTypeId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--Changes for Mantis Id: 0039838
DECLARE @lConfigValueDashboard nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValueDashboard = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 592 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValueDashboard, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;


IF(@lConfigValueDashboard <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValueDashboard <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

IF @rClassId=0
  BEGIN
--Orggroup wise Attendance
   IF @rTypeId=1 
   BEGIN
--Update Attendance
	IF(@rSyncDate =1) 
		BEGIN 
			--DELETE  sAttendance.tTempStudentAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			--IF EXISTS (SELECT 1 FROM sAttendance.tTempStudentAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))
			--				BEGIN
							IF(@rOrgGroupId !=0)
									--INSERT INTO sAttendance.tTempStudentAttendance
--Total Student All Orggroup
				   SELECT 
					OGM.Id AS OrgGroupId,
					OGM.Title As OrgGroupTitle,
					0 As OrgId,'' As OrgTitle,       
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
						  -- IsInContext
						  AND BM.IsInContext = 1
						 ) AS Total,       
--PresentStudent All Orggroup
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id 
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
						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
					  WHERE 
						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						-- IsInContext
						AND BME.IsInContext = 1
						) AS PresentStudent,
--AbsentStudent All Orggroup
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						-- IsInContext
						AND BME.IsInContext = 1
						) AS AbsentStudent,
--LessThen70 % All Orggroup
				   (select Count(StudentID) from(
						select  (SMD.Id)StudentID
						 
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
						  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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
					where 
						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						  AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						  -- IsInContext
						  AND BMEL.IsInContext = 1
						  GROUP BY SMD.Id
					--GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
					
					--HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
					)  As LessThen70,
--100% Attendance All Orggroup
				  (select Count(StudentID) from  (
					select  
						  OGMEL.Id AS OrgGroupId,
						  OGMEL.Title AS OrgGroupTitle,
						  OMEL.Id AS OrgId,
						  (OMEL.Title) As OrgTitle ,
						  DM.Code AS DivisionCode,
						  (SMD.Id)StudentID,
						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
						  (SC.ParentContactNo) AS ContactNo,
						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						   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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						   AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						   -- IsInContext
						   AND BMEL.IsInContext = 1
					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
					) AS HundredPer,
--Absent>3 All Orggroup
				   (SELECT COUNT(AcademicId) FROM(
					  SELECT 
						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
						AcademicId,AttendanceDate
					  FROM sAttendance.tStudentRegister d 		
						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						 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	
		
					  WHERE
						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
						 IsPresent IN(0) 
						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
						 and IsPresent=0
						 AND (d.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						 -- IsInContext
						 AND BMEL.IsInContext = 1
					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
					  ) AS AbsentCount,
--Leave Request All Orggroup
					(SELECT 
						COUNT(AcademicId) AS LeaveRequest
					 FROM sAttendance.tStudentLeaveRequest STSL
						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
					-- IsInContext
					AND BMEL.IsInContext = 1
					) AS LeaveRequest,
--AttnNotTakenClass All Orggroup
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
					 WHERE 
						 OGM.Id = OGMR.Id  and SM1.statusid =1 AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
					(select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126) AND (SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0))
					-- IsInContext
					AND BM.IsInContext = 1
					) 
					As AttnNotTakenClass,

				@rUptoDate AS StudentAttendanceDate
				,@rCommonOrgGroupBatchId AS CommonOrgGroupBatchId
				,GetDate() as UpdateDate
				FROM sSetup.tOrgGroupMaster OGM 
				WHERE OGM.Id<>1 AND ISNULL(OGM.IsObsolete,0) = 0
				AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
--				SELECT * FROM sAttendance.tTempStudentAttendance 
--			SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND Total !=0 ORDER BY OrgGroupId
--							END
--						ELSE
--							BEGIN
--									INSERT INTO sAttendance.tTempStudentAttendance
----Total Student All Orggroup
--				   SELECT 
--					OGM.Id AS OrgGroupId,
--					OGM.Title As OrgGroupTitle,
--					0 As OrgId,'' As OrgTitle,       
--					(Select count(SM1.ID)
--					 FROM sStudent.tStudentMaster SM1
--						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
--						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
--						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
--						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
--						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
--					 WHERE 
--						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
--						 -- IsInContext
--						 AND BM.IsInContext = 1
--						 ) AS Total,       
----PresentStudent All Orggroup
--					 (select count(*) from sAttendance.tStudentRegister SME 
--						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id 
--						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
--						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
--						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
--					  WHERE 
--						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
--						AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
--						-- IsInContext
--						AND BME.IsInContext = 1
--						) AS PresentStudent,
----AbsentStudent All Orggroup
--					 (select count(*) from sAttendance.tStudentRegister SME 
--						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
--						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
--						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
--						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
--						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
--						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
--						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
--					  WHERE 
--						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
--						AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
--						-- IsInContext
--						AND BME.IsInContext = 1
--						) AS AbsentStudent,
----LessThen70 % All Orggroup
--				   (select Count(StudentID) from(
--						select  
--						 OGMEL.Id AS OrgGroupId,
--						 OGMEL.Title AS OrgGroupTitle,
--						 OMEL.Id AS OrgId,
--						 (OMEL.Title) AS OrgTitle ,
--						 DM.Code As DivisionCode,
--						 (SMD.Id)StudentID,
--						 (SMD.FirstName + ' ' + SMD.LastName) AS StudentName,
--						 (SC.ParentContactNo) AS ContactNo,
--						 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
--					FROM sAttendance.tStudentRegister SMEL
--						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
--						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
--						  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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
--						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
--						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
--					where 
--						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
--						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
--						  AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
--						  -- IsInContext
--						  AND BMEL.IsInContext = 1
--					GROUP BY 
--						 OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
--					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
--					)  As LessThen70,
----100% Attendance All Orggroup
--				  (select Count(StudentID) from  (
--					select  
--						  OGMEL.Id AS OrgGroupId,
--						  OGMEL.Title AS OrgGroupTitle,
--						  OMEL.Id AS OrgId,
--						  (OMEL.Title) As OrgTitle ,
--						  DM.Code AS DivisionCode,
--						  (SMD.Id)StudentID,
--						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
--						  (SC.ParentContactNo) AS ContactNo,
--						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
--					FROM sAttendance.tStudentRegister SMEL
--						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
--						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						   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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
--						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
--						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
--					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
--						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
--						   AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
--						   -- IsInContext
--						   AND BMEL.IsInContext = 1
--					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
--					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
--					) AS HundredPer,
----Absent>3 All Orggroup
--				   (SELECT COUNT(AcademicId) FROM(
--					  SELECT 
--						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
--						AcademicId,AttendanceDate
--					  FROM sAttendance.tStudentRegister d 		
--						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
--						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						 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	
		
--					  WHERE
--						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
--						 IsPresent IN(0) 
--						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
--						 and IsPresent=0
--						 AND (d.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
--						 -- IsInContext
--						 AND BMEL.IsInContext = 1
--					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
--					  ) AS AbsentCount,
----Leave Request All Orggroup
--					(SELECT 
--						COUNT(AcademicId) AS LeaveRequest
--					 FROM sAttendance.tStudentLeaveRequest STSL
--						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
--						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
--						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
--						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
--					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
--					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
--					-- IsInContext
--					AND BMEL.IsInContext = 1
--					) AS LeaveRequest,
----AttnNotTakenClass All Orggroup
--					(Select count(SM1.ID)
--					 FROM sStudent.tStudentMaster SM1
--						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
--						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
--						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
--						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
--						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
--					 WHERE 
--						 OGM.Id = OGMR.Id  and SM1.statusid =1 AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
--					(select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126) AND (SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0))
--					-- IsInContext
--					AND BM.IsInContext = 1
--					) 
--					As AttnNotTakenClass,

--				@rUptoDate,@rCommonOrgGroupBatchId,GetDate()
--				FROM sSetup.tOrgGroupMaster OGM 
--				WHERE OGM.Id<>1 AND ISNULL(OGM.IsObsolete,0) = 0
--				AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
--			SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND Total !=0 ORDER BY OrgGroupId
--							END
--			INSERT INTO sAttendance.tTempStudentAttendance
----Total Student All Orggroup
--				   SELECT 
--					OGM.Id AS OrgGroupId,
--					OGM.Title As OrgGroupTitle,
--					0 As OrgId,'' As OrgTitle,       
--					(Select count(SM1.ID)
--					 FROM sStudent.tStudentMaster SM1
--						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
--						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
--						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
--						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
--						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
--					 WHERE 
--						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
--						 ) AS Total,       
----PresentStudent All Orggroup
--					 (select count(*) from sAttendance.tStudentRegister SME 
--						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id 
--						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
--						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
--						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
--					  WHERE 
--						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
--						) AS PresentStudent,
----AbsentStudent All Orggroup
--					 (select count(*) from sAttendance.tStudentRegister SME 
--						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
--						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
--						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
--						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
--						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
--						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
--						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
--					  WHERE 
--						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
--						) AS AbsentStudent,
----LessThen70 % All Orggroup
--				   (select Count(StudentID) from(
--						select  
--						 OGMEL.Id AS OrgGroupId,
--						 OGMEL.Title AS OrgGroupTitle,
--						 OMEL.Id AS OrgId,
--						 (OMEL.Title) AS OrgTitle ,
--						 DM.Code As DivisionCode,
--						 (SMD.Id)StudentID,
--						 (SMD.FirstName + ' ' + SMD.LastName) AS StudentName,
--						 (SC.ParentContactNo) AS ContactNo,
--						 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
--					FROM sAttendance.tStudentRegister SMEL
--						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
--						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
--						  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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
--						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
--						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
--					where 
--						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
--						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
--					GROUP BY 
--						 OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
--					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
--					)  As LessThen70,
----100% Attendance All Orggroup
--				  (select Count(StudentID) from  (
--					select  
--						  OGMEL.Id AS OrgGroupId,
--						  OGMEL.Title AS OrgGroupTitle,
--						  OMEL.Id AS OrgId,
--						  (OMEL.Title) As OrgTitle ,
--						  DM.Code AS DivisionCode,
--						  (SMD.Id)StudentID,
--						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
--						  (SC.ParentContactNo) AS ContactNo,
--						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
--					FROM sAttendance.tStudentRegister SMEL
--						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
--						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						   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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
--						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
--						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
--					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
--						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
--					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
--					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
--					) AS HundredPer,
----Absent>3 All Orggroup
--				   (SELECT COUNT(AcademicId) FROM(
--					  SELECT 
--						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
--						AcademicId,AttendanceDate
--					  FROM sAttendance.tStudentRegister d 		
--						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
--						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						 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	
		
--					  WHERE
--						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
--						 IsPresent IN(0) 
--						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
--						 and IsPresent=0
--					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
--					  ) AS AbsentCount,
----Leave Request All Orggroup
--					(SELECT 
--						COUNT(AcademicId) AS LeaveRequest
--					 FROM sAttendance.tStudentLeaveRequest STSL
--						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
--						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
--						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
--						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
--					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
--					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
--					) AS LeaveRequest,
----AttnNotTakenClass All Orggroup
--					(Select count(SM1.ID)
--					 FROM sStudent.tStudentMaster SM1
--						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
--						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
--						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
--						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
--						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
--					 WHERE 
--						 OGM.Id = OGMR.Id  and SM1.statusid =1 AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
--					(select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126))) 
--					As AttnNotTakenClass,

--				@rUptoDate,@rCommonOrgGroupBatchId,GetDate()
--				FROM sSetup.tOrgGroupMaster OGM 
--				WHERE OGM.Id<>1 AND OGM.IsObsolete = 0
--				AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
--			SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND Total !=0 ORDER BY OrgGroupId
		END
	ELSE
----Temp Atble Attendance
		BEGIN
			DELETE  sAttendance.tTempStudentAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId  AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			--IF EXISTS (SELECT 1 FROM sAttendance.tTempStudentAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))
			--				BEGIN
							IF(@rOrgGroupId !=0)
			INSERT INTO sAttendance.tTempStudentAttendance
--Total Student All Orggroup Temp		
				   SELECT 
					OGM.Id AS OrgGroupId,
					OGM.Title As OrgGroupTitle,
					0 As OrgId,'' As OrgTitle,       
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
						 -- IsInContext
						 AND BM.IsInContext = 1
						 ) AS Total,       
--PresentStudent All Orggroup Temp
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
						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
					  WHERE 
						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						-- IsInContext
						AND BME.IsInContext = 1
						) AS PresentStudent,
--AbsentStudent All Orggroup Temp
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						-- IsInContext
						AND BME.IsInContext = 1
						) AS AbsentStudent,
--LessThen70 All Orggroup Temp
				   (select Count(StudentID) from(
						select  
						 OGMEL.Id AS OrgGroupId,
						 OGMEL.Title AS OrgGroupTitle,
						 OMEL.Id AS OrgId,
						 (OMEL.Title) AS OrgTitle ,
						 DM.Code As DivisionCode,
						 (SMD.Id)StudentID,
						 (SMD.FirstName + ' ' + SMD.LastName) AS StudentName,
						 (SC.ParentContactNo) AS ContactNo,
						 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						  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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
					where 
						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						  -- IsInContext
						  AND BMEL.IsInContext = 1
					GROUP BY 
						 OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
					)As LessThen70,
--100 % HundredPer All Orggroup Temp
				  (select Count(StudentID) from  (
					select  
						  OGMEL.Id AS OrgGroupId,
						  OGMEL.Title AS OrgGroupTitle,
						  OMEL.Id AS OrgId,
						  (OMEL.Title) As OrgTitle ,
						  DM.Code AS DivisionCode,
						  (SMD.Id)StudentID,
						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
						  (SC.ParentContactNo) AS ContactNo,
						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						   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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1					
						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						   -- IsInContext
						   AND BMEL.IsInContext = 1
					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
					) AS HundredPer,
--AbsentCount All Orggroup Temp
				   (SELECT COUNT(AcademicId) FROM(
					  SELECT 
						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
						AcademicId,AttendanceDate
					  FROM sAttendance.tStudentRegister d 		
						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						 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	
					  WHERE
						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
						 IsPresent IN(0) 
						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
						 and IsPresent=0
						 -- IsInContext
						 AND BMEL.IsInContext = 1
					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
					  ) AS AbsentCount,
--LeaveRequest All Orggroup Temp
					(SELECT COUNT(AcademicId) AS LeaveRequest
					FROM sAttendance.tStudentLeaveRequest STSL
						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
					-- IsInContext
					AND BMEL.IsInContext = 1
					) AS LeaveRequest,
--AttnNotTakenClass All Orggroup Temp
					(Select count(SM1.ID)
					FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  
						 and SM1.statusid =1 
						 AND COGBM.Id=@rCommonOrgGroupBatchId 
						 AND A.Id  not in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126) AND (SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0))
						 -- IsInContext
						 AND BM.IsInContext = 1
					) 
					As AttnNotTakenClass,
				@rUptoDate AS StudentAttendanceDate
				,@rCommonOrgGroupBatchId AS CommonOrgGroupBatchId
				,GetDate() as UpdateDate
				FROM sSetup.tOrgGroupMaster OGM 
				WHERE OGM.Id<>1 AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
			SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND Total !=0
							--END
			
		END
	END

--Organization wise Attendance

ELSE IF @rTypeId=2
    BEGIN
    SELECT 
       OGMT.Id As OrgGroupId,
       OM.Id AS OrgId, 
       OM.Title AS OrgTitle,
       OGMT.Title As OrgGroupTitle,
       
--Total Organization wise
		   (Select count(SM1.ID)
			FROM sStudent.tStudentMaster SM1
				 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
				 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				 INNER JOIN sSetup.tOrganizationMaster OMR ON OM.Id = BM.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId		
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OMR.Id AND COGBM.Id=@rCommonOrgGroupBatchId
			      -- IsInContext
			      AND BM.IsInContext = 1
				 ) as Total,

--PresentStudent Organization wise
		 (SELECT count(*) 
			FROM sAttendance.tStudentRegister SME 
			   INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			   INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
			   INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
			   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
			WHERE OM.Id = OME.Id and SME.IsPresent=1 AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
			AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
			-- IsInContext
			AND BME.IsInContext = 1
			) AS PresentStudent,

--AbsentStudent Organization wise
		  (SELECT count(*) 
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OME.Id AND SME.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
			-- IsInContext
			AND BME.IsInContext = 1
			) AS AbsentStudent,
        
--LessThen70 Organization wise
			(SELECT COUNT(StudentID) 
			   FROM (
				 SELECT   
				   OGMEL.Id as OrgGroupId,
				   OGMEL.Title As OrgGroupTitle,
				   OMEL.Id As OrgId,
				   (OMEL.Title) As OrgTitle ,
				   DM.Code As DivisionCode,
				   (SMD.Id)StudentID,
				   (SMD.FirstName+' '+SMD.LastName) AS StudentName,
					(SC.ParentContactNo) AS ContactNo,
					((COUNT(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
				 FROM sAttendance.tStudentRegister SMEL
					INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
					INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
					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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
					INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1					
					LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			     
				WHERE OM.Id = OMEL.Id AND SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
				AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BMEL.IsInContext = 1
				GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
			   HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
			   ) AS Tmp)  
			   As LessThen70,
        
--HundredPer Organization wise
			 (SELECT COUNT(StudentID) from  (
				 SELECT  
				 OGMEL.Id as OrgGroupId,
				 OGMEL.Title As OrgGroupTitle,
				 OMEL.Id As OrgId,
				 (OMEL.Title) As OrgTitle ,
				 DM.Code As DivisionCode,
				 (SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				 (SC.ParentContactNo) AS ContactNo,
				 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
			 
			 FROM sAttendance.tStudentRegister SMEL
				 INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				 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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
				 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1						
				 LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			     
			 WHERE OM.Id = OMEL.Id AND
				   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
				   AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				   -- IsInContext
				   AND BMEL.IsInContext = 1
			 GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
				
				
			 HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
			 ) AS Tmp)  
			 As HundredPer,
        
--AbsentCount Organization wise
			(SELECT COUNT(AcademicId) FROM(
				SELECT 
				  ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				  AcademicId,
				  AttendanceDate
				FROM sAttendance.tStudentRegister d 
				 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
				 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				 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				
				WHERE OM.Id = OMEL.Id AND
				IsPresent IN(0) 
				AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
				AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
				AND (d.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BMEL.IsInContext = 1
				GROUP BY AcademicId,AttendanceDate
				) as sfsf
				WHERE rowno=3) 
				as AbsentCount,
        
--LeaveRequest Organization wise
			 (SELECT 
				COUNT(AcademicId) AS LeaveRequest
				FROM sAttendance.tStudentLeaveRequest STSL
				  INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
				  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				  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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
				  INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID

				WHERE OM.Id = OMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
				CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
				-- IsInContext
				AND BMEL.IsInContext = 1)
				As LeaveRequest,
        
--AttnNotTakenClass Organization wise
			(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
					 WHERE 
						 OM.Id = OMEL.Id  AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
					(select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126) AND (SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0))
					-- IsInContext
					AND BM.IsInContext = 1
					) 
					As AttnNotTakenClass,
			getdate() AS UpdateDate		  
              
     FROM sSetup.tOrgGroupMaster OGMT 
        INNER join sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId 
        --INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id  Comment for Mantis Id:0036412
     WHERE OGMT.Id=@rOrgGroupId 
	    -- AND U.UserId = @rUserId   Comment for Mantis Id:0036412
    ORDER BY OM.OrderIndex
    END

ELSE IF @rTypeId=11
	BEGIN
     	SELECT OGMR.Id AS OrgGroupId,
			OGMR.Title AS OrgGroupTitle,
			OM.Id As OrgId,(OM.Title) AS OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			0 AS SourceId,
			COUNT(A.StudentID) AS TotalStudent,
			COUNT(CASE WHEN SOD.GenderID=1 then 1 end) AS Male,
			COUNT(CASE WHEN SOD.GenderID=2 then 1 end) AS Female,
			OM.OrderIndex
		FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
		WHERE OGMR.Id=@rOrgGroupId
			AND COGBM.Id=@rCommonOrgGroupBatchId 
			-- IsInContext
			AND BM.IsInContext = 1
		GROUP BY OGMR.Id ,OGMR.Title,OM.Id ,OM.Title,CM.ID,CM.Code,OM.OrderIndex,CM.OrderIndex
		ORDER BY OM.OrderIndex,CM.OrderIndex-- CM.OrderIndex :add for mantis : 0042058	
    END

ELSE IF @rTypeId=21
    BEGIN
		SELECT OGMR.Id as OrgGroupId,
			OGMR.Title As OrgGroupTitle,
			OM.Id As OrgId,(OM.Title) As OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			0 AS SourceId,
			COUNT(A.StudentID) AS TotalStudent,
			COUNT(case when SOD.GenderID=1 then 1 end) AS Male,
			COUNT(case when SOD.GenderID=2 then 1 end) AS Female,
			OM.OrderIndex
		FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
		WHERE OM.Id=@rOrgId
			AND COGBM.Id=@rCommonOrgGroupBatchId
			-- IsInContext
			AND BM.IsInContext = 1 
		GROUP BY OGMR.Id ,OGMR.Title,OM.Id ,OM.Title,CM.ID,CM.Code,OM.OrderIndex
		ORDER BY OM.OrderIndex
     END
     
ELSE IF @rTypeId=12
    BEGIN
		SELECT OGME.Id as OrgGroupId,
			OGME.Title As OrgGroupTitle,
			OME.Id As OrgId,(OME.Title) As OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			0 AS SourceId,
			COUNT(AE.StudentID) AS TotalStudent,
			COUNT(case when SOD.GenderID=1 then 1 end) AS Male,
			COUNT(case when SOD.GenderID=2 then 1 end) AS Female,
			OME.OrderIndex				 
		FROM sAttendance.tStudentRegister SME 
			INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
			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 sSetup.tClassMaster CM ON CM.ID=AE.ClassId
			INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		WHERE OGME.Id=@rOrgGroupId and SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId   
			and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
			-- IsInContext
			AND BME.IsInContext = 1 
		GROUP BY OGME.Id,OGME.Title,OME.Id,OME.Title,CM.ID,CM.Code,OME.OrderIndex,CM.OrderIndex-- CM.OrderIndex :add for mantis : 0042058	
		ORDER BY OME.OrderIndex, CM.OrderIndex -- CM.OrderIndex :add for mantis : 0042058	
	
         
    END
   
ELSE IF @rTypeId=22
	BEGIN
          SELECT 
				OGME.Id as OrgGroupId,OGME.Title As OrgGroupTitle,
				OME.Id As OrgId,(OME.Title) As OrgTitle,
				 CM.ID AS ClassId,CM.Code AS ClassCode,
				 0 AS SourceId,
				COUNT(AE.StudentID) AS TotalStudent,
				COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female
		  FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				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 sSetup.tClassMaster CM ON CM.ID=AE.ClassId
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id 
		  WHERE OME.Id=@rOrgId and SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId  
				AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
				AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BME.IsInContext = 1 
		  GROUP BY OGME.Id,OGME.Title,OME.Id,OME.Title,CM.ID,CM.Code          
	END
   
ELSE IF @rTypeId=13
      BEGIN
      
          SELECT 
				OGMEA.Id as OrgGroupId,
				OGMEA.Title As OrgGroupTitle,
				OME.Id As OrgId,
				(OME.Title) As OrgTitle,
				CM.ID As ClassId,
				CM.Code As ClassCode,
				0 AS SourceId,
				COUNT(AE.StudentID) AS TotalStudent,
			    COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female,
				OME.OrderIndex
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.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 sSetup.tClassMaster CM ON CM.ID=AE.ClassID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
				Left JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			WHERE OGMEA.Id=@rOrgGroupId and SME.IsPresent=0  AND COGBM.Id=@rCommonOrgGroupBatchId  
				 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
				 AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				 -- IsInContext
				 AND BME.IsInContext = 1 
			GROUP BY OGMEA.Id,OGMEA.Title,OME.Id,OME.Title,CM.ID,CM.Code,OME.OrderIndex,CM.OrderIndex-- CM.OrderIndex :add for mantis : 0042058	
			ORDER BY OME.OrderIndex, CM.OrderIndex -- CM.OrderIndex :add for mantis : 0042058	
			
		 
       END
       
ELSE IF @rTypeId=23
       BEGIN
          (SELECT 
				OGMEA.Id as OrgGroupId,
				OGMEA.Title As OrgGroupTitle,
				OME.Id As OrgId,
				(OME.Title) As OrgTitle,
				CM.ID AS ClassId,CM.Code AS ClassCode,
				0 AS SourceId,
				COUNT(AE.StudentID) AS TotalStudent,
				COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female
		   FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.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 sSetup.tClassMaster CM ON CM.ID=AE.ClassId
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		   WHERE OME.Id=@rOrgId 
				AND SME.IsPresent=0 AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId  
				AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BME.IsInContext = 1
		   GROUP BY OGMEA.Id,OGMEA.Title,OME.Id,OME.Title,CM.ID,CM.Code
		  )
    
       END       
       
ELSE IF @rTypeId=14  
      BEGIN
			
       (SELECT *FROM  (
          SELECT 
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				DM.Code As DivisionCode,
				(SMD.Code)StudentID,
				AEL.Id AS SourceId,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
						  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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
					where 
						  OGMEL.Id=@rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						  AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
						  -- IsInContext
						  AND BMEL.IsInContext = 1
						  --GROUP BY SMD.Id
					 GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	   ) AS Tmp) 

      END
   
ELSE IF @rTypeId=24     
      BEGIN

      (SELECT *FROM  (
           SELECT 
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DM.Code As DivisionCode,
              (SMD.Code)StudentID,
        AEL.Id AS SourceId,
              (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			  (SC.ParentContactNo) AS ContactNo
	   FROM sAttendance.tStudentRegister SMEL
			   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
			   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
			   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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
			   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
			   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		WHERE OMEL.Id=@rOrgId AND
		      SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId  
			  AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
			  -- IsInContext
			  AND BMEL.IsInContext = 1
		GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)

	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	 ) AS Tmp) 
		
          
      END   
   
ELSE IF @rTypeId=15
	   BEGIN	
		(SELECT *FROM(
              SELECT  
                  OGMEL.Id as OrgGroupId,
                  OGMEL.Title As OrgGroupTitle,
                  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
                  DM.Code As DivisionCode,
                  (SMD.Code)StudentID,
                  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				  (SC.ParentContactNo) AS ContactNo,
				  AEL.Id AS SourceId
				  ,CM.OrderIndex as ClassOrderIndex	--add for mantis : 0042058
				,DM.OrderIndex AS DivisionOrderIndex	--add for mantis : 0042058
		      FROM sAttendance.tStudentRegister SMEL
				   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				   Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
				   INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId	--add for mantis : 0042058
			   WHERE OGMEL.Id=@rOrgGroupId AND
				   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
				   AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				   -- IsInContext
				   AND BMEL.IsInContext = 1
			   GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
			    ,CM.OrderIndex, DM.OrderIndex--add for mantis : 0042058
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	    ) AS Tmp) 
		 ORDER BY Tmp.ClassOrderIndex, Tmp.DivisionOrderIndex--add for mantis : 0042058
	   END
	   
ELSE IF @rTypeId=25
	BEGIN	
	 (SELECT *FROM(
           SELECT  
                OGMEL.Id as OrgGroupId,
                OGMEL.Title As OrgGroupTitle,
                OMEL.Id As OrgId,
                (OMEL.Title) As OrgTitle,
                DM.Code As DivisionCode,
                (SMD.Code)StudentID,
                (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
				AEL.Id AS SourceId
			FROM sAttendance.tStudentRegister SMEL
				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		    WHERE OMEL.Id=@rOrgId AND
				  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
				  AND (SMEL.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				  -- IsInContext
				  AND BMEL.IsInContext = 1
			GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	  ) AS Tmp) 

	   END
	   	   
ELSE IF @rTypeId=16   
   BEGIN
        
        (SELECT * FROM 
             (SELECT 
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
				DM.Code As DivisionCode,
				(SMD.Code)StudentID,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
						 AEL.Id AS SourceId
			  FROM sAttendance.tStudentLeaveRequest STSL
				INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	
			  WHERE OGMEL.Id=@rOrgGroupId 
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				AND CONVERT(char(10), @rUptoDate,126) between LeaveFromDate 
				AND LeaveToDate
				-- IsInContext
				AND BMEL.IsInContext = 1
		) as a) 
   END
      
ELSE IF @rTypeId=26   
   BEGIN
      
      (SELECT * FROM 
          (SELECT 
			  OGMEL.Id as OrgGroupId,
			  OGMEL.Title As OrgGroupTitle,
			  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
			  DM.Code As DivisionCode,(SMD.Code)StudentID,
			  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			  (SC.ParentContactNo) AS ContactNo,
			  AEL.Id AS SourceId
		   FROM sAttendance.tStudentLeaveRequest STSL 
			   INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
			   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
			   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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
			   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
			   INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID		 
		   WHERE OMEL.Id=@rOrgId 
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				AND CONVERT(char(10), @rUptoDate,126) between LeaveFromDate 
				AND LeaveToDate
				-- IsInContext
				AND BMEL.IsInContext = 1
		) as a) 
   END
   
ELSE IF @rTypeId=17   
   BEGIN
       
       (SELECT OrgGroupId,
                OrgGroupTitle,
                OrgId,
                OrgTitle,
                Code As DivisionCode,
                StudentID,
                SourceId,
                StudentName,
                ContactNo FROM( SELECT ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				AcademicId AS SourceId,
				AttendanceDate, 
				DM.Code,
				(SMD.Code)StudentID,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,(SC.ParentContactNo) As ContactNo
			 FROM sAttendance.tStudentRegister d 							
		 		INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		     WHERE
				OGMEL.Id=@rOrgGroupId AND
				IsPresent IN(0) 
				AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate   
				AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
				AND (d.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BMEL.IsInContext = 1
			 Group By AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName),SC.ParentContactNo 
			 ) as T
		WHERE rowno=3) 
   END
      
ELSE IF @rTypeId=27   
   BEGIN
       
        (SELECT OrgGroupId,
                OrgGroupTitle,
                OrgId,OrgTitle, 
                Code As DivisionCode,SourceId,
                StudentID,StudentName,
                ContactNo  FROM(
			SELECT 
				ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
                AcademicId AS SourceId,AttendanceDate, 
                DM.Code,
                (SMD.Code)StudentID,
                (SMD.FirstName+' '+SMD.LastName) AS StudentName,
                (SC.ParentContactNo) As ContactNo		
			FROM sAttendance.tStudentRegister d 		
		 		INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				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 sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID		
			WHERE
				OMEL.Id=@rOrgId AND
				IsPresent IN(0) 
				AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			    AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
				AND (d.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
				-- IsInContext
				AND BMEL.IsInContext = 1
			Group By AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName),SC.ParentContactNo
			) as sfsf
	   WHERE rowno=3) 
        
   END
   
ELSE IF @rTypeId=18
   BEGIN
			SELECT 
				OrgGroupId,
				OrgGroupTitle,
				OrgId,
				OrgTitle,
				ClassCode,
				StudentCount,
				SourceId,
				ISNULL(TeacherName,'') AS TeacherName,
				ISNULL(ContactNo,'')AS ContactNo  FROM(SELECT 
				O.Id as OrgGroupId,
				O.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				A.ClassId,
				DM.Code AS ClassCode,
				CM.OrderIndex as ClassOrderIndex	--add for mantis : 0042058
				,DM.OrderIndex AS DivisionOrderIndex,	--add for mantis : 0042058
				--(SELECT COUNT(A.Id) FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1 WHERE  
				--DivisionId= DM.Id AND BatchId = BM.Id) AS StudentCount,
				(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A1 ON A1.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM1 ON BM1.Id = A1.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = BM1.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR1 ON OGMR1.Id=OM1.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.Id=BM1.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId
         
					 WHERE 
						 O.Id = OGMR1.Id  and SM1.statusid =1 AND COGBM1.Id=@rCommonOrgGroupBatchId 
						 AND DivisionId= DM.Id AND BatchId = BM.Id AND A1.Id  not in 
					(select AcademicId from sAttendance.tStudentRegister SR1  WHERE SR1.AttendanceDate = CONVERT(char(10),@rUptoDate,126) AND (SR1.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0))
						-- IsInContext
						AND BM1.IsInContext = 1
					) 
					As StudentCount,
				--(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
				A.Id As SourceId,
				(EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.MobileNumber) AS ContactNo,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
			FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				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.tDivisionMaster DM ON DM.Id=A.DivisionId
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId	--add for mantis : 0042058
			WHERE  O.id = @rOrgGroupId AND  ISNULL(EM.IsOtherUser,0) = 0 AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  not in  ( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rUptoDate,126))
				   -- IsInContext
				   AND BM.IsInContext = 1
				) Temp 
		WHERE rowno=1  
		ORDER BY OrgId,
		--ClassCode desc
		ClassOrderIndex, DivisionOrderIndex --add for mantis : 0042058
		
   END
     
ELSE IF @rTypeId=28
   
   BEGIN

	SELECT 
				OrgGroupId,
				OrgGroupTitle,
				OrgId,
				OrgTitle,
				ClassCode,
				StudentCount,
				SourceId,
				ISNULL(TeacherName,'') AS TeacherName,
				ISNULL(ContactNo,'')AS ContactNo  FROM(SELECT 
				O.Id as OrgGroupId,
				O.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				A.ClassId,
				DM.Code AS ClassCode,
				(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
				A.Id As SourceId,
				(EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.MobileNumber) AS ContactNo,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
				FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				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.tDivisionMaster DM ON DM.Id=A.DivisionId
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				WHERE  OMEL.id = @rOrgId AND  ISNULL(EM.IsOtherUser,0) = 0 AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  not in  ( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rUptoDate,126) AND (SR.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0))
				-- IsInContext
				AND BM.IsInContext = 1
				) Temp 
				WHERE 
				rowno=1  
				ORDER BY OrgId,ClassCode desc
	   
   END

ELSE IF @rTypeId=1110
   BEGIN
	  SELECT 
	      (DM.Id) AS DivisionId,
	       SMD.Code As StudentId,
	       A.Id AS SourceId,
	       (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		   (SC.ParentContactNo) AS ContactNo
							
	  FROM sSetup.tDivisionMaster DM
			INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
			INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID and SMD.StatusId=1	
			INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	   WHERE DM.ID=@rDivisionId 
			 AND DM.OrgId=@rOrgId
			 AND BM.IsInContext = 1
	   ORDER BY SMD.Code												          
   END

ELSE IF @rTypeId=1111
	BEGIN
      SELECT 
         (DM.Id) AS DivisionId,
         SMD.Code As StudentId,
         A.Id AS SourceId,
         (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		 (SC.ParentContactNo) AS ContactNo
								
	  FROM sSetup.tDivisionMaster DM
		 INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID and SMD.StatusId=1	
		 INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	   WHERE DM.ID=@rDivisionId 
			AND SOD.GenderID=1 
			AND BM.IsInContext = 1
	   ORDER BY SMD.Code           
	END
	
ELSE IF @rTypeId=1112
	BEGIN	  
	  SELECT 
	    (DM.Id) AS DivisionId,
	    A.Id AS SourceId,
	    SMD.Code As StudentId,
	    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		(SC.ParentContactNo) AS ContactNo								
	  FROM sSetup.tDivisionMaster DM
		INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID and SMD.StatusId=1	
		INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	  WHERE DM.ID=@rDivisionId 
		AND SOD.GenderID=2 
		AND BM.IsInContext = 1
	  ORDER BY SMD.Code
	END 
	
  END
  ELSE
    BEGIN

     if @rTypeId=11 OR @rTypeId=21     
        BEGIN
			SELECT 
				(DM.Id) AS DivisionId,
				DM.Code AS ClassDivision,
				SM.Code As StudentId,
				A.Id AS SourceId,
				(SM.FirstName+' '+SM.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo
				,CM.OrderIndex  AS ClassOrderIndex
				,DM.OrderIndex AS DivisionOrder
			FROM sStudent.tStudentMaster SM 
				INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
				Left JOIN sStudent.tStudentCommunication SC on SM.Id=SC.StudentID
			WHERE 
				((@rOrgGroupId <>0 AND OGMR.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OM.Id=@rOrgId))
				AND DM.ClassId=@rClassId AND COGBM.Id=@rCommonOrgGroupBatchId
				AND ((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0))
				-- IsInContext
				AND BM.IsInContext = 1
		    ORDER BY CM.OrderIndex ,DM.OrderIndex ,SM.Code
        END
        
     ELSE IF @rTypeId=12 OR @rTypeId=22
      
        BEGIN
         
            SELECT 				
			   (DM.Id) AS DivisionId,
			   DM.Code AS ClassDivision,
			    SMD.Code As StudentId,
			    AE.Id AS SourceId,
			    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			    (SC.ParentContactNo) AS ContactNo
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				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 sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
				INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id and SMD.StatusId=1	
				Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			WHERE ((@rOrgGroupId <>0 AND OGME.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OME.Id=@rOrgId))
					AND SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
					AND SME.AttendanceDate=CONVERT(char(10), @rUpToDate,126)
					AND DM.ClassId=@rClassId AND COGBM.Id=@rCommonOrgGroupBatchId  
				    AND((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0))
					AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
					-- IsInContext
					AND BME.IsInContext = 1
			ORDER BY SMD.Code
       END  
    
     ELSE IF @rTypeId=13 OR @rTypeId=23
        BEGIN
         select 
			(DM.Id) AS DivisionId,
			   DM.Code AS ClassDivision,
			    SMD.Code As StudentId,
			    AE.Id AS SourceId,
			    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			    (SC.ParentContactNo) AS ContactNo
		  FROM sAttendance.tStudentRegister SME 
			 INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.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 sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
			 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
			 INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			 Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					
		   WHERE ((@rOrgGroupId <>0 AND OGMEA.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OME.Id=@rOrgId))
					AND SME.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId AND COGBM.Id=@rCommonOrgGroupBatchId  
					AND SME.AttendanceDate=CONVERT(char(10), @rUpToDate,126)--@rUptoDate
					AND DM.ClassId=@rClassId AND ((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0))
					AND (SME.AttendanceTypeId = @rAttendanceTypeId OR @rAttendanceTypeId = 0)
					-- IsInContext
					AND BME.IsInContext = 1
		  ORDER BY SMD.Code
        END
    END
END
GO
PRINT N'Altering Procedure [sBiometric].[pBiometricCloudDetailMappingGet]...';


GO

ALTER PROCEDURE [sBiometric].[pBiometricCloudDetailMappingGet] 
	 @rOrgId INT,
	 @rSourceTypeId INT,
	 @rIsEmpCodeDuplicate BIT = 0,
	 @rIsPuchIdDuplicate BIT = 0,
	--@rIsBiometricIdDuplicate bit = 0,
	 @rIsSourceIdDuplicate BIT = 0,
	 @rIsEmpNameDuplicate BIT = 0,
	 @rClassId INT = 0,
	 @rDivisionId INT = 0,
	 @rBatchId INT = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lQuery NVARCHAR(250)
	DECLARE @lTag NVARCHAR(MAX)
	DECLARE @lHavingQuery NVARCHAR(MAX)
	DECLARE @lHavingQuery1 NVARCHAR(MAX)
	DECLARE @lField NVARCHAR(MAX)
	DECLARE @lFinalQuery NVARCHAR(MAX)

	IF @rIsEmpCodeDuplicate = 1
	BEGIN
		SET @lQuery = 'Code'
		SET @lField = 'Code'
		SET @lTag = 'EmpId'
	END

	IF @rIsPuchIdDuplicate = 1
		AND LEN(@lField) > 1
	BEGIN
		SET @lQuery = @lQuery + ',PunchID'
		SET @lField = 'Punchid'
		SET @lTag = 'EmpPunchID'
	END

	IF @rIsPuchIdDuplicate = 1
		AND @lField IS NULL
	BEGIN
		SET @lQuery = 'PunchID'
		SET @lField = 'Punchid'
		SET @lTag = 'EmpPunchID'
	END

	--IF @rIsBiometricIdDuplicate = 1 AND 	LEN(@lHavingQuery)> 1		
	--BEGIN
	--	SET @lQuery = @lQuery + ',BiometricId'
	--	SET @lHavingQuery = 'BiometricId'
	--END
	--IF @rIsBiometricIdDuplicate = 1 AND 	@lHavingQuery Is Null
	--BEGIN
	--	SET @lQuery = 'BiometricId'
	--	SET @lHavingQuery = 'BiometricId'
	--END
	IF @rIsSourceIdDuplicate = 1
		AND LEN(@lField) > 1
	BEGIN
		SET @lQuery = @lQuery + ',Id'
		SET @lField = 'Id'
		SET @lTag = 'SourceId'
	END

	IF @rIsSourceIdDuplicate = 1
		AND @lField IS NULL
	BEGIN
		SET @lQuery = 'Id'
		SET @lField = 'Id'
		SET @lTag = 'SourceId'
	END

	IF @rIsEmpNameDuplicate = 1
		AND LEN(@lField) > 1
	BEGIN
		SET @lQuery = @lQuery + ',FirstName+ '' ''+LastName'
		SET @lField = 'FirstName+ '' ''+LastName'
		SET @lTag = 'EmpId'
	END

	IF @rIsEmpNameDuplicate = 1
		AND @lField IS NULL
	BEGIN
		SET @lQuery = 'FirstName+ '' ''+LastName'
		SET @lField = 'FirstName+ '' ''+LastName'
		SET @lTag = 'EmpName'
	END

	SET @lHavingQuery = ' AND SM.' + @lField + ' IN (Select ' + @lField + ' AS ' + @lTag + ' FROM sStudent.tStudentMaster   WHERE 
			((SM.OrgId = ' + CONVERT(NVARCHAR(10), @rOrgId) + ') OR (' + CONVERT(NVARCHAR(10), @rOrgId) + ' = 0))
			AND ((2001 = ' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ') OR (' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ' = 0))
			AND StatusId = 1
			AND PunchId is not null
			AND((A.ClassId=' + CONVERT(NVARCHAR(10), @rClassId) + ')OR(' + CONVERT(NVARCHAR(10), @rClassId) + '=0))
			AND((A.DivisionId=' + CONVERT(NVARCHAR(10), @rDivisionId) + ')OR(' + CONVERT(NVARCHAR(10), @rDivisionId) + '=0))
			AND(A.BatchId=' + CONVERT(NVARCHAR(10), @rBatchId) + ' or ' + CONVERT(NVARCHAR(10), @rBatchId) + ' = 0)
			GROUP BY ' + @lQuery + ' Having Count(' + @lField + ') >1'
	SET @lHavingQuery1 = ' AND EM.' + @lField + ' IN (Select ' + @lField + ' AS ' + @lTag + ' FROM sHrm.tEmployeeMaster   WHERE 
			((OrgId = ' + CONVERT(NVARCHAR(10), @rOrgId) + ') OR (' + CONVERT(NVARCHAR(10), @rOrgId) + ' = 0))
			AND ((3 = ' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ') OR (' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ' = 0)) 
			AND StatusId =7
			AND PunchId is not null
			GROUP BY ' + @lQuery + ' Having Count(' + @lField + ') >1'

	IF LEN(@lHavingQuery) > 0
	BEGIN
		SET @lFinalQuery = 'select 
				'''' as BiometricId,
				--SM.Id As EmpId,
				FirstName+ '' ''+LastName AS EmpName, 
				PunchId AS EmpPunchID,
				StatusId as ActiveStatus,
				SM.Id as SourceId,
				SM.OrgId as OrgId ,
				OM.DisplayTitle AS Organization,
				SM.Code AS EmpId,
				CM.DisplayTitle AS ClassName,
				DM.DisplayTitle AS DivisionName,
				'''' AS Dipartment
				
			from sStudent.tStudentMaster SM
			Inner Join sStudent.tAcademic A On SM.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 OM.Id = SM.OrgId 
			where StatusId = 1
				AND PunchId is not null
				AND((A.ClassId=' + CONVERT(NVARCHAR(10), @rClassId) + ')OR(' + CONVERT(NVARCHAR(10), @rClassId) + '=0))
				AND((A.DivisionId=' + CONVERT(NVARCHAR(10), @rDivisionId) + ')OR(' + CONVERT(NVARCHAR(10), @rDivisionId) + '=0))
				AND(A.BatchId=' + CONVERT(NVARCHAR(10), @rBatchId) + ' or ' + 
			CONVERT(NVARCHAR(10), @rBatchId) + ' = 0)
				AND ((SM.OrgId = ' + CONVERT(NVARCHAR(10), @rOrgId) + ') OR (' + CONVERT(NVARCHAR(10), @rOrgId) + ' = 0))
				AND ((2001 = ' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ') OR (' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ' = 0))
				' + @lHavingQuery + ') 
			Union ALL
			select 
				'''' AS BiometricId,
				--EM.Id AS EmpId,
				FirstName+ '' ''+LastName AS EmpName, 
				PunchId AS EmpPunchID,
				StatusId as ActiveStatus,
				EM.Id as SourceId,
				EM.OrgId as OrgId ,
				OM.DisplayTitle AS Organization,
				EM.Code AS EmpId,
				'''' AS ClassName,
				'''' AS DivisionName,
				DM.DisplayTitle AS Dipartment
			from sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId 
			where StatusId = 7
				AND PunchId is not null
				AND ((EM.OrgId = ' + CONVERT(
				NVARCHAR(10), @rOrgId) + ') OR (' + CONVERT(NVARCHAR(10), @rOrgId) + ' = 0))
					AND ((3 = ' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ') OR (' + CONVERT(NVARCHAR(10), @rSourceTypeId) + ' = 0))
					' + @lHavingQuery1 + ') 
				Order By EmpId'

		PRINT (@lFinalQuery)

		EXECUTE (@lFinalQuery)
	END
	ELSE
	BEGIN
		SELECT '' AS BiometricId
			,
			--SM.Id As EmpId,
			FirstName + ' ' + LastName AS EmpName
			,PunchId AS EmpPunchID
			,StatusId AS ActiveStatus
			,SM.Id AS SourceId
			,SM.OrgId AS OrgId
			,OM.DisplayTitle AS Organization
			,SM.Code AS EmpId
			,CM.DisplayTitle AS ClassName
			,DM.DisplayTitle AS DivisionName
			,'' AS Dipartment
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON SM.Id = A.StudentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
		WHERE (
				(SM.OrgId = @rOrgId)
				OR (@rOrgId = 0)
				)
			AND (
				(@rSourceTypeId = 2001)
				OR (@rSourceTypeId = 0)
				)
			AND StatusId = 1
			AND PunchId IS NOT NULL
			AND (
				(A.ClassId = @rClassId)
				OR (@rClassId = 0)
				)
			AND (
				(A.DivisionId = @rDivisionId)
				OR (@rDivisionId = 0)
				)
			AND (
				A.BatchId = @rBatchId
				OR @rBatchId = 0
				)
		
		UNION ALL
		
		SELECT '' AS BiometricId
			,
			--EM.Id AS EmpId,
			FirstName + ' ' + LastName AS EmpName
			,PunchId AS EmpPunchID
			,StatusId AS ActiveStatus
			,EM.Id AS SourceId
			,EM.OrgId AS OrgId
			,OM.DisplayTitle AS Organization
			,EM.Code AS EmpId
			,'' AS ClassName
			,'' AS DivisionName
			,DM.DisplayTitle AS Dipartment
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		WHERE (
				(EM.OrgId = @rOrgId)
				OR (@rOrgId = 0)
				)
			AND (
				(@rSourceTypeId = 3)
				OR (@rSourceTypeId = 0)
				)
			AND StatusId = 7
			AND PunchId IS NOT NULL
		ORDER BY EmpID
	END
END
GO
PRINT N'Altering Procedure [sBiometric].[pCloudTransactionDataAdd]...';


GO
ALTER PROCEDURE [sBiometric].[pCloudTransactionDataAdd]
	@rXmlDoc nvarchar(max) = ''

	AS
	SET NOCOUNT ON

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

	DECLARE @exceptiondetail NVARCHAR(MAX)

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

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

		UNION ALL

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

		--add for mantis: 10346, start
		INSERT INTO sAudit.tActivityLog
		SELECT TOP 1 * FROM
		(SELECT TOP 1 
				OM.OrgGroupId as OrgGroupId,
				EM.OrgId as OrgId,
				3 as UserId,
				'' as SessionId,
				30027 as ScreenId,
				sCommon.fGetDate() as AuditDate,
				'Scheduler-CloudTransactionData' as Activity,
				0 as RecordSourceId,
				'' as RecordDetail,
				3 as OSTypeId
		FROM sBiometric.tCloudTransactionData CTD WITH (NOLOCK)
			INNER JOIN #tTable t ON t.TransactionId = CTD.TransactionId
			INNER JOIN sHrm.tEmployeeMaster EM WITH (NOLOCK) ON EM.PunchId = t.PunchId
			INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = EM.OrgID
		WHERE CTD.SourceTypeId=95 
		
		UNION ALL
		
		SELECT TOP 1 
				OM.OrgGroupId as OrgGroupId,
				SM.OrgId as OrgId,
				3 as UserId,
				'' as SessionId,
				30027 as ScreenId,
				sCommon.fGetDate() as AuditDate,
				'Scheduler-CloudTransactionData' as Activity,
				0 as RecordSourceId,
				'' as RecordDetail,
				3 as OSTypeId
		FROM sBiometric.tCloudTransactionData CTD WITH (NOLOCK)
			INNER JOIN #tTable t ON t.TransactionId = CTD.TransactionId
			INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SM.PunchId = t.PunchId
			INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.Id = SM.OrgId
		WHERE CTD.SourceTypeId=2001
		) d

		--add for mantis: 10346, end

		DROP TABLE #tTable
	COMMIT TRANSACTION
	SELECT 1 AS Result
	END TRY

	BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
		
		SELECT -1 AS Result

		SET @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >
		<tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception ::
		 </td> </tr>
		<tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>
		<td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +','+ '[sBiometric].[tCloudTransactionData]' +'</td></tr>
		</Table>'
		 
		INSERT INTO sSystem.tExceptionLog(OrgGroupId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)
		SELECT 0,'tCloudTransactionData_DbError,'+ ' [sBiometric].[tCloudTransactionData]',ERROR_MESSAGE(),@exceptiondetail,sCommon.fGetDate()	
		RETURN		
    END CATCH
END
GO
PRINT N'Altering Procedure [sCertificate].[pStudentCustomFiledDataGet]...';


GO

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

BEGIN 

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

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

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


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

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

-- Execute the dynamic SQL
	EXEC sp_executesql @sql;

END
GO
PRINT N'Altering Procedure [sCommon].[pScreenGroupDataListGet]...';


GO
ALTER PROCEDURE [sCommon].[pScreenGroupDataListGet]          
           @rScreenGroupId int,
           @rUserId bigint   
AS
SET NOCOUNT ON
 
	BEGIN
	
	IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WITH (NOLOCK) WHERE UserId = @rUserId)
	BEGIN
		Select 
			S.Id AS Id, LEFT(S.Title,40) AS Title, S.IconPath,
			 CASE WHEN S.Id = 20020 THEN Page+'?MenuID=5310'
			      WHEN S.Id = 20033 THEN Page+'?MenuID=5410'
			      WHEN S.Id = 20037 THEN Page+'?MenuID=5111'
			      WHEN S.Id = 20038 THEN Page+'?MenuID=5112'
			      WHEN S.Id = 9018 THEN Page+'?MenuID=331111'
			      --WHEN S.Id = 297 THEN Page+'?MenuID=181115'
			      --WHEN S.Id = 296 THEN Page+'?MenuID=181116'
			      WHEN S.Id = 449 THEN Page+'?MenuID=221214'
			      WHEN S.Id = 5 THEN Page+'?MenuID=161014'
			      WHEN S.Id = 191 THEN Page+'?MenuID=15101015'
			      WHEN S.Id = 32 THEN Page+'?MenuID=141112'			         
			      --WHEN S.Id = 57 THEN Page+'?MenuID=312052'
			   ELSE Page 
			   END AS Page,
			   S.OrderIndex	,			   
			   ISNULL(S.ScreenGroupId,0) AS  ScreenGroupId,
			   T.ResourceTypeId,
			   RTM.Title AS ResourceTypeTitle			  		  
		 From sSecurity.tScreen S WITH (NOLOCK)  
		     INNER JOIN sSecurity.tPermissionUser P WITH (NOLOCK) ON P.TaskId=S.TaskId
		     --INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId
		     INNER JOIN sSecurity.tTask T WITH (NOLOCK) ON T.ID = p.TaskId
		     INNER JOIN sSecurity.tResourceTypeMaster RTM WITH (NOLOCK) ON RTM.ID = T.ResourceTypeId
		     INNER JOIN sSecurity.tOrganizationTask OT WITH (NOLOCK) ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
		     INNER JOIN sSecurity.tModulePermission MP WITH (NOLOCK) ON T.ModuleId = MP.ModuleId And OT.OrgGroupId = MP.OrgGroupId	 
		WHERE (P.Permission & 2) =2
		     AND (ScreenGroupId=@rScreenGroupId OR @rScreenGroupId = 0)
		     -- AND U.IsObsolete=0
		     AND P.UserId=@rUserId 
		     AND T.IsObsolete = 0
		     AND S.IsObsolete = 0
		     AND S.IsHideInScreenGroup = 0	
		--GROUP By S.Title,S.Id,Page,S.OrderIndex,S.IconPath
		Order by RTM.OrderIndex,S.OrderIndex,S.Title 
	END
	ELSE
	BEGIN
		Select 
			S.Id AS Id,
			LEFT(S.Title,40) AS Title, S.IconPath,
			 CASE WHEN S.Id = 20020 THEN Page+'?MenuID=5310'
			      WHEN S.Id = 20033 THEN Page+'?MenuID=5410'
			      WHEN S.Id = 20037 THEN Page+'?MenuID=5111'
			      WHEN S.Id = 20038 THEN Page+'?MenuID=5112'
			      WHEN S.Id = 9018 THEN Page+'?MenuID=331111'
			      --WHEN S.Id = 297 THEN Page+'?MenuID=181115'
			      --WHEN S.Id = 296 THEN Page+'?MenuID=181116'
			      WHEN S.Id = 449 THEN Page+'?MenuID=221214'
			      WHEN S.Id = 5 THEN Page+'?MenuID=161014'  			      
                  WHEN S.Id = 191 THEN Page+'?MenuID=15101015'
			      WHEN S.Id = 32 THEN Page+'?MenuID=141112'
                 --WHEN S.Id = 57 THEN Page+'?MenuID=312052'
			   ELSE Page 
			   END AS Page,
			   S.OrderIndex	,
			   ISNULL( S.ScreenGroupId,0) AS  ScreenGroupId,
			   T.ResourceTypeId,
			   RTM.Title AS ResourceTypeTitle		  
	    From sSecurity.tScreen S WITH (NOLOCK)    
		      INNER JOIN sSecurity.tPermission P WITH (NOLOCK) ON P.TaskId=S.TaskId
		      INNER JOIN sSecurity.tUserRole U WITH (NOLOCK) ON U.RoleId=P.RoleId


		      INNER JOIN sSecurity.tTask T WITH (NOLOCK) ON T.ID = p.TaskId
		      INNER JOIN sSecurity.tResourceTypeMaster RTM WITH (NOLOCK) ON RTM.ID = T.ResourceTypeId
		      INNER JOIN sSecurity.tOrganizationTask OT WITH (NOLOCK) ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
		      INNER JOIN sSecurity.tModulePermission MP WITH (NOLOCK) ON T.ModuleId = MP.ModuleId And OT.OrgGroupId = MP.OrgGroupId	 
		WHERE (P.Permission & 2) =2
		  AND (ScreenGroupId=@rScreenGroupId OR @rScreenGroupId = 0)
		  AND U.IsObsolete=0
		  AND U.UserId=@rUserId 
		  AND T.IsObsolete = 0
		  AND S.IsObsolete = 0
		  AND S.IsHideInScreenGroup = 0		
		  --GROUP By S.Title,S.Id,Page,S.OrderIndex,S.IconPath
		Order by RTM.OrderIndex,S.OrderIndex,S.Title
	END
	END
GO
PRINT N'Altering Procedure [sCommon].[pTableRowIdModify]...';


GO

ALTER PROCEDURE [sCommon].[pTableRowIdModify]
@rOrgGroupId [int],
@rTableTitle [nvarchar](100),
@rCurrentNumber [bigint] = NULL,
@rSeed [bigint] = NULL,
@rIncrement [bigint] = NULL,
@rIsCurrentNumber [bit] = 0,
@rNextNumber [bigint] = NULL OUTPUT

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
Begin tran
declare @exceptiondetail nvarchar(max)
	IF @rCurrentNumber > 0
	BEGIN
		UPDATE sCommon.tTableRowId WITH (rowlock) SET CurrentNumber = @rCurrentNumber
		--,UpdatedDateTime = sCommon.fGetDate() 
		WHERE TableTitle = @rTableTitle AND OrgId = @rOrgGroupId
	END
	ELSE
	BEGIN 
		UPDATE sCommon.tTableRowId WITH (rowlock) 
		SET @rNextNumber = CurrentNumber = (CASE @rIsCurrentNumber WHEN 1 THEN CurrentNumber ELSE 
		                                   (CASE WHEN CurrentNumber < Seed THEN Seed ELSE CurrentNumber + Increment END) END),
		Seed = ISNULL(@rSeed, Seed),
		Increment = ISNULL(@rIncrement, Increment),
		UpdatedDateTime = sCommon.fGetDate()
		WHERE TableTitle = @rTableTitle AND OrgId = @rOrgGroupId
	END
	commit tran
END TRY
BEGIN CATCH
 	
rollback tran
set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >
<tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception ::
 </td> </tr>
<tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>
<td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +','+ @rTableTitle +'</td></tr>
</Table>'
 
		insert into sSystem.tExceptionLog(OrgGroupId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)
		Select @rOrgGroupId,'TableRowId_DBError,'+ @rTableTitle,ERROR_MESSAGE(),@exceptiondetail,sCommon.fGetDate()	
Return
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

DECLARE @lIsEnableLog bit = 0 -- Set to 1 If want to add log for receipt add process

BEGIN
	BEGIN TRY
		
		IF(@lIsEnableLog = 1)
		BEGIN
		 INSERT INTO [sFee].[tFeeReceiptLog]
		 VALUES (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			    ,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			    ,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			    ,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt SP Main Process Start')
		END

		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 WITH (NOLOCK) 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 WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
					BEGIN
						SELECT -102 AS Result
						RETURN	
					END
				END
				-- #Start Mantis Id : 0036287
				ELSE IF(@lConfigValue='Continuous Batch')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId)
					BEGIN
						SELECT -102 AS Result
						RETURN	
					END
				END
				-- #End Mantis Id : 0036287

				-- Mantis - 0030695
				IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ChequeNo=@rChequeNo)
					BEGIN
						SELECT -103 AS Result
						RETURN	
					END
				END
				-- Mantis - 0030695

				-- For Mantis 0038951, By Foram
				IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WITH (NOLOCK) WHERE BatchId = @rBatchId AND OrgGroupBatchId = @rOrgGroupBatchId 
														AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId AND ReceiptBookId = @rReceiptBookId 
														AND PayTypeId = @rPayTypeId AND ChequeNo = @rChequeNo AND BankName = @rBankName AND Amount = @rTotalReceiptAmount AND ReceiptId > 0)
				BEGIN
					SELECT -104 AS Result
					RETURN	
				END
				-- For Mantis 0038951, By Foram
			END
			ELSE
			BEGIN
				IF(@lConfigValue='ReceiptBookWise')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) 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 WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId AND Id != @rId)
					BEGIN
						SELECT -102 AS Result
						RETURN	
					END
				END
				-- #Start Mantis Id : 0036287
				ELSE IF(@lConfigValue='Continuous Batch')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND Id != @rId)
					BEGIN
						SELECT -102 AS Result
						RETURN	
					END
				END
				-- #End Mantis Id : 0036287

				-- Mantis - 0030695
				IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
				BEGIN
					IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) 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	

		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			 VALUES
			 (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt No Generated and pReceiptAddValidate SP Start')
		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(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			 VALUES
			 (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pReceiptAddValidate SP End : ' + CAST(@lIsCreated AS NVARCHAR(10)))
		END

		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
	END TRY
	BEGIN CATCH 
		SELECT -1 AS Result, ERROR_Message()
	END CATCH	

	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		
		--Added By Dhruv
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) 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 WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		--Added By Dhruv

		-- #Start Mantis Id : 0036287
			ELSE IF(@lConfigValue='Continuous Batch')
			BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
			-- #End Mantis Id : 0036287

		-- Mantis - 0030695
		IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ChequeNo=@rChequeNo)
			BEGIN
				SELECT -103 AS Result
				RETURN	
			END
		END
		-- Mantis - 0030695

		-- For Mantis 0038951, By Foram
		IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WITH (NOLOCK) WHERE BatchId = @rBatchId AND OrgGroupBatchId = @rOrgGroupBatchId 
												AND SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId AND ReceiptBookId = @rReceiptBookId 
												AND PayTypeId = @rPayTypeId AND ChequeNo = @rChequeNo AND BankName = @rBankName AND Amount = @rTotalReceiptAmount AND ReceiptId > 0)
		BEGIN
			SELECT -104 AS Result
			RETURN	
		END
		-- For Mantis 0038951, By Foram

		Declare @lSourceTypeId int 
		SET @lSourceTypeId =(select ISNULL(SourceTypeId,0) from sSecurity.tUser WITH (NOLOCK) 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 

		

		BEGIN TRANSACTION

		DECLARE @lNextNumber BIGINT  , @lMaxReceiptId bigint = 0  
		--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output
		SELECT @lMaxReceiptId = ISNULL(MAX(R.Id), 0) FROM sFee.tReceipt R WITH (NOLOCK) INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK)  ON BM.id = R.BatchId WHERE Bm.OrgId = @rOrgId

		IF EXISTS(SELECT 1 FROM sAudit.tReceiptDelete RD WITH (NOLOCK) INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK)  ON BM.Id = RD.BatchId WHERE BM.OrgId = @rOrgId AND RD.Id > @lMaxReceiptId)
		BEGIN
			SELECT @lMaxReceiptId = ISNULL(MAX(RD.Id), 0) FROM sAudit.tReceiptDelete RD WITH (NOLOCK) INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK)  ON BM.Id = RD.BatchId WHERE Bm.OrgId = @rOrgId
		END

		IF(@lMaxReceiptId = 0)
		BEGIN
			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				VALUES
				(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
					,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
					,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
					,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pTableRowIdGet SP Start')
			END

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

			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				 VALUES
				 (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
					,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
					,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
					,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),CAST(@lNextNumber AS NVARCHAR(100))+'-pTableRowIdGet SP End & Receipt Add Start')
			END
		END
		ELSE
		BEGIN
			SET @lNextNumber =  @lMaxReceiptId + 1 
		END
		
	
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			 VALUES
			 (@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),CAST(@lNextNumber AS NVARCHAR(100))+'- ReceiptId - Receipt Add Start')
		END

		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
		   --Added for default value
		    ,IsChequeCleared
			,ChequeClearDate
			,AmountAfterDiscount
			,CGSTPercentage
			,SGSTPercentage
			,CGSTAmount
			,SGSTAmount
			,CancelStatusId
			,CancelStatusRemark
			,FirmReceiptBookId
			,TaxPercentage
			,CancelDateTime
        )
		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
			,0,NULL,0,0,0,0,0,0,NULL,0,0,NULL
		)
		
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt Add End and Receipt Detail Start') 
		END

		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		 IF(@lIsEnableLog = 1)
		         BEGIN
		         	INSERT INTO [sFee].[tFeeReceiptLog]
		         	VALUES
		         	(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
		         	,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
		         	,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
		         	,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt Detail End') 
		         END

		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
	    IF (@rCharge > 0)
		BEGIN
		    IF(@lIsEnableLog = 1)
		    BEGIN
		    	INSERT INTO [sFee].[tFeeReceiptLog]
		    	VALUES
		    	(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
		    	,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
		    	,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
		    	,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Charge Add Start') 
		    END
			
			EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@lCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
			
			IF(@lIsEnableLog = 1)
		    BEGIN
		    	INSERT INTO [sFee].[tFeeReceiptLog]
		    	VALUES
		    	(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
		    	,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
		    	,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
		    	,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Charge Add End') 
		    END
		END
			
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) 
		FROM sFee.tReceiptBookMaster WITH (NOLOCK) where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				VALUES
				(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pReceiptServiceTaxAdd SP Add Start')
			END

			EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@lCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
			
			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				VALUES
				(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pReceiptServiceTaxAdd SP Add End')
			END
		END

	    IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pFeeProcessGeneratePaidFeeAdd SP Start')
		END
		
		EXEC [sFee].[pFeeProcessGeneratePaidFeeAdd] @rOrgId,@rBatchId,@rSourceId,@lNextNumber,@lCreatedUserId
		
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'pFeeProcessGeneratePaidFeeAdd SP End')
		END
			
		SET @rId = @lNextNumber

		-- 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 WITH (NOLOCK) 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

		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'PDC Entry Done')
		END

		COMMIT TRANSACTION
	END 
	ELSE
	BEGIN
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Fee Receipt Update Start')
		END

		IF EXISTS(SELECT 1 FROM sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND Id = @rId)
		BEGIN
			BEGIN TRANSACTION
				UPDATE sFee.tReceipt SET
					ReceiptDate=@rReceiptDate,
					PayTypeId=@rPayTypeId,
					ChequeDate=@rChequeDate,
					ChequeNo=@rChequeNo,
					BankName=@rBankName,
					Remark=@rRemark
				WHERE Id=@rId

				-- For Mantis 0023321 By Foram on 14/03/2024 START
				DECLARE @lSourceId_1 bigint, @lSourceTypeId1_1 smallint, @lBatchId_1 int, @lOrgGroupBatchId_1 int, @lReceiptBookId_1 int, 
						@lPayTypeId_1 smallint, @lChequeNo_1 nvarchar(40), @lBankName_1 nvarchar(200), @lTotalReceiptAmount_1 decimal(12,2)

				SELECT
					@lSourceId_1 = SourceId, 
					@lSourceTypeId1_1 = SourceTypeId, 
					@lBatchId_1 = BatchId, 
					@lOrgGroupBatchId_1 = OrgGroupBatchId, 
					@lReceiptBookId_1 = ReceiptBookId, 
					@lPayTypeId_1 = PayTypeId, 
					@lChequeNo_1 = ChequeNo, 
					@lBankName_1 = BankName, 
					@lTotalReceiptAmount_1 = TotalReceiptAmount
				FROM sFee.tReceipt WHERE Id = @rId

				IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WITH (NOLOCK) WHERE BatchId = @lBatchId_1 AND OrgGroupBatchId = @lOrgGroupBatchId_1
																AND SourceTypeId = @lSourceTypeId1_1 AND SourceId = @lSourceId_1 AND ReceiptBookId = @lReceiptBookId_1 
																AND PayTypeId = @lPayTypeId_1 AND ChequeNo = @lChequeNo_1 AND BankName = @lBankName_1 AND Amount = @lTotalReceiptAmount_1)
				BEGIN
					UPDATE sFee.tPostDatePayment 
					SET ReceiptId = @rId, ReceiptDate = @rReceiptDate, StatusId = 752 
					WHERE BatchId = @lBatchId_1 AND OrgGroupBatchId = @lOrgGroupBatchId_1 
						AND SourceTypeId = @lSourceTypeId1_1 AND SourceId = @lSourceId_1 AND ReceiptBookId = @lReceiptBookId_1 
						AND PayTypeId = @lPayTypeId_1 AND ChequeNo = @lChequeNo_1 AND BankName = @lBankName_1 AND Amount = @lTotalReceiptAmount_1
				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
		
			SELECT @rId AS RESULT
		END
		ELSE
		IF(@rReceiptNumber <> 0)
		BEGIN
			IF(@lConfigValue='ReceiptBookWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) 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 WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END

		-- #Start Mantis Id : 0036287
			ELSE IF(@lConfigValue='Continuous Batch')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			-- #End Mantis Id : 0036287

		-- Mantis - 0030695
			IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt WITH (NOLOCK) where ChequeNo=@rChequeNo AND Id != @rId)
				BEGIN
					SELECT -103 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695

			BEGIN TRANSACTION

				UPDATE sFee.tReceipt SET
					ReceiptNumber = @rReceiptNumber,
					ReceiptDate=@rReceiptDate,
					PayTypeId=@rPayTypeId,
					ChequeDate=@rChequeDate,
					ChequeNo=@rChequeNo,
					BankName=@rBankName,
					Remark=@rRemark
				WHERE Id=@rId
		
				-- For Mantis 0023321 By Foram on 14/03/2024 START
				DECLARE @lSourceId_2 bigint, @lSourceTypeId1_2 smallint, @lBatchId_2 int, @lOrgGroupBatchId_2 int, @lReceiptBookId_2 int, 
						@lPayTypeId_2 smallint, @lChequeNo_2 nvarchar(40), @lBankName_2 nvarchar(200), @lTotalReceiptAmount_2 decimal(12,2)

				SELECT
					@lSourceId_2 = SourceId, 
					@lSourceTypeId1_2 = SourceTypeId, 
					@lBatchId_2 = BatchId, 
					@lOrgGroupBatchId_2 = OrgGroupBatchId, 
					@lReceiptBookId_2 = ReceiptBookId, 
					@lPayTypeId_2 = PayTypeId, 
					@lChequeNo_2 = ChequeNo, 
					@lBankName_2 = BankName, 
					@lTotalReceiptAmount_2 = TotalReceiptAmount
				FROM sFee.tReceipt WHERE Id = @rId

				IF EXISTS(SELECT 1 FROM sFee.tPostDatePayment WITH (NOLOCK) WHERE BatchId = @lBatchId_2 AND OrgGroupBatchId = @lOrgGroupBatchId_2
																AND SourceTypeId = @lSourceTypeId1_2 AND SourceId = @lSourceId_2 AND ReceiptBookId = @lReceiptBookId_2 
																AND PayTypeId = @lPayTypeId_2 AND ChequeNo = @lChequeNo_2 AND BankName = @lBankName_2 AND Amount = @lTotalReceiptAmount_2)
				BEGIN
					UPDATE sFee.tPostDatePayment 
					SET ReceiptId = @rId, ReceiptDate = @rReceiptDate, StatusId = 752 
					WHERE BatchId = @lBatchId_2 AND OrgGroupBatchId = @lOrgGroupBatchId_2
						AND SourceTypeId = @lSourceTypeId1_2 AND SourceId = @lSourceId_2 AND ReceiptBookId = @lReceiptBookId_2 
						AND PayTypeId = @lPayTypeId_2 AND ChequeNo = @lChequeNo_2 AND BankName = @lBankName_2 AND Amount = @lTotalReceiptAmount_2
				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
								
				SELECT @rId AS RESULT
			COMMIT TRANSACTION 
		END
	
			IF(@lIsEnableLog = 1)
			BEGIN
				INSERT INTO [sFee].[tFeeReceiptLog]
				VALUES
				(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
				,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
				,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
				,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Fee Receipt Update End')
			END
		END
	
	IF(@lIsEnableLog = 1)
	BEGIN
		INSERT INTO [sFee].[tFeeReceiptLog]
		VALUES
		(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
		,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
		,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
		,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),'Receipt SP Main Process End')
	END
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		IF(@lIsEnableLog = 1)
		BEGIN
			INSERT INTO [sFee].[tFeeReceiptLog]
			VALUES
			(@rOrgId,@rId,@rSourceTypeId,@rSourceId,@rReceiptNumber,@rReceiptDate,@rReceiptAmount
			,@rTotalReceiptAmount,@rDiscountAmount,@rPayTypeId,@rChequeNo,@rBankName,@rReceiptBookId,@rIsObsolete,@rCreatedUserId
			,@rBatchId,@rOrgGroupBatchId,@rRemark,@rReceiptDetailXml,@rChequeDate,@rCharge,@rFeeInvoiceId,@rCollectionGroupId
			,@rDepositedLedgerId,@rPaymentTransactionId,@rReceiptPrintGroupId,@rIsDiscountCoupon,GETDATE(),Error_Message())
			SELECT -1 AS Result, ERROR_Message()
		END
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sLibrary].[pMyBookLogAdd]...';


GO
ALTER PROCEDURE [sLibrary].[pMyBookLogAdd]
		--@rId bigint,
        @rReaderSourceTypeId smallint,
		@rReaderSourceId bigint,
		@rResourceSourceTypeId smallint,
		@rResourceSourceId bigint,
		@rLogDate date,
		@rDueDate date,
		@rStatusId smallint,
		@rRemark nvarchar(150),
		@rIsCurrentStatus bit,
		@rOrgId smallint,
		@rBatchId int,
		@rCreatedUserId bigint,
		@rLibraryId int,
		@rBookActionStatusId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
	--IF (@rId = 0)
	--BEGIN
	--add for mantis: 43750, start
	DECLARE @lReserveDays int=0
	DECLARE @Temp TABLE (NoOfBookIssuable smallint, IssueDays smallint, PenaltyPerDay decimal(12,2), ReserveDays smallint)
	INSERT INTO @Temp exec sLibrary.pIssueSettingDetailGet @rReaderSourceTypeId,@rReaderSourceId,@rOrgId,@rBatchId,@rLibraryId
	SELECT @lReserveDays = ReserveDays FROM @Temp
	--add for mantis: 43750, end

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

	UPDATE sLibrary.tBookLog
	    SET
			IsCurrentStatus=0,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
		WHERE ResourceSourceTypeId = @rResourceSourceTypeId AND ResourceSourceId = @rResourceSourceId
		--AND LibraryId = @rLibraryId


	INSERT INTO sLibrary.tBookLog
		(
			Id,
			ReaderSourceTypeId,
			ReaderSourceId,
			ResourceSourceTypeId,
			ResourceSourceId,
			LogDate,
			DueDate,
			StatusId,
			Remark,
			IsCurrentStatus,
			OrgId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			LibraryId,
			BookActionStatusId
		)
	VALUES
		(
			@lNextNumber,
			@rReaderSourceTypeId,
			@rReaderSourceId,
			@rResourceSourceTypeId,
			@rResourceSourceId,
			ISNULL(@rLogDate,sCommon.fGetDate()),
			--mantis: 43750, comment below line and add new line below it
			--ISNULL(@rDueDate,sCommon.fGetDate()),
			ISNULL(@rDueDate,DATEADD(DAY,@lReserveDays,sCommon.fGetDate())), --mantis: 43750
			@rStatusId,
			@rRemark,
			@rIsCurrentStatus,
			@rOrgId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLibraryId,
			@rBookActionStatusId
		)
		    SELECT @lNextNumber AS Result

	--END
	--ELSE
	-- BEGIN
	-- SET @lNextNumber = @rId
	--    UPDATE sLibrary.tBookLog
	--    SET
	--		ReaderSourceTypeId=@rReaderSourceTypeId,
	--		ReaderSourceId=@rReaderSourceId,
	--		ResourceSourceTypeId=@rResourceSourceTypeId,
	--		ResourceSourceId=@rResourceSourceId,
	--		LogDate=@rLogDate,
	--		DueDate=@rDueDate,
	--		StatusId=@rStatusId,
	--		Remark=@rRemark,
	--		IsCurrentStatus=@rIsCurrentStatus,
	--		UpdatedUserId=@rCreatedUserId,
	--		UpdatedDateTime=sCommon.fGetDate()

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


GO
ALTER PROCEDURE [sPayroll].[pPayrollGenerateReport]
	
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'Code',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',	 
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rPayrollId int,
	@rSalaryYear int,
	@rSalaryMonth int=0,
	@rIsCommonForOrg bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate='0001-01-01'
	IF(@rDOJFromDate IS NULL)
		SET @rDOJFromDate='0001-01-01'
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate='9999-12-31'
	IF(@rDOJToDate IS NULL)
		SET @rDOJToDate='9999-12-31'
	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sPayroll.tPayrollCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sPayroll.tPayrollCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrgId,
			Code,
			FirstName,	
			LastName,
			EmployeeTypeId,
			StatusId,
			OrganizationDepartmentId,
			ReligionId,
			MaritalStatusId,
			Qualification,
			GenderId,
			EmployeeDesignationId,
			BloodGroupId,	 
			DOBFromDate,
			DOBToDate,
			DOJFromDate,
			DOJToDate,
			IsCommon,
			CreatedUserId,
			CreatedDateTime,
			IsCommonForOrg
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrgId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rEmployeeTypeId,
			@rStatusId,
			@rOrganizationDepartmentId,
			@rReligionId,
			@rMaritalStatusId,
			@rQualification,
			@rGenderId,
			@rEmployeeDesignationId,
			@rBloodGroupId,	 
			@rDOBFromDate,
			@rDOBToDate,
			@rDOJFromDate,
			@rDOJToDate,
			@rIsCommon,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsCommonForOrg
		) 
	END
	
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rEmployeeTypeId=EmployeeTypeId,
				@rStatusId=StatusId,
				@rOrganizationDepartmentId=OrganizationDepartmentId,
				@rReligionId=ReligionId,
				@rMaritalStatusId=MaritalStatusId,
				@rQualification=Qualification,
				@rGenderId=GenderId,
				@rEmployeeDesignationId=EmployeeDesignationId,
				@rBloodGroupId=BloodGroupId,	 
				@rDOBFromDate=DOBFromDate,
				@rDOBToDate=DOBToDate,
				@rDOJFromDate=DOJFromDate,
				@rDOJToDate=DOJToDate
		FROM
			sPayroll.tPayrollCustomSearch
		WHERE
			Id=@rId
	END
	
	DECLARE @Sql nvarchar(MAX)
	SET @rColumnName=Replace(@rColumnName,'Code','Code')
	SET @rOrderBy=Replace(@rOrderBy,'Code','Code')
	SET  @rColumnName = Replace(@rColumnName,'Caste','Cast')
 
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)

	DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
	select @cols = STUFF((SELECT ',' + QUOTENAME(PED.Title,'[]'), '' AS EmployeeId, '' AS SalaryMonth
                    from sPayroll.tPayProcess PP 
                    INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.Id
                    INNER JOIN sPayroll.tPayProcessElement PPEl ON PPEl.PayProcessEmployeeId = PPE.ID
                    INNER JOIN sPayroll.tPayElement PE ON PE.ID = PPEl.PayElementId
					LEFT JOIN [sPayroll].[tPayElementDefault] PED ON PED.Id = PE.PayElementDefaultId
                    WHERE PE.PayrollId = @rPayrollId AND PP.SalaryYear = @rSalaryYear
                    group by PED.Title
                    order by PED.Title
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

    IF(@cols IS NOT NULL)
    BEGIN    
		
		--mantis: 43241, add below if condition only
		IF OBJECT_ID('sPayroll.tTempPayrol3','U') is not null
		BEGIN
			DROP TABLE sPayroll.tTempPayrol3
		END

		set @query = 'SELECT SalaryMonth AS SalaryMonth, EmployeeId AS EmployeeId1 ,' + @cols + ',NetAmount into sPayroll.tTempPayrol3 from 
             (
                select PP.SalaryMonth, PPE.EmployeeId, PPEl.Amount,PPE.NetAmount,
                PE.Title
                FROM
                sPayroll.tPayProcess PP 
                    INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.Id
                INNER JOIN sPayroll.tPayProcessElement PPEl ON PPEl.PayProcessEmployeeId = PPE.ID
                INNER JOIN sPayroll.tPayElement PE ON PE.ID = PPEl.PayElementId
                 WHERE PE.PayrollId = '+CONVERT(nvarchar,@rPayrollId)+'
                    AND PP.SalaryYear = '+CONVERT(nvarchar,@rSalaryYear)+'
            ) x 
            pivot 
            (
                SUM(Amount)
                for  Title in (' +@cols  + ')
            ) p '
         
         print   @query 
	    execute(@query)
		
		SELECT 
			* into sPayroll.tTempPayroll
		FROM 
			sPayroll.vPayrollCustomSearch PCS 
			INNER JOIN sPayroll.tTempPayrol3 t3 ON PCS.EmployeeId = t3.EmployeeId1
		WHERE 
			((PCS.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND PCS.PayrollId = @rPayrollId 
			AND ((PCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((PCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((PCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ISNULL(PCS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
			AND ((ISNULL(PCS.DateOfBirth,'') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
			AND ((ISNULL(PCS.DateOfBirth,'') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
			AND ((ISNULL(PCS.DateOfJoining,'') >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
			AND ((ISNULL(PCS.DateOfJoining,'') <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))	
			
			AND (ISNULL(PCS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
			
			AND (ISNULL(PCS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
			
		    AND (ISNULL(PCS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 
			
		    AND (ISNULL(PCS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
			
		    AND (ISNULL(PCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
			   
		    AND (ISNULL(PCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
			        
		    AND (ISNULL(PCS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
			 
		    AND (ISNULL(PCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
	
			AND ((PCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ISNULL(PCS.IsOtherUser,0) = 0
			
		SET @sql='SELECT '+ @rColumnName  +' FROM sPayroll.tTempPayroll ORDER BY '+@rOrderBy
		exec(@Sql)
		
		
		DROP Table sPayroll.tTempPayrol3
	END
	ELSE
	BEGIN
	
		--mantis: 43241, add below if condition only
		IF OBJECT_ID('sPayroll.tTempPayroll','U') is not null
		BEGIN
			DROP TABLE sPayroll.tTempPayroll
		END

		SELECT 
			0 AS NetAmount ,* into sPayroll.tTempPayroll
		FROM 
			sPayroll.vPayrollCustomSearch PCS 
		WHERE 
			((PCS.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND PCS.PayrollId = @rPayrollId 
			AND ((PCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((PCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((PCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ISNULL(PCS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
			AND ((ISNULL(PCS.DateOfBirth,'') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
			AND ((ISNULL(PCS.DateOfBirth,'') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
			AND ((ISNULL(PCS.DateOfJoining,'') >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
			AND ((ISNULL(PCS.DateOfJoining,'') <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))	
			
			AND (ISNULL(PCS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
			
			AND (ISNULL(PCS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
			
		    AND (ISNULL(PCS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 
			
		    AND (ISNULL(PCS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
			
		    AND (ISNULL(PCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
			   
		    AND (ISNULL(PCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
			        
		    AND (ISNULL(PCS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
			 
		    AND (ISNULL(PCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
	
			AND ((PCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ISNULL(PCS.IsOtherUser,0) = 0
			
		SET @sql='SELECT '+ @rColumnName  +' FROM sPayroll.tTempPayroll ORDER BY '+@rOrderBy
		exec(@Sql)
	END	
	DROP Table sPayroll.tTempPayroll	
END
GO
PRINT N'Altering Procedure [sPayroll].[pPaySetupAdd]...';


GO
ALTER PROCEDURE [sPayroll].[pPaySetupAdd] 
	      
	        @rID int
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rPayElementId int
           ,@rAmount decimal(22,6)
           ,@rPercentage decimal(5,2)
           ,@rProcessOrder tinyint
           ,@rOrgGroupId int
           ,@rIsObsolete bit
           ,@rPayrollId int
           ,@rOrderIndex int=0
           ,@rPayrollYearId int=0
           ,@rDefaultAmount decimal(22,2)=0
		   ,@rFormula nvarchar(200)=''
           
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	--Mantis Start - 43837
	IF EXISTS(select 1 from [sPayroll].[tPaySetup] where SourceTypeId=@rSourceTypeId and SourceId=@rSourceId and ProcessOrder=@rProcessOrder and PayrollId=@rPayrollId and PayrollYearId=@rPayrollYearId and Id <> @rID)
	BEGIN
		SELECT -101 AS Result
		return
	END
	--Mantis End - 43837
	BEGIN TRY
	BEGIN TRANSACTION  
	DECLARE @lNextNumber BIGINT
	
  IF(@rIsObsolete = 0 AND @rId > 0)
  BEGIN
    SET @lNextNumber = 1
    DELETE FROM sPayroll.tPaySetup Where SourceId = @rSourceId AND SourceTypeId = @rSourceTypeId AND PayElementId = @rPayElementId AND PayrollId = @rPayrollId
      
  END
 
  ELSE	
  
  BEGIN
  IF (@rId = 0 AND @rIsObsolete = 1)
    
    BEGIN	
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPaySetup', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sPayroll].[tPaySetup]
           ([ID]
           ,[SourceTypeId]
           ,[SourceId]
           ,[PayElementId]
           ,[Amount]
           ,[Percentage]
           ,[ProcessOrder]
           ,[PayrollId]
           ,[OrderIndex]
           ,[PayrollYearId]
           ,[DefaultAmount]
		   ,[Formula]
           )
     VALUES
           (
			@lNextNumber 
		   ,@rSourceTypeId 
		   ,@rSourceId 
		   ,@rPayElementId 
		   ,@rAmount 
		   ,@rPercentage 
		   ,@rProcessOrder 
		   ,@rPayrollId
		   ,@rOrderIndex
		   ,@rPayrollYearId
		   ,@rDefaultAmount
		   ,@rFormula
           )
    	END
    ELSE
		BEGIN    
		     SET @lNextNumber = @rId
		     UPDATE  [sPayroll].[tPaySetup]
			   SET       
				  [PayElementId] = @rPayElementId
				  ,[Amount] = @rAmount
				  ,[Percentage] = @rPercentage
				  ,[ProcessOrder] = @rProcessOrder
				  ,[PayrollId] = @rPayrollId
				  ,[OrderIndex] = @rOrderIndex
				  ,[PayrollYearId] = @rPayrollYearId
				  ,DefaultAmount=@rDefaultAmount
				  ,[Formula]=@rFormula
			WHERE Id = @rId		
		END 
		
 
		IF EXISTS(SELECT 1 FROM sPayroll.tPayElement WHERE ID=@rPayElementId  AND PayrollId =@rPayrollId AND IsEmployeeSpecific = 1   )
	 	BEGIN
			UPDATE sPayroll.tPaySetup
			   SET       
				  ProcessOrder = @rProcessOrder
			WHERE 	SourceTypeId = 95 AND PayElementId=@rPayElementId AND PayrollId =@rPayrollId AND PayrollYearId=@rPayrollYearId 
		END
		
	END       
	SELECT @lNextNumber AS Result	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	 RAISERROR ('Error Creating Pay Set Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH	
END
GO
PRINT N'Altering Procedure [sSecurity].[pUserLogAdd]...';


GO
ALTER PROCEDURE [sSecurity].[pUserLogAdd]
	@rOrgId int,
	@rUserId bigint,
	@rLoggedInIp [nvarchar](15),
	@rIsOnlinep [bit],
	@rLoggedInDateTime [datetime],
	@rLoggedOutDateTime [datetime],
	@rUiCultureIdp [tinyint],
	@rSessionIdp [nvarchar](100),
	@rLocalAddress [nvarchar](200)='',
	@rOSTypeId [tinyint]=0,
	@rDeviceUniqueId [nvarchar](100)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lIsLogEnable bit = 0

IF(@lIsLogEnable = 1)
BEGIN
	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('sSecurity.pUserLogAdd Start', 
	'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
	+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionIdp AS nvarchar(100)), 
	'', '', GETDATE(), 'sSecurity.pUserLogAdd')
END

DECLARE @lNextNumber BIGINT
EXECUTE sCommon.pTableRowIdGet @rOrgId,'sSecurity.tUserLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	--SELECT @lNextNumber

IF(@lIsLogEnable = 1)
BEGIN
	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('sSecurity.pUserLogAdd Table Row Id Generated', 
	'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
	+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionIdp AS nvarchar(100)), 
	CAST(@lNextNumber AS NVARCHAR(100)), '', GETDATE(), 'sSecurity.pUserLogAdd')
END

BEGIN
	INSERT INTO sSecurity.tUserLog WITH (ROWLOCK)
		(
			OrgId,
			Id,
			UserId,
			LoggedInIp,
			LoggedInDateTime,
			LoggedOutDateTime,
			IsOnline,
			UiCultureId,
			SessionId,
			LoggedInLocalIp,
			OSTypeId,
			DeviceUniqueId
		)
	VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rUserId,
			@rLoggedInIp,
			@rLoggedInDateTime,
			@rLoggedOutDateTime,
			@rIsOnlinep,
			@rUiCultureIdp,
			@rSessionIdp,
			@rLocalAddress,
			@rOSTypeId,
			@rDeviceUniqueId
		)

IF(@lIsLogEnable = 1)
BEGIN
	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('sSecurity.pUserLogAdd End', 
	'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
	+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionIdp AS nvarchar(100)), 
	'', '', GETDATE(), 'sSecurity.pUserLogAdd')
END

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


GO
ALTER PROCEDURE [sSecurity].[pUserValidate]
	@rOrgId int,
	@rUserTitle [nvarchar](100),
	@rUserPassword [nvarchar](1000),
	@rHostAddress [nvarchar](100),	
	@rSessionId [nvarchar](100),
	@rLocalAddress [nvarchar](100)='',
	@rOSTypeId [tinyint]=0,
	@rDeviceUniqueId [nvarchar](100)=''
	
WITH EXECUTE AS CALLER
AS

DECLARE @lIsLogEnable bit = 0

DECLARE @lUserId BIGINT
SET @lUserId = 0

DECLARE @lSourceTypeId SMALLINT
SET @lSourceTypeId = 0

DECLARE @lLoginAttempts INT	
SET @lLoginAttempts = 0

DECLARE @lLoginDateTime DateTime
SET @lLoginDateTime = sCommon.fGetDate()

DECLARE @lLastLockoutDate DateTime
SET @lLastLockoutDate = NULL

DECLARE @lValidUpto Date
SET @lValidUpto = NULL


DECLARE @lOrgGroupId int=0
SELECT @lOrgGroupId=OrgGroupId  FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId

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 = 2010 AND SourceId = @rOrgId WHERE CM.Id = 224

DECLARE @lTimePolicyId int
DECLARE @lIpPolicyId int
DECLARE @lAccessTime nvarchar(300)

DECLARE @lTimePolicy TABLE(Id int identity, AccessTime nvarchar(100))
DECLARE @lIpPolicyDetail TABLE(IP nvarchar(100))

IF(@rOSTypeId = 0)
BEGIN
	SET @rOSTypeId =3
END

SET NOCOUNT ON

BEGIN

IF(@lIsLogEnable = 1)
BEGIN
	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('sSecurity.pUserValidate Start', 
	'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
	+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
	'', '', GETDATE(), 'sSecurity.pUserValidate')
END

	SELECT 
		@lUserId = Id,
		@lValidUpto = ValidUpto,
		@lSourceTypeId = ISNULL(SourceTypeId,0)
	FROM sSecurity.tUser WITH (NOLOCK)
	WHERE 
		    UPPER(LoginTitle) = UPPER(@rUserTitle) AND
		   	(LoginPassword = @rUserPassword  OR @rUserPassword = '')  AND 
			NumberOfLogonAttempt <= 5000 AND
			IsObsolete = 0 AND
			OrgId = @rOrgId
	
	IF(@rSessionId = 'AndroidSession' AND (@lSourceTypeId = 0 OR @lSourceTypeId=1))
	BEGIN
		RAISERROR('Invalid User', 16, 1)
		
		IF(@lIsLogEnable = 1)
		BEGIN
			INSERT INTO [sSystem].[tTraceLog]
			(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
			VALUES
			('sSecurity.pUserValidate', 
			'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
			+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
			'Invalid User', 'Validation', GETDATE(), 'sSecurity.pUserValidate')
		END

		RETURN
	END
			
	IF @lUserId > 0
		BEGIN
			
			SELECT 
				@lTimePolicyId = TimePolicyId ,@lIpPolicyId = IpPolicyId 
			FROM sSecurity.tUserPolicy 
				WHERE  UserId = @lUserId
			
			IF(@lTimePolicyId IS NOT NULL AND @lTimePolicyId !=0)	
			BEGIN
				SELECT @lAccessTime = AccessTime FROM sSecurity.tTimePolicy	WHERE  Id = @lTimePolicyId
				INSERT @lTimePolicy SELECT * FROM sCommon.fnSplit(@lAccessTime,',')
				DECLARE @lCount int 
				SELECT @lCount = COUNT(AccessTime) FROM @lTimePolicy
				DECLARE @LoopCounter INT = 1
				DECLARE @lIsValid bit = 0
				
				WHILE (@LoopCounter <= @lCount)
				BEGIN
						
					DECLARE @lTime nvarchar(100)
					SELECT @lTime = AccessTime FROM @lTimePolicy WHERE Id = @LoopCounter
					DECLARE @lFromTime nvarchar(100)
					DECLARE @lToTime nvarchar(100)
					SELECT @lFromTime = SUBSTRING(@lTime, 1, 5 )
					SELECT @lToTime = SUBSTRING(@lTime, 7, 10 )
					IF(CONVERT(time,getdate()) BETWEEN CONVERT(time,@lFromTime) AND CONVERT(time,@lToTime))
					BEGIN	
						SET @lIsValid = 1
					END 
					ELSE IF(@lIsValid=0)
					BEGIN 
						RAISERROR('Not allowed due to time policy constrain', 16, 1)

						IF(@lIsLogEnable = 1)
						BEGIN
							INSERT INTO [sSystem].[tTraceLog]
							(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
							VALUES
							('sSecurity.pUserValidate', 
							'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
							+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
							'Not allowed due to time policy constrain', 'Validation', GETDATE(), 'sSecurity.pUserValidate')
						END

						RETURN
					END 
					 SET @LoopCounter  = @LoopCounter  + 1
				END
			END
			
			IF(@lIpPolicyId IS NOT NULL AND @lIpPolicyId !=0)	
			BEGIN
				
				INSERT @lIpPolicyDetail SELECT IP FROM sSecurity.tIpPolicyDetail WHERE  IpPolicyId = @lIpPolicyId
				
				IF(@lItemValue='False')
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM @lIpPolicyDetail WHERE IP = @rHostAddress)
					BEGIN 
						RAISERROR('Not allowed due to ip policy constrain', 16, 1)

						IF(@lIsLogEnable = 1)
						BEGIN
							INSERT INTO [sSystem].[tTraceLog]
							(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
							VALUES
							('sSecurity.pUserValidate', 
							'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
							+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
							'Not allowed due to ip policy constrain', 'Validation', GETDATE(), 'sSecurity.pUserValidate')
						END

						RETURN
					END
				END
				ELSE
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM @lIpPolicyDetail WHERE IP = @rLocalAddress)
					BEGIN 
						RAISERROR('Not allowed due to ip policy constrain', 16, 1)

						IF(@lIsLogEnable = 1)
						BEGIN
							INSERT INTO [sSystem].[tTraceLog]
							(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
							VALUES
							('sSecurity.pUserValidate', 
							'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
							+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
							'Not allowed due to ip policy constrain - else', 'Validation', GETDATE(), 'sSecurity.pUserValidate')
						END

						RETURN
					END
				END
			END
			
			IF(@lValidUpto IS NOT NULL)
			BEGIN
				IF(CONVERT(date, getdate()) > @lValidUpto)
				BEGIN
					RAISERROR('Your Account is expired', 16, 1)

					IF(@lIsLogEnable = 1)
					BEGIN
						INSERT INTO [sSystem].[tTraceLog]
						(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
						VALUES
						('sSecurity.pUserValidate', 
						'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
						+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
						'Your Account is expired', 'Validation', GETDATE(), 'sSecurity.pUserValidate')
					END
					RETURN
				END
			END
			
			--UPDATE sSecurity.tUser
			--SET IsOnline = 1,
			--	NumberOfLogonAttempt = 0,			
			--	UpdatedDate = sCommon.fGetDate()
			--WHERE Id = @lUserId
			IF(@lUserId != 1 AND @rUserTitle != 'SysSuperAdmin')
			BEGIN
			EXECUTE sSecurity.pUserLogAdd @rOrgId, @lUserId, @rHostAddress, 1, @lLoginDateTime, NULL, 1, @rSessionId,@rLocalAddress,@rOSTypeId,@rDeviceUniqueId
			END
			--INSERT INTO sSecurity.tUserLog(UserId, LoggedInIp, LoggedInDateTime)
			--VALUES (@lUserId, @rHostAddress, sCommon.fGetDate())

	--		SELECT Id, Title, TitleResourceKey 
	--		FROM sSecurity.tRole 
	--		INNER JOIN sSecurity.tUserRole
	--			ON RoleId = Id
	--		WHERE UserId = @lUserId AND sSecurity.tRole.IsObsolete = 0
			
		 --   UPDATE E
			--SET E.StatusId = 9
			--FROM sHrm.tEmployeeMaster E
			--JOIN sHrm.tEmployeeJobDetail J ON E.Id = J.EmployeeId 
			--WHERE 
			----J.activeupto <= getdate() and 
			--E.orgID= @rOrgId 	    
		    SELECT @lUserId as UserId
			--SELECT @lUserId 
		END
	ELSE
		BEGIN 
		
			DECLARE @lUpdatedDateTime datetime
			DECLARE @lMinute int = 0 
			
			SELECT @lUserId = Id,
					@lLoginAttempts = NumberOfLogonAttempt,
					@lLastLockoutDate = LastLockOutDate,
					@lUpdatedDateTime = UpdatedDateTime
					
			FROM sSecurity.tUser WITH (NOLOCK)
			WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND 
					OrgId = @rOrgId
			IF @lUserId > 0
				BEGIN
				
					DECLARE @lIsSecurityPolicy nvarchar(20) = ''
					SELECT @lIsSecurityPolicy = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
					FROM sConfig.tConfigurationMaster CM
					LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
					AND SourceTypeId = 2010 AND SourceId = @rOrgId WHERE CM.Id = 207

					IF(@lIsSecurityPolicy='True')
					BEGIN
						SET @lMinute = DateDiff(s, @lUpdatedDateTime, sCommon.fGetDate())%3600/60
						
						IF(@lMinute <> 0 AND @lMinute >= 10)
						BEGIN
							UPDATE sSecurity.tUser WITH (ROWLOCK)
							SET	
							SessionId = @rSessionId,				
							LastLockOutDate = sCommon.fGetDate(),
							UpdatedDateTime = sCommon.fGetDate(),
							NumberOfLogonAttempt = 0		
							WHERE 
							Id = @lUserId AND OrgId = @rOrgId
							
							SELECT @lLoginAttempts = NumberOfLogonAttempt FROM sSecurity.tUser WITH (NOLOCK) WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND OrgId = @rOrgId
						END
					
						IF @lLoginAttempts >= 5
						BEGIN
							IF @lLastLockoutDate IS NULL
								BEGIN
									UPDATE sSecurity.tUser WITH (ROWLOCK)
									SET LastLockOutDate = sCommon.fGetDate(),
										UpdatedDateTime = sCommon.fGetDate()
									WHERE Id = @lUserId AND
										 OrgId = @rOrgId
								END
							RAISERROR('Your access is blocked temporary due to 5 consecutive failed login attempts, Please try after some time to login with correct credential.', 16, 1)


							IF(@lIsLogEnable = 1)
							BEGIN
								INSERT INTO [sSystem].[tTraceLog]
								(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
								VALUES
								('sSecurity.pUserValidate', 
								'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
								+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
								'Your access is blocked temporary due to 5 consecutive failed login attempts, Please try after some time to login with correct credential.', 'Validation', GETDATE(), 'sSecurity.pUserValidate')
							END

							RETURN
						END
						ELSE
						BEGIN
							UPDATE sSecurity.tUser WITH (ROWLOCK)
							SET NumberOfLogonAttempt = NumberOfLogonAttempt + 1,
								UpdatedDateTime = sCommon.fGetDate()
							WHERE Id = @lUserId AND
								OrgId = @rOrgId
						END
					END
					
					--IF @lLoginAttempts > 250
					--	BEGIN
					--		IF @lLastLockoutDate IS NULL
					--			BEGIN
					--				UPDATE sSecurity.tUser
					--				SET LastLockOutDate = sCommon.fGetDate(),
					--					UpdatedDateTime = sCommon.fGetDate()
					--				WHERE Id = @lUserId AND
					--					 OrgId = @rOrgId
					--			END
					--		RAISERROR('User account locked', 16, 1)
					--		RETURN
					--	END
					--ELSE
					--	BEGIN
					--		UPDATE sSecurity.tUser
					--		SET NumberOfLogonAttempt = NumberOfLogonAttempt + 1,
					--			UpdatedDateTime = sCommon.fGetDate()
					--		WHERE Id = @lUserId AND
					--			OrgId = @rOrgId
					--	END
					
				END		

			RAISERROR('Username/password does not match or Inactive user.', 16, 1)	

			IF(@lIsLogEnable = 1)
			BEGIN
				INSERT INTO [sSystem].[tTraceLog]
				(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
				VALUES
				('sSecurity.pUserValidate', 
				'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
				+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
				'Username/password does not match or Inactive user.', 'Validation', GETDATE(), 'sSecurity.pUserValidate')
			END	
		END

IF(@lIsLogEnable = 1)
BEGIN
	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('sSecurity.pUserValidate End', 
	'UserTitle : ' + CAST(@rUserTitle AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
	+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
	'', '', GETDATE(), 'sSecurity.pUserValidate')
END

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


GO
ALTER PROCEDURE [sCommunication].[pRegisteredUsersAdd]
	 
        @rOrgId int,
        @rUserId bigint,
        @rUserSourceId bigint,
        @rUserSourceTypeId smallint,
        @rDeviceToken nvarchar(200),
        @rOSTypeId tinyint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	DECLARE @lIsLogEnable bit = 0

	IF(@lIsLogEnable = 1)
	BEGIN
		INSERT INTO [sSystem].[tTraceLog]
		(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
		VALUES
		('sCommunication.pRegisteredUsersAdd Start', 
		'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
		+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', DeviceToken : ' +  CAST(@rDeviceToken AS nvarchar(100)), 
		'', '', GETDATE(), 'sCommunication.pRegisteredUsersAdd')
	END
	
	DECLARE @lOrgGroupId int =0 
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WITH (NOLOCK) WHERE Id = @rOrgId
	
	 DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WITH (NOLOCK) WHERE ConfigurationId = 374 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId

	 IF @lConfigValue IS NULL 
		SET @lConfigValue = 'False'
	
	 IF @lConfigValue = 'True'
	 BEGIN
		DELETE FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId
	 END
	
	
	IF EXISTS(SELECT 1 FROM sCommunication.tRegisteredUsers WITH (NOLOCK)
	WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId 
	AND UserSourceTypeId = @rUserSourceTypeId AND DeviceToken=@rDeviceToken 
	AND OSTypeId = @rOSTypeId)
	BEGIN
		SELECT 1 AS Result
		RETURN
	END

	IF EXISTS(SELECT 1 FROM sCommunication.tRegisteredUsers WITH (NOLOCK) WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId 
	AND UserSourceTypeId = @rUserSourceTypeId AND DeviceToken <> '' AND DeviceToken IS NOT NULL)
	BEGIN
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WITH (NOLOCK) WHERE ConfigurationId = 468 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
		IF @lConfigValue IS NULL   
			SET @lConfigValue = 'False'  
		IF @lConfigValue = 'True'  
		BEGIN  
			SELECT -101 AS Result
			RETURN
		END
	END
	
	BEGIN TRANSACTION	

	INSERT INTO sCommunication.tRegisteredUsers WITH (ROWLOCK)
		(
			OrgId,
			UserId,
			UserSourceId,
			UserSourceTypeId,
			DeviceToken,
			OSTypeId,
			CreatedDateTime
		)
	VALUES
		(
			@rOrgId,
			@rUserId,
			@rUserSourceId,
			@rUserSourceTypeId,
			@rDeviceToken,
			@rOSTypeId,
			sCommon.fGetDate()
		)
	
	SELECT 1 AS Result

	COMMIT TRANSACTION		

	IF(@lIsLogEnable = 1)
	BEGIN
		INSERT INTO [sSystem].[tTraceLog]
		(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
		VALUES
		('sCommunication.pRegisteredUsersAdd End', 
		'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
		+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', DeviceToken : ' +  CAST(@rDeviceToken AS nvarchar(100)), 
		'', '', GETDATE(), 'sCommunication.pRegisteredUsersAdd')
	END

	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		IF(@lIsLogEnable = 1)
		BEGIN
			INSERT INTO [sSystem].[tTraceLog]
			(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
			VALUES
			('sCommunication.pRegisteredUsersAdd Error', 
			'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) 
			+ ', OSTypeId : ' +  CAST(@rOSTypeId AS nvarchar(10))  + ', DeviceToken : ' +  CAST(@rDeviceToken AS nvarchar(100)), 
			ERROR_MESSAGE(), '', GETDATE(), 'sCommunication.pRegisteredUsersAdd')
		END
		SELECT -1 AS Result
	END CATCH	
		
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 

--Update sSetup.tOrgGroupMaster Set IsObsolete=0 WHERE IsObsolete IS NULL 

--Changes for Mantis Id: 0039838
DECLARE @lConfigValue nvarchar(50)='', @lFromTime nvarchar(50)='', @lToTime nvarchar(50)='';

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WITH (NOLOCK) WHERE ConfigurationId = 592   AND SourceTypeId = 2010   AND SourceId = @rOrgGroupId;

WITH SplitData AS (SELECT cast(item AS nvarchar(50)) AS item, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum
    FROM sCommon.fnsplit(@lConfigValue, '-')
)
SELECT 
    @lFromTime = MAX(CASE WHEN RowNum = 1 THEN item END),
    @lToTime = MAX(CASE WHEN RowNum = 2 THEN item END)
FROM SplitData;

IF(@lConfigValue <> '' AND (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime) < (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime))
BEGIN
	SET @lToTime = CAST(CAST((GETDATE()+1) AS DATE) AS DATETIME) + @lToTime
END
ELSE
BEGIN
	SET @lToTime = (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lToTime)
END

IF(@lConfigValue <> '' AND (GETDATE() NOT BETWEEN (CAST(CAST(GETDATE() AS DATE) AS DATETIME) + @lFromTime) AND @lToTime))
BEGIN
	RETURN
END

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  WITH (NOLOCK)
						INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
						INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.ID = SA.OrgId
					WHERE	
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  --And ISNULL(O.IsObsolete,0) = 0
						  And O.IsObsolete <> 1
						  AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
						  AND FAS.PaidAmount >= 0		-- Added for Mantis : 0039379 By Dhananjay
						  AND FAS.ToPayAmount >= 0.00	-- Added for Mantis : 0039379 By Dhananjay
						  --AND SM.StatusId=1
						  -- IsInContext
						  AND BM.IsInContext = 1
					GROUP BY  o.Id,o.Title

					IF EXISTS (SELECT 1 FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) 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 WITH (NOLOCK) 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 WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
						END
				
				DROP TABLE #tempOrganizationSync			
		END
	ELSE
		BEGIN

			IF  Exists(select 1 from sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) where CONVERT(date,UpdatedDateTime) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))) 
			BEGIN
	
				SELECT * FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
						INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id 
						INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId -- Added AdmissionCategoryId Condition on join for Mantis : 0039379 By Dhananjay
						INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON OM.ID = SA.OrgId
						
					WHERE	
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  --And ISNULL(O.IsObsolete,0) = 0
						  And O.IsObsolete <> 1
						  AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
						  AND FAS.PaidAmount >= 0		-- Added for Mantis : 0039379 By Dhananjay
						  AND FAS.ToPayAmount >= 0.00	-- Added for Mantis : 0039379 By Dhananjay
						  -- IsInContext
						  AND BM.IsInContext = 1
					GROUP BY  o.Id,o.Title

						
				IF EXISTS (SELECT 1 FROM sFee.tTempOrgGroupFeeStatus WITH (NOLOCK) 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 WITH (NOLOCK) 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 WITH (NOLOCK) 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 WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId -- Added AdmissionCategoryId Condition on join for Mantis : 0039379 By Dhananjay
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) 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 O.IsObsolete <> 1
		AND FAS.PaidAmount >= 0		-- Added = for Mantis : 0039379 By Dhananjay
		AND FAS.ToPayAmount >= 0.00	-- Added for Mantis : 0039379 By Dhananjay
		-- 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 WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
	WHERE
		(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--nd ISNULL(O.IsObsolete,0) = 0 
		And O.IsObsolete <> 1
		AND FAS.ToPayAmount >= 0.00 --AND SA.StatusId=1 -- Added = for Mantis : 0039379 By Dhananjay
		AND FAS.PaidAmount >= 0		-- Added for Mantis : 0039379 By Dhananjay
		-- 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 WITH (NOLOCK)
				LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
			    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) 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 O.IsObsolete <> 1
				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 WITH (NOLOCK)
				LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId
			    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) 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 O.IsObsolete <> 1
				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 WITH (NOLOCK)
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id 
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId -- Added for Mantis : 0039379 By Hemali
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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
			 And O.IsObsolete <> 1
			 -- IsInContext
			AND FAS.PaidAmount >= 0	-- Added for Mantis : 0039379 By Hemali
			AND FAS.ToPayAmount >= 0.00  -- Added for Mantis : 0039379 By Hemali
				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 WITH (NOLOCK) 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
			--Added for query optimization - TRIS Loading issue - 10 Jan 2025
			DECLARE @lTopReceiptDate datetime = (SELECT TOP 1 ReceiptDate 
					FROM sFee.tReceipt R  WITH (NOLOCK)
					INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId 
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					ORDER BY ReceiptDate DESC)
			--Added for query optimization - TRIS Loading issue - 10 Jan 2025

			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,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					--(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,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					@lTopReceiptDate AS EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA WITH (NOLOCK)
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
		        INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id 
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id AND FS.AdmissionCategoryId=SA.AdmissionCategoryId   -- Added for Mantis : 0039379 By Hemali
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 --And ISNULL(O.IsObsolete,0) = 0
			 And O.IsObsolete <> 1
			 AND COGBM.Id=@rCommonOrgGroupBatchId 
			 -- IsInContext
				AND FAS.PaidAmount >= 0	  -- Added for Mantis : 0039379 By Hemali
				AND FAS.ToPayAmount >= 0.00  -- Added for Mantis : 0039379 By Hemali
				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 WITH (NOLOCK) 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 WITH (NOLOCK)
							INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId
							INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
							INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=R.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA.OrgId = OM.Id 
							INNER JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) 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
							And O.IsObsolete <> 1
							-- 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 WITH (NOLOCK)
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id AND FS.AdmissionCategoryId=SA.AdmissionCategoryId  -- Added for Mantis : 0039379 By Hemali
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 --And ISNULL(O.IsObsolete,0) = 0
			 And O.IsObsolete <> 1
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
			 -- IsInContext
				AND FAS.PaidAmount >= 0	  -- Added for Mantis : 0039379 By Hemali
				AND FAS.ToPayAmount >= 0.00  -- Added for Mantis : 0039379 By Hemali
				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 WITH (NOLOCK) 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 WITH (NOLOCK) where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
			BEGIN
	
				SELECT * FROM sFee.tTempTotalPaidDetails WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempTotalStudentCount WITH (NOLOCK) WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempPendingCount WITH (NOLOCK) 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 WITH (NOLOCK)
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id
					INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId AND FS.AdmissionCategoryId=SA.AdmissionCategoryId   -- Added for Mantis : 0039379 By Hemali
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
					INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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
				 And O.IsObsolete <> 1
				 -- IsInContext

				 -- Added for Mantis : 0039379 By Hemali
				AND FAS.PaidAmount >= 0	  
				AND FAS.ToPayAmount >= 0.00
				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 WITH (NOLOCK) 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
				--Added for query optimization - TRIS Loading issue - 10 Jan 2025
				DECLARE @lTopReceiptDate1 datetime = (SELECT TOP 1 ReceiptDate 
					FROM sFee.tReceipt R WITH (NOLOCK) 
					INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId 
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					ORDER BY ReceiptDate DESC)
				--Added for query optimization - TRIS Loading issue - 10 Jan 2025
	
				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,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					--(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,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					@lTopReceiptDate1 AS EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
				FROM 
					sStudent.tAcademic SA WITH (NOLOCK)
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id 
					INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id AND FS.AdmissionCategoryId=SA.AdmissionCategoryId  -- Added for Mantis : 0039379 By Hemali
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
					INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
					INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				 --And ISNULL(O.IsObsolete,0) = 0
				 And O.IsObsolete <> 1
				 AND COGBM.Id=@rCommonOrgGroupBatchId 
				 -- IsInContext
				 -- Added for Mantis : 0039379 By Hemali
				AND FAS.PaidAmount >= 0	
				AND FAS.ToPayAmount >= 0.00
				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 WITH (NOLOCK) 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)
				)
				
				--Added for query optimization - TRIS Loading issue - 10 Jan 2025
				DECLARE @lTopReceiptDate2 datetime = (SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId
					INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
					INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA.OrgId = OM.Id 
					INNER JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON CGM.ReceiptBookId = R.ReceiptBookId
					  WHERE  
							(LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
							AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
							And O.IsObsolete <> 1
						AND BM.IsInContext = 1
					  ORDER BY ReceiptDate DESC)
				--Added for query optimization - TRIS Loading issue - 10 Jan 2025

				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,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					--(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
					--		And O.IsObsolete <> 1
					--		-- IsInContext
					--	AND BM.IsInContext = 1
					--  ORDER BY ReceiptDate DESC) EndDate,
					--Commented due to not useful as getting same receiptdate for every record - TRIS Loading issue - 10 Jan 2025
					@lTopReceiptDate2 AS EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA WITH (NOLOCK)
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id AND FS.AdmissionCategoryId=SA.AdmissionCategoryId  -- Added for Mantis : 0039379 By Hemali
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 --And ISNULL(O.IsObsolete,0) = 0
			 And O.IsObsolete <> 1
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
			 -- IsInContext

			 -- Added for Mantis : 0039379 By Hemali
			AND FAS.PaidAmount >= 0	
			AND FAS.ToPayAmount >= 0.00
				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 WITH (NOLOCK) 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 WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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 O.IsObsolete <> 1
		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 WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FS.Id = FAS.FeeSetupId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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 O.IsObsolete <> 1
		 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 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) 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
		And O.IsObsolete <> 1
		-- 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 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) 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 O.IsObsolete <> 1
		--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 WITH (NOLOCK) 
		  INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
		  INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
		  INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
		  INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId 
		  INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		  INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
		  INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
		  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		  INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) 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
		   And O.IsObsolete <> 1
		   -- 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 WITH (NOLOCK)
		INNER JOIN #tempPFSMonthWise TPFS ON TPFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON TPFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON TPFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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
	And O.IsObsolete <> 1
	-- 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 WITH (NOLOCK)
		 INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	     INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		 INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	     INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	     INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	     INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId			 
		 INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
	   
		 INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) 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
		 And O.IsObsolete <> 1
		 -- 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 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) 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 WITH (NOLOCK) ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) 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
		And O.IsObsolete <> 1
		-- 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 WITH (NOLOCK) 
		INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) 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 WITH (NOLOCK)
		 LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPFSMonthWise1 TPFS1 ON TPFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK)
			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 WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON TPFS1.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON TPFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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
	And O.IsObsolete <> 1
	-- 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 WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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 O.IsObsolete <> 1
		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 WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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 O.IsObsolete <> 1
		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 WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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
	 And O.IsObsolete <> 1
	 -- 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 WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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 O.IsObsolete <> 1
	 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 WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE 
		   ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--And ISNULL(O.IsObsolete,0) = 0
			And O.IsObsolete <> 1
			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 WITH (NOLOCK)
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) ON FHM.Id=FM.FeeHeadId	
	WHERE 
		   ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--And ISNULL(O.IsObsolete,0) = 0
			And O.IsObsolete <> 1
			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 WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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 O.IsObsolete <> 1
	 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 WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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
	 And O.IsObsolete <> 1
	 -- 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 WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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
	 And O.IsObsolete <> 1
	 -- 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 WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS WITH (NOLOCK) ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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 O.IsObsolete <> 1
	 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 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- 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 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) 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
	   And O.IsObsolete <> 1
	   -- 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 WITH (NOLOCK)
		INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId 
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) 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
		And O.IsObsolete <> 1
		-- 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 WITH (NOLOCK)
		LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise TDFS ON TDFS.AcademicId=SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK) 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 WITH (NOLOCK) ON TDFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON TDFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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
	And O.IsObsolete <> 1
	-- 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 WITH (NOLOCK)
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA1.OrgId = OM.Id 
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		--And ISNULL(O.IsObsolete,0) = 0
		And O.IsObsolete <> 1
		-- 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 WITH (NOLOCK)
		INNER JOIN sFee.tFeeOptional FO WITH (NOLOCK) ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) 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
		And O.IsObsolete <> 1
		-- 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 WITH (NOLOCK)
		INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM WITH (NOLOCK) ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 WITH (NOLOCK) ON SA1.Id=R.SourceId 
		INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) 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 O.IsObsolete <> 1
		--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 WITH (NOLOCK)
		 LEFT JOIN sStudent.tStudentCommunication SC WITH (NOLOCK) ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise1 TDFS1 WITH (NOLOCK) ON TDFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA WITH (NOLOCK)
			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 WITH (NOLOCK) ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM WITH (NOLOCK) ON TDFS1.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) ON TDFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM WITH (NOLOCK) 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 O.IsObsolete <> 1
	 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 WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) 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 O.IsObsolete <> 1
				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 WITH (NOLOCK) 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 WITH (NOLOCK) 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 WITH (NOLOCK)
				INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId 
				INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
				INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) 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 WITH (NOLOCK) 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 WITH (NOLOCK)
			INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId
			INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN  sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA.OrgId = OM.Id 			
			INNER JOIN sFee.tFeeSetup FS WITH (NOLOCK) 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 WITH (NOLOCK) 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   
			And O.IsObsolete <> 1
			-- 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 WITH (NOLOCK)
			INNER JOIN sFee.tReceiptDetail RD WITH (NOLOCK) ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA WITH (NOLOCK) ON SA.Id=R.SourceId
			--INNER JOIN sStudent.tStudentMaster SM1 ON SA.StudentId = SM1.Id
			INNER JOIN sStudent.tStudentMaster SM WITH (NOLOCK) ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tOrganizationMaster OM WITH (NOLOCK) ON SA.OrgId = OM.Id AND SM.OrgId = OM.Id
			INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM WITH (NOLOCK) ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O WITH (NOLOCK) ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM WITH (NOLOCK) 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 WITH (NOLOCK) 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 WITH (NOLOCK) ON RBM.Id=FS.ReceiptBookId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM WITH (NOLOCK) 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 -- remove isnull because it will take more time to execute in all above conditions mantisid : 0038978
			--And O.IsObsolete = 0	
			And O.IsObsolete <> 1		
			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].[pFeeCustomSearchGet]...';


GO

ALTER PROCEDURE [sFee].[pFeeCustomSearchGet]
(
	@rOrgGroupBatchId int,
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'ReceiptNumber',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',	
	@rDivisionId nvarchar(max) = '',
	@rReceiptBookId nvarchar(max) = '',
	@rFromReceiptDate Date = '0001-01-01',
	@rToReceiptDate Date = '9999-12-31',
	@rFromReceiptNo int,
	@rToReceiptNo int,
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownReceiptBookId int,
	@rDepartmentId int=0,
	@rPageIndex int = null,
	@rAdmissionCategoryId int = 0
 )
AS
SET NOCOUNT ON
BEGIN
	create table #TEMPFee
	(
		tid int identity(1,1),t_AcedemicId bigint,t_ReceiptId bigint
	)
	
	DECLARE @Sql nvarchar(MAX)
	IF(@rFromReceiptDate IS NULL)
		SET @rFromReceiptDate='0001-01-01'
	IF(@rToReceiptDate IS NULL)
		SET @rToReceiptDate='9999-12-31'

		
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	
	SELECT FCS.AcademicId,FCS.ClassId,FCS.DivisionId,FCS.RollNo,FCS.OrgGroupBatchId,
	FCS.OrgId,FCS.BatchId,FCS.OrgGroupBatch,FCS.Organization,FCS.Batch,FCS.StudentId,
	FCS.Code,FCS.Number,FCS.FirstName,FCS.LastName,FCS.Name,FCS.StatusId,FCS.ClassName,
	FCS.DivisionName,FCS.StatusName,FCS.ReceiptId,FCS.ReceiptNumber,FCS.ReceiptDate,
	FCS.ReceiptAmount,FCS.ChequeNo,FCS.BankName,FCS.Remark,FCS.IsObsolete,FCS.FeeReceiptBookId,
	FCS.ReceiptBookCode,FCS.ReceiptBookName,FCS.Address1,FCS.Address2,FCS.BankAccountNumber,
	FCS.PayTypeId,FCS.PayType,FCS.CreatedUserId,FCS.CreatedUserName, FCS.ParentContactNo
	into sFee.tTempFee1
	FROM sFee.vFeeCustomSearch FCS
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = FCS.ClassId
	WHERE (FCS.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((FCS.OrgId = @rOrgId) OR (@rOrgId=0))
	AND ((FCS.BatchId = @rBatchId) OR (@rBatchId=0))
	AND ((FCS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((FCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((FCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((FCS.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo =0))
	AND ((FCS.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
	AND ((ISNULL(FCS.ReceiptDate,'0001-01-01') >= @rFromReceiptDate) OR (ISNULL(@rFromReceiptDate,'') = ''))
	AND ((ISNULL(FCS.ReceiptDate,'9999-12-31') <= @rToReceiptDate) OR (ISNULL(@rToReceiptDate,'') = ''))
	AND (FCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
	AND (FCS.FeeReceiptBookId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookId,','))OR @rReceiptBookId='')
	AND ((FCS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	AND (FCS.IsObsolete=@rIsObsolete)
	AND ((FCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((FCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
	AND ((FCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	AND ((FCS.FeeReceiptBookId = @rDropDownReceiptBookId) OR (@rDropDownReceiptBookId=0))
	AND ((Cm.DepartmentId =@rDepartmentId ) OR (@rDepartmentId=0))
	AND ((FCS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	
	SET @sql='SELECT Code AS Code,Name,ReceiptNumber,ReceiptDate,ReceiptAmount,
	PayType,ChequeNo,BankName,ReceiptBookName,Remark,OrgId,BatchId
	FROM sFee.tTempFee1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	SET @sql='INSERT INTO #TEMPFee SELECT AcademicId, ReceiptId
	FROM sFee.tTempFee1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	declare @lTotalRecords int,@lPageSize int = 10,@lPaging varchar(max)='',
			@lResult nvarchar(max)=''	--change varchar to nvarchar for mantis: 32993
	select @lTotalRecords = count(*) from #TEMPFee
	
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lTotalRecords,@lPageSize)
	
	select @lResult = @lResult + '<tr attrId="' + convert(varchar,isnull(t_AcedemicId,0)) 
	+ '"attrCode="' + isnull(Code,'') 
	+ '"attrReceiptNo="' + isnull(convert(varchar,ReceiptNumber),'') 
	+ '"attrBatchId="' + convert(varchar,@rBatchId) 
	+ '"attrOrgId="' + convert(varchar,@rOrgId) 
	+ '"attrOrgGroupBatchId="' + convert(varchar,@rOrgGroupBatchId) + '">
	<td><a style="cursor:pointer;" onclick="SecectThisRecord(this);">Select</a></td><td>' + isnull(Code,'') + '</td>
	<td>' + isnull(Name,'') + '</td><td>' + isnull(convert(varchar,ReceiptNumber),'') + '</td>
	<td>' + isnull(convert(varchar,ReceiptDate,103),'') + '</td>
	<td>' + isnull(convert(varchar,ReceiptAmount),'') + '</td><td>' + isnull(PayType,'') + '</td>
	<td>' + isnull(ChequeNo,'') + '</td><td>' + isnull(BankName,'') + '</td>
	<td>' + isnull(ReceiptBookName,'') + '</td><td>' + isnull(Remark,'') + '</td></tr>'
	from sFee.tTempFee1,#TEMPFee where t_AcedemicId = AcademicId AND t_ReceiptId = ReceiptId
	and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	
	select @lPaging as UserPaging,@lResult as UserResult,@lTotalRecords as UserTotal
			
	DROP Table sFee.tTempFee1
	drop Table #TEMPFee
END
GO
PRINT N'Altering Procedure [sFee].[pRptStudentOptionalFeeListGet]...';


GO

ALTER PROCEDURE [sFee].[pRptStudentOptionalFeeListGet]	 
		@rClassId int = 0,
		@rDivisionId int = 0,
		@rAdmissionCategoryId int = 0,		
		@rBatchId int = 0,
		@rOrgId int = 0,
		@rReceiptBookId int = 0,
		@rDepartmentId int = 0,
		@rOrgGroupBatchId int = 0,
		@rCommonBatch nvarchar(100)='', --nvarchar for mantis : 0044148
		@rFeeId nvarchar(max) = '',
		@rFromRollNo int = 0,
		@rToRollNo int = 0,
		@rFilterId int = 0,
		@rOrgGroupId int = 0,
		@rCode nvarchar(20) = '',
		@rReportId int = 0,
		@rIsDisplayOrgGroup bit = 0,
		@rIsFilter bit = 0,  
		@rBuilder1 nvarchar(max) = '',  
		@rBuilder2 nvarchar(max) = '',
		@rFeeHeadId int = 0

		WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
	SELECT 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			@rIsFilter AS IsFilter,
			@rBuilder1 AS Builder1,  
			@rBuilder2 AS Builder2,  
			SA.AcademicId,
			SA.Code,
			SA.Name,
			SA.RollNo,
			SA.ClassName,
			SA.DivisionName,
			ISNULL(FO.FeeSetupId,0) AS FeeSetupId,			
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			--Added by dhananjay mantis : 42689	
			SA.ClassOrderIndex,
			SA.DivisionOrder
			--Added by dhananjay mantis : 42689
	FROM 
		sFee.tFeeOptional FO
		INNER JOIN sStudent.vStudentAcademic SA ON FO.SourceId=SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FO.FeeSetupId AND FO.SourceTypeId=2001
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FO.BatchId AND SA.BatchId = BM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId	
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) 
		AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
		LEFT JOIN  
		(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 
			AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)
	WHERE 
		(RBM.OrgGroupId = @rOrgGroupId)
		AND	((SA.OrgId=@rOrgId) OR (@rOrgId = 0))		
		AND ((BM.Id=@rBatchId) OR (@rBatchId = 0))
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))		
		AND ((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))	
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))	
		AND ((OGBM.Id = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		--AND ((OGBM.CommonOrgGroupBatchId = @rCommonBatch) OR (@rCommonBatch = 0)) --comment for mantis : 0044148
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))--add for mantis : 0044148
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo = 0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo = 0))		
		AND (ISNULL(FS.FeeId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rFeeId,',')) OR @rFeeId='')
		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 ((SA.Code = @rCode) OR (@rCode = ''))
		ORDER BY SA.AcademicId
END
GO
PRINT N'Altering Procedure [sMis].[pRptStudentBirthdayList]...';


GO
ALTER PROCEDURE [sMis].[pRptStudentBirthdayList]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rOrgMainGroupId int,
	@rOrgSubGroupId int,
	@rOrgGroupId int,
	@rOrgId smallint,
	--@rOrgGroupBatchId int, 
	@rDepartmentId int,
	@rClassId int,
	@rDivisionId int,
    @rStudentStatusId int=0,
	@rMonth tinyint =0,

	@rIsTestMainGroup bit =0,
	@rIsTestSubGroup bit =0,	
	@rIsTestOrg bit=0,
	@rIsTestDepartment bit=0,
	@rIsTestClass bit=0,
	@rIsTestDivision bit=0,
	@rStrOrgMainGroupId nvarchar(max) = '',
	@rStrOrgSubGroupId nvarchar(max) = '',
	@rStrOrgId nvarchar(max) = '',
	@rStrDepartmentId nvarchar(max) = '',
	@rStrClassId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

Declare @lIDConfigValue nvarchar(50)='' 


 SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId

	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsTestClass AS IsTestClass,
			@rIsTestDivision AS IsTestDivision,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			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,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			SD.DepartmentId,
			DM.Title AS Department,
			@lIDConfigValue AS ItemValue 
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN	sSetup.tClassMaster CM	ON CM.Id=SD.ClassId	
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId		
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId	
			INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			--INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId = OG.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId			 --Mantis 43838(INNER to LEFT)
			--INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassID AND BC.BatchId = SD.BatchId 
			--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) OR (@rOrgId=0))
		And ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		And (Month(SD.DateOfBirth)=@rMonth OR @rMonth = 0)
		AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
		AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
		AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
		AND ((SD.StatusId  = @rStudentStatusId) OR (@rStudentStatusId = 0))
		AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
		AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
		AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit(@rStrOrgId,','))OR @rStrOrgId='')
		AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrDepartmentId,','))OR @rStrDepartmentId='')
		AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrClassId,','))OR @rStrClassId='')
		AND SD.IsActiveBatch = 1
	 Order by
	 SD.RollNo
	 --SD.AcademicId,SD.StudentId
END
GO
PRINT N'Altering Procedure [sPayroll].[pCalculatePayrollAmount]...';


GO
ALTER PROCEDURE [sPayroll].[pCalculatePayrollAmount] 
	      	        
            @1PaypSetupId int,
            @1PayElementId int,
            @1Percentage DECIMAl(5,2),
            @1SourceId bigint,
            @1OrgGroupId int,
            @1EmployeeId bigint,
            @lNextNumber bigint,
            @rPayrollId int,
	        @rPayrollYearId int,
			@lFormula nvarchar(200),
            @1Result decimal(22,6) output          
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
      
      DECLARE @lTotalAmount Decimal(22,2)
      DECLARE @1DependPayElementId int   
      DECLARE @1COUNT INT
      DECLARE @1Amount Decimal(22,2)
      DECLARE @1IsDepend bit
      DECLARE @1DependPaySetupId int   
      DECLARE @1DependPercentage decimal(5,2)  
      DECLARE @1PayElementTypeId int
      DECLARE @1DependentTotal decimal(22,2)
      DECLARE @1IsDeduct bit
      
      BEGIN  
   
    DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	
	--mantis: 43241, start
	DECLARE @lIsRoundOffToWholeNumber nvarchar(50)
	DECLARE @lRoundOffToWholeNumber int
	SELECT @lIsRoundOffToWholeNumber = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 248 AND SourceTypeId = 2010 AND SourceId = @1OrgGroupId
	
	IF (@lIsRoundOffToWholeNumber IS NULL) OR (@lIsRoundOffToWholeNumber = 'True')
		SET @lRoundOffToWholeNumber = 0
	ELSE
		SET @lRoundOffToWholeNumber = 2
	--mantis: 43241, end
      
		SET @lTotalAmount = 0   
      
        ----For Calculate EmployeeBasic
        --IF  EXISTS (Select 1 FROM sPayroll.tPaySetupDependent WHere PaySetupId = @1PaypSetupId AND DependentPayElementId = @lBasicPayElementId) AND   
        -- EXISTS(Select 1 FROM sPayroll.tPaySetup Where PayElementId = @lBasicPayElementId AND SourceId = @1EmployeeId   AND SourceTypeId = 95)
        --BEGIN   
        --    SELECT @lTotalAmount = ISNULL(Amount,0) from sPayroll.tPayProcessElement Where PayProcessEmployeeId = @lNextNumber AND PayElementId = @lBasicPayElementId
            
        --   SELECT @lTotalAmount,'Basic'
        --    --select Amount from sPayroll.tPayProcessElement Where PayProcessEmployeeId AND PayElementId
        --END
       
		CREATE TABLE #tmpDependPayElementDetail
		(
			Id INT IDENTITY (1, 1),
			DependPayElementId  int,
			ProgressOrder int,
			IsDeduct bit		 		
		)		
		INSERT INTO #tmpDependPayElementDetail		
		SELECT PayElementId,ProcessOrder,ISNULL(IsDeduct,0)  from sPayroll.tPaySetupDependent PSD INNER JOIN sPayroll.tPaySetup PS ON  
        DependentPayElementId = PayElementId WHERE PaySetupId = @1PaypSetupId AND PS.PayrollYearId = @rPayrollYearId
        AND SourceId = @1SourceId --AND SourceTypeId = 2020
        ORDER BY ProcessOrder DESC  
       
 
        
        SELECT @1COUNT = COUNT(*) FROM #tmpDependPayElementDetail
	    SET @1DependentTotal = 0
	      WHILE @1COUNT > 0
	        BEGIN	   
	          SET @1DependPayElementId = 0
	          SET @1Amount = 0.0
	          SET @1DependPercentage = 0
	          SET @1DependPaySetupId = 0 
	          SET @1PayElementTypeId = 0
	          
	           
	          
	           SELECT @1DependPayElementId = DependPayElementId,@1IsDeduct=IsDeduct FROM #tmpDependPayElementDetail WHERE Id = @1COUNT
	           SELECT @1DependPaySetupId = Id,@1DependPercentage = Percentage FROM sPayroll.tPaySetup PS WHERE PayElementId = @1DependPayElementId AND PS.PayrollYearId = @rPayrollYearId
	            AND SourceId = @1SourceId
	          SELECT @1Amount = AMOUNT from sPayroll.tPayProcessElement Where PayProcessEmployeeId = @lNextNumber AND PayElementId = @1DependPayElementId
	          
	           
	            
	           SELECT @1PayElementTypeId = PayElementTypeId FROM sPayroll.tPayElement Where Id = @1DependPayElementId  
	             
	           
	               IF EXISTS (SELECT 1 FROM sPayroll.tPaySetupDependent WHERE PaySetupId = @1DependPaySetupId)
	                BEGIN 	                   
	                   EXECUTE [sPayroll].[pCalculatePayrollAmount] @1DependPaySetupId,@1PayElementId,@1DependPercentage,@1SourceId,@1OrgGroupId,@1EmployeeId,@lNextNumber,@rPayrollId,@rPayrollYearId,@lFormula,@1Result OUTPUT
						
	                   IF(@1IsDeduct=0)
							SET @1DependentTotal = @1DependentTotal + ISNULL(@1Result,0)
					   ELSE
							SET @1DependentTotal = @1DependentTotal - ISNULL(@1Result,0)
							
	                END 
	               ELSE
	               BEGIN     
	                    IF(@1IsDeduct=0)    
							SET @1DependentTotal = ISNULL(@1DependentTotal,0) + ISNULL(@1Amount,0)	                  
						ELSE
							SET @1DependentTotal = ISNULL(@1DependentTotal,0) - ISNULL(@1Amount,0)	                  	
	               END  
	          
	            SET  @1COUNT = @1COUNT - 1               
	            
	        END	       
	        
			IF(@lFormula!='')
			BEGIN
			 
				SELECT   @lTotalAmount =   [sPayroll].[fCalculateDependentBasedOnFormula](@lFormula,@1DependentTotal)
				--SET @lTotalAmount = ROUND((@1DependentTotal * @1Percentage)/100,0)
            END
            ELSE
				SET @lTotalAmount = ROUND((@1DependentTotal * @1Percentage)/100,@lRoundOffToWholeNumber) --mantis: 43241

		    
		    SET @1Result = @lTotalAmount
	 
      END
      --SELECT * FROM #tmpDependPayElementDetail
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	
	 @rBatchId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

		SELECT
			@rOrderByField AS OrderByField,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			EM.EmployeeId, 
			PP.ID As PayProcessId,
			PPE.ID AS PayProcessEmployeeId,
			PP.SalaryMonth,
			PP.SalaryYear,
			tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
			EM.Code AS EmployeeCode,
			EM.EmployeeDesignation,
			EM.EmployeeGrade,
			ESO.EPFNumber,
			ESO.PanNumber,
			PPE.TotalEarning,		
			PPE.TotalDeduction,
			PPE.NetAmount,
			(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
			(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
			(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
			PE.Amount As PPEAmount,
			P.Title AS PayElementTitle,
			P.ID AS PayElementId,
			P.PayElementTypeId,
			ISNULL(ESO.BankName,'') AS BankName,
			ISNULL(ESO.AccountNumber,'') AS AccountNumber, 
			MM.Title AS MonthName,
			P.Title AS PayElementName,
			P.Code AS PayElementCode,
			(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.WorkingDays,@lMonthDay) else 0 END) AS WorkingDays,
			(CASE WHEN PayElementId = @lBasicPayElementId then PPE.Lwp else 0 END) AS Lwp,
			(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.PaidLeave,0) else 0 END) AS PaidLeave,
			P.SortOrder,
			PY.Title AS PayrollYearName,
			PGM.Id AS PayrollGroupId,
			PGM.Title AS PayrollGroupName,
			PPE.GrossBasic,
			P.PayElementDefaultId,
			ISNULL(EPD.Qualification,'') AS Qualification,
			EJD.DateOfJoining AS DateOfAppointment,
			ISNULL(ESO.PayScale,'') AS PayScale,
			EPD.DateOfBirth,
			ISNULL(ROG.SelectableField,'') AS SelectableField,
			RGO.SchoolRequiredSignature ,
			RGO.SchoolRemark1,
			ISNULL(ESO.BasicPay,0) AS BasicPay,
			DAY(DATEADD(DD,-1,DATEADD(mm, DATEDIFF(mm, 0, CONVERT(DATE,CONVERT(nvarchar,PP.SalaryMonth) +'/01/'+CONVERT(nvarchar,PP.SalaryYear)) ) + 1, 0))) AS MonthDay,
			ESO.UAN,
			EPD.GenderId,
			ISNULL(PPR.Remark,'') AS PayProcessEmployeeRemark,
			tEM.FirstName,
			tEm.LastName,
			EM.DateOfJoining,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			ISNULL(REPLACE(REPLACE(
			(SELECT STUFF(
			(
			  SELECT  ' ' + Leave FROM -- create comma separated values
				(
						Select '<br>'+('<b>'+ LTM.Code +'</b>' +' - '+ CAST(SUM(CAST(L.NoOfLeave AS FLOAT)) AS varchar(50)) ) + '</br>'AS Leave 
						from 
						sHrm.tLeaveTypeMaster LTM  
						INNER JOIN sHrm.tLeave L ON  EM.EmployeeId = L.EmployeeId 
						INNER JOIN sCommon.tStatusMaster SM ON SM.Id=L.StatusId
						Where EM.EmployeeId=EM.EmployeeId AND LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0 
						AND LTM.Id = L.LeaveTypeId AND SM.Id=550
						AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
						AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
						GROUP BY LTM.Code
						)AS T FOR XML PATH('')
			)
			,1,1,'')),'&lt;','<'),'&gt;','>')
			,'') AS LeaveCount,
			tEM.Number,
			(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
			ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
			ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
			ISNULL(EPD.AdhaarNumber,'') AS AdhaarNumber,
			EM.DepartmentName, --Mantis : 0029371
			ESO.ESINumber,
			CASE 
				WHEN ISNULL(P.IsEmployeeSpecific,0) = 1
				THEN
					(SELECT PS.Amount 
						FROM sPayroll.tPaySetup PS 
						WHERE PS.PayElementId = P.Id 
						AND (PS.SourceId = tEM.Id AND PS.SourceTypeId = 95) 
						AND PS.PayrollYearId = PP.PayrollYearId)
				ELSE
					(SELECT PS.Amount 
						FROM sPayroll.tPaySetup PS 
						WHERE PS.PayElementId = P.Id 
						AND (PS.SourceId = PPE.PayrollGroupId AND PS.SourceTypeId = 2020) 
						AND PS.PayrollYearId = PP.PayrollYearId) 
			END AS PaySetupAmount,					--MantisId = 0030726
			tEM.CreatedDateTime AS CreatedDateTime, --mantis - 0030732
			[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise,	--MantisId = 0030726
			ISNULL(PPR.ChequeNo,'') ChequeNo,	--#Start Mantis Id : 0031036
			PPR.PayDate,
			CASE WHEN ISNULL(PPR.PayTypeId,0) = 0 THEN ISNULL(ESO.PayTypeId,0)
				ELSE ISNULL(PPR.PayTypeId,0) END AS PayTypeId,
			CASE WHEN ISNULL(PPR.PayTypeId,0) = 0 THEN ISNULL(PTM2.Title,'')
				ELSE ISNULL(PTM.Title,'') END AS PayTypeName,	--#End Mantis Id : 0031036
			ESO.RetirementDate AS RetirementDate, --Mantis - 0031406
			PM.Title AS PayrollTitle,				-- Mantis Id : 0032059
			ISNULL(EI.EmployeePhoto,0x) AS EmployeePhoto,               -- Add for mentis : 0034079
			ESO.IncrementDate , --Add for mantis : 0036465

			   --Mantis Start - 43067
			   (
				SELECT TOP 1 ISNULL(WD.TotalDays, 0)
					FROM sHrm.tWorkingDays WD
					WHERE 
						PP.SalaryYear = WD.ForYear
						AND PP.SalaryMonth = WD.ForMonth
						AND WD.EmployeeGradeId = EJD.EmployeeGradeId
						AND (WD.BatchId = @rBatchId OR @rBatchId = 0)
				) AS TotalDays,
			 (
				SELECT TOP 1 ISNULL(EA.TotalWorkingDays, 0) - (ISNULL(EA.LWP, 0) + ISNULL(EA.PaidLeave, 0))
				FROM sHrm.tEmployeeAttendance EA
				WHERE 
					EA.EmployeeId = EM.EmployeeId
					AND PP.SalaryYear = EA.ForYear
					AND PP.SalaryMonth = EA.ForMonth
					AND (EA.BatchId = @rBatchId OR @rBatchId = 0)
			) AS PresentDays,
			--Mantis End - 43067
			CASE WHEN P.IsDepend = 0 AND P.PayElementTypeId <> 1 THEN 0.0
			ELSE sPayroll.fGetPayElementNetAmount(P.Id, tEM.Id, PPE.PayrollGroupId, PP.PayrollYearId,P.IsEmployeeSpecific) END AS DependSetupAmount		-- Mantis Id : 0043659	
		FROM 
			sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
			LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
			INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
			LEFT JOIN sCommon.tReportOrgGroup ROG ON ROG.OrgGroupId=PY.OrgGroupId AND (ROG.ReportId = @rReportId OR @rReportId = 0) 
			LEFT JOIN sCommon.tReportRemarkGroupOrg RGO ON RGO.OrgId = tEM.OrgID AND RGO.ReportRemarkGroupId =  4
			LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
			AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
			LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PPR.PayTypeId		--#Start Mantis Id : 0031036
			LEFT JOIN sFinanceCommon.tPayTypeMaster PTM2 ON PTM2.Id = ESO.PayTypeId		--#End Mantis Id : 0031036
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = tEM.Id                -- Add for mentis : 0034079
		where 
			(EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			AND (P.IsObsolete=0)
			AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
			AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
			AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
			AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
			AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
			AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
			AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
			AND ((EJD.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
			AND (EM.EmployeeGradeId = @rGradeId OR @rGradeId = 0)						-- MantisId : 0032059
			AND (EM.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	-- MantisId : 0032059
	
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockIssueStudent]...';


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

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

			(sFinanceCommon.fNumberToWordsWithDecimal(
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)),1,2,SI.OrgGroupId)
			) AS AmountInWords,
			SI.Remark,--Mantis - 0032620
			SI.TransactionDate AS TransactionDate, --Mantis : 0034980
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name  --Mantis - 43970
		
		FROM  
			sProcurement.tStockIssue SI		
			INNER JOIN sProcurement.tStockIssueDetail ID ON SI.Id = ID.StockIssueId
			INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
			LEFT JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
			INNER JOIN sStudent.tAcademic A on A.Id=IssueToSourceId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentID
			INNER JOIN sIp.tItemSubGroupMaster SG ON SG.Id=SIM.ItemSubGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tClassMaster CM on CM.id =A.ClassId 
			INNER JOIN sSetup.tDivisionMaster DM on DM.Id=A.DivisionId
			INNER JOIn sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		WHERE 
			 ((SI.Id = @rId) OR (@rId=0))
			 AND SI.FromStoreLocationId =@rStoreLocationId
			 AND ((SIM.ItemSubGroupId= @rSubGroupId) OR (@rSubGroupId=0))
			 AND ((SIM.Code = @rItemCode) OR (@rItemCode=''))	
			 AND ((SIM.Title = @rItemName) OR (@rItemName=''))
			 AND ((convert(Date,ISNULL(SI.CreatedDateTime,'')) >= @rFromDate) OR (convert(date,ISNULL(@rFromDate,''))=''))
			 AND ((convert(date,ISNULL(SI.CreatedDateTime,'')) <= @rToDate) OR (convert(date,ISNULL(@rToDate,''))=''))
			 AND SI.OrgGroupId = @rOrgGroupId
			 AND ((SI.ToOrganizationDepartmentId=@rToDepartmentId) OR (@rToDepartmentId=0))
			 AND ((SI.Number like @rNumber) OR  (ISNULL(@rNumber,'')= ''))
			 AND ((SI.IssueToSourceId= @rAcademicId) OR (ISNULL(@rAcademicId,0)=0))
			 AND SI.IssueToSourceTypeId = 2001
			 AND ((A.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			 AND ((A.ClassId =  @rClassId) OR (@rClassId=0)) --mantisid : 0034341
			 AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0)) --mantisid : 0034341
			 --AND ((A.BatchId = @rBatchId) OR (ISNULL(@rBatchId,0) = 0))
			 --Mantis : 39564 : Krunal K Patel
			 AND ((convert(Date,ISNULL(SI.TransactionDate,'')) >= @rFromIssueDate) OR (convert(date,ISNULL(@rFromIssueDate,''))=''))
			 AND ((convert(date,ISNULL(SI.TransactionDate,'')) <= @rToIssuedate) OR (convert(date,ISNULL(@rToIssuedate,''))=''))
			--Mantis : 39564 : Krunal K Patel
END
GO
PRINT N'Altering Procedure [sScholarship].[pScholarshipEligibleStudentAdd]...';


GO
ALTER PROCEDURE [sScholarship].[pScholarshipEligibleStudentAdd]
	 
	@rScholarshipId int,
	@rAcademicId bigint,
	@rEligibleAmount decimal(10,2),
	@rIsDeleted bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION	
-- For Delete sScholarship.tScholarshipStudentPaid
 If(@rIsDeleted=1) 
		BEGIN
			If Exists(select 1 from sScholarship.tScholarshipStudentPaid SSP INNER JOIN sScholarship.tScholarshipReceive SR ON SR.Id = SSP.ScholarshipReceiveId 
					AND SR.ScholarshipId=@rScholarshipId AND SSP.AcademicId=@rAcademicId AND SSP.PaidAmount > 0)
					BEGIN
						select -101 as Result
						COMMIT TRANSACTION
						RETURN
					END 
			 ELSE
					BEGIN
						Delete from sScholarship.tScholarshipEligibleStudent where ScholarshipId=@rScholarshipId AND AcademicId=@rAcademicId
						Select @rAcademicId as Result
						COMMIT TRANSACTION
					END
		END	
ELSE
BEGIN
	If Exists(select AcademicId from sScholarship.tScholarshipEligibleStudent where AcademicId=@rAcademicId AND ScholarshipId=@rScholarshipId)
		BEGIN
			select -103 as Result
			COMMIT TRANSACTION
			RETURN
		END 
	   
	INSERT INTO sScholarship.tScholarshipEligibleStudent
		(
			ScholarshipId,
			AcademicId,
			EligibleAmount
		)
	VALUES
		(
			@rScholarshipId,
			@rAcademicId,
			@rEligibleAmount
		)
		             
END	 
		SELECT @rAcademicId AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sSecurity].[pDashletGet]...';


GO
ALTER PROCEDURE [sSecurity].[pDashletGet]
	@rOrgGroupId int=0,
	@rDate date='',
	@rDashletId int=0,
	@rOrgGroupBatchId int=0,
	@rUserId bigint=0,
	@rUserSourceId bigint=0,
	@rUserSourceTypeId int=0,
	@rOrgId Int=0,
	@rSourceTypeId smallint=0,
	@rSourceId bigint=0,
	@rBatchId int=0,
	@rExamId int=0,
	@rStatusId int =0


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

			AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) <= CONVERT(VARCHAR(5),@TimeZoneDate+@BirthdayDays,110)
			AND CONVERT(VARCHAR(5),EM.DateOfBirth,110) >= CONVERT(VARCHAR(5),@TimeZoneDate,110)
			AND EM.DateOfBirth!='' AND EM.StatusId=7
		ORDER BY CONVERT(VARCHAR(5),EM.DateOfBirth,110)
	END
	if(@rDashletId='7')
	BEGIN
		SELECT SC.FirstName + ' ' + SC.MiddleName + ' ' + SC.LastName AS Name, SC.ClassName+' '+SC.DivisionName AS ClassName FROM sStudent.vStudentAllDetail SC
		WHERE SC.OrgId=@rOrgId AND SC.BatchId=@rBatchId
			AND (MONTH(SC.DateOfBirth) = CAST(MONTH(@TimeZoneDate) AS varchar(2))) AND SC.DateOfBirth!='' AND SC.StatusId=1
			AND (DAY(SC.DateOfBirth) = CAST(DAY(@TimeZoneDate) AS varchar(2)))
	END
	if(@rDashletId='10')
	BEGIN
		exec sAttendance.pDashletAttendanceStatusGet @rAcademicId=@rSourceId
	END

	if(@rDashletId='11')
	BEGIN
		SELECT EM.EmployeeName,L.FromDate,L.ToDate
		FROM  sHrm.tLeave L
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId
		WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND L.OrgId = @rOrgId
			AND (EJD.EmployeeManagerId = @rUserSourceId OR @rUserSourceId = 0)
			--AND ((L.FromDate >= @rDate) OR (ISNULL(@rDate,'') = '')) --comment for Mantis Id: 0030464
			AND EM.EmployeeStatusId=7
			AND L.StatusId = 549
		--exec [sHrm].[pLeaveListingGet] @rOrgId=@rOrgId,@rEmployeeId=@rUserSourceId,@rLeaveTypeId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromDate=@rDate,@rTodate=''
	END
	if(@rDashletId='12')
	BEGIN
		exec sCommunication.pPollGet @rOrgGroupBatchId=@rOrgGroupBatchId,@rSourceTypeId=@rUserSourceTypeId,@rCreatedUserId=@rUserId,@rCreatedDateTime=@rDate
	END
	if(@rDashletId='14')
	BEGIN
		exec sCommunication.pMyBookGet @rReaderSourceTypeId=@rUserSourceTypeId,@rReaderSourceId=@rUserSourceId,@rBatchId=@rBatchId,@rStatusId=@rStatusId
	END
	if(@rDashletId='16')
	BEGIN
		exec [sFee].[pRptFeeReceiptTotalGet] @rFromDate=@rDate,@rToDate=@rDate,@rOrgGroupBatchId=@rOrgGroupBatchId
	END

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

	if(@rDashletId='27')
	BEGIN
		--Asset Check
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),AM.CheckedLastDate,103) AS CheckedLastDate
		FROM sAssetManagement.tAssetMaster AM
			INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId
			INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		WHERE ISNULL(AM.IsCheckRequired,0) = 1 AND (AM.CheckFrequencyId=1 AND AM.CheckedLastDate <=  DATEADD(dd,1,@TimeZoneDate) OR AM.CheckFrequencyId=2 AND AM.CheckedLastDate <=  DATEADD(dd,7,@TimeZoneDate) OR AM.CheckFrequencyId=3 AND AM.CheckedLastDate <= DATEADD(dd,30,@TimeZoneDate)) AND AU.InchargeUserId =   @rUserId AND AM.OrgGroupId = @rOrgGroupId



		--SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),
		--AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate
		--FROM sAssetManagement.tAssetMaster AM
		--INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId
		--INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		-- WHERE AU.InchargeUserId = @rUserId AND AM.OrgGroupId = @rOrgGroupId
	END
	if(@rDashletId='28')
	BEGIN
		--Asset maintenance
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName,CONVERT(nvarchar(12),AM.LastMaintenanceDate,103) AS LastMaintenanceDate,CONVERT(nvarchar(12),AM.NextMaintenanceDate,103) AS NextMaintenanceDate
		FROM sAssetManagement.tAssetMaster AM
			INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId
			INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		WHERE AU.InchargeUserId = @rUserId AND AM.OrgGroupId = @rOrgGroupId
	END
	if(@rDashletId='29')
	BEGIN
		--Asset Renew
		SELECT LM.Title AS LocationName, AM.Code AS AssetCode, AM.Title AS AssetName, CONVERT(nvarchar(12),AM.RenewLastDate,103) AS RenewLastDate, CONVERT(nvarchar(12),AM.RenewNextDate,103) AS RenewNextDate
		FROM sAssetManagement.tAssetMaster AM
			INNER JOIN sAssetManagement.tAssetInchargeUser AU ON AM.Id = AU.AssetId
			INNER JOIN sFixedAsset.tLocationMaster LM ON LM.Id = AM.LocationId
		WHERE ISNULL(AM.IsRenewRequired,0) = 1
			--AND AM.RenewNextDate >= DATEADD(dd,ISNULL(AM.RenewAlertBeforeDays,0),AM.RenewLastDate)
			AND convert(Date,@TimeZoneDate) >=  DATEADD(dd,-ISNULL(AM.RenewAlertBeforeDays,0), AM.RenewNextDate)
			AND AU.InchargeUserId =  @rUserId
			AND AM.OrgGroupId = @rOrgGroupId
	END
	--Inward
	IF(@rDashletId='30')
	BEGIN
		DECLARE @InwardRegisterGrid VARCHAR(max)=''
		SELECT  @InwardRegisterGrid = @InwardRegisterGrid + '<tr>
	       <td align="left" scope="col">' + ISNULL(LetterNumber,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterSubject,'') + '</td>
	       <td align="left" scope="col">' + ISNULL(LetterFrom,'') + '</td>
	       <td align="left" scope="col">' + convert(varchar,isnull(ReceivedDate,'01/01/0001'),103) + '</td>
	 	</tr>'
		FROM sFrontOffice.tInwardRegister
		WHERE IsReplyRequired=1 AND IsReplied=0 AND OrgId=@rOrgId AND ReceivedDate<=convert(Date,@TimeZoneDate)
		Order by ReceivedDate Desc

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

		SELECT Isnull(@OutwardRegisterGrid,'') As	OutwardRegisterGrid
	END

	IF(@rDashletId='32')
	BEGIN
		DECLARE @ReorderQuantityGrid VARCHAR(max)=''
		SELECT   @ReorderQuantityGrid=@ReorderQuantityGrid+'<tr>
			<td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
			<td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
			<td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
			<td align="left" scope="col">' + convert(varchar,isnull(SP.ReOrderQuantity,0)) + '</td>
		</tr>'
		FROM sProcurement.tStockBatch SB
			INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
			INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
			INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
			--INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
		WHERE SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0
		group by SE.Title,SM.Title,SP.ReOrderQuantity,SP.ReOrderPoint
		HAVING SUM(SB.AvailableQuantity) < SP.ReOrderPoint

		SELECT Isnull(@ReorderQuantityGrid,'') As	ReorderQuantityGrid
	END

	IF(@rDashletId='33')
	BEGIN
		DECLARE @SafetyStockGrid VARCHAR(max)=''
		SELECT   @SafetyStockGrid=@SafetyStockGrid+'<tr>
			<td align="left" scope="col">' + ISNULL(SE.Title,'')  + '</td>
			<td align="left" scope="col">' +ISNULL(SM.Title,'')  + '</td>
			<td align="left" scope="col">' +convert(varchar,ISNULL(SUM(SB.AvailableQuantity),0))+ '</td>
			<td align="left" scope="col">' + convert(varchar,isnull(SP.SafetyStock,0)) + '</td>
		</tr>'
		FROM sProcurement.tStockBatch SB
			INNER JOIN sIp.tStockItemMaster SM ON SM.Id=SB.STockItemID
			INNER JOIN sIp.tStoreLocationMaster SE ON SE.Id=SB.StoreLocationId
			INNER JOIN sIp.tStockItemPlanning SP ON SP.STockItemID=SM.Id AND SP.StoreLocationId =SE.Id
			--INNER JOIN  sSecurity.tUserLocation UL ON UL.StoreLocationId = SB.StoreLocationId
		WHERE  SM.OrgGroupId=@rOrgGroupId AND SM.IsObsolete=0
		group by SE.Title,SM.Title,SP.SafetyStock,SP.ReOrderPoint
		HAVING SUM(SB.AvailableQuantity) < SP.SafetyStock

		SELECT Isnull(@SafetyStockGrid,'') As	SafetyStockGrid
	END
	IF(@rDashletId='34')
	BEGIN
		DECLARE @Increment varchar(max)=''
		SELECT @Increment=@Increment+'<tr>
			<td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
			<td align="left" scope="col">' +convert(varchar,isnull(IncrementDate,'01/01/0001'),103)  + '</td>
		</tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE IncrementDate BETWEEN GETDATE()-1 AND GETDATE()+7 AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Increment, '') As IncrementGrid
	END

	IF(@rDashletId='78')
	BEGIN
		DECLARE @Retirement varchar(max)=''
		SELECT @Retirement=@Retirement+'<tr>
			<td align="left" scope="col">' + ISNULL(EM.FirstName,'') + ' '+ISNULL(EM.LastName,'') + '</td>
			<td align="left" scope="col">' +convert(varchar,isnull(RetirementDate,'01/01/0001'),103)  + '</td>
		</tr>'
		FROM sHrm.tEmployeeStatutoryAndOther SA INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=SA.EmployeeId
		WHERE RetirementDate BETWEEN GETDATE()-1 AND GETDATE()+30 AND EM.OrgID=@rOrgId And EM.StatusId=7
		SELECT Isnull(@Retirement, '') As RetirementGrid
	END

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

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

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

	IF(@rDashletId='87')
	BEGIN
		Declare @lOrgGroupBatchId int=0
		select @lOrgGroupBatchId=OrgGroupBatchId from sSetup.tBatchMaster where Id=@rBatchId
		SELECT Distinct
			PDP.Id
			,ISNULL(SA.Code, '') AS IdNo
			,ISNULL(SA.Name, '') AS StudentName
			,PDP.Amount AS ReceiptAmount
			,PDP.ChequeNo
			,PDP.PaymentClearanceDate
		FROM
			sFee.tPostDatePayment PDP
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = PDP.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = PDP.BatchId
			INNER JOIN [sStudent].[vStudentAcademic] SA ON SA.AcademicId = PDP.SourceId AND PDP.SourceTypeId = 2001
		--Mantis: 40861, comment the below where condition and add new where condition
		--WHERE  (PDP.OrgId = @rOrgId OR @rOrgId = 0)
		--	AND (PDP.BatchId = @rBatchId OR @rBatchId = 0)
		--	AND (PDP.PaymentClearanceDate <= @rDate OR ISNULL(@rDate, '') = '')
		--	AND PDP.StatusId = 751
		WHERE (PDP.OrgGroupBatchId = @lOrgGroupBatchId OR @lOrgGroupBatchId = 0)
			AND (PDP.PaymentClearanceDate <= @rDate OR ISNULL(@rDate, '') = '')
			AND PDP.StatusId = 751
		ORDER BY PDP.PaymentClearanceDate DESC
	END

--Added by dhananjay for mantis : 41224
	IF(@rDashletId='88')
	BEGIN
		DECLARE @lForDate nvarchar(20), @Query nvarchar(max)
 
		Set @lForDate = Right('0'+(convert(nvarchar(2),(Day(@rDate)))),2)
 
		SET @Query='SELECT EM.Id as EmployeeId,  ISNULL(EM.FirstName, '''') + '' '' + ISNULL(EM.LastName, '''') AS EmpName, 
			isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ '+@lForDate+') as datetime),
			cast(rtrim(YEAR('''+convert(nvarchar(max),@rDate)+''') *10000+ Month('''+convert(nvarchar(max),@rDate)+''') *100+ '+@lForDate+') as datetime)),
			D'+@lForDate+',ISNULL(D'+@lForDate+'_IN,''00:00'') as FirstIn,ISNULL(D'+@lForDate+'_OUT,''00:00'') as LastOut,
			D'+@lForDate+'_O,D'+@lForDate+'_L,D'+@lForDate+'_T,D'+@lForDate+'_E,D'+@lForDate+'_S 
			FROM sHRM.tEmployeeMaster EM
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
				LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId 
						AND MT.ATTN_DT = cast(rtrim(YEAR('''+convert(nvarchar(max),@rDate)+''') *10000+ Month('''+convert(nvarchar(max),@rDate)+''') *100+ 01) as datetime)
			WHERE (EM.Id = '+convert(nvarchar(max),@rSourceId)+' OR '+convert(nvarchar(max),@rSourceId)+' = 0)
			AND EM.OrgId = '+convert(nvarchar(max),@rOrgId)+'
			AND (EJD.DateOfJoining<= '''+convert(nvarchar(max),@rDate)+''')
			AND (EJD.DateOfleaving>= '''+convert(nvarchar(max),@rDate)+''' OR ISNULL(EJD.DateOfleaving,'''')='''')
			AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
			AND EM.StatusId=7'
 
		EXEC(@Query)
	END
	--Added by dhananjay for mantis : 41224
END
GO
PRINT N'Altering Procedure [sSecurity].[pLoggedInUserGet]...';


GO
ALTER PROCEDURE [sSecurity].[pLoggedInUserGet]
	@rOrgId [smallint],
	@rUserId [bigint],
	@rStoreLocationId [int],
	@rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lOrgGroupId int
DECLARE @lBatchId int
DECLARE @lBatchTitle nvarchar(100)
DECLARE @lDisplayTitle nvarchar(100)
DECLARE @lAffiliationId smallint
DECLARE @lAffiliationTypeId smallint
DECLARE @lOrgGroupBatchId int
DECLARE	@lFromDate date
DECLARE	@lToDate date
DECLARE @lOrgLogo varbinary(max)
--DECLARE @lLocationId int
--DECLARE @lLocationName nvarchar(100)

--SELECT @lLocationId = LocationId, @lLocationName = LocationName FROM sSecurity.vExtUserLocation
--WHERE StoreLocationId = @rStoreLocationId AND UserId = @rUserId 
	SELECT
		@lOrgGroupId=OM.OrgGroupId,
		@lBatchId=BM.Id,
		@lBatchTitle=BM.Title,
		@lDisplayTitle=OM.DisplayTitle,
		@lAffiliationId=OM.AffiliationId,
		@lAffiliationTypeId=AT.AffiliationTypeId,
		@lOrgGroupBatchId=BM.OrgGroupBatchId,
		@lFromDate=BM.FromDate,
		@lToDate=BM.ToDate,
		@lOrgLogo=OM.OrgLogo
	FROM sSetup.tOrganizationMaster OM WITH (NOLOCK)
		INNER JOIN sSetup.tBatchMaster BM WITH (NOLOCK) ON BM.OrgId=OM.Id AND BM.Id = @rBatchId AND BM.OrgId=@rOrgId
		INNER JOIN sSetup.tAffiliationMaster AT WITH (NOLOCK) ON OM.AffiliationId = AT.Id 
		
	SELECT 
		@rOrgId AS OrgId,
		@lOrgGroupId AS OrgGroupId,
		@lBatchId AS BatchId,
		@lBatchTitle AS BatchTitle,
		@lDisplayTitle AS OrgDisplayTitle,
		UserTbl.Id AS UserId, 		
		UserTbl.LoginTitle,
		UserTbl.DisplayTitle,		 
		--UserTbl.EmployeeId AS EmployeeId, 
		UserTbl.SourceId AS UserSourceId,
		UserTbl.SourceTypeId AS UserSourceTypeId,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			(EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ' ' + EM.LastName)
		ELSE
			SA.Name
		END   AS EmployeeFullName,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			(EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ' ' + EM.LastName)
		ELSE
			SA.Name
		END   AS UserFullName,
		--CASE WHEN UserTbl.SourceTypeId = 95 THEN
		--	EM.EmployeeJobTitleId
		--ELSE
		--	0
		--END AS EmployeeJobTitleId,
		ScreenTbl.Page AS HomePageUrl,
		MenuTbl.Id AS MenuId,
		UserPrefTbl.FavoriteScreenID AS ScreenID,
		ISNULL(UserTbl.SessionId,'') AS SessionId,
		UR.RoleId,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			0
		ELSE
			SA.RollNo
		END AS UserNo,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			EM.DepartmentName
		ELSE
			SA.ClassName+' - '+SA.DivisionName
		END AS UserDepartment,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			EM.Code
		ELSE
			SA.Code
		END AS UserIdNo,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			EI.EmployeePhoto
		ELSE
			SI.StudentPhoto
		END AS UserPhoto,
		CASE WHEN UserTbl.SourceTypeId = 95 THEN
			EM.GenderId
		ELSE
			ISNULL(SO.GenderId,1)
		END AS GenderId,
		--0 AS AccountingYearId,
	 --   '' AS AccountingYearCode,
		--ISNULL((select Id from sAccounting.tAccountingYearMaster WHERE OrgId = @rOrgId AND IsActive = 1),0) AS AccountingYearId,
		--ISNULL((select Code from sAccounting.tAccountingYearMaster WHERE OrgId = @rOrgId AND IsActive = 1),0) AS AccountingYearCode,
		@lAffiliationId AS AffiliationId,
		@lOrgGroupBatchId AS OrgGroupBatchId,
		@lFromDate AS BatchFromDate,
		@lToDate AS BatchToDate,
		ISNULL(SA.AcademicId,0) AS AcademicId,
		@lAffiliationTypeId AS AffiliationTypeId,
		@lOrgLogo AS OrgLogo
		
		--@lLocationId AS LocationId,
		--@lLocationName AS LocationName	
					
	FROM sSecurity.tUser UserTbl WITH (NOLOCK)
		INNER JOIN sSecurity.tUserRole UR WITH (NOLOCK)
			ON UR.UserId=UserTbl.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND UR.UserId=@rUserId	
		LEFT JOIN sHrm.vExtEmployeeMaster EM WITH (NOLOCK)
			ON EM.Id = UserTbl.SourceId 
			--AND UserTbl.OrgId = EM.OrgId 
			AND UserTbl.SourceTypeId = 95 
			--AND EM.StatusId !=9
		LEFT JOIN sHrm.tEmployeeImages EI WITH (NOLOCK)
			ON EI.EmployeeId=EM.Id
		LEFT JOIN sStudent.vStudentAcademic SA WITH (NOLOCK)
			ON SA.StudentId = UserTbl.SourceId 
			--AND UserTbl.OrgId = SA.OrgId 
			AND SA.BatchId=@rBatchId 
			AND UserTbl.SourceTypeId = 2003	
		LEFT JOIN sStudent.tStudentOther SO WITH (NOLOCK) ON SO.StudentId=SA.StudentId
		LEFT JOIN sStudent.tStudentImages SI WITH (NOLOCK)
			ON SI.StudentId=SA.StudentId
		LEFT OUTER JOIN sSecurity.tUserPreference UserPrefTbl WITH (NOLOCK)
			ON UserTbl.Id = UserPrefTbl.UserId 
			--AND  UserTbl.OrgId = UserPrefTbl.OrgId
		LEFT OUTER JOIN sSecurity.tScreen ScreenTbl WITH (NOLOCK)
			ON UserPrefTbl.FavoriteScreenId = ScreenTbl.Id			
		LEFT OUTER JOIN sSecurity.tMenu MenuTbl WITH (NOLOCK)
			ON MenuTbl.ScreenId =  ScreenTbl.Id	
	WHERE 
		UserTbl.Id = @rUserId 
		AND UserTbl.IsObsolete=0
		AND ((EM.StatusId = 7 AND UserTbl.SourceTypeId = 95) OR (SA.StatusId = 1 AND UserTbl.SourceTypeId = 2003) OR (UserTbl.SourceTypeId=1) OR (ISNULL(UserTbl.SourceTypeId,0) = 0))
END
GO
PRINT N'Altering Procedure [sSecurity].[pMenu_Migration]...';


GO


ALTER PROCEDURE [sSecurity].[pMenu_Migration]
 @rUserId [bigint],
 @rMenuId int = 0,
 @rResourceTypeId int= 0,
 @rIsCoreMenu bit = 0,
 @rEnvironmentName nvarchar(max) ,
 @rScreenGroupId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 IF(@rIsCoreMenu=0)
 BEGIN
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
  BEGIN
   SELECT
    MenuID,
    ModuleId,
    ParentMenuID,
    MenuTitle,
    ScreenTitle,
    PageURL,
    ScreenId,
    Permission,
    OrderNumber,
    TaskId,
    PageURL  AS PagePath,
    IconPath

   FROM
     (SELECT Menu.Id AS MenuID,
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,
    Menu.Title AS MenuTitle,
    ISNULL(Screen.Title, '') AS ScreenTitle,
    ISNULL(Screen.Page, '') AS PageURL,
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
    ISNULL(Menu.ScreenId, 0) AS ScreenId,
    ISNULL(PermissionValue, 0) AS Permission,
    ISNULL(OrderNumber, 0) AS OrderNumber,
    ISNULL(Screen.TaskId,0) AS TaskId,
    ISNULL(Screen.IconPath,'') As IconPath,
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
    ISNULL(T.ModuleId,0) AS ModuleId


   FROM sSecurity.tMenu Menu
   LEFT OUTER JOIN sSecurity.tScreen Screen
    ON Menu.ScreenId = Screen.Id
   LEFT OUTER JOIN (
       SELECT
        TaskId,
        SUM(Permission & 2) PermissionValue
       FROM
        sSecurity.tPermissionUser P
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
       WHERE
        T.IsObsolete = 0 AND P.UserId = @rUserId
       GROUP BY
        TaskId) TBL2
       ON
        Screen.TaskId = TBL2.TaskId
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId

       WHERE
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
       AND ISNULL(Screen.IsObsolete, 0) = 0)
       MenuTable
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId
   WHERE
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2
    AND
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))

   ORDER BY
    ParentMenuID
  END
 ELSE
  BEGIN
   SELECT
    MenuID,
    ModuleId,
    ParentMenuID,
    MenuTitle,
    ScreenTitle,
    PageURL,
    ScreenId,
    Permission,
    OrderNumber,
    TaskId,
     PageURL  AS PagePath,
     IconPath

   FROM
     (SELECT Menu.Id AS MenuID,
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,
    Menu.Title AS MenuTitle,
    ISNULL(Screen.Title, '') AS ScreenTitle,
    ISNULL(Screen.Page, '') AS PageURL,
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
    ISNULL(Menu.ScreenId, 0) AS ScreenId,
    ISNULL(PermissionValue, 0) AS Permission,
    ISNULL(OrderNumber, 0) AS OrderNumber,
    ISNULL(Screen.TaskId,0) AS TaskId,
    ISNULL(Screen.IconPath,'') As IconPath,
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
    ISNULL(T.ModuleId,0) AS ModuleId


   FROM sSecurity.tMenu Menu
   LEFT OUTER JOIN sSecurity.tScreen Screen
    ON Menu.ScreenId = Screen.Id
   LEFT OUTER JOIN (
       SELECT
        TaskId,
        SUM(Permission & 2) PermissionValue
       FROM
        sSecurity.tPermission P
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId
        INNER JOIN
        (
        SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0
        ) B ON B.RoleId = P.RoleId
       WHERE
        T.IsObsolete = 0
       GROUP BY
        TaskId) TBL2
       ON
        Screen.TaskId = TBL2.TaskId
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId

       WHERE
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page
       AND ISNULL(Screen.IsObsolete, 0) = 0)
       MenuTable
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId
   WHERE
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2
    AND
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))

   ORDER BY
    ParentMenuID
  END
 END
 ELSE
 BEGIN
 if (@rScreenGroupId = 0)
 BEGIN
  SELECT
   MenuID,
   ModuleId,
   ParentMenuID,
   MenuTitle,
   ScreenTitle,
   PageURL,
   ScreenId,
   Permission,
   OrderNumber,
   TaskId,
   PageURL AS PagePath,
   MenuIsObsolete,
   Icon
  FROM
  (
	SELECT
   ISNULL(Menu.Id,0) AS MenuID,
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,
   ISNULL(Menu.Title,'') AS MenuTitle,
   ISNULL(Screen.Title, '') AS ScreenTitle,
   ISNULL(Screen.Page, '') AS PageURL,
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,
   ISNULL(Menu.ScreenId, 0) AS ScreenId,
   ISNULL(PermissionValue, 0) AS Permission,
   ISNULL(OrderNumber, 0) AS OrderNumber,
   ISNULL(Screen.TaskId,0) AS TaskId,
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
   ISNULL(T.ModuleId,0) AS ModuleId,
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,
   ISNULL(Screen.IconPath,'') AS Icon
  FROM
  sSecurity.tMenu Menu
  LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id
  LEFT OUTER JOIN
  (
  SELECT
   P.TaskId,
   SUM(OT.AvailablePermission & 2) PermissionValue
  FROM
   sSecurity.tPermission P
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId  AND T.IsObsolete = 0
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId
  GROUP BY P.TaskId
  ) TBL2 ON Screen.TaskId = TBL2.TaskId
  LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId
  WHERE (Menu.IsObsolete = 0)
  AND ISNULL(Screen.IsObsolete, 0) = 0
  AND (
		(@rEnvironmentName = 'Local' AND Menu.Id in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215,1822,19181017,52,5210,5211,2212,5514,5516,2212,5533,54,5410,19181033,19181023,5414,19184004,19181038,5411,1811)) -- updated by parth/Darsh for showing more menu inside the communication 07-02-2023
	OR (@rEnvironmentName = 'QA' AND Menu.Id in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215,1822,19181017,52,5210,5211,2212,5514,5516,2212,5533,54,5410,19181033,19181023,5414,19184004,19181038,5411,1811))
	OR (@rEnvironmentName = 'Production' AND Menu.Id in(24,55,2411,2412,2711,2714,19184006,19181022,2622,15,57,5535,19181039,5511,5510))
	)

  --AND Menu.Id  in (24,2711,2411)  -- Issue: For Only Student Center, My Communication Menu , Developer: Foram, Date: 15-07-2022
  --AND (Menu.Id  in (24,2711)
  --Or ParentMenuID  in (24,2711))
  --AND (Menu.Id IN (15, 32, 55,24, 19181042, 36, 3606,2714)
  --OR ParentMenuID IN (15, 32, 55, 19181042, 36, 24, 18))
  UNION

  SELECT

   ISNULL(Menu.Id, 0) AS MenuID,
   ISNULL(Menu.Id, 0) AS ParentMenuID,
   ISNULL(Screen1.Title,'') AS MenuTitle,
   ISNULL(Screen1.Title, '') AS ScreenTitle,
   ISNULL(Screen1.Page, '')  AS PageURL,
   ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,
   ISNULL(Menu.ScreenId, 0) AS ScreenId,
   ISNULL(PermissionValue, 0) AS Permission,
   ISNULL(OrderNumber, 0) AS OrderNumber,
   ISNULL(Screen1.TaskId,0) AS TaskId,
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
   ISNULL(T.ModuleId,0) AS ModuleId,
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,
   ISNULL(Screen1.IconPath,'') AS Icon
  FROM
   sSecurity.tMenu Menu
   LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id
   LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId
   LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId
   LEFT OUTER JOIN (
  SELECT
   P.TaskId,
   SUM(OT.AvailablePermission & 2) PermissionValue
  FROM
   sSecurity.tPermission P
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId   AND T.IsObsolete = 0
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId

  GROUP BY P.TaskId
  ) TBL2 ON Screen1.TaskId = TBL2.TaskId
  WHERE (Menu.IsObsolete = 0)
  AND ISNULL(Screen1.IsObsolete, 0) = 0
  --AND (Menu.ParentMenuID  in (24,2711)
  --or Menu.Id  in (24,2711))
  AND Screen1.Id IN (10187,30363,30342,20241,30282,20565,20563,30377,20915,30331,20564,20180,20617,30364,20130,30818,30828,20191,30787,20996,20717  -- Issue: For Only Student Center Menu , Developer: Foram, Date: 15-07-2022
		,9137,20054,20085,20088,20093,20099,20104,20107,20172,20198,20204,20209,20222,20566,20577,20692,20723,20724,30228,30242,30254,30365,30556,30559,30585,30794,30858,30943,31175,30921,20103,20102,30561, -- Issue: For Only My Communication Menu , Developer: Foram, Date: 20-07-2022
		30857,30696,30739,30284,20171,20105,31048,9136,30678,20179,30793,20720,20115,20693,20086,20819,20126,20950,20094,30856,30855,30795,30789,20697,20758,20083,30245,30246,20125,30874,30274,30817,30251,30252,30253,30247,30395, -- this line for communication screen changes by parth
		20983,30071,30103,30859,30935,30602,30848,30362,20181,20246,20576,20916,20979,30020,30093,30106,30115,30124,30134,30139,30149,30257,30327,30788,30455,30344,31005, -- this line for employee center screen changes by parth
		20108,30298,30552,20025,20026,20068,20336,20551,20719,20866,20894,20899,20900,3009530203,30296,30701,30816,30962, -- this line for fees screen changes by parth
		20396,20630,30138,30548,31012,20075,20161,20163,20167,20654,20985,30974,30994,20388,20073,20074,20165,20224,20462, -- this line for atte screen changes by parth
		20766,20927,20555,30366,20622,30651,30515,20554,20561,20159, 30664, -- this line is use for academic module
		30236,30500,30600,30604,31188,31182,30797,30471,30456,30411,30412,30409,30410,30447,30449,20949,20197,20056,20750,20759,20952,20059,20150,20153, --17/05/2023
		20951,20679,20233,31016,20124,30007,20120,20123,20375,20676,20986,20376,20122,30544,20194,30777,30193,30041,20131,20132,20133,20134,20374,20135,20136,20137,30381,30382,20677,20199,30292,20121,20413,31013,10160,20676,30390,30391,
		30100,30102,30105,30110,30107,30108,30113,
		31224,20930,20932,30936,30951,20284,20696,20698,20700,20776,20918,30164,30579,20570,20567,20568,20173,20174,20260, -- Payroll
		20187,20188,20189,30059,30034,
		20325,20379,20380,20631,20235,20043,
		20997,20201,20215,20297,20848,30235,30687,30688,30689,31307,20170,20195,30546,30547,20216,20221,30582,20961,20960,20962,
		20243,20244,20247,20945,30599,30755,30932,31179,30680,30116,30176,30070,20538,20687,20743,20816,20817,20248,20245,30694,20280,20537,10201,10202,10203,20846,30080,30081,30137,30346,30375,30682
		,30685,30580,30178,30180,20948,20919,20920,31382,
		30661,20845,20844,20843,20653,20681,20663,20658,30966,
		8,9,10,11,19,21,9013,9029,20018,20037,20142,20143,20144,20145,20146,20157,20173,20174,20332,20419,20678,20689,20835,20860,20941,30267,30698,30950,30985,31036,20728,20730,20831,7,20931,20,9030,18,
		30499,121,122,124,125,20158,20175,20176,20309,20596,30120,30122,30577,30602,30778,20250, -- Security
		20001,20002,20003,20004,20006,20007,20008,20285,30021,30338,30509,20953,31173,31379,20967,30995,20323,20616,20913,20055,30801,20632,30030,
		441,459,460,476,500,30699,30716,30847,31003,31004,31020,31021,31022,30852,30991,31177,31187,31257,30388,30627,20908,20909,20910,30269,30517,30567,30614,30617,20035,601,602,603,604,605,606,9084,20270,20339,20402,20230,20573,20586,20629,20836,31174,10117,524,30446,30451,30675,30676,30619,10217,30923,31025,31034,31035,10097,20904,20905,20638,20729,20834,20613,20432,20433,20435,31176,10118,31262,31303,30774,30849,30337,20249,20841,20965,30679,30691,
		20409,20727,20907,20919,20971,30564,30732,20998,31315,31027,31028,30019,30831,30850,30612,30626,30650,30535,20978,20882,20208,20416,20513,20514,20544,20553,20688,31348,31359,31364,20716,20268,20968,20828,30271,30343,31225,30931,30596,30597,20259,20623,30538,30545,30955,30957,30939,31383,
		20518,30908,30259,30208,30118,20878,20969,20975,20840,

500,476,459,460,449,408,409,449,472, -- this line for HR master module
31410,
20021,20643,30204,30205,30618,30796,30798,30971,30972,30970,30605,30609,31335,30329,30531,20628,20269,20539,20227,20127,20147,30268,30299,30554,20207,20539,30539,30615,30970,20963,20539,30098,30539,30096,30068,
20010,20013,20014,20016,20019,20560,20875,20973,20987,30234,30335,30332,30726,30534,20009,31433,31434, -- this line for Student Management and Setting module
20061,20063,20064,20065,20066,20067,20069,20070,20071,20072,20389,20390,20552,20557,30227,30457,30578, -- this line for Certificate module
20079,20080,20226,20540,20694,20695,20715,20726,20728,20818,20947,30008,30336,30549,30870,30958,31228,20917,20633,20168,30032, -- this line for Admission module
20058,20151,20621,20748,20751,31420, -- this line for Event | Activity Master
30027,20262,30111,30161,30243,30262,30415,30581,30976,30977,30978,30999,31038,31172,31204,31313,30889, -- this line for Biometric module
20033,20057,20034,20060,20062,20237,20258,20271,20276,20286,20316,20385,20418,20427,20464,20490,20682,20684,20711,20714,20761,20962,30072,30113,30114,30130,30132,30408,30450,30996,30997,31046,  -- this line for Assesment General module
20729,20741,20730,20742,20744,20745,20746,20749,20752,20829, -- this line for activity based
20096,20098,20239, -- line for cce
20076,20078,20081,20082,20084,20087,20090,20092,20072,20082,20932,20923,20925,20934,20995,30006,20434,20436,20468,20478,20479,20480,20618,20710, --co scholastic
20317, -- GSEB
20912, -- MHBHSE
30215, -- CBSE
143,127 -- Configuration
		)
  --AND Screen1.Id IN (9147, 30300, 30301, 30330, 30341, 30782, 30783, 30784, 30785, 30786, 30787, 30788, 30790, 30791, 30792, 30499,20246,
  --30914,30913,30912,30911
  --)
  ) MenuTable
  WHERE
  --(MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2)
  --AND
  ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
  AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))
  AND MenuIsObsolete = 0
  --AND MenuTable.MenuId IN (15,32,36,55,24,1515,3606,19184009,19181042,2714,19184020)
  AND (
		(@rEnvironmentName = 'Local' AND MenuTable.MenuId in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215,1822,19181017,52,5210,5211,2212,5514,5516,2212,5533,54,5410,19181033,19181023,5414,19184004,19181038,5411,1811)) -- updated by parth/Darsh for showing more menu inside the communication 07-02-2023
	OR (@rEnvironmentName = 'QA' AND MenuTable.MenuId in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511,19181043,58,1813,2216,19181039,5510,18,1815,1810,1821,2215,1822,19181017,52,5210,5211,2212,5514,5516,2212,5533,54,5410,19181033,19181023,5414,19184004,19181038,5411,1811))
	OR (@rEnvironmentName = 'Production' AND MenuTable.MenuId in(24,55,2411,2412,2711,2714,19184006,19181022,2622,15,57,5535,19181039,5511,5510))
	)
  --AND MenuTable.MenuId  in (24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622)  -- updated by parth for showing more menu inside the communication 07-02-2023
  --AND MenuTable.MenuId  in (24,2711,2411)  -- Issue: For Only Student Center, My Communication Menu , Developer: Foram, Date: 15-07-2022
  ORDER BY ParentMenuID
  END
  ELSE
  BEGIN
	IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
	BEGIN
		Select


				ISNULL(0, 0) AS MenuID,
				ISNULL(0, 0) AS ParentMenuID,
				ISNULL(S.Title,'') AS MenuTitle,
				ISNULL(S.Title, '') AS ScreenTitle,
				ISNULL(S.Page, '')  AS PageURL,
				ISNULL(S.ScreenGroupId,0) AS ScreenGroupId,
				ISNULL(S.Id, 0) AS ScreenId,
				ISNULL(0, 0) AS Permission,
				ISNULL(0, 0) AS OrderNumber,
				ISNULL(S.TaskId,0) AS TaskId,
				ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
				ISNULL(MP.ModuleId,0) AS ModuleId,
				ISNULL(1,1) AS MenuIsObsolete,
				ISNULL(S.IconPath,'') AS Icon

			   From sSecurity.tScreen S
		INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId
		--INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId
		INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId
		INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.ID = T.ResourceTypeId
		INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
		INNER JOIN sSecurity.tModulePermission MP ON T.ModuleId = MP.ModuleId And OT.OrgGroupId = MP.OrgGroupId

		WHERE
		(P.Permission & 2) =2
		AND ( ScreenGroupId=@rScreenGroupId OR @rScreenGroupId = 0)
		AND P.UserId=@rUserId
		AND T.IsObsolete = 0
		AND S.IsObsolete = 0
		AND S.IsHideInScreenGroup = 0
		Order by RTM.OrderIndex,S.OrderIndex
	END
	ELSE
	BEGIN
		Select

				ISNULL(0, 0) AS MenuID,
				ISNULL(0, 0) AS ParentMenuID,
				ISNULL(S.Title,'') AS MenuTitle,
				ISNULL(S.Title, '') AS ScreenTitle,
				ISNULL(S.Page, '')  AS PageURL,
				ISNULL(S.ScreenGroupId,0) AS ScreenGroupId,
				ISNULL(S.Id, 0) AS ScreenId,
				ISNULL(0, 0) AS Permission,
				ISNULL(0, 0) AS OrderNumber,
				ISNULL(S.TaskId,0) AS TaskId,
				ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,
				ISNULL(MP.ModuleId,0) AS ModuleId,
				ISNULL(1,1) AS MenuIsObsolete,
				ISNULL(S.IconPath,'') AS Icon


			   From sSecurity.tScreen S
		INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId
		INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId
		INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId
		INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.ID = T.ResourceTypeId
		INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId
		INNER JOIN sSecurity.tModulePermission MP ON T.ModuleId = MP.ModuleId And OT.OrgGroupId = MP.OrgGroupId

		WHERE
		(P.Permission & 2) =2
		AND ( ScreenGroupId=@rScreenGroupId OR @rScreenGroupId = 0)
		 AND U.IsObsolete=0
		AND U.UserId=@rUserId
		AND T.IsObsolete = 0
		AND S.IsObsolete = 0
		AND S.IsHideInScreenGroup = 0
		Order by RTM.OrderIndex,S.OrderIndex
	END
  END
 END
END
GO
PRINT N'Altering Procedure [sSecurity].[pMigrationModulePermissionAdd]...';


GO
ALTER PROCEDURE [sSecurity].[pMigrationModulePermissionAdd]
          
   @rOrgGroupId smallint,
   @rXML nvarchar(max)
 
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
DECLARE @loDoc INT

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION	
	
	EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
	CREATE TABLE #ListofData(AutoId int, [Key] VARCHAR(MAX),[Status] bit,Value VARCHAR(MAX),ERPProductId int,OrgGroupId int)
	insert into #ListofData
		select E.AutoId,E.[Key],E.[Status],E.Value,E.ERPProductId,E.OrgGroupId
		from
		(
			SELECT 
				AutoId,
				[Key],
				[Status],
				CASE WHEN CHARINDEX('<', Value) > 0 THEN REPLACE(Value, '<', '&lt;') 
				WHEN CHARINDEX('>', Value) > 0 THEN REPLACE(Value, '>', '&gt;') 
				ELSE Value END AS Value,
				ERPProductId,
				OrgGroupId 
			FROM
			OPENXML (@loDoc, '/Modules/Module', 2)
			WITH (
					AutoId int,
					[Key] VARCHAR(MAX), 
					[Status] bit,
					Value VARCHAR(MAX),
					ERPProductId int,
					OrgGroupId int
				)	
		)E 	

	 -- UPSERT logic: Update if AutoId > 0 and exists, else insert
    MERGE sSecurity.tMigrationModulePermission AS target
    USING (
        SELECT AutoId, [Key], [Status], Value, ERPProductId, OrgGroupId
        FROM #ListofData
    ) AS source
    ON target.OrgGroupId = source.OrgGroupId AND target.[Key] = source.[Key]
    WHEN MATCHED AND source.AutoId > 0 THEN
        UPDATE SET
            target.Value = source.Value,
            target.ERPProductId = source.ERPProductId,
            target.[Status] = source.[Status],
			target.UpdatedDateTime = GETDATE()
    WHEN NOT MATCHED BY TARGET THEN
        INSERT (OrgGroupId, [Key], Value, ERPProductId, [Status])
        VALUES (source.OrgGroupId, source.[Key], source.Value, source.ERPProductId, source.[Status]);

	--INSERT INTO sSecurity.tMigrationModulePermission(OrgGroupId,[Key],Value,ERPProductId,[Status])
	--SELECT OrgGroupId,[Key],Value,ERPProductId,[Status] FROM #ListofData WHERE [Status] = 1

	Drop Table #ListofData

	SELECT 1 AS Result
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result, ERROR_MESSAGE()
	END CATCH	
	
END
GO
PRINT N'Altering Procedure [sSecurity].[pPermissionGet]...';


GO
ALTER PROCEDURE [sSecurity].[pPermissionGet]
	@rOrgGroupId [int],
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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


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


GO
ALTER PROCEDURE [sSecurity].[pUserSessionIdModify]
	@rOrgId [smallint],
	@rUserId [bigint],
	@rSessionId [nvarchar](50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN		

DECLARE @lIsLogEnable bit = 0

IF(@lIsLogEnable = 1)
BEGIN
	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('sSecurity.pUserSessionIdModify Start', 
	'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
	'', '', GETDATE(), 'sSecurity.pUserSessionIdModify')
END

	DECLARE @lCurrentDateTime DATETIME
	EXECUTE @lCurrentDateTime = sCommon.fGetDate		
	BEGIN
			UPDATE sSecurity.tUser WITH (ROWLOCK)
			SET	
				SessionId = @rSessionId,				
				LastLockOutDate = @lCurrentDateTime,
				UpdatedDateTime = @lCurrentDateTime,
				NumberOfLogonAttempt = 0		
			WHERE 
				Id = @rUserId AND
				OrgId = @rOrgId
				
				
	END		
IF(@lIsLogEnable = 1)
BEGIN
	INSERT INTO [sSystem].[tTraceLog]
	(LogMessage, ExtraLogMessage, ExceptionLog, ExceptionDetailLog, CreatedDateTime, PagePath)
	VALUES
	('sSecurity.pUserSessionIdModify End', 
	'UserId : ' + CAST(@rUserId AS nvarchar(100)) + ', OrgId : ' + CAST(@rOrgId AS nvarchar(10)) + ', SessionId : ' +  CAST(@rSessionId AS nvarchar(100)), 
	'', '', GETDATE(), 'sSecurity.pUserSessionIdModify')
END
		
END
GO
PRINT N'Altering Procedure [sStudent].[pRptSiblingLinkListGet]...';


GO
ALTER PROCEDURE [sStudent].[pRptSiblingLinkListGet]	
	
	@rClassId int,
	@rDivisionId int,
	@rStudentId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rOrgId int,
	@rBatchID int,
	@rDepartmentId int,
	@rOrgGroupBatchId int,
	@rClassStatusId int=0,
	@rStatusId int=0	--Mantis - 40075
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 	 		
  SELECT 
		@rBuilder1 AS Builder1,
		DENSE_rank() OVER(ORDER BY LS.StudentId)AS RowNumber,
		SA.OrganizationName,
		SA.Name,
		SA.Code,		
		SA.ClassName+'-'+SA.DivisionName AS DivDept	,
		SA1.ClassName+'-'+SA1.DivisionName AS StudentClass,		
		LS.LinkedStudentId,
		LS.StudentId,
		SA1.Name As StudentName, --Mantis - 43522(SM.FirstName +' '+SM.MiddleName+' '+SM.LastName As StudentName to SA1.Name)
		SA.BatchName,
		SM.Code AS StudentCode
			
  FROM	sStudent.tLinkSibling LS
		INNER JOIN	sStudent.vStudentLastAcademic SA ON SA.StudentId=LS.LinkedStudentId		
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=LS.StudentId	
		INNER JOIN	sStudent.vStudentLastAcademic SA1 ON SA1.StudentId=LS.StudentId	
  WHERE 
		((LS.StudentId like @rStudentId) OR (ISNULL(@rStudentId,0) = 0)) 
		AND((SA.ClassId=@rClassId) OR  (@rClassId=0))
		AND ((Sa.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		--Mantis Id:- 30932, comment OrgGroupBatchId and add OrgId
		--AND LEFT(SA.OrgGroupBatchId,4) = @rOrgId
		AND SA.OrgId = @rOrgId
		AND SA.IsActiveBatch = 1
		AND SA.BatchId =@rBatchID
		AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND ((SM.StatusId=@rStatusId) OR (@rStatusId=0))	--Mantis - 40075
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))	--Mantis - 40075
		ORDER BY RowNumber
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentDataUpdateGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentDataUpdateGet]

	@rCategoryId int,
	@rSubCategory nvarchar(500),
	@rOrgId int,
	@rClassId int,
	@rDivisionId int,
	@rBatchId int,
	@rIsBlank bit,
	@rStatusId int,
	@rOrderBy int,
	@rUserId bigint=0	--add for mantis: 36241

AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory

		IF(@rSubCategory = 'Gender' OR @rSubCategory = 'Religion' OR @rSubCategory = 'BloodGroup'
			OR @rSubCategory = 'TransportMode' OR @rSubCategory = 'House'
			OR @rSubCategory = 'Quota' OR @rSubCategory = 'Nationality' OR @rSubCategory = 'AdmissionStandard' OR  @rSubCategory = 'AdmissionCategory'
			OR @rSubCategory = 'AdmissionQuota' OR @rSubCategory = 'Tribe' OR @rSubCategory = 'Club')
		BEGIN
			SET @rSubCategory =@rSubCategory + 'Id'
			 -- print @rSubCategory
		END
		IF(@rSubCategory = 'CasteCategory' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') + 'Id'
		END
		
		IF(@rSubCategory = 'FamilyCaste' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') 
		END
		IF(@rSubCategory = 'StudentGroup' OR @rSubCategory='StudentOtherGroup')
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory ,'StudentGroup','StudentGroupId')
			SET @rSubCategory = Replace(@rSubCategory ,'StudentOtherGroup','StudentOtherGroupId')
		END
		
		IF(@rSubCategory = 'FeeCategory' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'FeeCategory','AdmissionCategory') + 'Id'
		END

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

		Declare @Sql nvarchar(max)
		Declare @Sql1 nvarchar(max)
		 
		SET @Sql =  CASE @rCategoryId					  
					WHEN 1 THEN -- Communication
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
							CASE WHEN '+@lDataTypeId+'=1 THEN
							ISNULL(SC.'+@rSubCategory+','''') 
							WHEN '+@lDataTypeId+'=2 THEN
							ISNULL(SC.'+@rSubCategory+',''0'')
							WHEN '+@lDataTypeId+'=3 THEN
							ISNULL(SC.'+@rSubCategory+',''False'') 
							WHEN '+@lDataTypeId+'=4 THEN
							ISNULL(SC.'+@rSubCategory+',''0001/01/01'') 
							WHEN '+@lDataTypeId+'=5 THEN
							ISNULL(SC.'+@rSubCategory+',''0'') 
							END AS SubCategory
						FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005	--add for mantis: 36241
							LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
						Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SC.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SC.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SC.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SC.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							AND U.UserId ='+CAST(@rUserId AS nvarchar(15))	--add for mantis: 36241
							
					WHEN 2 THEN -- Other
						CASE WHEN @rSubCategory = 'ClubId' THEN
							'Select DISTINCT SA.StudentId,SA.AcademicId,SA.Code,SA.Name
							,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
							CASE WHEN '+@lDataTypeId+'=1 THEN
							ISNULL([sStudent].[fAssignedBulkClubGet](SA.AcademicId),'''')
							END AS SubCategory
						FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005	--add for mantis: 36241
							LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
							LEFT JOIN sActivity.tAssignClub AS AC ON AC.AcademicId = SA.AcademicId
						Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(AC.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(AC.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(AC.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(AC.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							AND U.UserId ='+CAST(@rUserId AS nvarchar(15))	--add for mantis: 36241 
						ELSE
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
							CASE 
							WHEN '+@lDataTypeId+'=1 THEN
							ISNULL(SO.'+@rSubCategory+','''')
							WHEN '+@lDataTypeId+'=2 THEN
							ISNULL(SO.'+@rSubCategory+',''0'')
							WHEN '+@lDataTypeId+'=3 THEN
							ISNULL(SO.'+@rSubCategory+',''False'')
							WHEN '+@lDataTypeId+'=4 THEN
							SO.'+@rSubCategory+'
							WHEN '+@lDataTypeId+'=5 THEN
							ISNULL(SO.'+@rSubCategory+',''0'')
							END AS SubCategory
						FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005	--add for mantis: 36241
							LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
						Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SO.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SO.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SO.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SO.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							AND U.UserId ='+CAST(@rUserId AS nvarchar(15))	--add for mantis: 36241
						END	
					WHEN 3 THEN -- Admission
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
							CASE WHEN '+@lDataTypeId+'=1 THEN
							ISNULL(SAD.'+@rSubCategory+','''')
							WHEN '+@lDataTypeId+'=2 THEN
							ISNULL(SAD.'+@rSubCategory+',''0'')
							WHEN '+@lDataTypeId+'=3 THEN
							ISNULL(SAD.'+@rSubCategory+',''False'')
							WHEN '+@lDataTypeId+'=4 THEN
							ISNULL(SAD.'+@rSubCategory+',''0001/01/01'')
							WHEN '+@lDataTypeId+'=5 THEN
							ISNULL(SAD.'+@rSubCategory+',''0'')
							END AS SubCategory 
						FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005	--add for mantis: 36241
							INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
						Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							AND U.UserId ='+CAST(@rUserId AS nvarchar(15))	--add for mantis: 36241
					 
					WHEN 4 THEN --Family
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
							CASE WHEN '+@lDataTypeId+'=1 THEN
							ISNULL(SAF.'+@rSubCategory+','''')
							WHEN '+@lDataTypeId+'=2 THEN
							ISNULL(SAF.'+@rSubCategory+',''0'')
							WHEN '+@lDataTypeId+'=3 THEN
							ISNULL(SAF.'+@rSubCategory+',''False'')
							WHEN '+@lDataTypeId+'=4 THEN
							ISNULL(SAF.'+@rSubCategory+',''0001/01/01'')
							WHEN '+@lDataTypeId+'=5 THEN
							ISNULL(SAF.'+@rSubCategory+',''0'')
							END AS SubCategory
						FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005	--add for mantis: 36241
							LEFT JOIN sStudent.tStudentFamily SAF ON SAF.StudentId=SA.StudentId
						Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAF.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAF.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAF.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAF.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							AND U.UserId ='+CAST(@rUserId AS nvarchar(15))	--add for mantis: 36241
				   
					WHEN 5 THEN --Health
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
							CASE WHEN '+@lDataTypeId+'=1 THEN
							ISNULL(SAH.'+@rSubCategory+','''')
							WHEN '+@lDataTypeId+'=2 THEN
							ISNULL(SAH.'+@rSubCategory+',''0'')
							WHEN '+@lDataTypeId+'=3 THEN
							ISNULL(SAH.'+@rSubCategory+',''False'')
							WHEN '+@lDataTypeId+'=4 THEN
							ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')
							WHEN '+@lDataTypeId+'=5 THEN
							ISNULL(SAH.'+@rSubCategory+',''0'')
							END AS SubCategory
						FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005	--add for mantis: 36241
							LEFT JOIN sStudent.tStudentHealth SAH ON SAH.StudentId=SA.StudentId
						Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAH.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAH.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAH.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							AND U.UserId ='+CAST(@rUserId AS nvarchar(15))	--add for mantis: 36241

					WHEN 6 THEN --Academic Detail
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
							CASE WHEN '+@lDataTypeId+'=1 THEN
							ISNULL(AD.'+@rSubCategory+','''')
							WHEN '+@lDataTypeId+'=2 THEN
							ISNULL(AD.'+@rSubCategory+',''0'')						
							WHEN '+@lDataTypeId+'=3 THEN
							ISNULL(AD.'+@rSubCategory+',''False'')
							WHEN '+@lDataTypeId+'=4 THEN
							ISNULL(AD.'+@rSubCategory+',''0001/01/01'')	
							WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''=''RepeatCount'' THEN
							ISNULL(AD.'+@rSubCategory+',''1'')
							WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''<>''RepeatCount'' THEN
							ISNULL(AD.'+@rSubCategory+',''0'')
							END AS SubCategory
						FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005	--add for mantis: 36241
							LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=SA.AcademicId
						Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(AD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(AD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(AD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(AD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							AND U.UserId ='+CAST(@rUserId AS nvarchar(15))	--add for mantis: 36241

					--WHEN 7 THEN --General
						
					--   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
					--	CASE WHEN '+@lDataTypeId+'=1 THEN
					--	ISNULL(SAH.'+@rSubCategory+','''')
					--	WHEN '+@lDataTypeId+'=2 THEN
					--	ISNULL(SAH.'+@rSubCategory+',''0'')
					--	WHEN '+@lDataTypeId+'=3 THEN
					--	ISNULL(SAH.'+@rSubCategory+',''False'')
					--	WHEN '+@lDataTypeId+'=4 THEN
					--	ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')
					--	WHEN '+@lDataTypeId+'=5 THEN
					--	ISNULL(SAH.'+@rSubCategory+',''0'')
					--	END AS SubCategory
					--		FROM 
					--		sStudent.vStudentAcademic SA
					--		LEFT JOIN sStudent.tStudentMaster SAH ON SAH.Id=SA.StudentId
					--		Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
					--		+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
					--		AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
					--		AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
					--		AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
					--		AND 
					--		('+CAST(@rIsBlank AS nvarchar(1))+'=0 
					--			OR ('+@lDataTypeId+'=1 AND ISNULL(SAH.'+@rSubCategory+','''')='''')
					--			OR ('+@lDataTypeId+'=2 AND ISNULL(SAH.'+@rSubCategory+',''0'')=''0'')
					--			OR ('+@lDataTypeId+'=3 AND ISNULL(SAH.'+@rSubCategory+',''False'')=''False'')
					--			OR ('+@lDataTypeId+'=4 AND ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
					--		)' 

					WHEN 8 THEN --Additonal Information
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
							CASE WHEN '+@lDataTypeId+'=1 THEN
							ISNULL(SAH.'+@rSubCategory+','''')
							WHEN '+@lDataTypeId+'=2 THEN
							ISNULL(SAH.'+@rSubCategory+',''0'')
							WHEN '+@lDataTypeId+'=3 THEN
							ISNULL(SAH.'+@rSubCategory+',''False'')
							WHEN '+@lDataTypeId+'=4 THEN
							ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')
							WHEN '+@lDataTypeId+'=5 THEN
							ISNULL(SAH.'+@rSubCategory+',''0'')
							END AS SubCategory
						FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005	--add for mantis: 36241
							LEFT JOIN sStudent.tStudentAdditional SAH ON SAH.StudentId=SA.StudentId
						Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAH.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAH.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAH.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							AND U.UserId ='+CAST(@rUserId AS nvarchar(15))	--add for mantis: 36241
					
					WHEN 9 THEN --Student Sibling
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
							CASE WHEN '+@lDataTypeId+'=1 THEN
							ISNULL(SS.'+@rSubCategory+','''')
							WHEN '+@lDataTypeId+'=2 THEN
							ISNULL(SS.'+@rSubCategory+',''0'')
							WHEN '+@lDataTypeId+'=3 THEN
							ISNULL(SS.'+@rSubCategory+',''False'')
							WHEN '+@lDataTypeId+'=4 THEN
							ISNULL(SS.'+@rSubCategory+',''0001/01/01'')
							WHEN '+@lDataTypeId+'=5 THEN
							ISNULL(SS.'+@rSubCategory+',''0'')
							END AS SubCategory
						FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005	--add for mantis: 36241
							LEFT JOIN sStudent.tStudentSibling SS ON SS.StudentId=SA.StudentId
						Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SS.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SS.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SS.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SS.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							AND U.UserId ='+CAST(@rUserId AS nvarchar(15))	--add for mantis: 36241
					END				
					


			SET @Sql1 = CASE WHEN @rCategoryId = 7 --AND @rSubCategory='AdmissionCategoryId'
						THEN 
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
							CASE WHEN '+@lDataTypeId+'=1 THEN
							ISNULL(SA.'+@rSubCategory+','''')
							WHEN '+@lDataTypeId+'=2 THEN
							ISNULL(SA.'+@rSubCategory+',''0'')
							WHEN '+@lDataTypeId+'=3 THEN
							ISNULL(SA.'+@rSubCategory+',''False'')
							WHEN '+@lDataTypeId+'=4 THEN
							ISNULL(SA.'+@rSubCategory+',''0001/01/01'')
							WHEN '+@lDataTypeId+'=5 THEN
							ISNULL(SA.'+@rSubCategory+',''0'')
							END AS SubCategory
						FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005	--add for mantis: 36241
							LEFT JOIN sStudent.tStudentMaster SAH ON SAH.Id=SA.StudentId
						Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SA.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SA.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SA.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SA.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							AND U.UserId ='+CAST(@rUserId AS nvarchar(15))	--add for mantis: 36241
						END
			Print @Sql
	   if(@Sql1 IS NOT NULL)		
			EXECUTE  sp_executesql @Sql1
	   else
			EXECUTE  sp_executesql @Sql
	   
END
GO
PRINT N'Altering Procedure [sStudent].[pValidateImportAdmissionInquiry]...';


GO
ALTER PROCEDURE [sStudent].[pValidateImportAdmissionInquiry]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rOrgGroupBatchId int=0, --add for mantis: 41088
	@rBatchId int=0 --add for mantis: 41088
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        
        @lClass nvarchar(100),
        @lInquiryDate nvarchar(15),
		@lInquiryStatus nvarchar(50),
        @lDOB nvarchar(15),             
        @1ReturnCode int = 1,
        @1ValidInquiryDate nvarchar(max)='',
        @1ValidDOB nvarchar(max) = '',
		@lNumber nvarchar(20)='', --mantis: 41088
		@lParentContactNo nvarchar(20)=''  --mantis: 0041560
--mantis: 41088, start
DECLARE @lConfigValueForAdmissionNumber nvarchar(50)=''
SELECT @lConfigValueForAdmissionNumber = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 462 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId 

DECLARE @lConfigValueAdmissionAlphaNUmeric nvarchar(50)=''
SELECT @lConfigValueAdmissionAlphaNUmeric = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 595 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

DECLARE @lConfigValue nvarchar(50)=''
SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 341 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
--mantis: 41088, end

-- --mantis: 0041560
DECLARE @lConfigValueAdmissionContactNoDigitVal nvarchar(50)='10'	--mantis: 44163, give the default value 10
SELECT @lConfigValueAdmissionContactNoDigitVal = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 599 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
----mantis: 0041560 end
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        FirstName nvarchar(100),
        MiddleName nvarchar(100),
        LastName nvarchar(100),
		Class nvarchar(100),
		
		InquiryDate nvarchar(15), 
        InquiryStatus nvarchar(50),
        DOB nvarchar(15),
        Gender nvarchar(10),
		InquiryMode nvarchar(50),
		 Number nvarchar(20), --mantis: 41088 
        ParentContactNo nvarchar(20) --mantis: 0041560
 
  )
  INSERT INTO #tTable1
	(
	    
	    FirstName,
	    MiddleName,
	    LastName,
	    Class,
	    InquiryDate,
	    InquiryStatus,
	    DOB,
	    Gender,
		InquiryMode,
		Number, --mantis: 41088
		ParentContactNo  --mantis: 0041560
    ) 
   SELECT
       
	    FirstName,
	    MiddleName,
	    LastName,
	    Class,
	    InquiryDate,
	    InquiryStatus,
	    DOB,
	    Gender,
		InquiryMode,
		Number, --mantis: 41088
        ParentContactNo   --mantis: 0041560
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        
        FirstName nvarchar(100) '@FirstName',
        MiddleName  nvarchar(100) '@MiddleName',
        LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		InquiryDate nvarchar(15) '@InquiryDate',
		InquiryStatus nvarchar(50) '@InquiryStatus',
		DOB nvarchar(15) '@DOB',
		Gender nvarchar(10) '@Gender' ,
		InquiryMode nvarchar(50) '@InquiryMode',
		Number nvarchar(20) '@Number', --mantis: 41088
		ParentContactNo nvarchar(20) '@ParentContactNo' --mantis: 0041560
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
	BEGIN
  
		SELECT         
			@lInquiryDate = InquiryDate 
				FROM #tTable1 WHERE Id = @lCount
		IF(@lInquiryDate = '')
		BEGIN    
			SELECT 'Inquiry date Should not be empty'   AS StudentCode
		END
		ELSE IF(ISDATE(@lInquiryDate) = 0 AND @lInquiryDate!='')
		BEGIN    
			SET @1ValidInquiryDate = @1ValidInquiryDate + @lInquiryDate+','
		END

		SELECT         
			@lDOB = DOB 
				FROM #tTable1 WHERE Id = @lCount
		IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
		BEGIN
			SET @1ValidDOB=@1ValidDOB +   @lDOB+','
		END

		--mantis: 44163, change the place for an issue, start
		SELECT @lParentContactNo = ParentContactNo FROM #tTable1 WHERE Id = @lCount   --mantis: 0041560
		IF(@lConfigValueAdmissionContactNoDigitVal is not null OR @lConfigValueAdmissionContactNoDigitVal !='')
		BEGIN
			IF(@lParentContactNo != '' AND LEN(@lParentContactNo) > 0)
			BEGIN
				declare @lParentContactNotmp nvarchar(20)
				set @lParentContactNotmp = LEN(@lParentContactNo)
				IF(@lParentContactNotmp != @lConfigValueAdmissionContactNoDigitVal)
				BEGIN
					SELECT 'Contact No should be atleast of '+ @lConfigValueAdmissionContactNoDigitVal +' digits' AS StudentCode
				END
			END
		END
		--mantis: 44163, change the place for an issue, end
		SET @lCount = @lCount - 1
	END	
   
   --mantis: 41088, start
	IF(@lConfigValueForAdmissionNumber is null OR @lConfigValueForAdmissionNumber='false')
	BEGIN
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number IS NULL OR Number COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Number Should not be empty' AS StudentCode
		END
	END
	----mantis: 41088, end 
   
   SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
		BEGIN
			SELECT         
			 @lClass = Class 
			FROM #tTable1 WHERE Id = @lCount

			IF NOT EXISTS (SELECT 1 FROM  
					 sSetup.tClassMaster CM  
						WHERE CM.Title COLLATE DATABASE_DEFAULT =@lClass COLLATE DATABASE_DEFAULT  )	
			BEGIN
				
				SELECT 'Enter proper value for Class ' + @lClass   AS StudentCode
				RETURN
			END
			--mantis: 41088, start
			SELECT @lNumber = Number FROM #tTable1 WHERE Id = @lCount
			IF((@lConfigValueForAdmissionNumber is null OR @lConfigValueForAdmissionNumber='false') AND @lNumber IS NOT NULL)
			BEGIN
				IF(@lConfigValueAdmissionAlphaNUmeric='False' AND @lConfigValue='Continuous')
				BEGIN
					IF EXISTS(SELECT 1 FROM sAdmission.tAdmissionInquiry WHERE OrgGroupId = @rOrgGroupId AND Number = @lNumber)
					BEGIN
						SELECT 'Inquiry Number already Exists: ' + @lNumber AS StudentCode
						RETURN
					END
				END
				ELSE IF(@lConfigValueAdmissionAlphaNUmeric='False' AND @lConfigValue='OrgGroupBatch')
				BEGIN
					IF EXISTS(SELECT 1 FROM sAdmission.tAdmissionInquiry AI INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId AND Number = @lNumber)
					BEGIN
						SELECT 'Inquiry Number already Exists: ' + @lNumber AS StudentCode
						RETURN
					END
				END
				ELSE IF(@lConfigValueAdmissionAlphaNUmeric='False' AND @lConfigValue='Batch')
				BEGIN
					IF EXISTS(SELECT 1 FROM sAdmission.tAdmissionInquiry AI WHERE AI.ForBatchId = @rBatchId AND Number = @lNumber)
					BEGIN
						SELECT 'Inquiry Number already Exists: ' + @lNumber AS StudentCode
						RETURN
					END
				END
			END
			--mantis: 41088, end
			SET @lCount = @lCount - 1	
		END
		   
		 
		  IF EXISTS(SELECT 1 FROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Surname Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'First Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE MiddleName IS NULL OR MiddleName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Middle Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Class Should not be empty' AS StudentCode
		END
		 
	 
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Gender Should not be empty' AS StudentCode
		END
 
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class  COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId))
		BEGIN
			SELECT 'Enter proper value for Class as per Institute Setup > Class Master' AS StudentCode
		END				
		 
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender NOT IN(SELECT Title FROM sCommon.tGenderMaster))
		BEGIN
			SELECT 'Enter proper value / Check spelling for gender ( Male / Female )' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionCategory!='' AND AdmissionCategory NOT IN(SELECT Title FROM sStudent.tAdmissionCategoryMaster))
		--BEGIN
		--	SELECT 'Enter proper value for Cast Category (Indian,NRI,General)' AS StudentCode
		--END
			 
		Else if Exists(Select 1 from #tTable1 where InquiryStatus COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND InquiryStatus NOT IN (Select Title from sAdmission.tInquiryStatusMaster))
		Begin
			Select 'Enter proper Value or check Spelling for Inquiry Status' AS StudentCode
		End
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE InquiryStatus IS NULL OR InquiryStatus COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Inquiry Status Should not be empty ' AS StudentCode
		END
		ELSE IF NOT EXISTS(SELECT 1 FROM #tTable1 WHERE InquiryMode IN(SELECT Title FROM sAdmission.tInquiryModeMaster ) OR InquiryMode='')
		BEGIN
			SELECT 'Inquiry Mode is not proper as per Inquiry Mode Master' AS StudentCode
		END
		ELSE
			
		BEGIN
			IF((@1ValidInquiryDate IS NULL OR @1ValidInquiryDate = '') AND (@1ValidDOB IS NULL OR @1ValidDOB = ''))
		BEGIN
			SELECT '' AS StudentCode
		END
		
		ELSE IF (@1ValidInquiryDate IS NOT NULL AND @1ValidInquiryDate != '')
			BEGIN
			select @1ValidInquiryDate
			SET @1ValidInquiryDate = 'Wrong Inquiry Date : ' + LEFT(@1ValidInquiryDate, LEN(@1ValidInquiryDate)-1)
			Select @1ValidInquiryDate AS StudentCode
			END

		ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
			BEGIN
			SET @1ValidDOB = 'Wrong DOB : ' + LEFT(@1ValidDOB, LEN(@1ValidDOB)-1)
			Select @1ValidDOB AS StudentCode
			END
		
		END
		 
END
GO
PRINT N'Creating Procedure [sBiometric].[pRptStudentBiometricReportData]...';


GO
CREATE PROCEDURE [sBiometric].[pRptStudentBiometricReportData]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int,
	@rDeptId int = 0,
	@rClassId int,
	@rDivisionId int,
	@rStatusId int = 0,
	@rStudentId bigint = 0,
	@rAcademicId bigint = 0,
	@rForYear int = 0,
	@rForMonth int = 0,
	@rOrgGroupId int = 0,
	@rOrgGroupBatchId int = 0


	
	
	--@rIsFirstIn bit=0,
	--@rIsLastOut bit=0,
	--@rIsOT bit=0,
	--@rIsLateBy	bit=0,
	--@rIsEarlyBy bit=0,
	--@rIsDuration  bit=0,
	--@OrgGroupDepartmentId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @lATTN_DATE nvarchar(20)
	DECLARE @lBatchID int
	DECLARE @Days int 
	SELECT @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1

	SET @lATTN_DATE = CONVERT(nvarchar(10),@rForYear) + '-' + Right('000000' + CONVERT(nvarchar, @rForMonth), 2) + '-01'
	
	DECLARE @lDN1 nvarchar(10),@lDN2 nvarchar(10),@lDN3 nvarchar(10),@lDN4 nvarchar(10),@lDN5 nvarchar(10),
	@lDN6 nvarchar(10),@lDN7 nvarchar(10),@lDN8 nvarchar(10),@lDN9 nvarchar(10),@lDN10 nvarchar(10),
	@lDN11 nvarchar(10),@lDN12 nvarchar(10),@lDN13 nvarchar(10),@lDN14 nvarchar(10),@lDN15 nvarchar(10),
	@lDN16 nvarchar(10),@lDN17 nvarchar(10),@lDN18 nvarchar(10),@lDN19 nvarchar(10),@lDN20 nvarchar(10),
	@lDN21 nvarchar(10),@lDN22 nvarchar(10),@lDN23 nvarchar(10),@lDN24 nvarchar(10),@lDN25 nvarchar(10),
	@lDN26 nvarchar(10),@lDN27 nvarchar(10),@lDN28 nvarchar(10),@lDN29 nvarchar(10),@lDN30 nvarchar(10),
	@lDN31 nvarchar(10)
	
	SET @lDN1 = '01 ' + substring(DATENAME( dw, convert( date, ( '01' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN2 = '02 ' + substring(DATENAME( dw, convert( date, ( '02' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN3 = '03 ' + substring(DATENAME( dw, convert( date, ( '03' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN4 = '04 ' + substring(DATENAME( dw, convert( date, ( '04' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN5 = '05 ' + substring(DATENAME( dw, convert( date, ( '05' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN6 = '06 ' + substring(DATENAME( dw, convert( date, ( '06' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN7 = '07 ' + substring(DATENAME( dw, convert( date, ( '07' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN8 = '08 ' + substring(DATENAME( dw, convert( date, ( '08' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN9 = '09 ' + substring(DATENAME( dw, convert( date, ( '09' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN10 = '10 ' + substring(DATENAME( dw, convert( date, ( '10' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN11 = '11 ' + substring(DATENAME( dw, convert( date, ( '11' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN12 = '12 ' + substring(DATENAME( dw, convert( date, ( '12' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN13 = '13 ' + substring(DATENAME( dw, convert( date, ( '13' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN14 = '14 ' + substring(DATENAME( dw, convert( date, ( '14' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN15 = '15 ' + substring(DATENAME( dw, convert( date, ( '15' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN16 = '16 ' + substring(DATENAME( dw, convert( date, ( '16' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN17 = '17 ' + substring(DATENAME( dw, convert( date, ( '17' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN18 = '18 ' + substring(DATENAME( dw, convert( date, ( '18' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN19 = '19 ' + substring(DATENAME( dw, convert( date, ( '19' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN20 = '20 ' + substring(DATENAME( dw, convert( date, ( '20' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN21 = '21 ' + substring(DATENAME( dw, convert( date, ( '21' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN22 = '22 ' + substring(DATENAME( dw, convert( date, ( '22' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN23 = '23 ' + substring(DATENAME( dw, convert( date, ( '23' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN24 = '24 ' + substring(DATENAME( dw, convert( date, ( '24' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN25 = '25 ' + substring(DATENAME( dw, convert( date, ( '25' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN26 = '26 ' + substring(DATENAME( dw, convert( date, ( '26' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN27 = '27 ' + substring(DATENAME( dw, convert( date, ( '27' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN28 = '28 ' + substring(DATENAME( dw, convert( date, ( '28' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2)
	SET @lDN29 = case when @Days >= 29 then '29 ' + substring(DATENAME( dw, convert( date, ( '29' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end
	SET @lDN30 = case when @Days >= 30 then '30 ' + substring(DATENAME( dw, convert( date, ( '30' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end
	SET @lDN31 = case when @Days < 31 Then '' else '31 ' + substring(DATENAME( dw, convert( date, ( '31' + '/' + CONVERT(nvarchar(2),@rforMonth) + '/' + CONVERT(nvarchar(4),@rforYear) ), 103 ) ),1,2) end

	SELECT 
		datediff(day, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE),
		dateadd(month, 1, dateadd(day, 1-day(@lATTN_DATE), @lATTN_DATE))) AS DayCount,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		
		@lDN1 as DN1,@lDN2 as DN2,@lDN3 as DN3,@lDN4 as DN4,@lDN5 as DN5,@lDN6 as DN6,@lDN7 as DN7,@lDN8 as DN8,@lDN9 as DN9,@lDN10 as DN10,
		@lDN11 as DN11,@lDN12 as DN12,@lDN13 as DN13,@lDN14 as DN14,@lDN15 as DN15,@lDN16 as DN16,@lDN17 as DN17,@lDN18 as DN18,@lDN19 as DN19,
		@lDN20 as DN20,@lDN21 as DN21,@lDN22 as DN22,@lDN23 as DN23,@lDN24 as DN24,@lDN25 as DN25,@lDN26 as DN26,@lDN27 as DN27,@lDN28 as DN28,	@lDN29 as DN29,@lDN30 as DN30,@lDN31 AS DN31,
		
		S.Code,	
		--E.ShortName,
		--DM.Displaytitle DeptName,
		--DM.Code AS DeptCode,
		S.OrgID,
		--DM.Id AS DepartmentId,
		--EDM.Title AS Designation,
		--EDM.Code AS DesignationCode,
		--@rIsFirstIn AS IsFirstIn,
		--@rIsLastOut AS IsLastOut,
		--@rIsOT AS IsOT,
		--@rIsLateBy	AS IsLateBy,
		--@rIsEarlyBy AS IsEarlyBy,
		--@rIsDuration  AS IsDuration,
		S.FirstName +' ' + S.MiddleName +' '+ S.LastName AS Name,
		--sBiometric.fEmployeeLeaveTypeGet(Attn_Dt,T.EmployeeId) AS LeaveStatus,
		--ISNULL(sBiometric.fEmployeeCLTypeGet(@rForMonth,@rForYear,T.EmployeeId),'') AS CLeaveStatus,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,1,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D01,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,2,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D02,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,3,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D03,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,4,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D04,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,5,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D05,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,6,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D06,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,7,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D07,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,8,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D08,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,9,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D09,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,10,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D10,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,11,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D11,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,12,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D12,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,13,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D13,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,14,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D14,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,15,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D15,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,16,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D16,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,17,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D17,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,18,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D18,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,19,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D19,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,20,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D20,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,21,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D21,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,22,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D22,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,23,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D23,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,24,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D24,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,25,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D25,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,26,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D26,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,27,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D27,
		--[sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,28,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) AS D28,
		--case when @Days >= 29 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,29,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D29,
		--case when @Days >= 30 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,30,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D30,
		--case when @Days >= 31 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,31,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D31,

		Attn_Dt, 
		
		D01_IN, D02_IN, D03_IN, D04_IN, D05_IN, D06_IN, D07_IN, D08_IN, D09_IN, D10_IN, D11_IN, D12_IN, D13_IN, D14_IN, D15_IN, 
		D16_IN, D17_IN, D18_IN, D19_IN, D20_IN, D21_IN, D22_IN, D23_IN, D24_IN, D25_IN, D26_IN, D27_IN, D28_IN, D29_IN, D30_IN, D31_IN, 
		D01_OUT, D02_OUT, D03_OUT, D04_OUT, D05_OUT, D06_OUT, D07_OUT, D08_OUT, D09_OUT, D10_OUT, D11_OUT, D12_OUT, D13_OUT, D14_OUT, D15_OUT, 
		D16_OUT, D17_OUT, D18_OUT, D19_OUT, D20_OUT, D21_OUT, D22_OUT, D23_OUT, D24_OUT, D25_OUT, D26_OUT, D27_OUT, D28_OUT, D29_OUT, D30_OUT, D31_OUT, 
		D01_O, D02_O, D03_O, D04_O, D05_O, D06_O, D07_O, D08_O, D09_O, D10_O, D11_O, D12_O, D13_O, D14_O, D15_O, 
		D16_O, D17_O, D18_O, D19_O, D20_O, D21_O, D22_O, D23_O, D24_O, D25_O, D26_O, D27_O, D28_O, D29_O, D30_O, D31_O, 
		D01_L, D02_L, D03_L, D04_L, D05_L, D06_L, D07_L, D08_L, D09_L, D10_L, D11_L, D12_L, D13_L, D14_L, D15_L, 
		D16_L, D17_L, D18_L, D19_L, D20_L, D21_L, D22_L, D23_L, D24_L, D25_L, D26_L, D27_L, D28_L, D29_L, D30_L, D31_L, 
		D01_T, D02_T, D03_T, D04_T, D05_T, D06_T, D07_T, D08_T, D09_T, D10_T, D11_T, D12_T, D13_T, D14_T, D15_T, 
		D16_T, D17_T, D18_T, D19_T, D20_T, D21_T, D22_T, D23_T, D24_T, D25_T, D26_T, D27_T, D28_T, D29_T, D30_T, D31_T, 
		D01_E, D02_E, D03_E, D04_E, D05_E, D06_E, D07_E, D08_E, D09_E, D10_E, D11_E, D12_E, D13_E, D14_E, D15_E, 
		D16_E, D17_E, D18_E, D19_E, D20_E, D21_E, D22_E, D23_E, D24_E, D25_E, D26_E, D27_E, D28_E, D29_E, D30_E, D31_E, 
		D01_S, D02_S, D03_S, D04_S, D05_S, D06_S, D07_S, D08_S, D09_S, D10_S, D11_S, D12_S, D13_S, D14_S, D15_S, 
		D16_S, D17_S, D18_S, D19_S, D20_S, D21_S, D22_S, D23_S, D24_S, D25_S, D26_S, D27_S, D28_S, D29_S, D30_S, D31_S, 
		Tot_Attn, Tot_Abs, Tot_WeekOFF, Tot_Holiday, TotalHour, Tot_HD, Tot_Early, Tot_Late, Tot_OT, Tot_OD, Tot_Leave, 
		Count_Late, Count_Early, Count_OT, Tot_CL, Tot_SL, Tot_EL, Tot_SP, Tot_C, Tot_PL, Tot_ML, T.EmployeeId,OM.Title AS OrganizationTitle,
		ISNULL(S.PunchId,'') AS PunchId
		--E.Number as EMPNumber            --Mantis - 30977
	FROM 
		sBiometric.tMonthTrans T
		INNER JOIN sStudent.tAcademic A ON A.Id = T.EmployeeId
		INNER JOIN sStudent.tStudentMaster S on S.Id = A.StudentId
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = S.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = S.OrgId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
		--LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
	WHERE 
		(S.OrgId=@rOrgId OR @rOrgId = 0)
		--AND (DM.Id = @rDeptId OR @rDeptId = 0)
		AND (T.Attn_dt = @lATTN_DATE)
		AND (MONTH(SA.LeftDate) >= @rForMonth AND YEAR(SA.LeftDate) >= @rForYear OR SA.LeftDate Is null)
		AND (S.StatusId = @rStatusId OR ISNULL(@rStatusId,0)=0)
		--AND ISNULL(E.IsOtherUser,0) = 0 
		AND ISNULL(T.SourceTypeId,2001) = 2001
		AND (T.EmployeeId = @rAcademicId OR @rAcademicId = 0)
		AND (CM.Id = @rClassId OR @rClassId = 0)
		AND (DM.Id = @rDivisionId OR @rDivisionId = 0)
		--AND OM.OrgGroupId = @rOrgGroupId
		--AND ((ED.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 
	ORDER BY 
	S.Code,T.Attn_dt
END
GO
PRINT N'Creating Procedure [sFee].[pDepositDefaultSetupAdd]...';


GO
CREATE PROCEDURE [sFee].[pDepositDefaultSetupAdd]	 
	@rDepositHeadId INT,
	@rOrgId INT,
	@rBatchId INT,
	@rSetupAmount DECIMAL(12,2)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF NOT EXISTS (select 1 from sFee.tDepositDefaultSetup where DepositHeadId = @rDepositHeadId AND OrgId = @rOrgId AND BatchId = @rBatchId)
	BEGIN
		INSERT INTO sFee.tDepositDefaultSetup
		(
			 DepositHeadId
			,OrgId
			,BatchId
			,Amount			
		)
		VALUES
		(
			 @rDepositHeadId
			,@rOrgId
			,@rBatchId
			,@rSetupAmount
			
		)
 
		SELECT 1 AS StatusCode	 
	END
	ELSE
	BEGIN
		
		UPDATE sFee.tDepositDefaultSetup
		SET Amount = @rSetupAmount
		WHERE 
			DepositHeadId = @rDepositHeadId 
			AND OrgId = @rOrgId 
			AND BatchId = @rBatchId

		SELECT 11 AS StatusCode	
	END	
END
GO
PRINT N'Creating Procedure [sFee].[pDepositDefaultSetupAmountGet]...';


GO
CREATE PROCEDURE [sFee].[pDepositDefaultSetupAmountGet] 
	 @rOrgId INT
	,@rOrgGroupId INT 
	,@rBatchId INT
	,@rCode nvarchar(100) = ''
AS
SET NOCOUNT ON

BEGIN
	DECLARE @lDepositHeadId int

	SET @lDepositHeadId = (select top 1 Id from sFee.tDepositHeadMaster 
		WHERE OrgGroupId = @rOrgGroupId and IsObsolete = 0 order by OrderIndex)

	IF(@lDepositHeadId > 0)
	BEGIN
		SELECT 
			 DFS.DepositHeadId AS DepositHeadId
			,DFS.Amount AS SetupAmount
		FROM  sFee.tDepositDefaultSetup DFS 
		WHERE 
			DFS.DepositHeadId = @lDepositHeadId
			AND DFS.OrgId = @rOrgId
			AND DFS.BatchId = @rBatchId
	END	
END
GO
PRINT N'Creating Procedure [sFee].[pDepositDefaultSetupGet]...';


GO
CREATE PROCEDURE [sFee].[pDepositDefaultSetupGet] 
	 @rOrgId INT
	,@rBatchId INT
	,@rOrgGroupId INT
	,@rDepositHeadId INT = 0
AS
SET NOCOUNT ON

BEGIN
	IF EXISTS(SELECT 1 FROM sFee.tDepositDefaultSetup Where OrgId =@rOrgId AND BatchId = @rBatchId)
	BEGIN
		SELECT 
			 DHM.Title AS DepositHead
			,DHM.Id AS DepositHeadId
			,DFS.Amount AS SetupAmount
		FROM [sFee].[tDepositHeadMaster] DHM
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = DHM.OrgGroupId
			LEFT JOIN sFee.tDepositDefaultSetup DFS ON DFS.DepositHeadId = DHM.Id AND DFS.OrgId = @rOrgId AND DFS.BatchId = @rBatchId
		WHERE 
			DHM.IsObsolete = 0 AND DHM.OrgGroupId = @rOrgGroupId
			AND (DHM.Id = @rDepositHeadId OR @rDepositHeadId = 0)
			AND	(((ISNULL(DFS.DepositHeadId, 0) > 0) AND (ISNULL(DFS.OrgId,0) = @rOrgId OR ISNULL(@rOrgId,0) = 0)) OR DFS.DepositHeadId IS NULL)
			AND	(((ISNULL(DFS.DepositHeadId, 0) > 0) AND (ISNULL(DFS.BatchId,0) = @rBatchId OR ISNULL(@rBatchId,0) = 0)) OR DFS.DepositHeadId IS NULL)

		Order by DHM.Title
	END
	
	ELSE
	BEGIN
		SELECT
			 DHM.Title AS DepositHead
			,DHM.Id AS DepositHeadId
			,OM.Id
			,'' AS SetupAmount
		FROM [sFee].[tDepositHeadMaster] DHM
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = DHM.OrgGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId = OGM.Id AND OM.Id = @rOrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.OrgID = OM.Id
		WHERE 
			DHM.IsObsolete = 0 AND DHM.OrgGroupId = @rOrgGroupId
			AND (DHM.Id = @rDepositHeadId OR @rDepositHeadId = 0)
			AND (ISNULL(BM.Id,0) = @rBatchId OR ISNULL(@rBatchId,0) = 0)
			AND (ISNULL(OM.Id,0) = @rOrgId OR ISNULL(@rOrgId,0) = 0)
		Order by DHM.Title
	END		
END
GO
PRINT N'Creating Procedure [sStudent].[pStudentClubDataModify]...';


GO
CREATE PROCEDURE [sStudent].[pStudentClubDataModify] 
	 @rCategoryId INT
	,@rXML NVARCHAR(max)
	,@rSubCategoryField NVARCHAR(100)
	,@rOrgId INT = 0
	,@rBatchId BIGINT = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @lInterrorCode INT
DECLARE @Sql NVARCHAR(max)
DECLARE @loDoc INT

EXEC sp_xml_preparedocument @loDoc OUTPUT
	,@rXML

BEGIN
	IF OBJECT_ID('ListofClubData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofClubData
	END	
	
	CREATE TABLE ListofClubData(AutoId BIGINT IDENTITY,AcademicId bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint);

	INSERT INTO ListofClubData
	(AcademicId,StudentId, SubCategory, UpdatedUserId)
	(
		SELECT Id,StudentId,sSetup.fPortalXMLTagsReplaceReverse(SubCategory),UpdatedUserId 
		FROM
		OPENXML (@loDoc, '/Students/Students', 2)
		WITH (
				Id BIGINT,
				StudentId BIGINT, 
				SubCategory nvarchar(150),
				UpdatedUserId bigint
			)	
	)

	DECLARE  @lStudentId bigint, @lAcademicID bigint, @lClubId int, @lSubCategory nvarchar(max)
	DECLARE @lCount INT

	SELECT @lCount =  COUNT(AutoId) FROM ListofClubData
	
	IF OBJECT_ID('#tempclubData') IS NOT NULL	
	BEGIN 
		DROP TABLE #tempclubData
	END	
	
	CREATE TABLE #tempclubData(Id bigint identity,AcademicId bigint,ClubId int);
	
	WHILE @lCount > 0 
	BEGIN
		SELECT @lAcademicID = AcademicId, @lSubCategory = SubCategory  FROM ListofClubData WHERE AutoId = @lCount 
		
		TRUNCATE TABLE #tempclubData

		IF(@lSubCategory <> '')
		BEGIN
		INSERT INTO #tempclubData(ClubId, AcademicId)
		SELECT CM.Id, @lAcademicID from [sActivity].[tClubMaster] CM
		INNER JOIN sActivity.tClubTypeMaster CTM ON CTM.Id = CM.ClubTypeId
		WHERE CM.ISObsolete = 0 AND CTM.IsObsolete = 0 AND  (CM.Title IN (SELECT CAST(item AS NVARCHAR) FROM sCommon.fnSplit(@lSubCategory, ',')) OR ISNULL(@lSubCategory, '') = '')

		DELETE FROM sActivity.tAssignClub WHERE AcademicId=@lAcademicId

		DECLARE @lClubCount int
		SELECT @lClubCount = COUNT(Id) FROM #tempclubData
		WHILE(@lClubCount > 0)
		BEGIN
			SELECT  @lClubId = ClubId, @lAcademicId = AcademicID from #tempclubData where Id = @lClubCount
			
			BEGIN TRY
				BEGIN TRANSACTION
					IF NOT EXISTS(Select 1 From sActivity.tAssignClub where ClubId=@lClubId AND AcademicId=@lAcademicId)
					BEGIN
						INSERT INTO sActivity.tAssignClub
							(
								ClubId,
								AcademicId
							)
						VALUES
							(
								@lClubId,
								@lAcademicId
							)						     
					END
					
				COMMIT TRANSACTION
				
			END TRY
			
			BEGIN CATCH 
				ROLLBACK TRANSACTION
				SELECT -1 AS Result
			END CATCH	

			SET @lClubCount = @lClubCount - 1
		END
		END

		ELSE
		BEGIN
			DELETE FROM sActivity.tAssignClub WHERE AcademicId=@lAcademicId
		END
		SET @lCount = @lCount - 1	
	END

	SELECT 1 AS StatusCode
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionFormAdd]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionFormAdd]
		 @rId bigint
		,@rFormNo int
		,@rFirstName nvarchar(100)
		,@rMiddleName nvarchar(100)
		,@rLastName	nvarchar(100)
		,@rForClassId int
		,@rForBatchId	int		 
		,@rDateOfBirth date
		,@rDateOfBirthInWord nvarchar(100)
		,@rOrgId smallint
		,@rBatchId int
		,@rStatusId	smallint
		,@rStreetOne nvarchar(150) --Changed length from 50 to 150 for mantis : 37243
		,@rStreetTwo nvarchar(50)
		,@rStreetThree nvarchar(50)
		,@rCountry nvarchar(50)
		,@rState nvarchar(50)
		,@rCity	nvarchar(50)
		,@rZipCode	nvarchar(20)
		,@rContactNo nvarchar(20)
		,@rContactEmail	nvarchar(50)
		,@rRemark nvarchar(200)
		,@rPreviousSchool nvarchar(200)
		,@rMeritMarks decimal(10, 2)
		,@rMeritGrade nvarchar(20)
		,@rGenderId	int
		,@rReligionId int
		,@rFamilyCast nvarchar(100)
		,@rFamilySubCast nvarchar(100)
		,@rCastCategoryId int
		,@rCreatedUserId bigint
		,@rFormPassword nvarchar(100)=''
		,@rDataEntryModeId smallint
		,@rDataEntryStatusId smallint
		,@rStudentPhoto varbinary(max),
		 @rNationality nvarchar(150),
		 @rMotherTongue nvarchar(150),
		 @rOtherInformation nvarchar(150),
		 @rIsPysicalDeformity bit,
		 @rPysicalDeformityRemark nvarchar(200),
         @rIsMajorIllness bit,
         @rMajorIllnessRemark nvarchar(200),
         @rIsAllergy bit,
         @rAllergyRemark nvarchar(200),
         @rBirthPlace nvarchar(150),
         @rBirthTaluka nvarchar(150),
         @rBirthDistrict nvarchar(150),
         @rBloodGroupId tinyint,
         @rAdhaarNumber nvarchar(20),
         @rIsHostelRequired bit=0,
		 @rIsTransportRequired bit=0,
		 @rBirthState nvarchar(150)='',
		 @rBirthCountry nvarchar(150)='',
		 @rCustomField1Answer nvarchar(200)='',
		 @rCustomField2Answer nvarchar(200)='',
		 @rCustomField3Answer nvarchar(200)='',
		 --@rFatherAdhaarNumber nvarchar(50) ,
		 @OutAdmissionFormId BIGINT = NULL OUTPUT,
		 @rOriginalStudentPhoto varbinary(max) = null,
		 @rAdmissionDate date='',
		 @rWhatsappContactNo nvarchar(20) = '' -- Added column of WhatsappContact for mantis : 29772
		 ,@rPENNumber bigint = 0 --mantis : 0043425
		,@rApaarIdNumber nvarchar(50) = '' --mantis : 0043425
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	

	
 --BEGIN TRANSACTION	
 DECLARE @lNextNumber BIGINT
 DECLARE @lBIGID BIGINT
 DECLARE @lSMALLID INT
 
 IF(@rId = 0)	
	BEGIN
	
	
	
		IF Exists(select FormNo from sAdmission.tAdmissionForm where FormNo=@rFormNo AND BatchId=@rBatchId)
			BEGIN
			select -101 as Result
			RETURN
		END 
	
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2006,@rStoreLocationId = 0, @rNextNumber  = @rFormNo OUTPUT

	--	SET @rFormNo = ISNULL(@rFormNo, '-300')

	--	IF @rFormNo = '-300'
	--  BEGIN
	--	SELECT -300 AS Result, '' AS Number, 0 AS Id 
	--	RETURN
	--  END
	IF(@rFormNo = 0)
	BEGIN
	SELECT @rFormNo = ISNULL(MAX(FormNo),0) + 1 FROM sAdmission.tAdmissionForm WHERE BatchId=@rBatchId
	
	END
	
	IF(@rFormPassword = '')
	BEGIN
	SELECT @rFormPassword = @rFormNo
	
	END
	
	
	BEGIN TRANSACTION	
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionForm', 0, 1, 1,@outNextNumber = @lNextNumber output
	
--SET	 @lBIGID  = @lNextNumber
--SET	 @lSMALLID  = CONVERT(int, @lBIGID)
	-- IF(@rFormNo = 0)
	-- BEGIN
	-- select convert(int,@lNextNumber)
	--SET @rFormNo = ISNULL(@rFormNo,@lNextNumber)
	--END

	INSERT INTO sAdmission.tAdmissionForm
		(
			 Id
			,FormNo
			,FirstName
			,MiddleName
			,LastName
			,ForClassId			 
			,ForBatchId
			,DateOfBirth
			,DateOfBirthInWord
			,OrgId
			,BatchId
			,StatusId
			,StreetOne
			,StreetTwo
			,StreetThree
			,Country
			,State
			,City
			,ZipCode
			,ContactNo
			,ContactEmail
			,Remark
			,PreviousSchool
			,MeritMarks
			,MeritGrade
			,GenderId
			,ReligionId
			,FamilyCast
			,FamilySubCast
			,CastCategoryId
			,CreatedUserId
			,CreatedDateTime
			,FormPassword
			,DataEntryModeId
			,DataEntryStatusId
			,StudentPhoto,
			Nationality,
			MotherTongue,
			OtherInformation,
			IsPysicalDeformity,
           PysicalDeformityRemark,
           IsMajorIllness,
           MajorIllnessRemark,
           IsAllergy,
           AllergyRemark,
           BirthPlace,
         BirthTaluka,
         BirthDistrict,
         BloodGroupId,
         AdhaarNumber,
         IsHostelRequired,
         IsTransportRequired,
         BirthState,
         BirthCountry,
         CustomField1Answer,
         CustomField2Answer,
         CustomField3Answer,
		 OriginalStudentPhoto,
		 AdmissionDate,
		 WhatsappContactNo -- Added column of WhatsappContact for mantis : 29772
         --FatherAdhaarNumber
		 ,PENNumber
		 ,ApaarIdNumber
		)
	VALUES
		(
			 @lNextNumber
			,@rFormNo
			,@rFirstName
			,@rMiddleName
			,@rLastName
			,@rForClassId			 
			,@rForBatchId
			,@rDateOfBirth
			,@rDateOfBirthInWord
			,@rOrgId
			,@rBatchId
			,@rStatusId
			,@rStreetOne
			,@rStreetTwo
			,@rStreetThree
			,@rCountry
			,@rState
			,@rCity
			,@rZipCode
			,@rContactNo
			,@rContactEmail
			,@rRemark
			,@rPreviousSchool
			,@rMeritMarks
			,@rMeritGrade
			,@rGenderId
			,@rReligionId
			,@rFamilyCast
			,@rFamilySubCast
			,@rCastCategoryId
			,@rCreatedUserId
			,sCommon.fGetDate()
			,@rFormPassword
			,@rDataEntryModeId
			,@rDataEntryStatusId
			,@rStudentPhoto,
			@rNationality,
			@rMotherTongue,
			@rOtherInformation,
			@rIsPysicalDeformity,
			   @rPysicalDeformityRemark,
			   @rIsMajorIllness,
			   @rMajorIllnessRemark,
			   @rIsAllergy,
			   @rAllergyRemark,
			  @rBirthPlace,
			 @rBirthTaluka,
			 @rBirthDistrict,
			 @rBloodGroupId,
			 @rAdhaarNumber,
			 @rIsHostelRequired,
			 @rIsTransportRequired,
			 @rBirthState,
			@rBirthCountry,
			 @rCustomField1Answer,
			 @rCustomField2Answer,
			 @rCustomField3Answer,
			 @rOriginalStudentPhoto,
			 @rAdmissionDate,
			 @rWhatsappContactNo -- Added column of WhatsappContact for mantis : 29772
			 --@rFatherAdhaarNumber
			,@rPENNumber
			,@rApaarIdNumber
		)
		             
	END	 
	 ELSE
	 BEGIN
	 
	 
	 
	 	IF Exists(select FormNo from sAdmission.tAdmissionForm where FormNo=@rFormNo AND BatchId=@rBatchId And Id <> @rId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		
	 BEGIN TRANSACTION	
	 SET @lNextNumber = @rId
	    UPDATE  sAdmission.tAdmissionForm
	    SET
	        FormNo = @rFormNo
			,FirstName=@rFirstName
			,MiddleName=@rMiddleName
			,LastName=@rLastName
			,ForClassId=@rForClassId			
			,DateOfBirth=@rDateOfBirth
			,DateOfBirthInWord=@rDateOfBirthInWord
			,StatusId=@rStatusId
			,StreetOne=@rStreetOne
			,StreetTwo=@rStreetTwo
			,StreetThree=@rStreetThree
			,Country=@rCountry
			,State=@rState
			,City=@rCity
			,ZipCode=@rZipCode
			,ContactNo=@rContactNo
			,ContactEmail=@rContactEmail
			,Remark=@rRemark
			,PreviousSchool=@rPreviousSchool
			,MeritMarks=@rMeritMarks
			,MeritGrade=@rMeritGrade
			,GenderId=@rGenderId
			,ReligionId=@rReligionId
			,FamilyCast=@rFamilyCast
			,FamilySubCast=@rFamilySubCast
			,CastCategoryId=@rCastCategoryId
			,UpdatedUserId=@rCreatedUserId
			,UpdatedDateTime=sCommon.fGetDate()
			--,DataEntryModeId = @rDataEntryModeId
			--,DataEntryStatusId = @rDataEntryStatusId
			,StudentPhoto = @rStudentPhoto,
			Nationality =@rNationality,
			MotherTongue=@rMotherTongue,
			OtherInformation=@rOtherInformation,
			IsPysicalDeformity=@rIsPysicalDeformity,
           PysicalDeformityRemark=@rPysicalDeformityRemark,
           IsMajorIllness=@rIsMajorIllness,
           MajorIllnessRemark=@rMajorIllnessRemark,
           IsAllergy=@rIsAllergy,
           AllergyRemark=@rAllergyRemark,
           BirthPlace=@rBirthPlace,
		   BirthTaluka=@rBirthTaluka,
			BirthDistrict=@rBirthDistrict,
			BloodGroupId=@rBloodGroupId,
			AdhaarNumber=@rAdhaarNumber,
			IsHostelRequired= @rIsHostelRequired,
			IsTransportRequired=@rIsTransportRequired,
			BirthState=@rBirthState,
			BirthCountry=@rBirthCountry,
			CustomField1Answer=@rCustomField1Answer,
			CustomField2Answer=@rCustomField2Answer,
			CustomField3Answer=@rCustomField3Answer,
			OriginalStudentPhoto=@rOriginalStudentPhoto,
			AdmissionDate=@rAdmissionDate,
			WhatsappContactNo = @rWhatsappContactNo  -- Added column of WhatsappContact for mantis : 29772
			--FatherAdhaarNumber = @rFatherAdhaarNumber
			,PENNumber=@rPENNumber
			,ApaarIdNumber = @rApaarIdNumber
	      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 [sTool].[pUpgradeVersion]...';


GO
ALTER PROCEDURE [sTool].[pUpgradeVersion]
	 
	@rVersionId int,
	@rVersion nvarchar(20),
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

if 	@rVersionId = 0
BEGIN
SELECT 'Enter Version Id'
return	
END


if 	@rVersion = ''
BEGIN
SELECT 'Enter Version Detail'
return	
END

if 	@rOrgGroupId = 0
BEGIN
SELECT 'Enter Org Group Id'
return	
END



--if 	@rOrgGroupId = 1
--BEGIN
--SELECT '1 OrgGroup Not Valid'
--return	
--END

IF NOT EXISTS (SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Id = @rOrgGroupId)
BEGIN
SELECT 'Org Group Not Exists'
return	
END

-- For Upgrade Vesion Start
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES(@rVersion,@rVersionId,'BEGIN','Upgrade Vesion',sCommon.fGetDate(),sCommon.fGetDate(),@rOrgGroupId)

--exec [sTool].[pInsertStaticData]
		
-- add newly added task for admin role
exec [sSecurity].[pNewTaskAdd] @rOrgGroupId

-- update tablerowid master data from excel to table

--pass orgGroupId
-- add new table row ids added
exec [sTool].[pTableRowIdAdd] @rOrgGroupId

-- Pass OrgGroupId
-- Remove tablrowid for organization
--exec sTool.pTableRowChangeOrgToOrgGroupRemove @rOrgGroupId

update sstudent.tAcademic   set rollno = 0 where RollNo is null



delete from sSecurity.tPermission where TaskId in (select ID from sSecurity.tTask where IsObsolete = 1)
delete from sSecurity.tPermission where TaskId not in (select ID from sSecurity.tTask)




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId

IF NOT EXISTS(SELECT 1 FROM sCommunication.teContentTypeMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
 BEGIN
				INSERT INTO sCommunication.teContentTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,'Subject'
						,'Subject'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						
 END


IF NOT EXISTS(SELECT 1 FROM sCommunication.tCircularTypeMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
 BEGIN
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,'Circular'
						,'Circular'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						,NULL
 END

IF NOT EXISTS(SELECT 1 FROM sCommon.tPublishDocumentMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN				
				INSERT INTO sCommon.tPublishDocumentMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 VALUES
						(sCommon.fGetIntIdForOrg(1,@rOrgGroupId),'Fee Receipt','Fee Receipt',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(2,@rOrgGroupId),'Bonafide','Bonafide',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(3,@rOrgGroupId),'Trial','Trial',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(4,@rOrgGroupId),'Charactor','Charactor',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(5,@rOrgGroupId),'Id Card','Id Card',0,1,Getdate(),1,Getdate(),@rOrgGroupId)
						
END


IF NOT EXISTS(SELECT 1 FROM sAdmission.tInquiryStatusMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sAdmission.tInquiryStatusMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,StatusId
					   --,HighlightColor
					   --,InquiryMainStatusId
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Title
						,Title
						,0
						,1
						,getdate()
						,NULL
						,NULL
						,@rOrgGroupId
						,Id	
						--,ISM.HighlightColor
						--,ISM.InquiryMainStatusId					
						FROM sCommon.tStatusMaster
						--INNER JOIN sAdmission.tInquiryStatusMaster ISM ON SM.Id = ISM.StatusId AND ISM.OrgGroupId = 1
						where statustypeId = 104


						UPDATE ISM  
							SET ISM.HighlightColor = ISM1.HighlightColor ,
								ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId
							FROM sAdmission.tInquiryStatusMaster ISM  
							INNER JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM.StatusId = ISM1.StatusId AND ISM1.OrgGroupId = 1
							INNER JOIN sCommon.tStatusMaster SM ON SM.Id = ISM1.StatusId 
							where SM.statustypeId = 104 AND ISM.OrgGroupId = @rOrgGroupId

						
	DECLARE @lMaxId int
	SET @lMaxId = sCommon.fGetIntIdForOrg(213,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sAdmission.tInquiryStatusMaster', @rCurrentNumber = @lMaxId
						
END

--static entry in tVisitorTypeMaster

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE Id = 1)
BEGIN	
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId])
     VALUES
           (1,
		   'Visitor',
		   'Visitor',
		   0,
		   1,
		   GetDate(),
		   NULL,
		   NULL,
		   1)
END

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE Id = 2)
BEGIN	
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId])
     VALUES
           (2,
		   'Parents',
		   'Parents',
		   0,
		   1,
		   GetDate(),
		   NULL,
		   NULL,
		   1)
END

--OrgGoup wise VisitorTypeMaster entry
IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE OrgGroupId = @rOrgGroupId AND Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId])
		 VALUES
			   (
			   sCommon.fGetIntIdForOrg(1,@rOrgGroupId),
			   'Visitor',
			   'Visitor',
			   0,
			   --1,
			   [sCommon].[fGetBigIntIdForOrg](3,@rOrgGroupId),
			   GetDate(),
			   NULL,
			   NULL,
			   @rOrgGroupId)
END

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE OrgGroupId = @rOrgGroupId AND Id = sCommon.fGetIntIdForOrg(2,@rOrgGroupId))
BEGIN
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId])
		 VALUES
			   (
			   sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
			   'Parents',
			   'Parents',
			   0,
			   --1,
			   [sCommon].[fGetBigIntIdForOrg](3,@rOrgGroupId),
			   GetDate(),
			   NULL,
			   NULL,
			   @rOrgGroupId)
END

--PeriodNoMaster Entry

IF NOT EXISTS(SELECT 1 FROM [sAttendance].[tPeriodNoMaster])
BEGIN	

INSERT INTO [sAttendance].[tPeriodNoMaster]
           ([Id]
           ,[Title]
           ,[IsObsolete])
     VALUES
          (1, '1', 0),
		  (2, '2', 0),
		  (3, '3', 0),
		  (4, '4', 0),
		  (5, '5', 0),
		  (6, '6', 0),
		  (7, '7', 0),
		  (8, '8', 0),
		  (9, '9', 0),
		  (10,'10', 0),
		  (11,'11', 0),
		  (12,'12', 0)

END

IF NOT EXISTS(SELECT 1 FROM sCommon.tCastCategoryMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sCommon.tCastCategoryMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   , MainCastCategoryId 
					   ,OrderIndex)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Id	
						,Code
						,Title
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						,Id
						,Id						
						FROM sCommon.tMainCastCategoryMaster
						 
						
	DECLARE @lMaxCatId int
	SET @lMaxCatId = sCommon.fGetIntIdForOrg(100,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sCommon.tCastCategoryMaster', @rCurrentNumber = @lMaxCatId

UPDATE
    o
SET
    o.CastCategoryId	=  sCommon.fGetIntIdForOrg(o.CastCategoryId,@rOrgGroupId)
FROM
    sStudent.tStudentOther o
    INNER JOIN
    sStudent.tStudentMaster S ON S.Id = o.StudentId
WHERE
o.CastCategoryId < 100 
AND CastCategoryId IS NOT NULL
AND S.OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)		
			
UPDATE sAdmission.tAdmissionForm SET CastCategoryId	= sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100 
AND OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)

UPDATE sCommon.tFamiliyCastMaster SET 	CastCategoryId	=  sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100   AND OrgGroupId = @rOrgGroupId

UPDATE sCommon.tSurnameMaster SET 	CastCategoryId	=  sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100 AND OrgGroupId = @rOrgGroupId
			
			
END


IF NOT EXISTS(SELECT 1 FROM sTransport.tTransportMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sTransport.tTransportMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]					    
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,1
						,'Common'
						,'Common'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						 
		DECLARE @lMaxTranId int
	SET @lMaxTranId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sTransport.tTransportMaster', @rCurrentNumber = @lMaxTranId
						 
					 				
	INSERT INTO sTransport.tAssignTransportOrg
					   (TransportId
					   ,OrgId					    				    
					   )
	SELECT 		
	@lMaxTranId
	,Id
	FROM
	sSetup.tOrganizationMaster
	WHERE OrgGroupId = 		@rOrgGroupId	 
						 
						

UPDATE sTransport.tBusRouteMaster
SET TransportId = @lMaxTranId WHERE OrgGroupId = @rOrgGroupId

UPDATE sTransport.tVehicleMaster
SET TransportId = @lMaxTranId WHERE OrgGroupId = @rOrgGroupId


			
			
END


IF NOT EXISTS(SELECT 1 FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId AND Id =  sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN				
				INSERT INTO sSetup.tBatchGroupMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[OrgGroupId]					    
					   ,[OrderIndex]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,1
						,'Common'
						,'Common'
						,@rOrgGroupId
						,1
						
						,1
						,getdate()
						,1
						,getdate()
						
						 
	--DECLARE @lBatchGroupId int
	--SET @lMaxTranId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)					
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sSetup.tBatchGroupMaster', @rCurrentNumber = @lBatchGroupId
	
	UPDATE B    
	SET BatchGroupId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
	FROM sSetup.tBatchMaster B INNER JOIN sSetup.tOrganizationMaster O ON B.OrgId = O.ID
	WHERE O.OrgGroupId = @rOrgGroupId AND B.BatchGroupId IS NULL

END


UPDATE sSetup.tClassMaster SET DepartmentId = sCommon.fGetIntIdForOrg(OrgId,1) where DepartmentId is null

if (@rOrgGroupId <> 1154)
BEGIN
UPDATE sCommon.tReport SET IsObsolete = 1
 Where Id in (20642,20643,20644,20645,20646,20647,20648,20649,20650,20665,20718,20779,20692,20693,20694)

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

UPDATE sSystem.tDatabaseInfo SET 
VersionNumber = @rVersion,
VersionId = @rVersionId,
LastVersionUpdateDateTime = getdate() ,
IsNewVersion = 1
WHERE ApplicationId = 1 
 
-- for student - remove permission for employee center
DECLARE @lRoleId int = 0
DECLARE @lDefaultRoleId int = 10
SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
 
--DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
--WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId AND T.ModuleId =  234

---- for employee - remove permisiion for student center
--SET @lDefaultRoleId = 22
--SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
--DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
--WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId AND T.ModuleId =  233

-- for SysSuperAdmin
SET @lDefaultRoleId = 1
SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId
AND T.Id IN (30258,30262,30266,30257,30160,30243,30244)

IF NOT EXISTS (SELECT 1 FROM sSecurity.tOrganizationTask  T   WHERE TaskId = 20596  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tOrganizationTask 
	(OrgGroupId, TaskId, AvailablePermission)
	SELECT  @rOrgGroupId,20596,2
END

--default permission for Lesson Plan Complete Task for Admin only (for execute permission)
IF NOT EXISTS (SELECT 1 FROM sSecurity.tOrganizationTask  T   WHERE TaskId = 31244  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tOrganizationTask 
	(OrgGroupId, TaskId, AvailablePermission)
	SELECT  @rOrgGroupId,31244,64
END

IF NOT EXISTS (SELECT * FROM sSecurity.tPermission   WHERE RoleId =sCommon.fGetIntIdForOrg(2,@rOrgGroupId) AND TaskId = 20596  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tPermission(TaskId, RoleId, Permission, IsObsolete, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime,OrgGroupId)
	SELECT  20596,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId
	FROM sSecurity.tOrganizationTask WHERE OrgGroupId = @rOrgGroupId
END

---- for SysSuperAdmin update password
--UPDATE sSecurity.tUser SET LoginPassword='XAqFcL/nd0bnDNhkyF/PxobplNJ+ggbN9370AHxj7oU=' WHERE Id = sCommon.fGetBigIntIdForOrg(1,@rOrgGroupId)
--UPDATE sSecurity.tUser SET LoginPassword='XAqFcL/nd0bnDNhkyF/PxobplNJ+ggbN9370AHxj7oU=' WHERE Id = 1

-- for SysSuperAdmin update password
--UPDATE sSecurity.tUser SET LoginPassword='5MM16xTaq777OzqQHkRp4g==' WHERE Id = sCommon.fGetBigIntIdForOrg(1,@rOrgGroupId)
--UPDATE sSecurity.tUser SET LoginPassword='5MM16xTaq777OzqQHkRp4g==' WHERE Id = 1

 -- For Upgrade Vesion END
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES(@rVersion,@rVersionId,'END','Upgrade Vesion',sCommon.fGetDate(),sCommon.fGetDate(),@rOrgGroupId)

END
GO
PRINT N'Altering Procedure [sAdmission].[pImportAdmissionForm]...';


GO

ALTER PROCEDURE [sAdmission].[pImportAdmissionForm]
    @rOrgId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rBatchId int,
	@rOrgGroupId int


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,@intDoc INT,
		@lFormNo int,@lStudentName nvarchar(100),@lFatherName nvarchar(100),@lSurName nvarchar(100),@lForClassId int,@lForClass nvarchar(100),
		@lDateOfBirth date,@lDateOfBirthInWord nvarchar(100),@lStreetOne nvarchar(50),@lStreetTwo nvarchar(50),@lStreetThree nvarchar(50),
		@lCountry nvarchar(50),@lState nvarchar(50),@lCity nvarchar(50),@lZipCode nvarchar(20),@lContactNo nvarchar(20),@lContactEmail nvarchar(50),
		@lRemark nvarchar(200),@lPreviousSchool nvarchar(200),@lMeritMarks decimal(10,2),@lMeritGrade nvarchar(20),@lGenderId int,@lReligionId int,
        @lGender nvarchar(100),@lReligion nvarchar(100),@lFamilyCaste nvarchar(100),@lCastCategory nvarchar(20),
		@lHostelRequired nvarchar(20) ,@lTransportRequired nvarchar(20),@lHostelRequiredId int ,
		@lTransportRequiredId int,@lCastCategoryId int=0,@lBirthPlace nvarchar(150),
		@lPlaceOfBirth nvarchar(150),@lFatherFullName nvarchar(100), @lFatherOccupation  nvarchar(50),
	    @lFatherContactNo nvarchar(50), @lFatherDesignation nvarchar(100),@lMotherContactNo nvarchar(50), @lMotherDesignation nvarchar(100),@lMotherIncome int,
	    @lFatherIncome int, @lMotherFullName nvarchar(100)='', @lMotherOccupation  nvarchar(50),@lMotherQualification nvarchar(50)='',@lFatherQualification nvarchar(50)
		,@lPENNumber BIGINT,@lApaarIdNumber NVARCHAR(50) --add for mantis : 0043425
			
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,
		FormNo int,
		ForClass nvarchar(100),
		StudentName nvarchar(100), 
		FatherName nvarchar(100),
		SurName nvarchar(100),
		DateOfBirth date ,
		DateOfBirthInWord nvarchar(100),
	    StreetOne nvarchar(50), 
	    StreetTwo nvarchar(50), 
	    StreetThree nvarchar(50), 
	    State nvarchar(50), 
	    City nvarchar(50),
	    Country nvarchar(50), 
	    ZipCode nvarchar(20), 
	    ContactNo nvarchar(20), 
	    ContactEmail nvarchar(50), 
	    Remark nvarchar(200) , 
	    PreviousSchool nvarchar(200),
	    MeritMarks decimal(10,2),
	    MeritGrade nvarchar(20), 
	    Gender nvarchar(100), 
	    Religion nvarchar(100), 
	    FamilyCaste nvarchar(100), 
	    CastCategory nvarchar(100),
	    HostelRequired nvarchar(20), 
	    TransportRequired nvarchar(20),
	    PlaceOfBirth nvarchar(150),
	    FatherFullName nvarchar(100), 
	    FatherQualification nvarchar(50),
	    FatherOccupation  nvarchar(50),
	    FatherContactNo nvarchar(50),
	    FatherDesignation nvarchar(100),
	    FatherIncome int,
	    MotherFullName nvarchar(100), 
	    MotherQualification nvarchar(50),
	    MotherOccupation  nvarchar(50),
	    MotherContactNo nvarchar(50),
	    MotherDesignation nvarchar(100),
	    MotherIncome int
		,PENNumber BIGINT --add for mantis : 0043425
		,ApaarIdNumber NVARCHAR(50) --add for mantis : 0043425
	)
	INSERT INTO #tTable
	(   FormNo,ForClass,StudentName,FatherName,SurName,DateOfBirth,DateOfBirthInWord, StreetOne, StreetTwo, StreetThree, 
	    State,  City,Country,ZipCode,ContactNo, ContactEmail,Remark,PreviousSchool,MeritMarks,MeritGrade, Gender,	  Religion,FamilyCaste,CastCategory,HostelRequired,TransportRequired,PlaceOfBirth,FatherFullName,FatherQualification,
		FatherOccupation,FatherContactNo,FatherDesignation,FatherIncome,
	    MotherFullName,MotherQualification,MotherOccupation,MotherContactNo,MotherDesignation,MotherIncome
		,PENNumber
		,ApaarIdNumber
	)
	SELECT
		FormNo,ForClass,StudentName,FatherName,SurName,DateOfBirth, DateOfBirthInWord,StreetOne, StreetTwo, StreetThree, 
	    State,  City,Country,ZipCode,ContactNo, ContactEmail,Remark,PreviousSchool,MeritMarks,MeritGrade, Gender,	Religion,FamilyCaste,CastCategory,HostelRequired,TransportRequired,PlaceOfBirth,FatherFullName,FatherQualification,
		FatherOccupation,FatherContactNo,FatherDesignation,FatherIncome,
	    MotherFullName,MotherQualification,MotherOccupation,MotherContactNo,MotherDesignation,MotherIncome
		,PENNumber 
		,ApaarIdNumber
	FROM OPENXML (@intDoc, '/Table/ImportAdmissionForm', 1)
	WITH
	( 	
	    FormNo int  '@FormNo',
		ForClass nvarchar(100) '@ForClass',
		StudentName nvarchar(100) '@StudentName', 
		FatherName nvarchar(100) '@FatherName',
		SurName nvarchar(100) '@SurName',
		DateOfBirth date  '@DateOfBirth',
		DateOfBirthInWord nvarchar(100) '@DateOfBirthInWord',
	    StreetOne nvarchar(50) '@StreetOne', 
	    StreetTwo nvarchar(50) '@StreetTwo', 
	    StreetThree nvarchar(50) '@StreetThree', 
	    State nvarchar(50) '@State', 
	    City nvarchar(50) '@City',
	    Country nvarchar(50) '@Country', 
	    ZipCode nvarchar(20) '@ZipCode', 
	    ContactNo nvarchar(20) '@ContactNo', 
	    ContactEmail nvarchar(50) '@ContactEmail', 
	    Remark nvarchar(200) '@Remark' , 
	    PreviousSchool nvarchar(200) '@PreviousSchool',
	    MeritMarks decimal(10,2) '@MeritMarks',
	    MeritGrade nvarchar(20) '@MeritGrade', 
	    Gender nvarchar(100) '@Gender', 
	    Religion nvarchar(100) '@Religion', 
	    FamilyCaste nvarchar(100) '@FamilyCaste', 
	    CastCategory nvarchar(100) '@CastCategory',
	    HostelRequired nvarchar(20) '@HostelRequired', 
	    TransportRequired nvarchar(20) '@TransportRequired',
	    PlaceOfBirth nvarchar(150) '@PlaceOfBirth',
	    FatherFullName nvarchar(100) '@FatherFullName', 
	    FatherQualification nvarchar(50) '@FatherQualification',
	    FatherOccupation  nvarchar(50) '@FatherOccupation',
	    FatherContactNo nvarchar(50) '@FatherContactNo',
	    FatherDesignation nvarchar(100) '@FatherDesignation',
	    FatherIncome int '@FatherIncome',
	    MotherFullName nvarchar(100) '@MotherName', 
	    MotherQualification nvarchar(50) '@MotherQualification',
	    MotherOccupation  nvarchar(50) '@MotherOccupation',
	    MotherContactNo nvarchar(50) '@MotherContactNo',
	    MotherDesignation nvarchar(100) '@MotherDesignation',
	    MotherIncome int '@MotherIncome'
		,PENNumber BIGINT '@PENNumber'--Mantis - 0043425
		,ApaarIdNumber NVARCHAR(50) '@ApaarIdNumber'--Added by 0043425
	    )

SELECT @lCount =  COUNT(Id) FROM #tTable

WHILE @lCount > 0 
BEGIN	
	SET @lFormNo=0
	SET @lForClass=''
	SET @lStudentName=''
	SET @lFatherName=''
	SET @lSurName=''
	SET @lDateOfBirth =''
	SET @lStreetOne=''
	SET @lStreetTwo=''
	SET @lStreetThree=''
	SET @lState=''
	SET @lCity=''
	SET @lCountry=''
	SET @lZipCode=''
	SET @lContactNo=''
	SET @lContactEmail=''
	SET @lRemark=''
	SET @lPreviousSchool=''
	SET @lMeritMarks=0
	SET @lMeritGrade=''
	SET @lGender =''
	SET @lReligion=''
	SET @lFamilyCaste=''
	SET @lCastCategory=''
	SET @lHostelRequired=''
	SET @lTransportRequired=''
	SET @lForClassId=0
	SET @lGenderId=0
	SET @lReligionId=0
	SET @lBirthPlace=''
	SET @lForClassId=0
	SET @lDateOfBirthInWord =''
    SET  @lHostelRequiredId=0
    SET @lTransportRequiredId=0
    SET @lCastCategoryId=0
    SET @lPlaceOfBirth =''
    SET @lFatherFullName =''
    SET @lFatherOccupation  =''
	SET @lFatherContactNo =''
	SET @lFatherDesignation =''
	SET @lMotherContactNo =''
	SET @lMotherDesignation =''
	SET @lMotherIncome=0
	SET @lFatherIncome=0
	SET @lMotherFullName=''
	SET @lMotherOccupation =''
	SET @lMotherQualification=''
	SET @lFatherQualification=''
	SET @lPENNumber = NULL --Mantis - 0043425
	SET @lApaarIdNumber = '' --mantis : 0043425

  SELECT		
		@lFormNo=FormNo,
		@lForClass=ForClass,
		@lStudentName=StudentName,
		@lFatherName=FatherName,
		@lSurName=SurName,
		@lDateOfBirth =DateOfBirth ,
		@lDateOfBirthInWord=DateOfBirthInWord,
		@lStreetOne=StreetOne,
		@lStreetTwo=StreetTwo,
		@lStreetThree= StreetThree,
		@lState= State,
		@lCity=City,
		@lCountry=Country,
		@lZipCode=ZipCode,
		@lContactNo=ContactNo,
		@lContactEmail=ContactEmail,
		@lRemark=Remark,
		@lPreviousSchool=PreviousSchool,
		@lMeritMarks=MeritMarks,
		@lMeritGrade=MeritGrade,
		@lGender = Gender ,
		@lReligion= Religion,
		@lFamilyCaste=FamilyCaste,
		@lCastCategory=CastCategory,
		@lHostelRequired=HostelRequired,
		@lTransportRequired=TransportRequired,
		@lBirthPlace =PlaceOfBirth,
		 @lFatherFullName =FatherFullName,
		 @lFatherOccupation  =FatherOccupation,
		 @lFatherContactNo =FatherContactNo,
		 @lFatherDesignation =FatherDesignation,
		 @lMotherContactNo =MotherContactNo,
		 @lMotherDesignation =MotherDesignation,
		 @lMotherIncome=MotherIncome,
		 @lFatherIncome=FatherIncome,
		 @lMotherFullName=MotherFullName,
		 @lMotherOccupation =MotherOccupation,
		 @lMotherQualification=MotherQualification,@lFatherQualification=FatherQualification
		 ,@lPENNumber = PENNumber --Mantis - 0043425
		 ,@lApaarIdNumber = ApaarIdNumber --mantis : 0043425

FROM #tTable WHERE Id = @lCount  

SELECT	@lGenderId = Id FROM sCommon.tGenderMaster WHERE Title = @lGender AND IsObsolete=0
SELECT	@lForClassId  = Id FROM sSetup.tClassMaster WHERE Title = @lForClass AND OrgId = @rOrgId AND IsObsolete=0
SELECT	@lReligionId = Id FROM sCommon.tReligionMaster WHERE Title = @lReligion AND OrgGroupId=@rOrgGroupId AND IsObsolete=0
SELECT  @lCastCategoryId=Id  FROM sCommon.tCastCategoryMaster WHERE IsObsolete = 0 AND OrgGroupId=@rOrgGroupId AND Title = @lCastCategory
SET @lHostelRequiredId=0 SET @lTransportRequiredId=0
if(@lHostelRequired='Yes')
BEGIN
SET @lHostelRequiredId=1
END
if(@lTransportRequired='Yes')
BEGIN
SET @lTransportRequiredId=1
END
	--BEGIN TRANSACTION
		DECLare @lAdmissionFormId bigint=0,@OutAdmissionFormId bigint=0
--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionForm', 0, 1, 1,@outNextNumber = @lAdmissionFormId output

  BEGIN	
 -- INSERT INTO sAdmission.tAdmissionForm
	--	(Id, FormNo, FirstName, MiddleName, LastName, ForClassId, ForBatchId, ForBatch, DateOfBirth, DateOfBirthInWord, OrgId, BatchId, StatusId, 
	--	StreetOne, StreetTwo,StreetThree, Country, State, City, ZipCode, ContactNo, ContactEmail, Remark, PreviousSchool, MeritMarks, MeritGrade,GenderId, ReligionId,
	--	 FamilyCast, FamilySubCast, CastCategoryId, CreatedUserId, CreatedDateTime, FormPassword, DataEntryModeId, DataEntryStatusId, StudentPhoto, AdmissionCategoryId, Nationality, MotherTongue, 
	--	 OtherInformation, IsPysicalDeformity, PysicalDeformityRemark, IsMajorIllness, MajorIllnessRemark, IsAllergy, AllergyRemark, BirthPlace, BirthTaluka, BirthDistrict, BloodGroupId, AdhaarNumber, IsHostelRequired, IsTransportRequired, BirthState, BirthCountry
	--	)
	--VALUES
	--	( @lAdmissionFormId,@lFormNo,@lStudentName,@lFatherName,@lSurName,@lForClassId,0,null,@lDateOfBirth,@lDateOfBirthInWord,@rOrgId,@rBatchId,207
	--	     ,@lStreetOne,@lStreetTwo,@lStreetThree,@lCountry,@lState,@lCity,@lZipCode,@lContactNo,@lContactEmail,@lRemark,@lPreviousSchool,@lMeritMarks
	--		,@lMeritGrade,@lGenderId,@lReligionId,@lFamilyCaste,null,@lCastCategoryId,@rUserId,sCommon.fGetDate(),@lFormNo,572,562,null, 0, null, null,null,
	--	 	 0,  null, 0, null, 0, null,@lBirthPlace,null, null,0,null, @lHostelRequiredId, @lTransportRequiredId, null, null
	--	) 
	
    EXEC [sAdmission].[pAdmissionFormAdd] 0,@lFormNo,@lStudentName,@lFatherName,@lSurName,@lForClassId,0,@lDateOfBirth,@lDateOfBirthInWord,@rOrgId,@rBatchId,207,@lStreetOne,
    @lStreetTwo,@lStreetThree,@lCountry,@lState,@lCity,@lZipCode,@lContactNo,@lContactEmail,@lRemark,@lPreviousSchool,@lMeritMarks,@lMeritGrade,@lGenderId,
	@lReligionId,@lFamilyCaste,null,@lCastCategoryId,@rUserId,@lFormNo,562,572,null,null,null,null,0,null,0,null,0,null,@lBirthPlace,null,null,0,null,
	@lHostelRequiredId,@lTransportRequiredId,null,null,null,null,null,@OutAdmissionFormId  output
	,null,'',null,@lPENNumber,@lApaarIdNumber
   END
   BEGIN
   INSERT INTO  sAdmission.tAdmissionFormFamilyDetail(AdmissionFormId,FatherName, FatherOccupation,FatherQualification,MotherQualification,
		 FatherContactNo,FatherIncome,MotherName,MotherOccupation,MotherContactNo,MotherIncome,CreatedUserId, CreatedDateTime,MotherDesignation,FatherDesignation
		) VALUES(@OutAdmissionFormId,@lFatherFullName, @lFatherOccupation,@lFatherQualification,@lMotherQualification,
		 @lFatherContactNo,@lFatherIncome,@lMotherFullName,@lMotherOccupation,@lMotherContactNo,@lMotherIncome,@rUserId,sCommon.fGetDate(),@lMotherDesignation,@lFatherDesignation)
   END
		 SET @lCount = @lCount - 1
		 
	--COMMIT TRANSACTION	
END
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END
GO
PRINT N'Altering Procedure [sAlert].[pAlertLogAdd]...';


GO
ALTER PROCEDURE [sAlert].[pAlertLogAdd]
	
	@rXML nvarchar(max),
	@rOrgId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN
BEGIN TRY
	
	BEGIN TRANSACTION
	 
	SET @rXML=REPLACE(@rXML,'&','&amp;')
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,
			@intDoc INT

			--SET @rXML=Replace(@rXML,'<br/>',char(13))
			--SET @rXML=Replace(Replace(@rXML,'&nbsp;',' '),'<br/>',char(13))
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXML
	
	--Select @rXML

	-- Added @lMaxAlertLogId logic for loading and deadlock issue on 19/05/2025 by Foram
	DECLARE @lNextNumber BIGINT, @lMaxAlertLogId bigint = 0 
	DECLARE @lFromNextNumber BIGINT  
	
	SELECT @lMaxAlertLogId = ISNULL(MAX(Id), 0) FROM sAlert.tAlertLog WITH (NOLOCK) WHERE OrgId = @rOrgId
	
	IF(@lMaxAlertLogId = 0)
	BEGIN
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAlert.tAlertLog', 0, 1, 1,@outNextNumber = @lNextNumber output
	END
	ELSE
	BEGIN
		SET @lNextNumber =  @lMaxAlertLogId + 1 
	END

	
	SET @lFromNextNumber=@lNextNumber-1
	INSERT INTO sAlert.tAlertLog
		(
			Id,
			ContactId,
			AlertMessage,
			AlertSubject,
			StatusId,
			ResultMessage,
			SMSType,
			SourceEvent,
			EventId,
			AlertModeId,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			ReceiverSourceTypeId,
			ReceiverSourceId
		)
	SELECT
			@lFromNextNumber + ROW_NUMBER() OVER(ORDER BY ContactId),
			ContactId,
			sSetup.fPortalXMLTagsReplaceReverse(AlertMessage),
			--AlertMessage,
			sSetup.fPortalXMLTagsReplaceReverse(AlertSubject),
			StatusId,
			ResultMessage,
			SMSType,
			SourceEvent,
			EventId,
			AlertModeId,
			@rOrgId,
			CASE WHEN CreatedUserId = 1 THEN sCommon.fGetBigIntIdForOrg(CreatedUserId,@rOrgId) ELSE CreatedUserId END,			
			sCommon.fGetDate(),
			ReceiverSourceTypeId,
			ReceiverSourceId
		
	FROM OPENXML (@intDoc, '/Table/AlertLog', 1)
	WITH
	(
		ContactId nvarchar(100) 'ContactId',
		AlertMessage nvarchar(max) 'AlertMessage',
		AlertSubject nvarchar(500) 'AlertSubject',
		StatusId int 'StatusId',
		ResultMessage nvarchar(500) 'ResultMessage',		-- Changed Length 255 to 500 For Mantis 0035547 by Foram
		SMSType nvarchar(50) 'SMSType',
		SourceEvent nvarchar(50) 'SourceEvent',
		EventId int 'EventId',
		AlertModeId tinyint 'AlertModeId',
		CreatedUserId bigint 'CreatedUserId',
		ReceiverSourceTypeId smallint 'ReceiverSourceTypeId',
		ReceiverSourceId bigint 'ReceiverSourceId'
	)

	SELECT @lCount = COUNT(1) FROM OPENXML (@intDoc, '/Table/AlertLog', 1)
				 WITH ( ContactId nvarchar(50))
	SET @lNextNumber  = @lCount + @lFromNextNumber 
		
	--EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAlert.tAlertLog', @rCurrentNumber = @lNextNumber 
	UPDATE sCommon.tTableRowId WITH (rowlock) 
	SET CurrentNumber = @lNextNumber,UpdatedDateTime = sCommon.fGetDate() 
	WHERE TableTitle = 'sAlert.tAlertLog' AND OrgId = @rOrgId

	EXEC sp_xml_removedocument @intDoc
		
	SELECT 1 AS Result,@lFromNextNumber+1 AS FromId,@lNextNumber AS ToId
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sCertificate].[pCharacterAdd]...';


GO


ALTER PROCEDURE [sCertificate].[pCharacterAdd]

	@rId bigint
   ,@rAcademicId bigint
   ,@rNumber int
   ,@rCharacterDate date
   ,@rCreatedUserId bigint
   ,@rOrgId int
   ,@rRemark nvarchar(200)
   ,@rBatchId int
   ,@rIsNumberBatchWise bit = 0
	       
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		
	
	If(@rIsNumberBatchWise = 1)	
	BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tCharacter WHERE OrgId=@rOrgId AND BatchId = @rBatchId
		END	
		
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sCertificate.tCharacter WHERE Number=@rNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END
	END
	ELSE
	BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tCharacter WHERE OrgId=@rOrgId 
		END	
		
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sCertificate.tCharacter WHERE Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END
	END
		
	 DECLARE @lNextNumber BIGINT
	 BEGIN TRANSACTION
	  IF(@rId = 0)	
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tCharacter', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCertificate.tCharacter
			(
				Id
			   ,AcademicId
			   ,Number
			   ,characterDate
			   ,OrgId
			   ,CreatedUserId
			   ,CreatedDateTime
			   ,Remark
			   ,BatchId
			)
			VALUES
			(	@lNextNumber
			   ,@rAcademicId
			   ,@rNumber
			   ,@rCharacterDate
			   ,@rOrgId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate() 
			   ,@rRemark
			   ,@rBatchId
			)
		END
		ELSE
		BEGIN
			SET @lNextNumber = @rId
			UPDATE  sCertificate.tCharacter
			SET
				AcademicId=@rAcademicId,
				characterDate=@rCharacterDate,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate(),
				Remark=@rRemark,
				BatchId = @rBatchId
			  WHERE Id = @rId
		END  	
	SELECT @lNextNumber AS Result
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		Select error_message()
	END CATCH	
	
END
GO
PRINT N'Altering Procedure [sCertificate].[pLeavingAdd]...';


GO
ALTER PROCEDURE [sCertificate].[pLeavingAdd]
			
		@rId bigint
       ,@rAcademicId bigint
       ,@rLCNumber int
       ,@rLCDate date
       ,@rLeftDate date
       ,@rLCCopy tinyint
       ,@rLCRemark nvarchar(200)
       ,@rLCProgress nvarchar(200)
       ,@rLCConduct nvarchar(200)
       ,@rLCReason nvarchar(200)
       ,@rLCBookNumber nvarchar(20)
       ,@rCreatedUserId bigint
       ,@rOrgId int
       ,@rToCollege nvarchar(200)
	   ,@rToCollegeAddress nvarchar(200)
	   ,@rLastExamName nvarchar(200)
	   ,@rLastExamResult nvarchar(200)
	   ,@rRepeatDetail nvarchar(100)
	   ,@rSubjectStudied nvarchar(300)
	   ,@rPromoteToClass nvarchar(50)
	   ,@rFeeDetail nvarchar(100)
	   ,@rFeeConcessionDetail nvarchar(100)
	   ,@rExtraCurricularActivities nvarchar(200)
	   ,@rNCCScoutDetail nvarchar(100)
	   ,@rTermsInInstitute nvarchar(500)
	   ,@rBatchId int
	   ,@rIsNumberBatchWise bit = 0
	   ,@rTotalDays int=0
	   ,@rPresentDays int=0
	   ,@rProofOfDOB nvarchar(200)
	   ,@rLCCopyRemark nvarchar(max)
       ,@rLCDisplayName nvarchar(200)	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	DECLARE @lNextNumber BIGINT
	DECLARE @lStudentId bigint
	DECLARE @lClassId bigint
	DECLARE @lAdmissionDate Date
	 
	SELECT @lStudentId=StudentId,@lClassId=ClassId FROM sStudent.tAcademic WHERE Id=@rAcademicId
	UPDATE sStudent.tAcademic SET BatchStatusId = 1 WHERE BatchStatusId is null
	 
	If(@rIsNumberBatchWise = 1)
	BEGIN
		IF(@rLCNumber = 0)	
		BEGIN
			SELECT @rLCNumber = ISNULL(MAX(LCNumber),0) + 1 FROM sCertificate.tLeaving WHERE OrgId=@rOrgId AND BatchId = @rBatchId
		END	
	 
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tLeaving WHERE AcademicId = @rAcademicId AND BatchId = @rBatchId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tLeaving WHERE LCNumber=@rLCNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	END	--add this for mantis: 43914
	ELSE
 	BEGIN
		IF(@rLCNumber = 0)	
		BEGIN
			SELECT @rLCNumber = ISNULL(MAX(LCNumber),0) + 1 FROM sCertificate.tLeaving WHERE OrgId=@rOrgId
		END	
	 
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tLeaving WHERE AcademicId = @rAcademicId)-- IN(SELECT Id FROM sStudent.tAcademic WHERE StudentId=@lStudentId))
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tLeaving WHERE LCNumber=@rLCNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	END
			
	IF EXISTS(SELECT 1 FROM sAttendance.tStudentRegister WHERE AttendanceDate>@rLeftDate AND AcademicId=@rAcademicId)
	BEGIN
		SELECT -101 AS Result
		RETURN
	END
			
	SELECT @lAdmissionDate = AdmissionDate FROM sStudent.tStudentAdmission WHERE StudentId=@lStudentId
	IF (@lAdmissionDate > @rLCDate)
	BEGIN
		SELECT -105 AS Result
		RETURN
	END
		
	IF EXISTS(SELECT Id FROM sCertificate.tLeaving WHERE AcademicId=@rAcademicId AND Id<>@rId)
	BEGIN
		SELECT -103 AS Result
		RETURN
	END
		
		BEGIN TRANSACTION	
			
			IF(@rId = 0)	
			BEGIN
	
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tLeaving', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sCertificate.tLeaving
				(
					Id
				   ,AcademicId
				   ,LCNumber
				   ,LCDate
				   ,LeftDate
				   ,LCCopy
				   ,LCRemark
				   ,LCProgress
				   ,LCConduct
				   ,LCReason
				   ,LCBookNumber
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime
				   ,ToCollege
				   ,ToCollegeAddress
				   ,LastExamName 
		           ,LastExamResult 
		           ,RepeatDetail 
		           ,SubjectStudied
		           ,PromoteToClass 
		           ,FeeDetail 
		           ,FeeConcessionDetail
		           ,ExtraCurricularActivities
		           ,NCCScoutDetail 
		           ,TermsInInstitute
		           ,BatchId
				   ,TotalDays
				   ,PresentDays
				   ,ProofOfDOB
				   ,LCCopyRemark
				   ,DisplayName
				)
				VALUES
				(	@lNextNumber
				   ,@rAcademicId
				   ,@rLCNumber
				   ,@rLCDate
				   ,@rLeftDate
				   ,@rLCCopy
				   ,@rLCRemark
				   ,@rLCProgress
				   ,@rLCConduct
				   ,@rLCReason
				   ,@rLCBookNumber
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate() 
				   ,@rToCollege
				   ,@rToCollegeAddress
				   ,@rLastExamName 
		           ,@rLastExamResult 
		           ,@rRepeatDetail 
		           ,@rSubjectStudied
		           ,@rPromoteToClass 
		           ,@rFeeDetail 
		           ,@rFeeConcessionDetail
		           ,@rExtraCurricularActivities
		           ,@rNCCScoutDetail 
		           ,@rTermsInInstitute
		           ,@rBatchId
				   ,@rTotalDays 
			       ,@rPresentDays 
				   ,@rProofOfDOB
				   ,@rLCCopyRemark
				   ,@rLCDisplayName
				)	
				SELECT @lNextNumber AS Result 
				 
			END
		
		ELSE
		
		BEGIN
		
			 select 111
			 SET @lNextNumber = @rId
				UPDATE  sCertificate.tLeaving
				SET
					AcademicId=@rAcademicId,
					LCDate=@rLCDate,
					LeftDate=@rLeftDate,
					LCCopy=@rLCCopy,
					LCRemark=@rLCRemark,
					LCProgress=@rLCProgress,
					LCConduct=@rLCConduct,
					LCReason=@rLCReason,
					LCBookNumber=@rLCBookNumber,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					ToCollege=@rToCollege,
				    ToCollegeAddress=@rToCollegeAddress,
				    LastExamName=@rLastExamName 
				    ,LastExamResult=@rLastExamResult 
				    ,RepeatDetail=@rRepeatDetail 
				    ,SubjectStudied=@rSubjectStudied
				    ,PromoteToClass=@rPromoteToClass 
				    ,FeeDetail=@rFeeDetail 
				    ,FeeConcessionDetail=@rFeeConcessionDetail
				    ,ExtraCurricularActivities=@rExtraCurricularActivities
				    ,NCCScoutDetail=@rNCCScoutDetail 
				    ,TermsInInstitute=@rTermsInInstitute
				    ,BatchId = @rBatchId
					,TotalDays = @rTotalDays 
			        ,PresentDays = @rPresentDays 
					,ProofOfDOB = @rProofOfDOB
					,LCCopyRemark = @rLCCopyRemark
					,DisplayName = @rLCDisplayName
				WHERE Id = @rId
				
		 
		END 
		
		
				UPDATE sStudent.tStudentAdmission
				SET
				  LeftStandardId=@lClassId,
				  LeftDate = @rLeftDate, 
				  LeftReason = @rLCReason, 
				  LCProgress = @rLCProgress,
				  LCConduct = @rLCConduct, 
				  LCBook = @rLCBookNumber, 
				  LCNumber = @rLCNumber,
				  LCDate = @rLCDate, 
				  LCRemark = @rLCRemark, 
				  LCCopy = @rLCCopy, 
				  LcId = @lNextNumber, 
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE StudentId = @lStudentId 
				
				UPDATE sStudent.tStudentMaster
				SET
				  StatusId=3,
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE Id = @lStudentId 
				
			  UPDATE sSecurity.tUser
			   SET IsObsolete=1 
			   WHERE SourceTypeId=2003 AND Sourceid=@lStudentId
			   
		 COMMIT TRANSACTION		
		 
		  --Update Batch Status 
			UPDATE A
			SET BatchStatusId = 3 
			FROM sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON A.StudentId = SA.StudentId AND A.ClassId = SA.LeftStandardId
			WHERE SM.StatusId = 3 AND SM.Id = @lStudentId
		 --Ends

		   --Update Class Status 
			UPDATE A
			SET ClassStatusId = 3 ,
			 UpdatedUserId = @rCreatedUserId, 
		     UpdatedDateTime =sCommon.fGetDate()
			FROM sStudent.tAcademic A
			WHERE A.Id = @rAcademicId
		 --Ends
		 
		  SELECT @lNextNumber AS Result
	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
	
END
GO
PRINT N'Altering Procedure [sCommon].[pAreaMasterAdd]...';


GO
ALTER PROCEDURE [sCommon].[pAreaMasterAdd]
	@rOrgId [int],
	@rOrgGroupId [int],
	@rTitle [nvarchar](100),
	@rCityId [int] = 0,
	@rCreatedUserID [bigint],
	@rIsShow [bit] = 0,
	@rZipCode nvarchar(10)=''
WITH EXECUTE AS CALLER
AS
--@rAreaId dInt = 0 OUTPUT
SET NOCOUNT ON

BEGIN
--SET @rOrgId = 0
 DECLARE @lId	Int
 DECLARE @lNextNumber INT     
IF(@rIsShow = 0)
		 BEGIN
			 IF(@rCityId = 0)
				 BEGIN
					 IF EXISTS(SELECT 1 FROM sCommon.tAreaMaster WHERE Title = @rTitle AND (CityId IS NULL OR (CityId = @rCityId))AND IsShow = 0 AND OrgGroupId = @rOrgGroupId)
							BEGIN
									SELECT CAST(Id AS Int) Id FROM sCommon.tAreaMaster WHERE Title = @rTitle AND IsShow = 0 AND CityId IS NULL  AND OrgGroupId = @rOrgGroupId
									RETURN

							END
				 END
			 ELSE
				 BEGIN
					 IF EXISTS(SELECT 1 FROM sCommon.tAreaMaster WHERE Title = @rTitle AND ((CityId = @rCityId)) AND IsShow = 0  AND OrgGroupId = @rOrgGroupId)
							BEGIN
									SELECT CAST(Id AS Int) Id FROM sCommon.tAreaMaster WHERE Title = @rTitle AND IsShow = 0 AND ((CityId = @rCityId)  AND OrgGroupId = @rOrgGroupId)
									RETURN
							END
				 END
		 END
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommon.tAreaMaster', 0, 1, 1,@outNextNumber = @lNextNumber output	--Mantis - 43779(@rOrgId to @rOrgGroupId)
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommon.tAreaMaster', 0, 1, 1,@outNextNumber = @lId output
	
		IF(@rIsShow = NULL)
			 BEGIN
				SET @rIsShow = 1
			 END
		
		INSERT INTO sCommon.tAreaMaster
			(
				Id,
				Title,
				CityId,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				IsObsolete, 
				IsShow,
				OrgGroupId,
				ZipCode
			)
		VALUES
			(
				@lNextNumber,
				@rTitle,
				(CASE @rCityId WHEN 0 THEN NULL ELSE @rCityId END),
				@rCreatedUserID,
				sCommon.fGetDate(),
				@rCreatedUserID,
				sCommon.fGetDate(),
				0, 
				@rIsShow,
				@rOrgGroupId,
				@rZipCode
			)
	
		--SET @rAreaId = @lId
		SELECT @lNextNumber AS RESULT
END
GO


PRINT N'Update complete.';
GO

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

