

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

PRINT N'Altering Table [sAdmission].[tAdmissionFormReceipt]...';


GO
ALTER TABLE [sAdmission].[tAdmissionFormReceipt]
    ADD [ChequeDate] DATE CONSTRAINT [DF_tAdmissionFormReceipt_ChequeDate] DEFAULT (NULL) NULL;


GO
PRINT N'Altering Table [sAlert].[tEventMaster]...';


GO
ALTER TABLE [sAlert].[tEventMaster] ALTER COLUMN [Fields] NVARCHAR (1000) NULL;


GO
PRINT N'Altering Table [sHrm].[tEmployeeCustomFieldMaster]...';


GO
ALTER TABLE [sHrm].[tEmployeeCustomFieldMaster]
    ADD [CustomFieldMasterId] INT NULL;


GO
PRINT N'Altering Table [sOp].[tGatewayProduct]...';


GO
ALTER TABLE [sOp].[tGatewayProduct]
    ADD [RazorpayCollectNowMID]       NVARCHAR (50) NULL,
        [RazorpayCollectNowKeyID]     NVARCHAR (50) NULL,
        [RazorpayCollectNowSecretKey] NVARCHAR (50) NULL;


GO
PRINT N'Creating Table [sRecruitment].[tVacancyCustomFieldData]...';


GO
CREATE TABLE [sRecruitment].[tVacancyCustomFieldData] (
    [AutoId]               INT            IDENTITY (1, 1) NOT NULL,
    [CandidateId]          BIGINT         NOT NULL,
    [VacancyCustomFieldId] INT            NOT NULL,
    [FieldData]            NVARCHAR (500) NOT NULL,
    [CreatedUserId]        BIGINT         NULL,
    [CreatedDateTime]      DATETIME       NULL,
    [UpdatedUserId]        BIGINT         NULL,
    [UpdatedDateTime]      DATETIME       NULL,
    CONSTRAINT [PK_tEmployeeCustomFieldData] PRIMARY KEY CLUSTERED ([AutoId] ASC) WITH (FILLFACTOR = 85)
);


GO
PRINT N'Creating Table [sRecruitment].[tVacancyCustomFieldMaster]...';


GO
CREATE TABLE [sRecruitment].[tVacancyCustomFieldMaster] (
    [Id]                  INT            NOT NULL,
    [FieldTitle]          NVARCHAR (500) NOT NULL,
    [FieldTypeId]         TINYINT        NOT NULL,
    [FieldList]           NVARCHAR (500) NULL,
    [IsFieldMandatory]    BIT            NOT NULL,
    [FieldGroup]          NVARCHAR (200) NULL,
    [FieldOrder]          SMALLINT       NULL,
    [IsObsolete]          BIT            NULL,
    [CreatedUserId]       BIGINT         NULL,
    [CreatedDateTime]     DATETIME       NULL,
    [UpdatedUserId]       BIGINT         NULL,
    [UpdatedDateTime]     DATETIME       NULL,
    [OrgGroupId]          SMALLINT       NULL,
    [DataId]              INT            NULL,
    [CustomFieldMasterId] INT            NOT NULL,
    CONSTRAINT [PK_tVacancyCustomFieldMaster] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (FILLFACTOR = 85)
);


GO
PRINT N'Creating Table [sSetup].[tCustomFieldMaster]...';


GO
CREATE TABLE [sSetup].[tCustomFieldMaster] (
    [Id]              INT            NOT NULL,
    [FieldGroup]      NVARCHAR (200) NULL,
    [FieldTitle]      NVARCHAR (500) NOT NULL,
    [FieldTypeId]     TINYINT        NOT NULL,
    [FieldList]       NVARCHAR (500) NULL,
    [IsEmployee]      BIT            NOT NULL,
    [IsVacancy]       BIT            NOT NULL,
    [CreatedUserId]   BIGINT         NULL,
    [CreatedDateTime] DATETIME       NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL,
    [OrgGroupId]      SMALLINT       NULL,
    [DataId]          INT            NULL,
    CONSTRAINT [PK_tCustomFieldMaster] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (FILLFACTOR = 85)
);


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
  FROM sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SAD.AdmissionStandardId
	INNER JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	INNER JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	INNER JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	INNER JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	INNER JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	INNER JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	INNER JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	INNER JOIN sCommon.tCountryMaster NM ON NM.Id=SO.NationalityId
	INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	INNER JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	INNER JOIN sStudent.tStudentadditional AD ON AD.StudentId= SA.StudentId
	INNER JOIN sStudent.tStudentBatchStatus SBS ON SBS.AcademicId = SA.AcademicId
	INNER JOIN sStudent.tBatchStatusMaster BSM ON BSM.Id = SBS.BatchStatusId
	INNER JOIN sStudent.tStudentSibling SS ON SS.StudentId= SA.StudentId
	INNER JOIN sStudent.tCollegeDetail CD ON CD.StudentId = SA.StudentId
	INNER JOIN sHostel.tAssignRoom HAR ON HAR.SourceId = SA.StudentId
	INNER JOIN sHostel.tRoomMaster HRM ON HRM.Id = HAR.RoomId
	INNER JOIN sHostel.tBuildingMaster HBM ON HBM.HostelId = HRM.HostelId
	INNER JOIN sHostel.tHostelMaster HHM ON HHM.Id = HRM.HostelId
	INNER JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SA.StudentGroupId
	INNER JOIN sStudent.tStudentOtherGroupMaster SGMO ON SGMO.Id = SA.StudentOtherGroupId
    INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId
	INNER JOIN sCommon.tStatusMaster STM ON STM.Id = SA.RecordStatusId AND STM.StatusTypeId=102
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
	LEFT JOIN sTransport.tBusRouteDestinationMaster BDM2 ON BDM2.Id=AR.DropDestinationId -- Added for mantis : 34483
	LEFT JOIN sTransport.tBusRouteMaster BRM2 ON BRM2.Id=BDM2.BusRouteId -- Added for mantis : 34483
GO
PRINT N'Altering View [sStudent].[vStudentCustomSearch]...';


GO

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

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


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

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

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

    RETURN @lResult 
END
GO
PRINT N'Creating Function [sFee].[fnGetSumByReceiptBookWise]...';


GO

Create FUNCTION [sFee].[fnGetSumByReceiptBookWise]
(
    @rAcademicId Bigint,
    @rBatchId INT,
    @rReceiptBookId INT
  --  @rSourceId INT
)
RETURNS DECIMAL(12, 2)
AS
BEGIN
    DECLARE @SumAmount DECIMAL(12, 2);
    
    SELECT @SumAmount = SUM(ISNULL(PDP.Amount, 0))
    FROM sFee.tPostDatePayment PDP

    where BatchId = @rBatchId
      AND ReceiptBookId = @rReceiptBookId
      AND SourceId = @rAcademicId
	  AND SourceTypeId = 2001

	  

    RETURN @SumAmount;
END;
GO
PRINT N'Creating Function [sHrm].[fEmployeeHolidayDatesList]...';


GO
CREATE FUNCTION [sHrm].[fEmployeeHolidayDatesList](
    @rEmployeeId bigint,
    @rDepartmentId int, 
    @rForYear int,
    @rForMonth int,
    @rBatchId int,
    @rOrgId int
)
RETURNS VARCHAR(MAX)
AS 
BEGIN
    DECLARE @FirstDate DATE;
    DECLARE @LastDate DATE;
    DECLARE @HolidayDays VARCHAR(MAX) = '';

    SET @FirstDate = CONVERT(DATE, CAST(@rForYear AS VARCHAR(4)) + '-' + RIGHT('0' + CAST(@rForMonth AS VARCHAR(2)), 2) + '-01');
    SET @LastDate = DATEADD(DAY, -1, DATEADD(MONTH, 1, @FirstDate));

    ;WITH HolidayEvents AS (
        SELECT ES.FromDate, ES.ToDate
        FROM sActivity.tEventSchedule ES
        INNER JOIN sActivity.tEventAssign EA ON EA.EventScheduleId = ES.Id AND EA.SourceTypeId IN (2004, 95)
        LEFT JOIN sHrm.vEmployeeCommunication EC ON EC.EmployeeId = EA.SourceId AND (EC.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
        WHERE ES.BatchId = @rBatchId
          AND ((SourceId = @rDepartmentId) OR (@rDepartmentId = 0))
          AND MONTH(ES.FromDate) = @rForMonth AND YEAR(ES.FromDate) = @rForYear
          AND MONTH(ES.ToDate) = @rForMonth AND YEAR(ES.ToDate) = @rForYear
          AND ES.IsHoliday = 1
    ),
    DateRange AS (
        SELECT HE.FromDate AS HolidayDate, HE.ToDate
        FROM HolidayEvents HE
        UNION ALL
        SELECT DATEADD(DAY, 1, DR.HolidayDate), DR.ToDate
        FROM DateRange DR
        WHERE DATEADD(DAY, 1, DR.HolidayDate) <= DR.ToDate
    )
    SELECT @HolidayDays = STUFF((
        SELECT DISTINCT ',' + CAST(DAY(HolidayDate) AS VARCHAR)
        FROM DateRange
        WHERE HolidayDate BETWEEN @FirstDate AND @LastDate
        FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '');

    RETURN @HolidayDays;
END;
GO
PRINT N'Creating Function [sProcurement].[fnGetStockDepositeDetail]...';


GO

CREATE FUNCTION [sProcurement].[fnGetStockDepositeDetail](@rDepositHeadId int,@rAcademicId bigint, @rFromDate date,@rToDate date)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS 
BEGIN	

	DECLARE @lStockItemName nvarchar(max)=''

	SELECT @lStockItemName = STUFF((SELECT ',' + (ISNULL(SIM.Title,''))
							 FROM sIp.tStoreLocationMaster SLM
								INNER JOIN sProcurement.tStockIssue SI ON SI.FromStoreLocationId = SLM.Id --AND SI.IssueToSourceId =  @rAcademicId 
								INNER JOIN sProcurement.tStockIssueDetail SD ON SD.StockIssueId = SI.Id
								INNER JOIN sStudent.tAcademic A ON A.Id = SI.IssueToSourceId
								INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SD.StockItemId

								WHERE 
								A.Id = @rAcademicId 
								AND SLM.DepositHeadId = @rDepositHeadId
								AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
								AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
								FOR XML PATH(''), TYPE
								).value('.', 'NVARCHAR(MAX)') 
							,1,1,'')
 
	RETURN ISNULL(@lStockItemName,'')
END
GO
PRINT N'Creating Function [sStudent].[fGetDashboardStudentCount]...';


GO
CREATE FUNCTION [sStudent].[fGetDashboardStudentCount](@rStatusId INT,@rCommonOrgGroupBatchId INT,@rType nvarchar(100),@rOrgId int)
RETURNS [int] WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @StudentCount INT

IF(@rType= 'OrgGroupwiseStudentCount')
BEGIN
	SELECT @StudentCount= (SELECT COUNT(SM.ID)
			 FROM sStudent.tStudentMaster SM
				 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID 
				 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 COGBM.Id=@rCommonOrgGroupBatchId AND (SM.StatusId=@rStatusId OR @rStatusId=0)
				  AND BM.IsInContext = 1)
	
END

IF(@rType= 'OrgwiseStudentCount')
BEGIN
	SELECT @StudentCount= (SELECT COUNT(SM.ID) FROM sStudent.tStudentMaster SM
				 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID 
				 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					WHERE COGBM.Id=@rCommonOrgGroupBatchId AND (SM.StatusId=@rStatusId OR @rStatusId=0) AND OM.Id = @rOrgId AND BM.IsInContext = 1)
END

IF(@rType= 'OrgSubGroupwiseStudentCount')
BEGIN
	SELECT @StudentCount = (SELECT COUNT(SM.ID) FROM sStudent.tStudentMaster SM
				 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID 
				 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			 WHERE COGBM.Id=@rCommonOrgGroupBatchId AND (SM.StatusId=@rStatusId OR @rStatusId=0) AND ((OM.OrgSubGroupId = @rOrgId))			 
				  AND BM.IsInContext = 1)
END

IF(@rType= 'DeptwiseStudentCount')
BEGIN
	SELECT @StudentCount = (SELECT COUNT(SM.ID) FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDepartmentMaster DM on DM.Id=CM.DepartmentId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
	WHERE COGBM.Id=@rCommonOrgGroupBatchId AND (SM.StatusId=@rStatusId OR @rStatusId=0) AND ((DM.Id = @rOrgId)) AND BM.IsInContext = 1)
END

IF(@rType= 'ClasswiseStudentCount')
BEGIN
	SELECT @StudentCount = (SELECT COUNT(SM.ID) FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDepartmentMaster DM on DM.Id=CM.DepartmentId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
	WHERE COGBM.Id=@rCommonOrgGroupBatchId AND (SM.StatusId=@rStatusId OR @rStatusId=0) AND ((CM.Id = @rOrgId)) AND BM.IsInContext = 1)
END
	RETURN  @StudentCount 
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionFormReceiptAdd]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionFormReceiptAdd]
	
	@rOrgId smallint,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rReceiptDate date,
	@rReceiptAmount decimal(12,2),
	@rPayTypeId smallint,
	@rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	DECLARE @lNextNumber BIGINT=0
	DECLARE @lReceiptNumber int=0
	
	IF NOT EXISTS(SELECT 1 FROM sAdmission.tAdmissionFormReceipt WHERE SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId)
	BEGIN
	
	--SELECT @lReceiptNumber = COUNT(ISNULL(Id,0)) + 1 FROM sAdmission.tAdmissionFormReceipt WHERE BatchId=@rBatchId
	SELECT @lReceiptNumber = MAX(ReceiptNumber) + 1 FROM sAdmission.tAdmissionFormReceipt WHERE BatchId=@rBatchId
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionFormReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAdmission.tAdmissionFormReceipt
		(
			Id,
			SourceTypeId,
			SourceId,
			ReceiptNumber,
			ReceiptDate,
			ReceiptAmount,
			PayTypeId,
			ChequeNo,
			BankName,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
			@lReceiptNumber,
			sCommon.fGetDate(),
			@rReceiptAmount,
			@rPayTypeId,
			NULL,
			NULL,
			@rBatchId,
			0,
			sCommon.fGetDate(),
			0,
			sCommon.fGetDate()
		)

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


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


GO
 
ALTER PROCEDURE [sCommon].[pOrgGroupSetupRemove]
	 
	 @rOrgGroupId smallint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
	
	IF EXISTS(SELECT TOP 1 1 FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
	BEGIN
	SELECT -101 AS Result
	RETURN
	END
	
	
	BEGIN TRANSACTION
	 
	EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    




DELETE FROM sAccounting.tAccountingYearMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tAccountMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerGroupMaster  WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransaction WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sActivity.tActivityTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tClubMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tImmunizationChart WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryReferenceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAttendance.tAbsentReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingConductMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingProgressMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingRemarkMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAreaMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tBirthPlaceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCountryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tDistrictMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHobbyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tMotherTongueMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tNationalityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tOccupationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tPreviousSchoolMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tReligionMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tStateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tSurnameMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBehaviourTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlogComment WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogFavorite WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogScope WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircular WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCircularScope WHERE CAST(LEFT(CircularId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularView WHERE CAST(LEFT(CircularId, 4) AS BIGINT) =@rOrgGroupId
DELETE FROM sCommunication.tNews WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tNewsComment WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tNewsScope WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPhotoCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPoll WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPollAnswer WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollMember WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollResult WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQuery WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryAssignedTo WHERE CAST(LEFT(QueryCategoryId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryComment WHERE CAST(LEFT(QueryId, 4) AS BIGINT) =  @rOrgGroupId
DELETE FROM sEExam.tDataBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataSubjectMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionOption WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionParagraph WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateQuestion WHERE CAST(LEFT(TestTemplateId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tStockUomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sGSEB.tActivityGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityIndicatorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tRoomCategoryMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tRoomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tQualificationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tItemMainGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tItemSubGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemCategoryMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tStoreLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAgeGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAuthorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLanguageMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLocationMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookPublisherMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSupplierMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookTagMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tLibraryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tEsiProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tEsiSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayElement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcess WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessElement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessEmployee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetupDependent WHERE CAST(LEFT(PaySetupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcessCharge WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tProfessionalTaxRange WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sProcurement.tVendorCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrganizationTask WHERE CAST(LEFT(OrgGroupId, 4) AS SMALLINT) = @rOrgGroupId
DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRole WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

 
DELETE FROM sStudent.tAdmissionCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTax.tTaxGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteDestinationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tFamiliyCastMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sScholarship.tScholarshipTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgMainGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgSubGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tVisitorGatePass WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollYearMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sActivity.tEventTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRoleDashlet WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId


DELETE FROM sCommon.tFrequencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tRangeDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tRangeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFinanceCommon.tCurrencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierDispatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierReceive WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tBuildingMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tChangeRoom WHERE CAST(LEFT(RoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelAdmission WHERE CAST(LEFT(Hosteld, 4) AS INT) = @rOrgGroupId

DELETE FROM sLibrary.tLibraryAttendance WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineReceive WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tFuelLogs WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tFuelTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleDocumentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTransport.tVehicleDocuments WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenance WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenanceDetail WHERE CAST(LEFT(VehicleMaintenanceId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleTypeMaster WHERE OrgGroupId = @rOrgGroupId

--DELETE FROM sTimetable.tAssignSchoolRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tDivisionTimeOff WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolBuildingMaster WHERE  OrgGroupId = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomMaster WHERE  CAST(LEFT(SchoolBuildingId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tTeacherTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

DELETE FROM sCommunication.tEbook WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tEbookScope WHERE  CAST(LEFT(EbookId, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sActivity.tClubTypeMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tHouseGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryStatusMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroup WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroupMember WHERE  CAST(LEFT(CustomGroupId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sTally.tFeeLedgerMapping WHERE CAST(LEFT(FeeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptBookCompanyMapping WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptPosting WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoom WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoomTimeOff WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tSchoolBuilding WHERE  OrgGroupId = @rOrgGroupId
 DELETE FROM sCommon.tCastCategoryMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tTransportMaster WHERE  OrgGroupId = @rOrgGroupId

DELETE FROM sAlert.tOtherGroupDetail WHERE  CAST(LEFT(OtherGroupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tOtherGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAdmissionQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tCollectionGroupMaster WHERE  CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId

DELETE FROM sHrm.tWorkAreaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItem WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItemSize WHERE  CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sIp.tUniformStock WHERE  CAST(LEFT(UniformSizeId, 4) AS INT) = @rOrgGroupId

DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tReportOrgGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayConfiguration WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sTimetable.tDivisionClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tSubjectClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tTimeTableDetail WHERE CAST(LEFT(TimetableId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeDetail WHERE CAST(LEFT(ExemptionTypeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSecurity.tRoleModulePermission WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId

/* -- Date : 13/06/2016 -- */
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenIssueDetail WHERE CAST(LEFT(CanteenIssueId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tFoodItemMaster WHERE CAST(LEFT(CanteenId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFrontOffice.tLostFoundRegister WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sHostel.tAssetTypeMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tAssignRoomAsset WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tRoomAssetMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tLeaveReasonMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sSetup.tOrgGroupSetting WHERE OrgGroupId = @rOrgGroupId
 
DELETE FROM sStudent.tSUIdConfig WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTimetable.tAssignDivision WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

/* -- Date : 12/08/2016 -- */
DELETE FROM sHostel.tHostelDepositAdd WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositAdjustment WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositRefund WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSystem.tExceptionLog WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 17/09/2016 -- */
DELETE FROM sCommon.tReportClient WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tTempCircularScope WHERE CAST(LEFT(SourceID, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sErp.tCustomerMaster WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 05/10/2016 -- */
DELETE FROM sHostel.tAttendanceRegister WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateCommunications WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateImages WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidatePreviousEmployment WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateQualification WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateVacancyCriteriaScore WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tInterviewCriteria WHERE CAST(LEFT(VacancyId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tRecruitmentStatusLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tVacancy WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 24/11/2016 -- */

DELETE FROM siTax.tAssessmentYear WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16 WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16Detail WHERE CAST(LEFT(Form16Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxChallan WHERE CAST(LEFT(AssesmentYearId, 4) AS INT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSlab WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSubGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tPlacementCompanyMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAppraisal.tConductTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sErp.tCustomerActivationLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicyDetail WHERE  CAST(LEFT(IpPolicyId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tTimePolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserPolicy WHERE  CAST(LEFT(TimePolicyId, 4) AS int) = @rOrgGroupId


DELETE FROM sAppraisal.tKPATemplateDetail WHERE CAST(LEFT(KPATemplateId, 4) AS int) = @rOrgGroupId
DELETE FROM sAppraisal.tKPATemplateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayProduct WHERE CAST(LEFT(GatewayConfigurationId, 4) AS int) = @rOrgGroupId
DELETE FROM sOp.tGatewayProductReceiptBookMapping WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tSstockIssueTypeMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sFee.tFeeDepositExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelAttendanceTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseSubTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelGatePassReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformOrderItem WHERE CAST(LEFT(StockItemId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturn WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturnBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentOtherGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentUIdMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAssetManagement.tAssetCheck WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAssetManagement.tAssetInchargeUser WHERE CAST(LEFT(AssetId, 4) AS int) = @rOrgGroupId
DELETE FROM sCanteen.tBreakTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tDailyMenu WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId

DELETE FROM sAlert.tAdVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeAccountMapping WHERE CAST(LEFT(ChargeId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tChargeAccountPosting WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountMapping WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountPosting WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId

DELETE FROM sCommunication.tFeedback WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeDetail WHERE CAST(LEFT(FeedbackAnswerTypeId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAssign WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackFor WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackQuestionResponse WHERE CAST(LEFT(FeedbackResponseId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackResponse WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplate WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplateQuestion WHERE CAST(LEFT(FeedbackTemplateId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tStockReset WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockResetBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tBackupLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSystem.tPortalSync WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sAccounting.tBudget WHERE CAST(LEFT(LedgerId, 4) AS int) = @rOrgGroupId
DELETE FROM sAccounting.tTransactionApprove WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionApproveDetail WHERE CAST(LEFT(LedgerId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSetup.tScreenMandatoryFeild WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sCommunication.tPhotoCategoryScope WHERE CAST(LEFT(PhotoCategoryId, 4) AS int) = @rOrgGroupId
DELETE FROM sTool.tTestCase WHERE CAST(LEFT(Id, 4) AS int) = @rOrgGroupId

DELETE FROM sLibrary.tMagazineTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrgGroupMobileAppDetail WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sLibrary.tBookCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookSubCategoryMaster WHERE OrgGroupId = @rOrgGroupId


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

	-- special case will come orgwise and orggroupwise

DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgGroupId 
DELETE FROM sConfig.tConfigurationSetup WHERE SourceTypeId = 2010 AND SourceId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupBatchMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupMaster WHERE Id=@rOrgGroupId


DELETE FROM sCanteen.tGuestRequest WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tLimitLog WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sProcurement.tOtherStockBatch WHERE CAST(LEFT(StockBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockIssue WHERE CAST(LEFT(StoreLocationId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockIssueBatch WHERE CAST(LEFT(OtherStockBatchId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sVts.tvtsOrgGroupMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sLibrary.tBookGroup1Master WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookGroup2Master WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sHostel.tHostelEventAssign WHERE CAST(LEFT(HostelEventScheduleId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tHostelEventAttendance WHERE CAST(LEFT(HostelEventScheduleId, 4) AS int) = @rOrgGroupId

DELETE FROM sHostel.tHostelEventSchedule WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tHostelEventTypeMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId

DELETE FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @rOrgGroupId



DELETE FROM sCommon.tOrgGroupDepartmentMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sFee.tFeeExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserOrgGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupEIS WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteTripLog WHERE CAST(LEFT(BusRouteId, 4) AS int) = @rOrgGroupId
DELETE FROM sTransport.tBusRouteTripTemplate WHERE CAST(LEFT(BusRouteId, 4) AS int) = @rOrgGroupId


DELETE FROM sCommunication.tCircularTypeAssignedTo WHERE CAST(LEFT(CircularTypeId, 4) AS int) = @rOrgGroupId
DELETE FROM sErp.tSupportTicket WHERE OrgGroupId= @rOrgGroupId
DELETE FROM siTax.tTaxPlanning WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sStudent.tStudentCustomFieldMaster WHERE OrgGroupId= @rOrgGroupId

DELETE FROM sErp.tCustomerPlugInLog WHERE OrgGroupId= @rOrgGroupId

DELETE FROM sErp.tScreenFunctionalityTraining WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommon.tPhysicalDisabilityCategoryMaster WHERE OrgGroupId= @rOrgGroupId

DELETE FROM siTax.tForm16SubDetail WHERE CAST(LEFT(Form16Id, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSecurity.tAssignSubRole WHERE CAST(LEFT(RoleId, 4) AS int) = @rOrgGroupId

DELETE FROM sCommunication.tChatGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tChatGroupScope WHERE CAST(LEFT(ChatGroupId, 4) AS int) = @rOrgGroupId


DELETE FROM sAcademic.tOnlineMeetingAccount WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommunication.teContentTypeMaster WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommunication.teContent WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sPayroll.tPayElementHistory WHERE CAST(LEFT([PayrollId], 4) AS int) = @rOrgGroupId

DELETE FROM [sHrm].[tEmployeeCustomFieldMaster] WHERE OrgGroupId= @rOrgGroupId

DELETE FROM [sCommunication].[tDailyThoughtMaster] WHERE OrgGroupId= @rOrgGroupId
DELETE FROM [sCommunication].[tDailyThoughtSubjectMaster] WHERE OrgGroupId= @rOrgGroupId
DELETE FROM [sCommunication].[tDailyThoughtTemp] WHERE OrgGroupId= @rOrgGroupId

DELETE FROM [sErp].[tCustomerMessage] WHERE OrgGroupId= @rOrgGroupId

DELETE FROM[sCommunication].[tPlaylistMaster] WHERE OrgGroupId= @rOrgGroupId
DELETE FROM [sCommunication].[tPlaylistDetails] WHERE CAST(LEFT(PlaylistId, 4) AS int) =  @rOrgGroupId

DELETE FROM sRecruitment.tRecruitmentCriteriaDocument WHERE CAST(LEFT([VacancyId], 4) AS bigint) =  @rOrgGroupId
DELETE FROM sRecruitment.tRecruitmentRecruiterDocument WHERE CAST(LEFT([RecruitmentId], 4) AS bigint) =  @rOrgGroupId
DELETE FROM [sCommon].[tPublishDocumentMaster] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM [sFee].[tApplicablePayType] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateFamilyDetails WHERE OrgGroupId = @rOrgGroupId

DELETE FROM[sCommunication].[tQueryCategoryScope] WHERE CAST(LEFT([QueryCategoryId], 4) AS int) = @rOrgGroupId
DELETE FROM [sTransport].[tVehicleLog] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sIp.tStockChargeMapping  WHERE CAST(LEFT([ChargeId], 4) AS int) = @rOrgGroupId

DELETE FROM [sCommon].[tFamiliySubCasteMaster] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM [sSetup].[tOnlineFormSetup] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM [sLibrary].[tNewspaperMaster] WHERE CAST(LEFT([Id], 4) AS int) = @rOrgGroupId

DELETE FROM [sHrm].[tCommitteeMaster] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM [sHrm].[tHouseMaster] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM [sHrm].[tClubMaster] WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHrm.tAssignClub WHERE CAST(LEFT([ClubId], 4) AS int) = @rOrgGroupId
DELETE FROM sHrm.tAssignHouse WHERE CAST(LEFT([HouseId], 4) AS int) = @rOrgGroupId
DELETE FROM sHrm.tAssignCommittee WHERE CAST(LEFT([CommitteeId], 4) AS int) = @rOrgGroupId
DELETE FROM sIp.tStockDefectiveItemMaster WHERE OrgGroupId = @rOrgGroupId
	
DELETE FROM sCommon.tTribeMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM[sCommunication].[tMultiPhotoCategoryMaster] WHERE [OrgGroupId] = @rOrgGroupId
DELETE FROMsCommunication.tMultiPhotoCategoryScope WHERE CAST(LEFT([MultiPhotoCategoryId], 4) AS bigint) = @rOrgGroupId


DELETE FROM [sAssetManagement].[tAssetCustomFieldMaster] WHERE [OrgGroupId] = @rOrgGroupId
DELETE FROM sAssetManagement.tAssetCustomFieldData WHERE CAST(LEFT([AssetCustomFieldId], 4) AS int) = @rOrgGroupId

--remove from VitorTypeMaster
DELETE FROM [sFrontOffice].[tVisitorTypeMaster] WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sProcurement.tStockKitMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sSetup.tCustomFieldMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tVacancyCustomFieldMaster WHERE OrgGroupId = @rOrgGroupId

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


GO
ALTER PROCEDURE [sOp].[pGatewayProductAdd]
	 
    @rId int,
	@rGatewayConfigurationId int,
	@rTitle nvarchar(150),
	@rGatewayURL nvarchar(1000),
	@rServerPort nvarchar(50),
	@rLoginId nvarchar(50),
	@rLoginPassword nvarchar(50),
	@rProductId nvarchar(100),
	@rOrgGroupId int,
		
	@rCCAvenueMerchantID nvarchar(50)='',
	@rCCAvenueAccessCode nvarchar(100)='',
	@rCCAvenueWorkingKey nvarchar(100)='',
	@rCCAvenueWhitelistURL nvarchar(500)='',
	@rCCAvenueSubAccountId nvarchar(100)='',
		
	@rAtomReqHashKey nvarchar(100)='',
	@rAtomRespHashKey nvarchar(100)='',
		
	@rPaytmMID nvarchar(50)='',
	@rPaytmMerchantKey nvarchar(50)='',
	@rPaytmChannelId nvarchar(20)='',
	@rPaytmIndustryTypeId nvarchar(20)='',
	@rPaytmWebsite nvarchar(20)='',
	@rPaytmStatusCheckURL nvarchar(500)='',
		
	@rPayUMoneyMERCHANTID nvarchar(20)='',
	@rPayUMoneyMERCHANTKEY nvarchar(20)='',
	@rPayUMoneySALT nvarchar(20)='',
	@rPayUMoneyHASHSEQUENCE nvarchar(200)='',
	@rPayUMoneyAUTHHEADER nvarchar(50)='',
		
	@rBillDeskMerchantID nvarchar(50)='',
	@rBillDeskChecksumKey nvarchar(50)='',
	@rBillDeskSecurityID nvarchar(50)='',
	@rBillDeskUniqueIdentifier nvarchar(50)='',
		
	@rEazypayMerchantId nvarchar(50)='',
	@rEazypayAESKey nvarchar(50)='',
		
	@rAxisMerchantId nvarchar(50)='',
	@rAxisAPIKey nvarchar(50)='',
	@rAxisResponseKey nvarchar(50)='',
		
	@rRazorpayMID nvarchar(50)='',
	@rRazorpayKeyID nvarchar(50)='',
	@rRazorpaySecretKey nvarchar(50)='',
	@rRazorpaySubMerchantId nvarchar(50)='',
	
	@rBBPSCharge nvarchar(500) = '',
	@rBBPSGST decimal(12,2) = 0,
		
	@rGrayQuestClientId nvarchar(50)='',
	@rGrayQuestSecretKey nvarchar(50)='',
	@rGrayQuestApiKey nvarchar(50)='',

	@rEasebuzzKey nvarchar(50)='',
	@rEasebuzzSalt nvarchar(50)='',
	@rEasebuzzIsLiveEnvironment bit = null,
	@rEasebuzzIsEnableiFrame bit = null,
	@rEasebuzzSubMerchantId nvarchar(50)='',

	@rHesabeAccessCode nvarchar(50)='',
	@rHesabeMerchantCode nvarchar(50)='',
	@rHesabeMerchantKey nvarchar(50) = '',
	@rHesabeMerchantIV nvarchar(50)='',
	@rHesabeVersion nvarchar(10) = '2.0',
	@rHesabeIsLiveEnvironment bit = null,

	--For Mantis 0034589 by Foram
	@rRazorpayCollectNowMID	nvarchar(50) = '',
	@rRazorpayCollectNowKeyID nvarchar(50) = '',
	@rRazorpayCollectNowSecretKey nvarchar(50) = ''
	--For Mantis 0034589 by Foram
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

	IF(@rId = 0)	
	BEGIN
		IF EXISTS(SELECT Id FROM [sOp].[tGatewayProduct] WHERE GatewayConfigurationId=@rGatewayConfigurationId AND Title=@rTitle AND ProductId = @rProductId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		IF  EXISTS(SELECT Id FROM [sOp].[tGatewayProduct] WHERE GatewayConfigurationId=@rGatewayConfigurationId AND Title=@rTitle AND ProductId = @rProductId AND Id<>@rId)
		BEGIN
			SELECT -101 AS Result
			RETURN
		END
	END	

	BEGIN TRANSACTION	
	DECLARE @lNextNumber INT     
	IF(@rId = 0)	
	BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sOp.tGatewayProduct', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sOp].[tGatewayProduct]
		(
			[Id],
			[GatewayConfigurationId],
			[Title],
			[GatewayURL],
			[ServerPort],
			[LoginId],
			[LoginPassword],
			[ProductId],
			[CCAvenueMerchantID],
			[CCAvenueAccessCode],
			[CCAvenueWorkingKey],
			[CCAvenueWhitelistURL],
			[CCAvenueSubAccountId],
			[AtomReqHashKey],
			[AtomRespHashKey],
			[PaytmMID],
			[PaytmMerchantKey],
			[PaytmChannelId],
			[PaytmIndustryTypeId],
			[PaytmWebsite],
			[PaytmStatusCheckURL],
			[PayUMoneyMERCHANTID],
			[PayUMoneyMERCHANTKEY],
			[PayUMoneySALT],
			[PayUMoneyHASHSEQUENCE],
			[PayUMoneyAUTHHEADER],
			[BillDeskMerchantID],
			[BillDeskChecksumKey],
			[BillDeskSecurityID],
			[BillDeskUniqueIdentifier],
			[EazypayMerchantId],
			[EazypayAESKey],
			[AxisMerchantId],
			[AxisAPIKey],
			[AxisResponseKey],
			[RazorpayMID],
			[RazorpayKeyID],
			[RazorpaySecretKey],
			[BBPSCharges],
			[BBPSGST],
			[GrayQuestClientId],
			[GrayQuestSecretKey],
			[GrayQuestAPIKey],
			[EasebuzzKey],
			[EasebuzzSalt],
			[EasebuzzIsLiveEnvironment],
			[EasebuzzIsEnableiFrame],
			[EasebuzzSubMerchantId],
			HesabeAccessCode,
			HesabeMerchantKey,
			HesabeMerchantIV,
			HesabeMerchantCode,
			HesabeVersion,
			HesabeIsLiveEnvironment,
			RazorpaySubMerchantId,
			--For Mantis 0034589 by Foram Start
			RazorpayCollectNowMID,
			RazorpayCollectNowKeyID,
			RazorpayCollectNowSecretKey
			--For Mantis 0034589 by Foram End
		)
		VALUES
		(
			@lNextNumber,
			@rGatewayConfigurationId,
			@rTitle,
			@rGatewayURL,
			@rServerPort,
			@rLoginId,
			@rLoginPassword,
			@rProductId,
			@rCCAvenueMerchantID,
			@rCCAvenueAccessCode,
			@rCCAvenueWorkingKey,
			@rCCAvenueWhitelistURL,
			@rCCAvenueSubAccountId,
			@rAtomReqHashKey,
			@rAtomRespHashKey,
			@rPaytmMID,
			@rPaytmMerchantKey,
			@rPaytmChannelId,
			@rPaytmIndustryTypeId,
			@rPaytmWebsite,
			@rPaytmStatusCheckURL,
			@rPayUMoneyMERCHANTID,
			@rPayUMoneyMERCHANTKEY,
			@rPayUMoneySALT,
			@rPayUMoneyHASHSEQUENCE,
			@rPayUMoneyAUTHHEADER,
			@rBillDeskMerchantID,
			@rBillDeskChecksumKey,
			@rBillDeskSecurityID,
			@rBillDeskUniqueIdentifier,
			@rEazypayMerchantId,
			@rEazypayAESKey,
			@rAxisMerchantId,
			@rAxisAPIKey,
			@rAxisResponseKey,
			@rRazorpayMID,
			@rRazorpayKeyID,
			@rRazorpaySecretKey,
			@rBBPSCharge,
			@rBBPSGST,
			@rGrayQuestClientId,
			@rGrayQuestSecretKey,
			@rGrayQuestApiKey,
			@rEasebuzzKey,
			@rEasebuzzSalt,
			@rEasebuzzIsLiveEnvironment,
			@rEasebuzzIsEnableiFrame,
			@rEasebuzzSubMerchantId,
			@rHesabeAccessCode,
			@rHesabeMerchantKey,
			@rHesabeMerchantIV,
			@rHesabeMerchantCode,
			@rHesabeVersion,
			@rHesabeIsLiveEnvironment,
			@rRazorpaySubMerchantId,
			--For Mantis 0034589 by Foram Start
			@rRazorpayCollectNowMID,
			@rRazorpayCollectNowKeyID,
			@rRazorpayCollectNowSecretKey
			--For Mantis 0034589 by Foram End
		)
		    SELECT 1 AS Result
	END	 
ELSE
	 BEGIN
		SET @lNextNumber = @rId
	    UPDATE  [sOp].[tGatewayProduct]
	    SET
			[GatewayConfigurationId]=@rGatewayConfigurationId,
			[Title]=@rTitle,
			[GatewayURL]=@rGatewayURL,
			[ServerPort]=@rServerPort,
			[LoginId]=@rLoginId,
			[LoginPassword]=@rLoginPassword,
			[ProductId]=@rProductId,
			[CCAvenueMerchantID]=@rCCAvenueMerchantID,
			[CCAvenueAccessCode]=@rCCAvenueAccessCode,
			[CCAvenueWorkingKey]=@rCCAvenueWorkingKey,
			[CCAvenueWhitelistURL]=@rCCAvenueWhitelistURL,
			[CCAvenueSubAccountId]=@rCCAvenueSubAccountId,
			[AtomReqHashKey]=@rAtomReqHashKey,
			[AtomRespHashKey]=@rAtomRespHashKey,
			[PaytmMID]=@rPaytmMID,
			[PaytmMerchantKey]=@rPaytmMerchantKey,
			[PaytmChannelId]=@rPaytmChannelId,
			[PaytmIndustryTypeId]=@rPaytmIndustryTypeId,
			[PaytmWebsite]=@rPaytmWebsite,
			[PaytmStatusCheckURL]=@rPaytmStatusCheckURL,
			[PayUMoneyMERCHANTID]=@rPayUMoneyMERCHANTID,
			[PayUMoneyMERCHANTKEY]=@rPayUMoneyMERCHANTKEY,
			[PayUMoneySALT]=@rPayUMoneySALT,
			[PayUMoneyHASHSEQUENCE]=@rPayUMoneyHASHSEQUENCE,
			[PayUMoneyAUTHHEADER]=@rPayUMoneyAUTHHEADER,
			[BillDeskMerchantID]=@rBillDeskMerchantID,
			[BillDeskChecksumKey]=@rBillDeskChecksumKey,
			[BillDeskSecurityID]=@rBillDeskSecurityID,
			[BillDeskUniqueIdentifier]=@rBillDeskUniqueIdentifier,
			[EazypayMerchantId]=@rEazypayMerchantId,
			[EazypayAESKey]=@rEazypayAESKey,
			[AxisMerchantId]=@rAxisMerchantId,
			[AxisAPIKey]=@rAxisAPIKey,
			[AxisResponseKey]=@rAxisResponseKey,
			[RazorpayMID]=@rRazorpayMID,
			[RazorpayKeyID]=@rRazorpayKeyID,
			[RazorpaySecretKey]=@rRazorpaySecretKey,
			[BBPSCharges] = @rBBPSCharge,
			[BBPSGST] = @rBBPSGST,
			GrayQuestClientId = @rGrayQuestClientId,
			GrayQuestSecretKey = @rGrayQuestSecretKey,
			GrayQuestAPIKey = @rGrayQuestApiKey,
			[EasebuzzKey] = @rEasebuzzKey,
			[EasebuzzSalt] = @rEasebuzzSalt,
			[EasebuzzIsLiveEnvironment] = @rEasebuzzIsLiveEnvironment,
			[EasebuzzIsEnableiFrame] = @rEasebuzzIsEnableiFrame,
			[EasebuzzSubMerchantId] = @rEasebuzzSubMerchantId,
			HesabeAccessCode = @rHesabeAccessCode,
			HesabeMerchantKey = @rHesabeMerchantKey,
			HesabeMerchantIV = @rHesabeMerchantIV,
			HesabeMerchantCode = @rHesabeMerchantCode,
			HesabeVersion = @rHesabeVersion,
			HesabeIsLiveEnvironment = @rHesabeIsLiveEnvironment,
			RazorpaySubMerchantId = @rRazorpaySubMerchantId,
			--For Mantis 0034589 by Foram Start
			RazorpayCollectNowMID = @rRazorpayCollectNowMID,
			RazorpayCollectNowKeyID = @rRazorpayCollectNowKeyID,
			RazorpayCollectNowSecretKey	= @rRazorpayCollectNowSecretKey
			--For Mantis 0034589 by Foram End
	    WHERE Id = @rId
	    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 [sOp].[pGatewayProductGet]...';


GO
ALTER PROCEDURE [sOp].[pGatewayProductGet]

	 @rId int,
	 @rGatewayConfigurationId int,
	 @rTitle nvarchar(150),
	 @rOrgGroupId int
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			GP.Id,
			GP.GatewayConfigurationId,
			PGM.Title AS PaymentGatewayName,
			GP.Title AS GatewayProductName,
			ISNULL(GP.GatewayURL,'') AS GatewayURL,
			ISNULL(GP.ServerPort,'') AS ServerPort,
			ISNULL(GP.LoginId,'') AS LoginId,
			ISNULL(GP.LoginPassword,'') AS LoginPassword,
			ISNULL(GP.ProductId,'') AS ProductId,
			
			ISNULL(GP.CCAvenueMerchantID,'') AS CCAvenueMerchantID,
			ISNULL(GP.CCAvenueAccessCode,'') AS CCAvenueAccessCode,
			ISNULL(GP.CCAvenueWorkingKey,'') AS CCAvenueWorkingKey,
			ISNULL(GP.CCAvenueWhitelistURL,'') AS CCAvenueWhitelistURL,
			ISNULL(GP.CCAvenueSubAccountId,'') AS CCAvenueSubAccountId,
			
			ISNULL(GP.AtomReqHashKey,'') AS AtomReqHashKey,
			ISNULL(GP.AtomRespHashKey,'') AS AtomRespHashKey,
			ISNULL(GP.PaytmMID,'') AS PaytmMID,
			ISNULL(GP.PaytmMerchantKey,'') AS PaytmMerchantKey,
			ISNULL(GP.PaytmChannelId,'') AS PaytmChannelId,
			ISNULL(GP.PaytmIndustryTypeId,'') AS PaytmIndustryTypeId,
			ISNULL(GP.PaytmWebsite,'') AS PaytmWebsite,
			ISNULL(GP.PaytmStatusCheckURL,'') AS PaytmStatusCheckURL,
			ISNULL(GP.PayUMoneyMERCHANTID,'') AS PayUMoneyMERCHANTID,
			ISNULL(GP.PayUMoneyMERCHANTKEY,'') AS PayUMoneyMERCHANTKEY,
			ISNULL(GP.PayUMoneySALT,'') AS PayUMoneySALT,
			ISNULL(GP.PayUMoneyHASHSEQUENCE,'') AS PayUMoneyHASHSEQUENCE,
			ISNULL(GP.PayUMoneyAUTHHEADER,'') AS PayUMoneyAUTHHEADER,
			
			ISNULL(GP.BillDeskMerchantID,'') AS BillDeskMerchantID,
			ISNULL(GP.BillDeskChecksumKey,'') AS BillDeskChecksumKey,
			ISNULL(GP.BillDeskSecurityID,'') AS BillDeskSecurityID,
			ISNULL(GP.BillDeskUniqueIdentifier,'') AS BillDeskUniqueIdentifier,
			ISNULL(GP.EazypayMerchantId,'') AS EazypayMerchantId,
			ISNULL(GP.EazypayAESKey,'') AS EazypayAESKey,

			ISNULL(GP.AxisMerchantId,'') AS AxisMerchantId,
			ISNULL(GP.AxisAPIKey,'') AS AxisAPIKey,
			ISNULL(GP.AxisResponseKey,'') AS AxisResponseKey,

			ISNULL(GP.RazorpayMID,'') AS RazorpayMID,
			ISNULL(GP.RazorpayKeyID,'') AS RazorpayKeyID,
			ISNULL(GP.RazorpaySecretKey,'') AS RazorpaySecretKey,

			ISNULL(GP.BBPSCharges,'') AS BBPSCharges,
			ISNULL(GP.BBPSGST,0) AS BBPSGST,

			ISNULL(GP.GrayQuestClientId,'') AS GrayQuestClientId,
			ISNULL(GP.GrayQuestSecretKey,'') AS GrayQuestSecretKey,
			ISNULL(GP.GrayQuestApiKey,'') AS GrayQuestApiKey,

			ISNULL(GP.EasebuzzKey,'') AS EasebuzzKey,
			ISNULL(GP.EasebuzzSalt,'') AS EasebuzzSalt,
			ISNULL(GP.EasebuzzIsLiveEnvironment, 0) AS EasebuzzIsLiveEnvironment,
			ISNULL(GP.EasebuzzIsEnableiFrame, 0) AS EasebuzzIsEnableiFrame,
			ISNULL(GP.EasebuzzSubMerchantId,'') AS EasebuzzSubMerchantId,

			ISNULL(GP.HesabeAccessCode,'') AS HesabeAccessCode,
			ISNULL(GP.HesabeMerchantKey,'') AS HesabeMerchantKey,
			ISNULL(GP.HesabeMerchantIV, '') AS HesabeMerchantIV,
			ISNULL(GP.HesabeMerchantCode, '') AS HesabeMerchantCode,
			ISNULL(GP.HesabeVersion, '2.0') AS HesabeVersion,
			ISNULL(GP.HesabeIsLiveEnvironment,0) AS HesabeIsLiveEnvironment,

			ISNULL(GP.RazorpaySubMerchantId, '') AS RazorpaySubMerchantId,

			--For Mantis 0034589 by Foram
			ISNULL(RazorpayCollectNowMID, '') AS RazorpayCollectNowMID,
			ISNULL(RazorpayCollectNowKeyID, '') AS RazorpayCollectNowKeyID,
			ISNULL(RazorpayCollectNowSecretKey, '') AS RazorpayCollectNowSecretKey
			--For Mantis 0034589 by Foram

	FROM 
			[sOp].[tGatewayProduct] GP
			INNER JOIN [sOp].[tGatewayConfiguration] GC ON GC.Id = GP.GatewayConfigurationId
			INNER JOIN [sOp].[tPaymentGatewayMaster] PGM ON PGM.Id = GC.PaymentGatewayId
	WHERE 
			(GC.OrgGroupId = @rOrgGroupId)
			AND	((GP.Id = @rId) OR (@rId = 0))
			AND	((GP.GatewayConfigurationId = @rGatewayConfigurationId) OR (@rGatewayConfigurationId = 0))
			AND ((GP.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ISNULL(GC.IsObsolete,0) = 0
END
GO
PRINT N'Altering Procedure [sAcademic].[pClassworkStudentGet]...';


GO
ALTER PROCEDURE [sAcademic].[pClassworkStudentGet]

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

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

	DECLARE @lDivisionId int,@lAcademicId Bigint
	SELECT @lDivisionId = DivisionId, @lAcademicId=ID FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
	
	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsClassworkHomeworkBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 323 AND SourceTypeId = 2010 AND SourceId = LEFT(@lOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsClassworkHomeworkBasedOnApproval = 0
	ELSE
	SET @lIsClassworkHomeworkBasedOnApproval = 1	

	DECLARE @lIsOptional INT = 0
	SET @lIsOptional =(SELECT TOP 1 1 FROM sAcademic.tClasswork AC 
						INNER Join sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
						INNER Join sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
						INNER Join sSetup.tClassMaster CM On CM.Id = AC.ClassId
						INNER Join sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
						INNER JOIN sStudent.vStudentAcademic SA  ON AC.ClassId=SA.ClassId AND AC.DivisionId=SA.DivisionId
						INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = AC.ClassId AND CS.SubjectId = SM.Id
						where CS.IsOptional=1 AND SA.AcademicId =@lAcademicId)
	
	IF (@lIsOptional=1)
	BEGIN
	print @lIsOptional
	SELECT distinct
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    AC.Classwork,
		    AC.Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    OM.OrgGroupId AS OrgId,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC			 
			INNER Join sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER Join sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER Join sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER Join sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sStudent.vStudentAcademic SA  ON AC.ClassId=SA.ClassId AND AC.DivisionId=SA.DivisionId
			INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = AC.ClassId AND CS.SubjectId = SM.Id
			LEFT JOIN [sAssessment].[tOptionalSubject] OS ON OS.ClassSubjectId = CS.Id AND Os.AcademicId = SA.AcademicId
	WHERE 
	    AC.DivisionId = @lDivisionId		 
		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
		AND (AC.HomeWorkEndDate>=@rHomeWorkEndDate OR ISNULL(@rHomeWorkEndDate,'')='')
		AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
		AND ISNULL(EM.IsOtherUser,0) = 0 
		AND OS.AcademicId IS NULL
	END

	ELSE 
	BEGIN
		SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
		    AC.Classwork,
		    AC.Homework,
		    AC.ClassWorkDate,
		    AC.HomeWorkEndDate,
		    --ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
		    ISNULL(SM.Title,'') as SubjectName,
		    ISNULL(EM.FirstName +' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(CM.Title,'') AS ClassName,
		    ISNULL(DM.Title,'') AS DivisionName,
		    OM.OrgGroupId AS OrgId,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC			 
			INNER Join sSetup.tSubjectMaster SM On SM.Id=AC.SubjectId
			INNER Join sHrm.tEmployeeMaster EM On EM.Id = AC.EmployeeId
			INNER Join sSetup.tClassMaster CM On CM.Id = AC.ClassId
			INNER Join sSetup.tDivisionMaster DM On DM.Id = AC.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			
	WHERE 
	    AC.DivisionId = @lDivisionId		 
		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
		AND (AC.HomeWorkEndDate>=@rHomeWorkEndDate OR ISNULL(@rHomeWorkEndDate,'')='')
		AND ((@lIsClassworkHomeworkBasedOnApproval=0) OR (@lIsClassworkHomeworkBasedOnApproval=1 AND AC.StatusId=550))
		AND ISNULL(EM.IsOtherUser,0) = 0 
		AND AC.BatchId = @rBatchId
		order by  AC.CreatedDateTime desc
	END
END
GO
PRINT N'Altering Procedure [sAcademic].[pClassworkStudentWithStatusGet]...';


GO
ALTER PROCEDURE [sAcademic].[pClassworkStudentWithStatusGet]

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

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

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

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

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

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


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

BEGIN

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

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

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

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

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

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

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

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

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

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

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

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

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

		SET @LOpeningBalance = @LOpeningBalance  +  @OpeningBalance

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

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

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

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


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

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

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

		INSERT INTO #tempClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Trasaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @lStartDate,@lEndDate,@rOrgGroupId,@lAccountYearId,@LedgerId,''
		SET @lCount = @lCount - 1
	END
	
	DECLARE  @columns NVARCHAR(MAX) = '', @sql     NVARCHAR(MAX) = '';	
	SET @columns =(SELECT STUFF(
    ( SELECT  distinct ',' +  QUOTENAME(title) FROM sAccounting.tLedgerMaster where OrgGroupId = @rOrgGroupId AND IsObsolete = 0
	FOR XML PATH('')), 1, 1, '') AS Ledgers)

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

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


GO
ALTER PROCEDURE [sAdmission].[pAdmissionAndInquiryConsolidateDashBoardGet]
                              
    @rTypeId int, -- 1-Admission, 2-Inquiry 
    @rType nvarchar(200), -- OrgGroup, Organization
    @rOrgGroupId int=0,
    @rOrgId int=0,
    @rCommonOrgGroupBatchId int=0,
	@rInquiryStatusId int=0,
	@rClassId int =0,
	@rSyncDate int =0,
	@rInquiryMainStatus int =0
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
	INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
	SELECT 
		OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
	FROM
		sSetup.tOrganizationMaster OM
		INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
	WHERE 
		((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
		AND BM.IsObsolete = 0 AND COGBM.Id=@rCommonOrgGroupBatchId
		AND BM.IsInContext = 1
	GROUP BY
		OM.Id
		
	DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
	INSERT INTO @lTempBatchId (OrgId , BatchId)
	SELECT 
		BM.OrgId AS OrgId,
		BM.Id AS BatchId
	FROM 
		sSetup.tBatchMaster BM
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
	WHERE
		BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id=@rCommonOrgGroupBatchId
		AND BM.IsInContext = 1
	
	DECLARE @lConfigValue nvarchar(50)=''
	IF(@rOrgGroupId = 0)
	BEGIN
		DECLARE @lOrgGroupId int
		SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
		
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 397 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	END
	ELSE
	BEGIN
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 397 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	END
	IF @lConfigValue = ''
		SET @lConfigValue = 'False' 

-- For Admission TypeId=1
	IF(@rTypeId=1) 
	BEGIN
		IF(@rType='OrgGroup')
		BEGIN

		IF(@rSyncDate =1)
				BEGIN
				DELETE  sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND (OrgGroupId = @rOrgGroupId))  
				BEGIN  
					IF(@rOrgGroupId !=0)  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1  
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = null) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
					
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
				ELSE  
				BEGIN  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
				    LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount

					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
		END
		ELSE
			BEGIN
			 IF  Exists(select 1 from sAdmission.tTempAdmissionFormCount   where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102) AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId)   
			 BEGIN  
				 SELECT * FROM sAdmission.tTempAdmissionFormCount   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				 return  
			 END  
			 ELSE  
			 BEGIN  
				DELETE  sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))  
				BEGIN  
					IF(@rOrgGroupId !=0)  
        
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),
				
					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
					  
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId  AND BM.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
				ELSE  
				BEGIN  
					INSERT INTO sAdmission.tTempAdmissionFormCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate(),
			
					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId  AND BM1.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id IS NULL) as PendingCount,

					(SELECT ISNULL(COUNT(AF1.Id),0) FROM sSetup.tOrgGroupMaster OGM1     
					INNER JOIN sSetup.tOrganizationMaster OM1 ON OGM1.Id = OM1.OrgGroupId   
					INNER JOIN @lTempBatchId TB1 ON TB1.OrgId = OM1.Id  
					LEFT JOIN sSetup.tBatchMaster BM1 ON BM1.Id = TB1.BatchId AND BM1.IsInContext = 1 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM1 ON OGBM1.ID=BM1.OrgGroupBatchId AND OGM1.Id = OGBM1.OrgGroupId   
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM1 ON COGBM1.Id=OGBM1.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF1 ON BM1.Id = AF1.BatchId
					LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF1.Id = AFS.AdmissionFormId
					LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId WHERE OGM1.Id<>1 AND COGBM1.Id = COGBM.Id AND OGM1.Id = OGM.Id AND ASM.Id = 3) as ConfirmCount
				     
					FROM sSetup.tOrgGroupMaster OGM     
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1   
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId AND OGM.Id = OGBM.OrgGroupId   
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
					LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId  
					WHERE   
					OGM.Id<>1 AND  
					COGBM.Id=@rCommonOrgGroupBatchId AND  
					--BM.IsActive = 1  
					BM.Id = TB.BatchId  
					GROUP BY OGM.Id,OGM.Title,COGBM.Id  
					SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				END  
			END  
		END
	END
-- For Admission TypeId=1
	IF(@rType='Organization')
		BEGIN
			SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,OM.OrderIndex
			FROM sAdmission.tAdmissionForm AF 
			LEFT JOIN  sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId AND BM.IsInContext = 1
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			
			LEFT JOIN @lTempBatchId TB ON TB.OrgId = OM.Id and BM.Id = TB.BatchId
			WHERE --BM.IsActive = 1 
			OM.OrgGroupId = @rOrgGroupId 	
			AND BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId 
			And ISNULL(O.IsObsolete,0) = 0
			GROUP BY OM.Id,OM.Title,OM.OrderIndex
			Order BY OM.OrderIndex
		END
-- For Admission TypeId=1
	IF(@rType='Status')
		BEGIN
			SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount ,0 AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.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 @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId AND OM.Id = @rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId 
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title,OM.OrderIndex
			Order By OM.OrderIndex
		END
-- For Admission TypeId=1
	IF(@rType='StatusOrgGroupWise')
		BEGIN
		    CREATE Table #MyTempTable(
						  OrgId Int,
						  Organization nvarchar(100),
                          StatusName nvarchar(100),
                          StatusCount BigInt)
            INSERT INTO #MyTempTable(OrgId,Organization,StatusName,StatusCount)
			SELECT OM.Id,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,AF.Id AS StatusCount 			
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.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 @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1

	DECLARE 
    @columns NVARCHAR(MAX) = '', 
    @sql     NVARCHAR(MAX) = '';

	SELECT 
    @columns+=QUOTENAME(ASM.Title) + ','
  FROM 
    sAdmission.tAdmissionStatusMaster ASM
  ORDER BY 
    ASM.Title;
  -- Add Pending Column
  SET @columns = LEFT(@columns, LEN(@columns) - 1)+',Pending';


  -- construct dynamic SQL
  SET @sql ='
  SELECT * FROM #MyTempTable MT  
  PIVOT(
    Count(MT.StatusCount)
    FOR MT.StatusName IN ('+ @columns +')
  ) AS pivot_table;';

  -- execute the dynamic SQL
  EXECUTE sp_executesql @sql;
  DROP Table #MyTempTable
		END

	--For Admission Form Count
	IF(@rType='AdmissionFormOrgGroupWise')
	BEGIN
		SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount , 0 AS InquiryMainStatusId
		,OM.OrderIndex
		FROM sAdmission.tAdmissionForm AF 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.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 @lTempBatchId TB ON TB.BatchId = BM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
		
		LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
		LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
		WHERE --BM.IsActive = 1 
		BM.Id = TB.BatchId
		AND BM.IsInContext = 1
		AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
		And ISNULL(O.IsObsolete,0) = 0
		GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title,OM.OrderIndex
		Order BY OM.OrderIndex	
	END

	IF(@rType='AdmissionFormStatusWise')
	BEGIN
		SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount , 0 AS InquiryMainStatusId
		,OM.OrderIndex
		FROM sAdmission.tAdmissionForm AF 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.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 @lTempBatchId TB ON TB.BatchId = BM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
		
		LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
		LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
		WHERE --BM.IsActive = 1 
		BM.Id = TB.BatchId
		AND BM.IsInContext = 1
		AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
		And ISNULL(O.IsObsolete,0) = 0
		AND ISNULL(ASM.Id,0)=@rInquiryStatusId
		GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title,OM.OrderIndex
		Order BY OM.OrderIndex	
	END
-- For Admission TypeId=1
	ELSE IF(@rType='StatusClassWise')
		BEGIN
		
			SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(AF.Id),0) AS StatusCount ,CM.OrderIndex 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN 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 @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id

			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND (@rInquiryStatusId = -1 OR (ISNULL(ASM.Id,0)=@rInquiryStatusId))
			And ISNULL(O.IsObsolete,0) = 0
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND BM.IsInContext = 1
			GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
		END
-- For Admission TypeId=1
ELSE IF(@rType='StatusClassWise')
		BEGIN
		
			SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(AF.Id),0) AS StatusCount ,CM.OrderIndex 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN 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 @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id

			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ( @rInquiryStatusId = -1 OR (ISNULL(ASM.Id,0)=@rInquiryStatusId) )
			And ISNULL(O.IsObsolete,0) = 0
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND BM.IsInContext = 1
			GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
		END
-- For Admission TypeId=1
ELSE IF(@rType='StatusStudentList')
			BEGIN
			SELECT AF.FormNo As InquiryId, AF.FirstName+' '+AF.MiddleName +' '+ AF.LastName AS StudentName,AF.ContactNo AS ContactNo 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN 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 @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId 
			AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ( @rInquiryStatusId = -1 OR (ISNULL(ASM.Id,0)=@rInquiryStatusId) )
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			AND((CM.Id = @rClassId)OR(@rClassId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY AF.FirstName,AF.MiddleName,AF.LastName,AF.ContactNo,AF.FormNo
			END
			END
	
-- For Inquiry
	IF(@rTypeId=2)
	BEGIN
	IF(@rType='OrgGroup')
		BEGIN
			IF(@rSyncDate =1)
				BEGIN
			DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND (OrgGroupId = @rOrgGroupId))  
				   BEGIN  
				   IF(@rOrgGroupId !=0)  
				   INSERT INTO sAdmission.tTempAdmissionInquiryCount  
					SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
					FROM   
					sSetup.tOrgGroupMaster OGM  
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
			        
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
			        
					LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId    
					WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
					--BM.IsActive = 1  
					GROUP BY OGM.Id,OGM.Title  
					SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				   END  
      ELSE   
       BEGIN  
		    INSERT INTO sAdmission.tTempAdmissionInquiryCount  
        SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
       FROM   
       sSetup.tOrgGroupMaster OGM  
       INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
       
       INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
       LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
       INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
       INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
       INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
       LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
       WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
       --BM.IsActive = 1  
       GROUP BY OGM.Id,OGM.Title  
		  SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
       END  
				END
			ELSE
				BEGIN
						IF  Exists(select 1 from sAdmission.tTempAdmissionInquiryCount   where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId  AND (OrgGroupId = @rOrgGroupId))  
			  BEGIN  
			   SELECT  OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			   return  
			  END  
			 ELSE  
			  BEGIN  
			  DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			  IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))  
			   BEGIN  
				IF(@rOrgGroupId !=0)  
				INSERT INTO sAdmission.tTempAdmissionInquiryCount  
				 SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
				FROM   
				sSetup.tOrgGroupMaster OGM  
				INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
		        
				INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
		        
				LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
				WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
				--BM.IsActive = 1  
				GROUP BY OGM.Id,OGM.Title  
				SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
			   END  
			  ELSE  
			   BEGIN  
				DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
				INSERT INTO sAdmission.tTempAdmissionInquiryCount  
				 SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()  
				FROM   
				sSetup.tOrgGroupMaster OGM  
				INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId   
				INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id  
				LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId AND BM.IsInContext = 1
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId  
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId        
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId   
				LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId  
				WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId   
				--BM.IsActive = 1  
				GROUP BY OGM.Id,OGM.Title  
				SELECT OrgGroupTitle AS OrgGroup,0 AS PendingCount,0 AS ConfirmCount,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))  
       END  
		END  
		 END		
		END
-- For Inquiry
	IF(@rType='Organization')
		BEGIN
			SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			LEFT JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId AND BM.IsInContext = 1
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			
			--sAdmission.tAdmissionForm AF 
			--LEFT JOIN  sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 	
			--LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			--LEFT JOIN @lTempBatchId TB ON TB.OrgId = OM.Id and BM.Id = TB.BatchId
			WHERE BM.Id = TB.BatchId
			And ISNULL(O.IsObsolete,0) = 0
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			GROUP BY OM.Id,OM.Title,OM.OrderIndex
			ORDER BY OM.OrderIndex
		END
-- For Inquiry
	IF(@rType='Status')
		BEGIN
		IF(@lConfigValue = 'True')
		BEGIN
-- 11
-- Inquiry Form 
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId >= 11
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 21
-- Admission Form Given
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI1.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId AND BM.IsInContext = 1
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 21
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 31
-- Admission Form Submitted
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 21
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =31
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 41
-- Appeared For Entrance Exam
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 31
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =41
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 51
-- Came for Interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =51 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 61
-- Not Came for interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 51  AND ISM.InquiryMainStatusId !=71
			AND ISM.InquiryMainStatusId = 61

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 61 

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		
		    UNION ALL
			
-- 71
--Confirmed Admission

			SELECT
			ISM.Id AS InquiryStatusId, 
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 61 

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =71
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 81
-- Rejected Form
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0)) AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 91
-- Fees Paid

			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101

			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =91

 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 101		
-- Fees not paid
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 111			
-- Refunded Fees
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =111
 
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		END
		ELSE 
		BEGIN
			SELECT 
			ISM1.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM1.Title,'') AS StatusName,
			ISNULL(COUNT(ISM1.Id),0) AS StatusCount, 
			ISM1.InquiryMainStatusId AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND((OM.Id = @rOrgId)OR(@rOrgId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM1.Id,ISM1.Title,ISM1.InquiryMainStatusId,AI.OrgId,OM.OrderIndex
			ORDER BY OM.OrderIndex
		END
		END
		
	IF(@rType='StatusOrgGroupWise')
		BEGIN
		IF(@lConfigValue = 'True')
		BEGIN

-- 11
-- Inquiry Form 
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId >= 11
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount,
			ISNULL(ISM.InquiryMainStatusId,0) AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 21
-- Admission Form Given
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI1.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 21
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 31
-- Admission Form Submitted
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 21
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =31
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 41
-- Appeared For Entrance Exam
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 31
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =41
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			
			
			UNION ALL
-- 51
-- Came for Interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =51 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			
			UNION ALL
-- 61
-- Not Came for interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 51  AND ISM.InquiryMainStatusId !=71
			AND ISM.InquiryMainStatusId = 61

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId = 61 

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		
		UNION ALL
			
-- 71
--Confirmed Admission

			SELECT
			ISM.Id AS InquiryStatusId, 
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 61 

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =71
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 81
-- Rejected Form
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =81
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 91
-- Fees Paid

			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =91

 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 101		
-- Fees not paid
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
			UNION ALL
-- 111			
-- Refunded Fees
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI1.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI1.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI1.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId  AND OM.Id = AI.OrgId
			AND BM.IsInContext = 1
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =111
 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId,AI.OrgId
		 END
		 ELSE
		 BEGIN
			SELECT 
			ISM1.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM1.Title,'') AS StatusName,
			ISNULL(COUNT(ISM1.Id),0) AS StatusCount,
			ISNULL(ISM1.InquiryMainStatusId,0) AS InquiryMainStatusId
			,OM.OrderIndex
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId = 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			And ISNULL(O.IsObsolete,0) = 0
			AND BM.IsInContext = 1
			GROUP BY OM.Id,OM.Title,ISM1.Id,ISM1.Title,ISM1.InquiryMainStatusId,AI.OrgId,OM.OrderIndex
			ORDER BY OM.OrderIndex
		 END
		END

	IF(@rType='StatusClassWise')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInquiryMainStatus nvarchar(500)='' 
				IF(@rInquiryMainStatus=11)
				SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId >= 11'
				ELSE IF(@rInquiryMainStatus=21)
				SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId > 11'
				ELSE IF(@rInquiryMainStatus=31)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 21'
				ELSE IF(@rInquiryMainStatus=41)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 31'
				ELSE IF(@rInquiryMainStatus=51)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				ELSE IF(@rInquiryMainStatus=61)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 61 '
				ELSE IF(@rInquiryMainStatus=71)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 61'
				ELSE IF(@rInquiryMainStatus=81)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 81'
				ELSE IF(@rInquiryMainStatus=91)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				ELSE IF(@rInquiryMainStatus=101)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 101'
				ELSE IF(@rInquiryMainStatus=111)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 101'
				ELSE IF(@rInquiryMainStatus = 0)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 0'


				DECLARE @lSQLString nvarchar(max)=''

				SET @lSQLString = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInquiryMainStatus)+' and AI2.ForClassId = CM.Id
							AND BM.IsInContext = 1
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND BM.IsInContext = 1
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							'+CONVERT(nvarchar(500),@lInquiryMainStatus)+'
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex '

						print @lSQLString

						execute(@lSQLString)
				END
				ELSE 
				BEGIN
						DECLARE @lSQLString1 nvarchar(max)=''

						SET @lSQLString1 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								and ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND BM.IsInContext = 1
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ISM1.InquiryMainStatusId  = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							AND BM.IsInContext = 1
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex,ISM1.InquiryMainStatusId'

						print @lSQLString1

						execute(@lSQLString1)
				END
			END

	ELSE IF(@rType='StatusStudentList')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInquiryMainStatusStudent nvarchar(500)='' 
				IF(@rInquiryMainStatus=11)
				SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId >=11'
				ELSE IF(@rInquiryMainStatus=21)
				SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId > 11'
				ELSE IF(@rInquiryMainStatus=31)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 21'
				ELSE IF(@rInquiryMainStatus=41)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 31'
				ELSE IF(@rInquiryMainStatus=51)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				ELSE IF(@rInquiryMainStatus=61)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71'
				ELSE IF(@rInquiryMainStatus=71)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 61'
				ELSE IF(@rInquiryMainStatus=81)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 71 AND ISM.InquiryMainStatusId !=91'
				ELSE IF(@rInquiryMainStatus=91)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				ELSE IF(@rInquiryMainStatus=101)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 91 AND ISM.InquiryMainStatusId !=111'
				ELSE IF(@rInquiryMainStatus=111)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 101'
				ELSE IF(@rInquiryMainStatus=0)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId = 0'

				DECLARE @lSQLStduentList nvarchar(max)=''

				SET @lSQLStduentList = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
		
							SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
								sAdmission.tAdmissionInquiry AI 
								INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
								INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
								INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
								INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
								LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
								INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
								LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
								WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInquiryMainStatusStudent)+'
								AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
								AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
								AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
								AND BM.IsInContext = 1
								GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					--print @lSQLStduentList

					execute(@lSQLStduentList)

					END
					ELSE
					BEGIN	
						DECLARE @lSQLStduentList1 nvarchar(max)=''

						SET @lSQLStduentList1 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
								INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
								SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
								FROM
									sSetup.tOrganizationMaster OM
									INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
								WHERE 
									((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
									AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
									AND BM.IsInContext = 1
								GROUP BY
									OM.Id
		
								DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
								INSERT INTO @lTempBatchId (OrgId , BatchId)
								SELECT 
									BM.OrgId AS OrgId,
									BM.Id AS BatchId
								FROM 
									sSetup.tBatchMaster BM
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
									--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
								WHERE
									BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
									AND BM.IsInContext = 1
		
		
									SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
										sAdmission.tAdmissionInquiry AI 
										INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
										INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
										INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
										INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
										INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
										LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
										INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
										LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
										WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
										 AND ISM.InquiryMainStatusId = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
										AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
										AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
										AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
										AND BM.IsInContext = 1
										GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					print @lSQLStduentList1

						execute(@lSQLStduentList1)
			END
		END

    ELSE IF(@rType='NotDoneStatusClassWise')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInqMainStatus nvarchar(500)='' 
				SET  @lInqMainStatus = 'AND ISM.Id =' + CONVERT(nvarchar,@rInquiryStatusId)
				--IF(@rInquiryMainStatus=11)
				--SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId >= 11'
				--ELSE IF(@rInquiryMainStatus=21)
				--SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId > 11'
				--ELSE IF(@rInquiryMainStatus=31)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 21'
				--ELSE IF(@rInquiryMainStatus=41)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 31'
				--ELSE IF(@rInquiryMainStatus=51)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				--ELSE IF(@rInquiryMainStatus=61)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 61 '
				--ELSE IF(@rInquiryMainStatus=71)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 61'
				--ELSE IF(@rInquiryMainStatus=81)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 81'
				--ELSE IF(@rInquiryMainStatus=91)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				--ELSE IF(@rInquiryMainStatus=101)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId = 101'
				--ELSE IF(@rInquiryMainStatus=111)
				--SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 101'


				DECLARE @lSQLString3 nvarchar(max)=''

				SET @lSQLString3 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInqMainStatus)+' and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND BM.IsInContext = 1
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							'+CONVERT(nvarchar(500),@lInqMainStatus)+'
							AND BM.IsInContext = 1
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex '

						print @lSQLString3

						execute(@lSQLString3)
				END
				ELSE 
				BEGIN
						DECLARE @lSQLString4 nvarchar(max)=''

						SET @lSQLString4 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		 
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1

						SELECT 
							AI2.ForClassId AS ClassId,CM.Title AS ClassName,CM.OrderIndex,
							(SELECT ISNULL(COUNT(ISM.Id),0) AS StatusCount 
							FROM sAdmission.tAdmissionInquiry AI 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
							WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								and ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId and AI2.ForClassId = CM.Id
							--BM.IsActive = 1 And ISNULL(O.IsObsolete,0) = 0
							AND BM.IsInContext = 1
							AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)))
							AS StatusCount
						FROM 
							sAdmission.tAdmissionInquiry AI2
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI2.ForClassId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI2.ForBatchId
							LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
							LEFT JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM1.Id = AI2.InquiryStatusId
						WHERE BM.Id = TB.BatchId 
						--and OM.OrgId = @rOrgId
							--and Ai2.ForClassId = CM.Id
							--AND COGBM.Id=1
							AND ISM1.InquiryMainStatusId  = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
							AND ((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+' )OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
							AND BM.IsInContext = 1
						Group BY 
							AI2.ForClassId,CM.Title,CM.OrderIndex,ISM1.InquiryMainStatusId'

						print @lSQLString4

						execute(@lSQLString4)
				END
			END

	ELSE IF(@rType='NotDoneStatusStudentList')
		BEGIN
				IF(@lConfigValue = 'True')
				BEGIN

				DECLARE @lInqMainStatusStudent nvarchar(500)='' 
				 
				SET  @lInqMainStatusStudent = 'AND ISM.Id =' + CONVERT(nvarchar,@rInquiryStatusId)
				--IF(@rInquiryMainStatus=11)
				--SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId >=11'
				--ELSE IF(@rInquiryMainStatus=21)
				--SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId > 11'
				--ELSE IF(@rInquiryMainStatus=31)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 21'
				--ELSE IF(@rInquiryMainStatus=41)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 31'
				--ELSE IF(@rInquiryMainStatus=51)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 41 and ISM.InquiryMainStatusId <> 61'
				--ELSE IF(@rInquiryMainStatus=61)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71'
				--ELSE IF(@rInquiryMainStatus=71)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 61'
				--ELSE IF(@rInquiryMainStatus=81)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 71 AND ISM.InquiryMainStatusId !=91'
				--ELSE IF(@rInquiryMainStatus=91)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=101'
				--ELSE IF(@rInquiryMainStatus=101)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 91 AND ISM.InquiryMainStatusId !=111'
				--ELSE IF(@rInquiryMainStatus=111)
				--SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 101'


				DECLARE @lSQLStduentList3 nvarchar(max)=''

				SET @lSQLStduentList3 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
						INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
						SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
						FROM
							sSetup.tOrganizationMaster OM
							INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						WHERE 
							((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
							AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
						GROUP BY
							OM.Id
		
						DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
						INSERT INTO @lTempBatchId (OrgId , BatchId)
						SELECT 
							BM.OrgId AS OrgId,
							BM.Id AS BatchId
						FROM 
							sSetup.tBatchMaster BM
							INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
							--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
							INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
						WHERE
							BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
							AND BM.IsInContext = 1
		
							SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
								sAdmission.tAdmissionInquiry AI 
								INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
								INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
								INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
								INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
								INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
								LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
								INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
								LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
								WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
								'+CONVERT(nvarchar(500),@lInqMainStatusStudent)+'
								AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
								AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
								AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
								AND BM.IsInContext = 1
								GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					--print @lSQLStduentList

					execute(@lSQLStduentList3)

					END
					ELSE
					BEGIN	
						DECLARE @lSQLStduentList4 nvarchar(max)=''

						SET @lSQLStduentList4 = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
								INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
								SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
								FROM
									sSetup.tOrganizationMaster OM
									INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
								WHERE 
									((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
									AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
									AND BM.IsInContext = 1
								GROUP BY
									OM.Id
		
								DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
								INSERT INTO @lTempBatchId (OrgId , BatchId)
								SELECT 
									BM.OrgId AS OrgId,
									BM.Id AS BatchId
								FROM 
									sSetup.tBatchMaster BM
									INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
									--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
									INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
								WHERE
									BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
									AND BM.IsInContext = 1
		
		
									SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
										sAdmission.tAdmissionInquiry AI 
										INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
										INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
										INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
										INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
										INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			
				
										LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
										INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
										LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId --AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
										WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
										 AND ISM.InquiryMainStatusId = '+CONVERT(nvarchar(20),@rInquiryMainStatus)+'
										AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			
										AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
										AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
										AND BM.IsInContext = 1
										GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

					print @lSQLStduentList4

						execute(@lSQLStduentList4)
			END
		END
	END


	-- For AdmissionConverted Tab
	IF(@rTypeId = 3)
	BEGIN
		IF(@rType='OrgGroupWise')
		BEGIN
			-- Organization wise Count
			SELECT OrgId, Organization, ISNULL(Inquiry, 0) AS InquiryCount, ISNULL(Form, 0) AS FormCount, (ISNULL([Converted Inquiry], 0) + ISNULL([Converted Form], 0)) AS ConvertedCount
			FROM  
			(
				SELECT 
					ISNULL(OM.Id,0) AS OrgId,
					OM.Title AS Organization,
					'Inquiry' AS Type,
					ISNULL(COUNT(AI.Id),0) AS Total
				FROM sAdmission.tAdmissionInquiry AI 
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					--AND OM.OrgGroupId = @rOrgGroupId
					And ISNULL(O.IsObsolete,0) = 0
					AND BM.IsInContext = 1
				GROUP BY OM.Id,OM.Title

				UNION ALL

				SELECT 
					OM.Id, 
					OM.Title AS Organization,
					'Form' AS Type,
					COUNT(AF.Id) AS Total
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.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 @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND BM.IsInContext = 1
				GROUP BY OM.Id, OM.Title

				UNION ALL

				SELECT
					ISNULL(OM.Id,0) AS OrgId,
					OM.Title AS Organization,
					'Converted Inquiry' AS Type,
					COUNT(AI.Id) AS Total
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId AND BM.IsInContext = 1
					LEFT JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					LEFT JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					LEFT JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					LEFT JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
					LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
				WHERE 
					BM.Id = TB.BatchId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					AND ISM.InquiryMainStatusId = 71
					--AND OM.OrgGroupId = @rOrgGroupId
					And ISNULL(O.IsObsolete,0) = 0
				GROUP BY OM.Id, OM.Title

				UNION ALL

				SELECT 
					OM.Id, 
					OM.Title AS Organization,
					'Converted Form' AS Type,
					COUNT(AF.Id) AS Total
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.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 @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id = @rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND AF.StatusId = 208 --Closed
					AND BM.IsInContext = 1
				GROUP BY OM.Id, OM.Title
			   ) AS A
				PIVOT  
				(SUM(Total) FOR [Type] IN ([Inquiry],[Form],[Converted Inquiry],[Converted Form])) AS A1
		END

		IF(@rType='ClassWise')
		BEGIN
			-- Class wise Count
			SELECT ClassId, ClassName, OrderIndex, ISNULL(Inquiry, 0) AS InquiryCount, ISNULL(Form, 0) AS FormCount,(ISNULL([Converted Inquiry], 0) + ISNULL([Converted Form], 0)) AS ConvertedCount
			FROM  
			(
				--Inquiry
				SELECT 
					AI.ForClassId AS ClassId, CM.Title AS ClassName, 'Inquiry' AS Type, ISNULL(COUNT(AI.Id),0) AS Total, CM.OrderIndex
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
				WHERE 
					BM.Id = TB.BatchId 
					AND ((CM.OrgId = @rOrgId) OR (@rOrgId=0))
					AND BM.IsInContext = 1				
				Group BY AI.ForClassId,CM.Title,CM.OrderIndex 

				UNION ALL 

				-- Form
				SELECT 
					CM.Id AS ClassId, CM.DisplayTitle AS ClassName, 'Form' AS Type, ISNULL(COUNT(AF.Id),0) AS Total, CM.OrderIndex 
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN 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 @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = 9911 AND COGBM.Id=@rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND ((CM.OrgId = @rOrgId) OR (@rOrgId=0))
					AND BM.IsInContext = 1
				GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex

				UNION ALL
				
				SELECT 
					AI.ForClassId AS ClassId, CM.Title AS ClassName, 'Converted Inquiry' AS Type, ISNULL(COUNT(AI.Id),0) AS Total, CM.OrderIndex
				FROM sAdmission.tAdmissionInquiry AI
					INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
				WHERE 
					BM.Id = TB.BatchId 
					AND ((CM.OrgId = @rOrgId )OR(@rOrgId=0))
					AND ISM.InquiryMainStatusId = 71		
					AND BM.IsInContext = 1	
				Group BY AI.ForClassId,CM.Title,CM.OrderIndex 

				UNION ALL

				SELECT 
					CM.Id AS ClassId, CM.DisplayTitle AS ClassName, 'Converted Form' AS Type, ISNULL(COUNT(AF.Id),0) AS Total, CM.OrderIndex 
				FROM sAdmission.tAdmissionForm AF 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
					INNER JOIN 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 @lTempBatchId TB ON TB.BatchId = BM.Id
					INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
				WHERE 
					BM.Id = TB.BatchId
					AND OM.OrgGroupId = @rOrgGroupId 
					AND COGBM.Id=@rCommonOrgGroupBatchId
					And ISNULL(O.IsObsolete,0) = 0
					AND AF.StatusId = 208 --Closed
					AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
					AND BM.IsInContext = 1
				GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
			)  
			AS A
			PIVOT  
			(SUM(Total) FOR [Type] IN ([Inquiry],[Form],[Converted Inquiry],[Converted Form])) AS A2
		END
	END

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


GO


ALTER PROCEDURE [sAdmission].[pAdmissionStudentDocumentGet]
	 
    @rAdmissionFormId bigint,
	@rOrgId bigint,
	@rClassId bigint,
	@rBatchId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN

	SELECT 
		ISNULL(D.Id,0) AS DocumentId,
		ISNULL(D.DocumentName,'')AS DocumentName,
		S.DocumentName AS DocumentFileName ,
		D.Id AS AdmissionDocumentId
		FROM sCommon.tSubmitDocumentMaster D
		INNER JOIN sAdmission.tAdmissionStudentDocument  S ON S.SubmitDocumentMasterId=D.Id AND (S.AdmissionFormId= @rAdmissionFormId  OR @rAdmissionFormId=0)	-- MantisId : 0033671
		-- #Start : Comment for Mantis Id: 	0033671 
		--INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id
		--INNER JOIN 
		--(Select D1.DocumentName,D1.Id AS AdmissionDocumentId,S.DocumentName AS DocumentFileName FROM sCommon.tSubmitDocumentMaster D1
		--INNER JOIN sAdmission.tAdmissionStudentDocument  S ON S.SubmitDocumentMasterId=D1.Id AND (S.AdmissionFormId= @rAdmissionFormId  OR @rAdmissionFormId=0)
		--WHERE  D1.SubmitDocumentFunctionalityId='3' AND D1.OrgId=@rOrgId 
		--AND D1.Id IN (select SubmitDocumentMasterId from sAdmission.tAdmissionCriteriaDocument WHERE ClassId=@rClassId AND BatchId = @rBatchId  ))A ON  A.DocumentName = D.DocumentName
		-- #End : Comment for Mantis Id: 	0033671

		WHERE OrgId=@rOrgId AND D.SubmitDocumentFunctionalityId='3' -- AND DS.SourceTypeId = 2016 AND DS.SourceId = @rClassId   : Comment for Mantis Id: 	0033671
			
END
GO
PRINT N'Altering Procedure [sAlert].[pBookIssueGet]...';


GO
ALTER PROCEDURE [sAlert].[pBookIssueGet]
	 	 
		 @rBookIssueId bigint,
	 	 @rLibraryId int,
	 	 @rBatchId int,	 	 	 	
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),	 	
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 

			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (		--Mantis: 34674
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[LibraryName]',LM.Title),
			'[IssueDate]',BL.LogDate),
			'[DueDate]',BL.DueDate)		--Mantis: 34674
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			BM.Code AS BookCode,
			BM.Title AS BookName,
			LM.Title AS LibraryName,
			BL.LogDate AS IssueDate,
			SC.WhatsAppContactNo
		
		
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sLibrary.tBookLog BL ON BL.ReaderSourceId=SC.StudentId AND BL.ReaderSourceTypeId=2003 
			AND BL.IsCurrentStatus=1 AND BL.StatusId=523 
			INNER JOIN sLibrary.tLibraryMaster LM on LM.Id=BL.LibraryId
	INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId AND BL.ResourceSourceTypeId=2009
	WHERE
	BL.Id=@rBookIssueId AND BL.LibraryId=@rLibraryId and
		 (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
	
END
GO
PRINT N'Altering Procedure [sAlert].[pBookIssueListGet]...';


GO
ALTER PROCEDURE [sAlert].[pBookIssueListGet]
	 	 
		 --@rBookIssueId bigint,
		 @rOrgId int,
		 @rBatchId int,
		 @rDepartmentId int,
		 @rClassId int,
		 @rDivisionId int,	 	 	 	
	 	 @rLibraryId int,
		 @rIssueDate date,
	 	 @rTemplate nvarchar(max),	 	
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 

			SC.OrgGroupId,
			SC.OrgId,
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (		--Mantis Id: 34674
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[LibraryName]',LM.Title),
			'[IssueDate]',BL.LogDate),
			'[DueDate]',BL.DueDate)		--Mantis Id: 34674
			 AS Template,
			replace (		--Mantis Id: 34674
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),			
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[LibraryName]',LM.Title),
			'[IssueDate]',BL.LogDate),
			'[DueDate]',BL.DueDate)		--Mantis Id: 34674
			 AS MsgText,
			'2003' AS SourceTypeId,
			SC.StudentId AS SourceId,
			@rMailSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			BM.Code AS BookCode,
			BM.Title AS BookName,
			LM.Title AS LibraryName,
			BL.LogDate AS IssueDate,
			SC.WhatsAppContactNo
		
		
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sLibrary.tBookLog BL ON BL.ReaderSourceId=SC.StudentId AND BL.ReaderSourceTypeId=2003 AND SC.OrgId = BL.OrgId
		AND BL.IsCurrentStatus=1 
		AND BL.StatusId=523 
		INNER JOIN sLibrary.tLibraryMaster LM on LM.Id=BL.LibraryId
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId AND BL.ResourceSourceTypeId=2009
	WHERE
		(SC.OrgId = @rOrgId)
		AND (SC.BatchId = @rBatchId)
		AND ((SC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND BL.LibraryId=@rLibraryId
		AND BL.LogDate <= @rIssueDate
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
	
END
GO
PRINT N'Altering Procedure [sAlert].[pClassworkStudentListGet]...';


GO
ALTER PROCEDURE [sAlert].[pClassworkStudentListGet]
	 
		 @rDivisionId bigint,
		 @rOrgId int,
	 	 @rBatchId int,	 	 	 	
	 	 @rTemplate nvarchar(max) 	,
		 @rMailSubject nvarchar(500)='',
		 @rSubjectId bigint,
		 @rClassworkId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	declare @lIsOptional int = 0
	SET @lIsOptional =(select top 1 1 from sAcademic.tClasswork AC 
						INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = AC.ClassId AND CS.SubjectId = AC.SubjectId 
						where AC.DivisionId = @rDivisionId AND AC.SubjectId = @rSubjectId AND AC.Id =@rClassworkId AND CS.IsOptional = 1)

	IF (@lIsOptional=1)
	BEGIN
			Select 
		SC.OrgGroupId,
		SC.OrgId,
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		(replace(replace(replace(replace(replace
		(@rTemplate,'[TeacherName]',EM.FirstName +''+EM.MiddleName+''+EM.LastName), 
		'[SubjectName]',SM.Title),
		'[ClassWork]',AC.Classwork), 
		'[HomeWork]',AC.Homework), 
		'[HomeworkEndDate]',AC.HomeWorkEndDate)) AS MsgText,
		'2003' AS SourceTypeId,
		SC.StudentId AS SourceId,
		2003 AS ReceiverSourceTypeId,
		SC.StudentId AS ReceiverSourceId,
		@rMailSubject AS Subject,
		AC.ClassId,
		AC.DivisionId,
		AC.SubjectId,
		EM.FirstName +''+EM.MiddleName+''+EM.LastName AS TeacherName,
		SM.Title AS SubjectName,
		AC.Classwork,
		AC.Homework,
		AC.HomeWorkEndDate,
		SC.WhatsAppContactNo,
		AC.Id AS DocumentId
				
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sAcademic.tClasswork AC ON AC.ClassId = SC.ClassId AND AC.DivisionId=SC.DivisionId AND AC.BatchId =SC.BatchId
		INNER JOIN sStudent.vStudentAcademic SA  ON SC.AcademicId=SA.AcademicId AND SC.ClassId=SA.ClassId AND SC.DivisionId=SA.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId AND OM.Id=SC.OrgId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = AC.SubjectId
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=AC.EmployeeId
		INNER JOIN [sSetup].[tClassSubject] CS ON CS.ClassId = SC.ClassId AND CS.SubjectId = SM.Id
		LEFT JOIN [sAssessment].[tOptionalSubject] OS ON OS.ClassSubjectId = CS.Id AND Os.AcademicId = SA.AcademicId
	WHERE (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
		AND (SC.DivisionId = @rDivisionId)
		AND (AC.SubjectId=@rSubjectId)
		AND AC.Id = @rClassworkId
		AND OS.AcademicId IS NOT NULL
	END

	ELSE 
	BEGIN
		Select 
		SC.OrgGroupId,
		SC.OrgId,
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo AS MobileNo,	
		SC.ParentEmail AS EmailId,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SC.StudentEmail,'') AS StudentEmail,
		ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
		ISNULL(SC.FatherMail,'') AS FatherMail,
		ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
		ISNULL(SC.MotherMail,'') AS MotherMail,
		--@rTemplate AS MsgText,
		(replace
			(replace
				(replace
					(replace
						(replace(@rTemplate,'[TeacherName]',EM.FirstName +''+EM.MiddleName+''+EM.LastName), 
					'[SubjectName]',SM.Title),
				'[ClassWork]',AC.Classwork), 
			'[HomeWork]',AC.Homework), 
		'[HomeworkEndDate]',AC.HomeWorkEndDate)) AS MsgText,
		'2003' AS SourceTypeId,
		SC.StudentId AS SourceId,
		2003 AS ReceiverSourceTypeId,
		SC.StudentId AS ReceiverSourceId,
		@rMailSubject AS Subject,
		AC.ClassId,
		AC.DivisionId,
		AC.SubjectId,
		EM.FirstName +''+EM.MiddleName+''+EM.LastName AS TeacherName,
		SM.Title AS SubjectName,
		AC.Classwork,
		AC.Homework,
		AC.HomeWorkEndDate,
		SC.WhatsAppContactNo,
		AC.Id AS DocumentId
				
		From 
			sStudent.vStudentCommunication SC
			INNER JOIN sAcademic.tClasswork AC ON AC.ClassId = SC.ClassId AND AC.DivisionId=SC.DivisionId AND AC.BatchId =SC.BatchId
			INNER JOIN sStudent.vStudentAcademic SA  ON SC.AcademicId=SA.AcademicId AND SC.ClassId=SA.ClassId AND SC.DivisionId=SA.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId AND OM.Id=SC.OrgId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = AC.SubjectId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=AC.EmployeeId
		WHERE (SC.OrgId=@rOrgId)
			AND (SC.BatchId=@rBatchId)
			AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0	
			AND (SC.DivisionId = @rDivisionId)
			AND (AC.SubjectId=@rSubjectId)
			AND AC.Id = @rClassworkId

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


GO
 

ALTER PROCEDURE [sAlert].[pResultWithSubjectGet]
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rExamId int,
	 	 @rSubjectId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ExamName]',ES.Title),
			'[SubjectMark]', CHAR(13) + [sAlert].[fResultGet](R.Id,@rSubjectId,1)),
			'[SubjectMarkWithMax]',[sAlert].[fResultWithMaxGet](R.Id,@rSubjectId)),
			'[TotalMarks]',CONVERT(int,TotalMarks)),
			'[ObtainMarks]',CONVERT(int,TotalObtain)),
			'[ResultStatus]',R.ResultStatus),
			'[ResultGrade]',R.ResultGrade),
			'[ResultGradePoint]',R.ResultGradePoint),
			'[RankNumber]',R.RankNumber),
			'[Percentage]',R.Percentage),
			'[SubjectGrade]',[sAlert].[fResultGet](R.Id,@rSubjectId,2)),
			'[Percentile]',R.Percentile),
			'[ExamTopic]',sAlert.fExamDetailGet(@rExamId,@rSubjectId,1)),
			'[ExamTime]',sAlert.fExamDetailGet(@rExamId,@rSubjectId,2)),
			'[ExamDate]',sAlert.fExamDetailGet(@rExamId,@rSubjectId,3))
			
			 AS Template,
			 SC.ClassName AS Class,
			 SC.DivisionName AS Division,
			 ES.Title AS ExamName,
			 CONVERT(int,TotalMarks) AS TotalMarks,
			 CONVERT(int,TotalObtain) AS ObtainMarks,
			 R.ResultStatus AS ResultStatus,
			 R.ResultGrade AS ResultGrade,
			 R.ResultGradePoint AS ResultGradePoint,
			 R.RankNumber AS RankNumber,
			 R.Percentage AS Percentage,
			 R.Percentile AS Percentile,
			 [sAlert].[fResultGet](R.Id,@rSubjectId,2) AS SubjectGrade,
			 [sAlert].[fResultWithMaxGet](R.Id,@rSubjectId) AS SubjectMarkWithMax,
			 SC.WhatsAppContactNo
		
	From 
	sStudent.vStudentCommunication SC
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SC.AcademicId AND (R.ExamId=@rExamId OR @rExamId=0)
	INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = E.ExamSubGroupId
	 
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))	 
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1) AND SC.IsBlockAllAlert=0
	ORDER BY SC.DivisionOrderIndex,SC.Rollno
END
GO
PRINT N'Altering Procedure [sCertificate].[pLeavingGet]...';


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

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

			
  WHERE 
			((L.Id = @rId) OR (@rId = 0))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId =@rDivisionId) OR (@rDivisionId = 0))
			AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SA.Name like @rName) OR (ISNULL(@rName,'') = ''))
			AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((L.LCNumber >= @rFromNo) OR (@rFromNo = 0))
			AND ((L.LCNumber <= @rToNo) OR (@rToNo = 0))
		
			ORDER BY L.LCNumber
END
GO
PRINT N'Altering Procedure [sCommonService].[pMenuGet]...';


GO
-- exec sCommonService.pMenuGet 9911000000270,19184029,0,1,98
-- exec sCommonService.pMenuGet 9911000000270,19184030,0,1,97
-- exec sCommonService.pMenuGet 9911000000270,19184031,0,1,99
ALTER PROCEDURE [sCommonService].[pMenuGet]
 @rUserId [bigint],    
 @rMenuId int = 0,    
 @rResourceTypeId int= 0,    
 @rIsCoreMenu bit = 0,
 @rModuleId 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 AND TBL2.PermissionValue > 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 END    
 ELSE    
 BEGIN     
 SELECT    
   MenuID,    
   ModuleId,    
   ParentMenuID,    
   MenuTitle,      
   ScreenTitle,       
   PageURL,    
   ScreenId,    
   Permission,    
   OrderNumber,      
   TaskId,      
   PageURL  AS PagePath,    
   MenuIsObsolete,    
   Icon     
  FROM    
  (    

SELECT    
   ISNULL(Menu.Id,0) AS MenuID,     
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
   ISNULL(Menu.Title,'') AS MenuTitle,       
   ISNULL(Screen.Title, '') AS ScreenTitle,        
   ISNULL(Screen.Page, '') AS PageURL,    
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Screen.Id, 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,
   ISNULL(Screen.OrderIndex,0) As OrderIndex     
  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 (Menu.Id  IN (@rMenuId))   
  --OR ParentMenuID  in (24,2711))     
  --AND (
  ----Menu.Id IN (19184027)  
  ----OR ParentMenuID IN (55)
  --)  

  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(Screen1.Id, 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,
   ISNULL(Screen1.OrderIndex,0) As OrderIndex    
  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 TBL2.PermissionValue > 0
  AND Screen1.Id Not In(31358,31376)
  --AND Screen1.Id IN (31336,31337,31338,31339,31340)
  ) 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 (@rMenuId)   
  AND ModuleId IN (@rModuleId)
  ORDER BY MenuTable.OrderIndex, ParentMenuID
 END    
END
GO
PRINT N'Altering Procedure [sFee].[pFeeAllocationAdd]...';


GO

ALTER PROCEDURE [sFee].[pFeeAllocationAdd]
	
	@rXmlDoc nvarchar(MAX),
	@rClassId int,
	@rDivisionId int,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rFeeSetupId int,
	@rCreatedUserId bigint,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lInterrorCode INT,
			@intDoc INT
	--BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	IF(@rFeeSetupId=0 AND @rClassId=0 AND @rSourceTypeId!=0 AND @rSourceId!=0)
	BEGIN
		DELETE FROM sFee.tFeeAllocation WHERE SourceTypeId=@rSourceTypeId AND SourceId=@rSourceId
	END
	ELSE IF(@rFeeSetupId!=0 AND @rClassId!=0 AND @rSourceTypeId=0 AND @rSourceId=0)
	BEGIN
		DELETE sFee.tFeeAllocation FROM sFee.tFeeAllocation FA
		INNER JOIN (
			SELECT
			SourceTypeId,
			SourceId,
			FeeSetupId
			 
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId'
		 
	) )TEMP ON Temp.SourceId=FA.SourceId AND Temp.SourceTypeId=FA.SourceTypeId AND FA.FeeSetupId = Temp.FeeSetupId AND FA.FeeSetupId=@rFeeSetupId
		--)
		--INNER JOIN 
		--(
		--	SELECT
		--			2001 AS SourceTypeId,
		--			AcademicId 
		--	FROM 
		--			sStudent.vStudentAcademic WHERE ClassId=@rClassId AND DivisionId=@rDivisionId
		--) Temp ON Temp.AcademicId=FA.SourceId AND Temp.SourceTypeId=FA.SourceTypeId AND FeeSetupId=@rFeeSetupId
	END
	
	INSERT INTO sFee.tFeeAllocation
		(
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			NotApplicableAmount,
			AdditionalAmount,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark
		)
	SELECT
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			NotApplicableAmount,
			AdditionalAmount,
			Remark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark	
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId',
		VariableAmount decimal(12,2) '@VariableAmount',
		DiscountAmount decimal(12,2) '@DiscountAmount',
		NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
		AdditionalAmount decimal(12,2) '@AdditionalAmount',
		Remark nvarchar(200) '@Remark',
		DiscountRemark nvarchar(200) '@DiscountRemark',
		AdditionalRemark nvarchar(200) '@AdditionalRemark',
		NotApplicableRemark nvarchar(200) '@NotApplicableRemark'
	) 
		  
   DELETE FROM  sFee.tFeeAllocation WHERE ISNULL(VariableAmount,0) = 0 AND ISNULL(DiscountAmount,0) = 0 AND ISNULL(AdditionalAmount,0) = 0 AND ISNULL(NotApplicableAmount,0) = 0 AND ISNULL(Remark,'') = '' -- Add Remark condition for mantis Id : 0034345
   
   EXEC [sFee].[pFeeProcessGenerateFeeAllocationAdd] @rXmlDoc,@rOrgId,@rCreatedUserId

   SELECT 1 AS Result 
	
 --   UPDATE sFee.tFeeAllocation
 --   SET
	--	VariableAmount=Temp.VariableAmount,
	--	DiscountAmount=Temp.DiscountAmount,
	--	NotApplicableAmount=Temp.NotApplicableAmount,
	--	AdditionalAmount=Temp.AdditionalAmount,
	--	Remark=Temp.Remark,
	--	UpdatedUserId=@rCreatedUserId,
	--	UpdatedDateTime=sCommon.fGetDate() 
	--FROM sFee.tFeeAllocation FA 
	--INNER JOIN 
	--(SELECT
	--		SourceTypeId,
	--		SourceId,
	--		FeeSetupId,
	--		VariableAmount,
	--		DiscountAmount,
	--		NotApplicableAmount,
	--		AdditionalAmount,
	--		Remark
		
	--FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	--WITH
	--(
	--	SourceTypeId smallint '@SourceTypeId',
	--	SourceId bigint '@SourceId',
	--	FeeSetupId int '@FeeSetupId',
	--	VariableAmount decimal(12,2) '@VariableAmount',
	--	DiscountAmount decimal(12,2) '@DiscountAmount',
	--	NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
	--	AdditionalAmount decimal(12,2) '@AdditionalAmount',
	--	Remark nvarchar(200) '@Remark',
	--	IsRecordExist bit '@IsRecordExist'
	--) 
	--WHERE IsRecordExist=1) Temp ON Temp.SourceTypeId=FA.SourceTypeId 
	--	AND Temp.SourceId=FA.SourceId
	--	AND Temp.FeeSetupId=FA.FeeSetupId
 	 
	--	SELECT 11 AS Result    
		
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
PRINT N'Altering Procedure [sFee].[pFeePostingGet]...';


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

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

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


GO

ALTER PROC [sFee].[pRptDepositStudentLedgerGet]

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


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

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

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

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

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

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

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


GO

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

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	

DECLARE @lReceiptId bigint
CREATE TABLE #tmp
(
	Id int IDENTITY,
	ReceiptId bigint
)

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

SELECT @lCountReceiptId=COUNT(Id) FROM #tmp
SELECT Top 1 @lId=Id FROM #tmp
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	Declare @lIDConfigValue nvarchar(50)='',@lOrgGroup_Id int=0
	Select @lOrgGroup_Id = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	 
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId


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

WHILE @lId <= @lCountReceiptId
	BEGIN

	SELECT @lReceiptId = ReceiptId FROM #tmp WHERE Id = @lId
	
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @lReceiptId

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

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

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

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

	SET @lId=@lId+1
	END


	Select * from #ReceiptDetail
	DROP TABLE #tmp
	DROP TABLE #ReceiptDetail
END

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

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

GO

ALTER PROCEDURE [sHrm].[pEmployeeAttendanceAPIGet]
	 	 
	 	  @rForMonth smallint = 0,
	      @rForYear smallint = 0,
	      @rEmployeeId bigint = 0,	      
	      @rBatchId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	Select 
	 
	        CAST(DAY(ER.AttendanceDate) AS NVARCHAR) AS DayNo,
			
			CASE  
			      WHEN ER.IsPresent = 1  THEN 'P' 
				  WHEN ER.IsPresent = 0 THEN 'A'
				  ELSE  '' END AS  Presence,			
			OM.WeekOffs,
			ISNULL(CAST([sHrm].[fEmployeeHolidayDatesList](EM.Id, ISNULL(EJD.OrganizationDepartmentId,0), @rForYear,@rForMonth,@rBatchId, EM.OrgID) AS NVARCHAR),'')  As Holidays,--Changed by Nilesh for mantis : 34328
			CAST((SELECT COUNT(IsPresent) FROM sHrm.tEmployeeAttendanceRegister ER WHERE EmployeeId = @rEmployeeId AND IsPresent = 1 AND AttendanceDate <= GETDATE()) AS NVARCHAR) AS UptoPresentCount,
			CAST((SELECT COUNT(IsPresent) FROM sHrm.tEmployeeAttendanceRegister ER WHERE EmployeeId = @rEmployeeId AND AttendanceDate <= GETDATE()) AS NVARCHAR) AS TotalCount
	From  
			sHrm.tEmployeeMaster EM
            INNER JOIN sHrm.tEmployeeAttendanceRegister ER ON ER.EmployeeId=EM.Id
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			LEFT JOIN  sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	
	WHERE			
		EM.Id=@rEmployeeId
		AND YEAR(ER.AttendanceDate)=@rForYear
		AND MONTH(ER.AttendanceDate)=@rForMonth
		AND ER.BatchId=@rBatchId
		
		ORDER BY DayNo ASC
	
END
GO
PRINT N'Altering Procedure [sLibrary].[pRptBookLogRegisterGet]...';


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

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


END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockIssueReturnRegisterGet]...';


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

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

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

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




/****** Object:  StoredProcedure [sProcurement].[pRptStockItemMaxInventory]    Script Date: 07/09/2013 16:27:32 ******/
SET ANSI_NULLS ON
GO
PRINT N'Altering Procedure [sSecurity].[pAppPermissionGet]...';


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

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


GO

ALTER PROCEDURE [sSecurity].[pMenu_Migration]    
 @rUserId [bigint],    
 @rMenuId int = 0,    
 @rResourceTypeId int= 0,    
 @rIsCoreMenu bit = 0,
 @rEnvironmentName nvarchar(max) ,
 @rScreenGroupId int = 0     
      
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
    
BEGIN    
 IF(@rIsCoreMenu=0)    
 BEGIN    
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)    
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
    PageURL  AS PagePath,    
    IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermissionUser P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
       WHERE    
        T.IsObsolete = 0 AND P.UserId = @rUserId    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 ELSE     
  BEGIN    
   SELECT    
    MenuID,    
    ModuleId,    
    ParentMenuID,    
    MenuTitle,      
    ScreenTitle,       
    PageURL,    
    ScreenId,    
    Permission,    
    OrderNumber,      
    TaskId,      
     PageURL  AS PagePath,    
     IconPath    
        
   FROM    
     (SELECT Menu.Id AS MenuID,     
    ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
    Menu.Title AS MenuTitle,       
    ISNULL(Screen.Title, '') AS ScreenTitle,        
    ISNULL(Screen.Page, '') AS PageURL,    
    ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
    ISNULL(Menu.ScreenId, 0) AS ScreenId,    
    ISNULL(PermissionValue, 0) AS Permission,    
    ISNULL(OrderNumber, 0) AS OrderNumber,    
    ISNULL(Screen.TaskId,0) AS TaskId,    
    ISNULL(Screen.IconPath,'') As IconPath,     
    ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
    ISNULL(T.ModuleId,0) AS ModuleId    
       
       
   FROM sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen    
    ON Menu.ScreenId = Screen.Id      
   LEFT OUTER JOIN (     
       SELECT     
        TaskId,     
        SUM(Permission & 2) PermissionValue          
       FROM     
        sSecurity.tPermission P    
        INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId    
        --INNER JOIN sSecuirty.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = P.OrgGroupId     
        INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgGroupId = P.OrgGroupId    
        INNER JOIN    
        (    
        SELECT RoleId FROM sSecurity.tUserRole UR WHERE  UserId = @rUserId AND IsObsolete = 0    
        ) B ON B.RoleId = P.RoleId    
       WHERE    
        T.IsObsolete = 0    
       GROUP BY     
        TaskId) TBL2    
       ON     
        Screen.TaskId = TBL2.TaskId     
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
          
       WHERE     
       (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page    
       AND ISNULL(Screen.IsObsolete, 0) = 0)     
       MenuTable      
       --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId     
   WHERE     
    MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2     
    AND     
    ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))    
    AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))    
        
   ORDER BY     
    ParentMenuID    
  END    
 END    
 ELSE    
 BEGIN     
 if (@rScreenGroupId = 0)
 BEGIN
  SELECT    
   MenuID,    
   ModuleId,    
   ParentMenuID,    
   MenuTitle,      
   ScreenTitle,       
   PageURL,    
   ScreenId,    
   Permission,    
   OrderNumber,      
   TaskId,      
   PageURL AS PagePath,    
   MenuIsObsolete,    
   Icon      
  FROM    
  (    
	SELECT    
   ISNULL(Menu.Id,0) AS MenuID,     
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,     
   ISNULL(Menu.Title,'') AS MenuTitle,       
   ISNULL(Screen.Title, '') AS ScreenTitle,        
   ISNULL(Screen.Page, '') AS PageURL,    
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Menu.ScreenId, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen.IconPath,'') AS Icon    
  FROM     
  sSecurity.tMenu Menu     
  LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
  LEFT OUTER JOIN     
  (    
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId  AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId      
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id        
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId     
  GROUP BY P.TaskId    
  ) TBL2 ON Screen.TaskId = TBL2.TaskId     
  LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId    
  WHERE (Menu.IsObsolete = 0)    
  AND ISNULL(Screen.IsObsolete, 0) = 0    
  AND (
		(@rEnvironmentName = 'Local' AND Menu.Id in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511)) -- updated by parth for showing more menu inside the communication 07-02-2023 
	OR (@rEnvironmentName = 'QA' AND Menu.Id in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511))
	OR (@rEnvironmentName = 'LiveEnvironment' 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))
	)
	
  --AND Menu.Id  in (24,2711,2411)  -- Issue: For Only Student Center, My Communication Menu , Developer: Foram, Date: 15-07-2022
  --AND (Menu.Id  in (24,2711)   
  --Or ParentMenuID  in (24,2711))     
  --AND (Menu.Id IN (15, 32, 55,24, 19181042, 36, 3606,2714)  
  --OR ParentMenuID IN (15, 32, 55, 19181042, 36, 24, 18))  
  UNION    
       
  SELECT     
  
   ISNULL(Menu.Id, 0) AS MenuID,     
   ISNULL(Menu.Id, 0) AS ParentMenuID,     
   ISNULL(Screen1.Title,'') AS MenuTitle,       
   ISNULL(Screen1.Title, '') AS ScreenTitle,        
   ISNULL(Screen1.Page, '')  AS PageURL,    
   ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,    
   ISNULL(Menu.ScreenId, 0) AS ScreenId,    
   ISNULL(PermissionValue, 0) AS Permission,    
   ISNULL(OrderNumber, 0) AS OrderNumber,    
   ISNULL(Screen1.TaskId,0) AS TaskId,    
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,    
   ISNULL(T.ModuleId,0) AS ModuleId,    
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,    
   ISNULL(Screen1.IconPath,'') AS Icon    
  FROM     
   sSecurity.tMenu Menu     
   LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id        
   LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId     
   LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId   
   LEFT OUTER JOIN (     
  SELECT     
   P.TaskId,     
   SUM(OT.AvailablePermission & 2) PermissionValue          
  FROM     
   sSecurity.tPermission P    
   INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId   AND T.IsObsolete = 0  
   INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId        
   INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0    
   INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id       
   INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId    
            
  GROUP BY P.TaskId    
  ) TBL2 ON Screen1.TaskId = TBL2.TaskId    
  WHERE (Menu.IsObsolete = 0) 
  AND ISNULL(Screen1.IsObsolete, 0) = 0   
  --AND (Menu.ParentMenuID  in (24,2711)   
  --or Menu.Id  in (24,2711))   
  AND Screen1.Id IN (10187,30363,30342,20241,30282,20565,20563,30377,20915,30331,20564,20180,20617,30364,20130,30818,30828,20191,30787,20996,20193,20717  -- Issue: For Only Student Center Menu , Developer: Foram, Date: 15-07-2022  
		,9137,20054,20085,20088,20093,20099,20104,20107,20172,20198,20204,20209,20222,20566,20577,20692,20723,20724,30228,30242,30254,30365,30556,30559,30585,30794,30858,30943,31175,30921,20103,20102,20223,30561, -- Issue: For Only My Communication Menu , Developer: Foram, Date: 20-07-2022  
		30857,30696,30739,30284,20171,20105,31048,9136,30678,20179,30793,20720,20115,20693,20086,20819,20126,20950,20094,30856,30855,30795,30789,20697,20758,20083,30245,30246,20125,30874,30274,30817,30251,30252,30253,30247,30395, -- this line for communication screen changes by parth
		20983,30071,30103,30859,30935,30602,30848,30362,20181,20246,20576,20916,20979,30020,30093,30106,30115,30124,30134,30139,30149,30257,30327,30788,30455,30344,31005, -- this line for employee center screen changes by parth
		20108,30298,30552,20025,20026,20068,20336,20551,20719,20866,20894,20899,20900,3009530203,30296,30701,30816,30962, -- this line for fees screen changes by parth
		20396,20630,30138,30548,31012,20075,20161,20163,20167,20654,20985,30974,30994,20388,20073,20074,20165, -- this line for atte screen changes by parth
		20766,20927,20555,30366,20622,30651,30515,20554,20561,20159, 30664, -- this line is use for academic module
		30236,30500,30600,30604,31188,31182,30797,30471,30456,30411,30412,30409,30410,30447,30449,20949,20197,20056,20952,20059,20150,20153, --17/05/2023
		20951,20679,20233,31016,20124,30007,20120,20123,20375,20676,20986,20376,20122,30544,20194,30777,30193,30041,20131,20132,20133,20134,20374,20135,20136,20137,30381,30382,20677,20199,30292,20121,20413,31013,10160,20676,30390,30391,
		30100,30102,30105,30110,30107,30108,30113,
		31224,20930,20932,30936,30951,20284,20696,20698,20700,20776,20918,30164,30579,20570,20567,20568,20173,20174,
		20187,20188,20189,30059,30034,
		20325,20379,20380,20631,20235,20043)
  --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)) -- updated by parth for showing more menu inside the communication 07-02-2023 
	OR (@rEnvironmentName = 'QA' AND MenuTable.MenuId in(24,2711,2411,2714,55,2412,53,52,5515,19181022,19184006,2622,15,5524,552417,22,23,19181046,57,5535,5511))
	OR (@rEnvironmentName = 'LiveEnvironment' 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))
	)
  --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 [sSetup].[pBulkMasterDataUpdateGet]...';


GO
ALTER PROCEDURE [sSetup].[pBulkMasterDataUpdateGet]
	 
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rOrgGroupId int,
	 @rIsBlank int=0,
	 @rOrgGroupBatchId int = 0

AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory --and Id=@rCategoryId
		
		IF(@rSubCategory = 'InchargeEmployee')
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory ,'InchargeEmployee','InchargeEmployeeId')			
		END 
		
		IF(@rSubCategory = 'DisplayTitle' AND @rCategoryId=9)
		BEGIN
		SET @rSubCategory = Replace(@rSubCategory ,'DisplayTitle','ExamSubGroupDisplayTitle	')
		END
		
		 Declare @Sql nvarchar(max)
		
		 SET @Sql =  CASE @rCategoryId	
		 				  
					 WHEN 1 THEN -- Organization
						'Select OM.Id,OM.Code,OM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(OM.'+@rSubCategory+','''') 
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(OM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(OM.'+@rSubCategory+',''False'') 
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(OM.'+@rSubCategory+',''0001/01/01'') 
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(OM.'+@rSubCategory+',''0'') 
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sSetup.tOrganizationMaster OM where OM.OrgGroupId='+CAST(@rOrgGroupId AS nvarchar(15))+'							
							 AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(OM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(OM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(OM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(OM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
							
					 WHEN 2 THEN -- Class
						'Select CM.Id,CM.Code,CM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(CM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(CM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(CM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						CM.'+@rSubCategory+'
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(CM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sSetup.tClassMaster CM where CM.OrgId='+CAST(@rOrgId AS nvarchar(15))+'	 						
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(CM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(CM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(CM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(CM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
							
					WHEN 3 THEN -- Division
						'Select DM.Id,DM.Code,DM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(DM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(DM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(DM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(DM.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(DM.'+@rSubCategory+',''0'')
						--END AS OrderIndex 
						END AS SubCategory
							FROM 
							sSetup.tDivisionMaster DM where DM.OrgId='+CAST(@rOrgId AS nvarchar(15))+'							
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(DM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(DM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(DM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(DM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
					 
					WHEN 4 THEN --SubjectMaster
					   'Select SM.Id,SM.Code,SM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SM.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sSetup.tSubjectMaster SM where SM.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
				   
					WHEN 5 THEN --tOrgGroupBatchMaster
					   'Select OGM.Id,OGM.Code,OGM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(OGM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(OGM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(OGM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(OGM.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(OGM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sSetup.tOrgGroupBatchMaster OGM	where OGM.OrgGroupId='+CAST(@rOrgGroupId AS nvarchar(15))+'						
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(OGM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(OGM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(OGM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(OGM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
					WHEN 6 THEN --BatchMaster
					   'Select BM.Id,BM.Code,BM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(BM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(BM.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(BM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(BM.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''=''RepeatCount'' THEN
						ISNULL(BM.'+@rSubCategory+',''1'')
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''<>''RepeatCount'' THEN
						ISNULL(BM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sSetup.tBatchMaster BM where BM.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(BM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(BM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(BM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(BM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
							
					WHEN 7 THEN --DepartmentMaster
					   'Select DM.Id,DM.Code,DM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(DM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(DM.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(DM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(DM.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''=''RepeatCount'' THEN
						ISNULL(DM.'+@rSubCategory+',''1'')
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''<>''RepeatCount'' THEN
						ISNULL(DM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sSetup.tDepartmentMaster DM where DM.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(DM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(DM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(DM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(DM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
							
					WHEN 8 THEN --OrgGroupDepartmentMaster
					   'Select GDM.Id,GDM.Code,GDM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(GDM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(GDM.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(GDM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(GDM.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''=''RepeatCount'' THEN
						ISNULL(GDM.'+@rSubCategory+',''1'')
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''<>''RepeatCount'' THEN
						ISNULL(GDM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sCommon.tOrgGroupDepartmentMaster GDM where GDM.OrgGroupId='+CAST(@rOrgGroupId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(GDM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(GDM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(GDM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(GDM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
						WHEN 9 THEN --ExamSubGroup
					   'Select ESGM.Id,ESGM.Code,ESGM.Title,ESGM.ExamSubGroupDisplayTitle AS Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(ESGM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(ESGM.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(ESGM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(ESGM.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''=''RepeatCount'' THEN
						ISNULL(ESGM.'+@rSubCategory+',''1'')
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''<>''RepeatCount'' THEN
						ISNULL(ESGM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sAssessment.tExamSubGroupMaster ESGM where ESGM.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(ESGM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(ESGM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(ESGM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(ESGM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory
							 '
							WHEN 10 THEN --ReligionMaster
					   'Select GDM.Id,GDM.Code,GDM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(GDM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(GDM.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(GDM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(GDM.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''=''RepeatCount'' THEN
						ISNULL(GDM.'+@rSubCategory+',''1'')
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''<>''RepeatCount'' THEN
						ISNULL(GDM.'+@rSubCategory+',''0'')
						--END AS OrderIndex
						END AS SubCategory
							FROM 
							sCommon.tReligionMaster GDM where GDM.OrgGroupId='+CAST(@rOrgGroupId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(GDM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(GDM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(GDM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(GDM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory'

					WHEN 11 THEN --Topic
					   'Select TM.Id,TM.Title AS Code,TM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(TM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(TM.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(TM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(TM.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(TM.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sAcademic.tTopicMaster TM where TM.OrgId='+CAST(@rOrgId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(TM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(TM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(TM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(TM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory'


						WHEN 12 THEN --CollectionGroup
					   'Select CGM.Id,RBM.Title AS Code,CGM.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(CGM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(CGM.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(CGM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(CGM.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(CGM.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sFee.tCollectionGroupMaster CGM 
							INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=CGM.ReceiptBookId 
							where CGM.OrgGroupBatchId='+CAST(@rOrgGroupBatchId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(CGM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(CGM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(CGM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(CGM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) order by SubCategory'
							 
					END		
					
					
			
	
			EXECUTE  sp_executesql @Sql
			Print @Sql
	   
END
GO
PRINT N'Altering Procedure [sSetup].[pMastedDataModify]...';


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

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'InchargeEmployee') 	
		SET @rSubCategoryField = @rSubCategoryField + 'Id'	
		
	IF(@rSubCategoryField = 'DisplayTitle' AND @rCategoryId = 9) 	
		SET @rSubCategoryField = 'ExamSubGroupDisplayTitle'
	
	
	IF OBJECT_ID('ListofData') IS NOT NULL	
			DROP TABLE ListofData
		
	CREATE TABLE ListofData(Id int,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)  
		BEGIN
		
		insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
						
		select *from ListofData				
		UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tOrganizationMaster ) 
		
		set @sql='INSERT INTO sSetup.tOrganizationMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tOrganizationMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tOrganizationMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
	else IF(@rCategoryId= 2)     
	 
	 BEGIN
	 
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tClassMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tClassMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tClassMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tClassMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  END
	  
	  
	  else IF(@rCategoryId= 3)
	  BEGIN
	     
	     insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tDivisionMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tDivisionMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tDivisionMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tDivisionMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		--print @sql
		--return
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    
	  
	  END    
	  
	  else IF(@rCategoryId= 4)
	  BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tSubjectMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tSubjectMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tSubjectMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tSubjectMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  
	  END 
	    
	 else IF(@rCategoryId= 5)
	 
	 BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tOrgGroupBatchMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tOrgGroupBatchMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tOrgGroupBatchMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tOrgGroupBatchMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  
	  END 
	  
   else IF(@rCategoryId= 6)
	 BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tBatchMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tBatchMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tBatchMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tBatchMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	  
	else IF(@rCategoryId= 7)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tDepartmentMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tDepartmentMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tDepartmentMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tDepartmentMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	  
	  
 else IF(@rCategoryId= 8)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sCommon.tOrgGroupDepartmentMaster ) 
	    
	    set @sql='INSERT INTO sCommon.tOrgGroupDepartmentMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sCommon.tOrgGroupDepartmentMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sCommon.tOrgGroupDepartmentMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	    
	   else IF(@rCategoryId= 9)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sAssessment.tExamSubGroupMaster ) 
	    
	    set @sql='INSERT INTO sAssessment.tExamSubGroupMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sAssessment.tExamSubGroupMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sAssessment.tExamSubGroupMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 

	   else IF(@rCategoryId= 10)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sCommon.tReligionMaster ) 
	    

	    set @sql='INSERT INTO sCommon.tReligionMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sCommon.tReligionMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sCommon.tReligionMaster RM 
					INNER JOIN ListofData LD ON RM.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	    
	else IF(@rCategoryId= 11)
	 BEGIN
	  insert into ListofData
		select E.Id,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sAcademic.tTopicMaster) 
	    

	    set @sql='INSERT INTO sAcademic.tTopicMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sAcademic.tTopicMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sAcademic.tTopicMaster TM 
					INNER JOIN ListofData LD ON TM.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	 else IF(@rCategoryId= 12)
	 BEGIN
	  insert into ListofData
		select E.Id,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sFee.tCollectionGroupMaster) 
	    Select * from ListofData

	    set @sql='INSERT INTO sFee.tCollectionGroupMaster
					(Id,'+@rSubCategoryField+')
					SELECT
						LD.Id,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		--print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sFee.tCollectionGroupMaster set '+@rSubCategoryField+' = LD.SubCategory
					from sFee.tCollectionGroupMaster TM 
					INNER JOIN ListofData LD ON TM.Id=LD.Id AND IsExist=0'
		
		--print @sql
		Exec sp_executesql @sql
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END	
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
GO
PRINT N'Altering Procedure [sTimetable].[pRptDivisionTimeTableGet]...';


GO
ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


GO
ALTER PROCEDURE [sTransport].[pRptBuswiseCapacityUtilizationListGet]
	 
	 @rOrgGroupBatchId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rRouteId int=0,
	 @rVehicleId int=0,
	 @rTransportId int =0
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BRM.Id AS BusRouteId,
			BRM.Title AS BusRoute,
			BRM.OrderIndex AS RouteOrder,
			VM.Id AS VehicleId,
			VM.Title AS Vehicle,
			VM.NoOfSeats,
			ISNULL(VM.RegistrationNumber,'') AS RegistrationNumber,
			(SELECT COUNT(1) FROM sTransport.tAssignRoute AR INNER JOIN sTransport.tBusRouteDestinationMaster DM
			 ON AR.PickupDestinationId = DM.Id AND DM.BusRouteId = BRM.Id 
			 INNER JOIN sStudent.tStudentMaster SM ON AR.SourceId = SM.Id AND AR.SourceTypeId = 2003 where SM.StatusId = 1) AS SeatAllocated  -- MantisID : 0034343
	FROM 
		 sTransport.tBusRouteMaster BRM 
		 INNER JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
			
	WHERE 
			(BRM.OrgGroupBatchId=@rOrgGroupBatchId)
			AND 
			((BRM.Id=@rRouteId) OR (@rRouteId=0))
			AND ((VM.Id=@rVehicleId) OR (@rVehicleId=0))
			AND ((VM.TransportId=@rTransportId) OR (@rTransportId=0))
	END
GO
PRINT N'Creating Procedure [sAdmission].[pAdmissionFormFeeReceiptAdd]...';


GO
CREATE PROCEDURE [sAdmission].[pAdmissionFormFeeReceiptAdd]
	
			@rOrgId smallint,
			@rSourceTypeId smallint,
			@rSourceId bigint,
			--@rReceiptDate date,
			@rReceiptAmount decimal(12,2),
			@rPayTypeId smallint,
			@rBatchId int,
			@rBankName nvarchar(100)='',
			@rChequeNo nvarchar(40)='',
			@rChequeDate date=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
	
	DECLARE @lNextNumber BIGINT=0
	DECLARE @lReceiptNumber int=0
	
	IF NOT EXISTS(SELECT 1 FROM sAdmission.tAdmissionFormReceipt WHERE SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId)
	BEGIN
	
	--SELECT @lReceiptNumber = COUNT(ISNULL(Id,0)) + 1 FROM sAdmission.tAdmissionFormReceipt WHERE BatchId=@rBatchId
	SELECT @lReceiptNumber = MAX(ReceiptNumber) + 1 FROM sAdmission.tAdmissionFormReceipt WHERE BatchId=@rBatchId
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionFormReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAdmission.tAdmissionFormReceipt
		(
			Id,
			SourceTypeId,
			SourceId,
			ReceiptNumber,
			ReceiptDate,
			ReceiptAmount,
			PayTypeId,
			ChequeNo,
			BankName,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			ChequeDate
		)
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
			@lReceiptNumber,
			sCommon.fGetDate(),
			@rReceiptAmount,
			@rPayTypeId,
			@rChequeNo,
			@rBankName,
			@rBatchId,
			0,
			sCommon.fGetDate(),
			0,
			sCommon.fGetDate(),
			@rChequeDate
		)

	SELECT @lNextNumber AS Result
	
	END
	
	--SELECT 0 AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating Procedure [sAssessment].[pRptResultSheetCoScholasticSubCombineNewGet]...';


GO


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

BEGIN 

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


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

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

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

	SELECT
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,
		Convert(nvarchar(20),@rBatchId) AS   BatchIdText,
		@rAcademicId AS AcademicId,
		@rExamId AS ExamId,
		cceCSM.Title AS CoSubject,
		cceCSGM.Title AS CoSubjectGroup,
		cceCSGM.OrderIndex AS CoSubjectGroupOrder,
		cceCSM.OrderIndex AS CoSubjectOrder,
		Convert(nvarchar(20), @rCoScholasticScopeId ) AS CoScholasticScopeIdText,
		@lIsCoScholasticGrade AS IsCoScholasticGrade,
		@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
		@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
		ISNULL(@lCoScholasticTitle,'') AS CoScholasticTitle,
		cceCST.Id AS GroupTypeId,
		cceCST.Title AS GroupType
	FROM 
		sAssessment.tCCECSMaster cceCSM
		INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
		INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
		INNER JOIN sStudent.tAcademic A ON A.Id = @rAcademicId
		INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
		INNER JOIN sAssessment.tCCECSForClass FC ON FC.ClassId = A.ClassId AND cceCSM.Id = FC.CCECSId 
		LEFT JOIN sAssessment.tOptionalCCECS OCS ON OCS.AcademicId = A.Id AND OCS.CCECSId = cceCSM.Id


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

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

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

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

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

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

		SET @lCount = @lCount - 1
	END

	SELECT * FROM #CoScholasticTempTable


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

END
GO
PRINT N'Creating Procedure [sFee].[pRptPDCStatusWiseDetails]...';

GO
 
CREATE PROCEDURE [sFee].[pRptPDCStatusWiseDetails]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	WITH CTE AS (
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status,
			SC.ParentContactNo,
			--ISNULL(PDP.Amount,0) As PDCEntryAmount,
			ISNULL(sFee.fnGetSumByReceiptBookWise(SA.AcademicId,SA.BatchId,FS.ReceiptBookId),0) AS PDCEntryAmount,
			ROW_NUMBER() OVER (PARTITION BY SA.AcademicId, FS.ReceiptBookId ORDER BY (SELECT NULL)) AS rn

	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN sStudent.tStudentCommunication SC ON  SC.StudentId=SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			--LEFT JOIN  sFee.tPostDatePayment PDP ON PDP.SourceId = SA.AcademicId AND PDP.SourceTypeId = 2001 AND FS.ReceiptBookId = PDP.ReceiptBookId AND SA.BatchId = PDP.BatchId--MAntis - 0034487

			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		
		)

		SELECT
			Builder1,
			Builder2,
			IsDetail,
			IsFilter,
			IsHeader, 
			IsDisplayOrgGroup,
			AcademicId,
			RollNo,
			Name,
			Code,
			ClassId,
			DivisionId,
			ClassName,
			DivisionName,
			DivisionOrderIndex,
			ClassOrderIndex,
			ClassDivision,
			FeeSetupId,
			IsVariable,
			Amount,
			StartDate,
			EndDate,
			FAAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			PaidAmount,
			PendingAmount,
			Remark,
			ReceiptBookId,
			FeeName,
			FeeCode,
			FeeOrderIndex,
			OrgId,
			OrgName,
			OrgOrderIndex,
			ReceiptBookTitle,
			ReceiptOrderIndex,
			DepartmentId,
			DepartmentName,
			ExemptionTypeId,
			ExemptionType,
			FeeHeadId,
			FeeHeadName,
			FeeHeadOrderIndex,
			FeeGroup,
			BatchId,
			BatchName,
			CancelAmount,
			Discount,
			Status,
			ParentContactNo,
			CASE
				WHEN rn = 1 THEN PDCEntryAmount
				ELSE 0
			END AS PDCEntryAmount
		FROM
			CTE
			Order by  FeeHeadOrderIndex,FeeOrderIndex,RollNo
	
END
GO
PRINT N'Creating Procedure [sHostel].[pRptRoomwiseEmployeeListGet]...';
GO

CREATE PROCEDURE [sHostel].[pRptRoomwiseEmployeeListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rRoomId int=0,
	 --@rEmployeeName nvarchar(100)='',
	 @rEmployeeCode nvarchar(100)='',
	 @rDepartmentId int=0,
	 @rFromAllocateDate date='',
	 @rToAllocateDate Date=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 

	SELECT
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
       'Employee' AS SourceType,
		95 AS SourceTypeId,
		ISNULL(EM.Id,0) as SourceId,
		EM.Code as SourceCode,
		EM.FirstName+' '+EM.LastName as SourceName,
		OM.DisplayTitle AS OrganizatinName,
		ODM.Title as DepartmentName,
		EC.MobileNumber,
	    OM.Id AS OrgId,
	    '' AS SUId,
	    '' AS City,	   
	    [sHostel].[fAssignRoomEmployeeAssetGet](@rHostelId ,@rRoomId,AR.SourceId ) AS AssetNumber,
	    RM.Id AS RoomId,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		RM.Title AS Room,		
		HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
	   (SELECT sum(Total) FROM(SELECT Max(StudentsPerRoom) AS Total FROM sHostel.tRoomMaster RM 
		LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=95   AND  AR.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON AR.SourceId=EM.Id 
		WHERE ((RM.HostelId=@rHostelId) OR (@rHostelId=0)) AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		Group By RM.Id)A) AS TotalStudentPerRoom
		
	FROM sHostel.tRoomMaster RM 
		LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=95  AND  AR.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON AR.SourceId=EM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
		LEFT JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
		LEFT JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
		LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=95 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
	WHERE 
		(HAM.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((EM.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((RM.HostelId=@rHostelId) OR (@rHostelId=0))
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((EM.Code Like @rEmployeeCode) OR (ISNULL(@rEmployeeCode,'')=''))
		AND ((ODM.Id = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
	
	END
GO
PRINT N'Creating Procedure [sHrm].[pEmployeeCustomFieldUpdate]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeCustomFieldUpdate]
		 
	@rId int,
	@rOrgId int,
	--@rFieldTitle nvarchar(500),
	--@rFieldTypeId tinyint,
	--@rFieldList nvarchar(500),
	@rIsFieldMandatory bit,
	--@rFieldGroup nvarchar(200),
	@rFieldOrder smallint,
	--@rCreatedUserId bigint,	
	--@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rIsObsolete int =0
	--@rDataTypeId int = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		BEGIN TRANSACTION	

			DECLARE @lOrgGroupId int=0
			SELECT @lOrgGroupId= OrgGroupId FROM sSetup.tOrganizationMAster WHERE Id = @rOrgId
 
			--IF(@rId = 0)	
			--BEGIN
				--IF NOT EXISTS(SELECT 2 FROM sHrm.tEmployeeCustomFieldMaster WHERE FieldTitle=@rFieldTitle AND FieldGroup=@rFieldGroup AND DataId=@rDataTypeId AND OrgGroupId=@lOrgGroupId)
				----IF NOT EXISTS(SELECT 2 FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle=@rFieldTitle)
				--BEGIN
	      --DECLARE @lNextNumber int
--	      EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
--Print @lNextNumber
--	      INSERT INTO sHrm.tEmployeeCustomFieldMaster
--	      (
--		    Id
--		   ,FieldTitle
--		   ,FieldTypeId
--		   ,FieldList
--		   ,IsFieldMandatory
--		   ,FieldGroup
--		   ,FieldOrder
--		   ,CreatedUserId
--		   ,CreatedDateTime
--		   ,OrgGroupId
--		   ,IsObsolete
--		   ,DataId
--	      )
--	     VALUES
--	     (
--		   @lNextNumber
--		  ,@rFieldTitle
--		  ,@rFieldTypeId
--		  ,@rFieldList
--		  ,@rIsFieldMandatory
--		  ,@rFieldGroup
--		  ,@rFieldOrder
--		  ,@rCreatedUserId
--		  ,@rCreatedDateTime
--		  ,@lOrgGroupId
--		  ,@rIsObsolete
--		  ,@rDataTypeId
--	     )
--     END
--	 ELSE
--	 SELECT -101 As RESULT
--END
	 	 
--ELSE
--BEGIN
	--SET @lNextNumber = @rId

	
	
			UPDATE sHrm.tEmployeeCustomFieldMaster
			SET 
				--FieldTitle = @rFieldTitle
				--,FieldTypeId = @rFieldTypeId
				--,FieldList=@rFieldList
				IsFieldMandatory=@rIsFieldMandatory
				,IsObsolete=@rIsObsolete
				--,FieldGroup=@rFieldGroup
				,FieldOrder=@rFieldOrder
				,UpdatedUserId=@rUpdatedUserId
				,UpdatedDateTime=@rUpdatedDateTime
				--,DataId = @rDataTypeId
			WHERE Id = @rId 
	
	
--END  
			SELECT @rId AS Result
	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating Procedure [sHrm].[pNewEmployeeCustomFieldAdd]...';


GO
CREATE PROCEDURE [sHrm].[pNewEmployeeCustomFieldAdd]
		 
	--@rId int,
	@rOrgId int,
	@rFieldTitle nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	--@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	--@rFieldOrder smallint,
	@rCreatedUserId bigint,	
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	--@rIsObsolete int =0,
	@rDataTypeId int = 1,
	@rCustomFieldMasterId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		BEGIN TRANSACTION	

			DECLARE @lOrgGroupId int=0, @lIsEmployee bit = 0
			SELECT @lOrgGroupId= OrgGroupId FROM sSetup.tOrganizationMAster WHERE Id = @rOrgId
			select @lIsEmployee = IsEmployee From sSetup.tCustomFieldMaster WHERE FieldTitle=@rFieldTitle AND FieldGroup=@rFieldGroup AND DataId=@rDataTypeId AND OrgGroupId=@lOrgGroupId
 
			IF(@lIsEmployee=1)	
			BEGIN
				IF NOT EXISTS(SELECT 2 FROM sHrm.tEmployeeCustomFieldMaster WHERE CustomFieldMasterId=@rCustomFieldMasterId)
				BEGIN
					DECLARE @lNextNumber int
					EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
					Print @lNextNumber
					INSERT INTO sHrm.tEmployeeCustomFieldMaster
					(
						Id
					   ,FieldTitle
					   ,FieldTypeId
					   ,FieldList
					   ,IsFieldMandatory
					   ,FieldGroup
					   ,FieldOrder
					   ,CreatedUserId
					   ,CreatedDateTime
					   ,OrgGroupId
					   ,IsObsolete
					   ,DataId
					   ,CustomFieldMasterId		--add for mantis: 32799
					)
					VALUES
					(
					   @lNextNumber
					  ,@rFieldTitle
					  ,@rFieldTypeId
					  ,@rFieldList
					  ,0
					  ,@rFieldGroup
					  ,0
					  ,@rCreatedUserId
					  ,@rCreatedDateTime
					  ,@lOrgGroupId
					  ,0
					  ,@rDataTypeId
					  ,@rCustomFieldMasterId	--add for mantis: 32799
					)
				END
			--ELSE
	--	 SELECT -101 As RESULT
	--END
	 	 
				ELSE
				BEGIN
				--SET @lNextNumber = @rId

					UPDATE sHrm.tEmployeeCustomFieldMaster
					SET 
						FieldTitle = @rFieldTitle
						,FieldTypeId = @rFieldTypeId
						,FieldList=@rFieldList
						--,IsFieldMandatory=@rIsFieldMandatory
						--,IsObsolete=@rIsObsolete
						,FieldGroup=@rFieldGroup
						--,FieldOrder=@rFieldOrder
						,UpdatedUserId=@rUpdatedUserId
						,UpdatedDateTime=@rUpdatedDateTime
						,DataId = @rDataTypeId
					WHERE CustomFieldMasterId=@rCustomFieldMasterId
	
	
				END  
			END
			ELSE
			BEGIN
				IF EXISTS(SELECT 2 FROM sHrm.tEmployeeCustomFieldMaster WHERE CustomFieldMasterId=@rCustomFieldMasterId)
				BEGIN
					DECLARE @lEmployeeCustomFieldMasterId int=0
					SELECT @lEmployeeCustomFieldMasterId = Id FROM sHrm.tEmployeeCustomFieldMaster WHERE CustomFieldMasterId=@rCustomFieldMasterId

					EXEC sHrm.pEmployeeCustomFieldDelete @lEmployeeCustomFieldMasterId, @rOrgId, @lOrgGroupId
				END
			END	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating Procedure [sProcurement].[UpdateWacBulk]...';


GO

Create PROCEDURE  [sProcurement].[UpdateWacBulk]	
	
	@rStoreLocationId Bigint = 0,
	--@rItemcode varchar(50) = '' ,
	----@rWeightedAverageoldcost Decimal(18,5) =0,
	--@rWeightedAverageCost Decimal(18,5) = 0,
	@rOrgId int =0,
	@rStrXML Nvarchar (max),
	@rScreenId int = 0,
	@rCreatedUserId bigint = 0 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lInterrorCode INT,
			@intDoc INT,
			@lCount Int ,
			@lItemCode nvarchar(50),
			@lWeightedAverageCost Decimal(22,6),
			@lOperationRemark NVARCHAR(100),
			@lCreatedDateTime datetime = sCommon.fGetDate()
	--BEGIN TRY
	 BEGIN TRANSACTION	
	 
	 EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXML

		CREATE TABLE #tempValue (
			Id int IDENTITY(1,1),
			ItemCode nVarchar (50) ,
			WeightedAverageCost Decimal(22,6));

		Insert into  #tempValue(ItemCode, WeightedAverageCost)
		Select ItemCode, WeightedAverageCost
		FROM OPENXML (@intDoc, '/Table/StockWacBulk', 1)
		WITH
		(
			ItemCode nVarchar(50) '@ItemCode',
			WeightedAverageCost Decimal(22,6) '@WeightedAverageCost'

		)
		--Select * from #tempValue
		Select @lCount =Max(Id) from #tempValue

	while (@lCount > 0)
	Begin
		Select @lItemCode = ItemCode from #tempValue where Id = @lCount
		Select @lWeightedAverageCost = WeightedAverageCost from #tempValue where Id = @lCount


		Declare @lItemId bigint = 0,@lStockItemPlanningId bigint = 0,@lStockInwardDetailId bigint = 0,@lStockBatchId bigint = 0,@llocationId bigint = 0

		Select @llocationId = LocationId from sIp.tStoreLocationMaster where Id = @rStoreLocationId and OrgGroupId=@rOrgId
		Select @lItemId =  Id from sIp.tStockItemMaster where locationId=@llocationId and code=@lItemCode and OrgGroupId = @rOrgId
		Select @lStockItemPlanningId =  Id from sIp.tStockItemPlanning where StockItemId = @lItemId 
		 
		

		select @lStockInwardDetailId = SIDE.ID from sProcurement.tStockInward SI 
		inner join sProcurement.tStockInwardDetail SIDE on SIDE.StockInwardId = SI.Id
		inner join  sProcurement.tStockInwardBatch SIB on SIB.StockInwardDetailId = SIDE.Id
		inner join sProcurement.tStockBatch SB on SB.id = SIB.StockBatchId
		Where SIDE.StockItemId=@lItemId  and SI.OrgGroupId=@rOrgId


		select @lStockBatchId = SB.ID from sProcurement.tStockInward SI 
		inner join sProcurement.tStockInwardDetail SIDE on SIDE.StockInwardId = SI.Id
		inner join  sProcurement.tStockInwardBatch SIB on SIB.StockInwardDetailId = SIDE.Id
		inner join sProcurement.tStockBatch SB on SB.id = SIB.StockBatchId
		Where SIDE.StockItemId=@lItemId  and SI.OrgGroupId=@rOrgId

		---StockItemMaster In Planning cost update 

		Update sIp.tStockItemPlanning set WeightedAverageCost=@lWeightedAverageCost  where StockItemId =@lItemId
		and Id=@lStockItemPlanningId and OrgGroupId=@rOrgId

		---Tranjection table Cost Update

		update sIp.tWeightedAverageCostLog set WeightedAverageCost=@lWeightedAverageCost 
		where ItemSourceId =@lItemId and StoreLocationId=@rStoreLocationId and OrgGroupId=@rOrgId


		---Tranjection table Value Update

		update sIp.tWeightedAverageCostLog set ClosingValue=(ClosingQuantity*WeightedAverageCost) 
		where ItemSourceId =@lItemId and StoreLocationId=@rStoreLocationId and OrgGroupId=@rOrgId


		---Stock Batch Price Update If Inward Avaliable 

		if(len(@lStockBatchId) > 0)
		Update sProcurement.tStockBatch set ItemRate=@lWeightedAverageCost where StockItemId=@lItemId
		 and id=@lStockBatchId and StoreLocationId=@rStoreLocationId and OrgGroupId=@rOrgId

		 DECLARE @ConvertedValue NVARCHAR(50)
		SET @ConvertedValue = CONVERT(NVARCHAR(50), STR(@lWeightedAverageCost, 50, 2))

		 SET @lOperationRemark =  ' Updated WAC : ' + CONVERT(Nvarchar(50),@ConvertedValue)
		 Exec sAudit.pStockOperationLogAdd @rScreenId , @lItemId, 34, 15, @lOperationRemark,
		  @rCreatedUserId,@lCreatedDateTime
		 Set @lCount = @lCount - 1;
	END
	  COMMIT TRANSACTION
END
GO
PRINT N'Creating Procedure [sRecruitment].[pRptVacancyCustomFieldGet]...';


GO
CREATE PROCEDURE [sRecruitment].[pRptVacancyCustomFieldGet]	 
	@rOrgGroupId int,
	@rCandidateId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		VM.Id,
	    VM.FieldTitle,	
		VM.FieldGroup,	
		VM.FieldTypeId,
		VM.FieldList,
		VM.IsFieldMandatory,
		VM.IsObsolete,
		VM.FieldOrder,
		VCF.FieldData
	FROM 
		 sRecruitment.tVacancyCustomFieldMaster VM
		 INNER JOIN sRecruitment.tVacancyCustomFieldData VCF ON VCF.VacancyCustomFieldId=VM.Id AND VCF.CandidateId=@rCandidateId

	WHERE 
		OrgGroupId = @rOrgGroupId
		AND (VCF.FieldData <> '0' AND VCF.FieldData<>'' AND VCF.FieldData IS NOT NULL AND VCF.FieldData<>'- Select -')
		
END
GO
PRINT N'Creating Procedure [sRecruitment].[pVacancyCustomFieldDataAdd]...';


GO
CREATE PROCEDURE [sRecruitment].[pVacancyCustomFieldDataAdd]
	  
	@rCandidateId bigint=0,
	@rStrXml nvarchar(max) 
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
print @rStrXml
DECLARE @loDoc INT

EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml

BEGIN
	BEGIN TRY
		
	UPDATE sRecruitment.tVacancyCustomFieldData 
			SET 
				VacancyCustomFieldId=A.VacancyCustomFieldId,
				FieldData= [sSetup].[fPortalXMLTagsReplaceReverse](A.FieldData),				
				UpdatedUserId=A.UpdatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
			FROM (
			SELECT
				VacancyCustomFieldId,FieldData,UpdatedUserId,CandidateId,AutoId	
				FROM OPENXML (@loDoc, '/Table/VacancyCustomField', 1)
			WITH
			(
				AutoId int '@AutoId',		
				CandidateId Bigint '@CandidateId',
				VacancyCustomFieldId INT '@VacancyCustomFieldId',
				FieldData nvarchar(max) '@FieldData',
				CreatedUserId bigint,
				UpdatedUserId bigint
			))A 
			INNER JOIN sRecruitment.tVacancyCustomFieldData VCM ON  VCM.CandidateId=A.CandidateId AND VCM.AutoID=A.AutoId 
	
	
	  INSERT INTO sRecruitment.tVacancyCustomFieldData
		(
		    
			CandidateId,
			VacancyCustomFieldId,
			FieldData,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
		SELECT
				A.CandidateId,A.VacancyCustomFieldId,[sSetup].[fPortalXMLTagsReplaceReverse](A.FieldData),A.CreatedUserId,sCommon.fGetDate(),A.UpdatedUserId,sCommon.fGetDate()	
				FROM OPENXML (@loDoc, '/Table/VacancyCustomField', 1)
			WITH
			(		
			    AutoId int '@AutoId',		
				CandidateId Bigint '@CandidateId',
				VacancyCustomFieldId INT '@VacancyCustomFieldId',
				FieldData nvarchar(max) '@FieldData',
				CreatedUserId bigint,
				UpdatedUserId bigint
			)A 
			LEFT JOIN sRecruitment.tVacancyCustomFieldData VCM ON VCM.CandidateId=A.CandidateId AND VCM.AutoID=A.AutoId 
			WHERE VCM.CandidateId IS NULL 
			
	
		
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating Procedure [sRecruitment].[pVacancyCustomFieldDelete]...';


GO
CREATE PROCEDURE [sRecruitment].[pVacancyCustomFieldDelete]

@rId int,
@rOrgId smallint=0,
@rOrgGroupId int=0
AS
BEGIN
 	 
	IF NOT EXISTS(Select 1 from sRecruitment.tVacancyCustomFieldData VCF 
				INNER JOIN sRecruitment.tCandidateMaster CM ON CM.Id=VCF.CandidateId
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId 
			WHERE VCF.VacancyCustomFieldId=@rId
				AND (VCF.FieldData <> '0' AND VCF.FieldData<>'' AND VCF.FieldData IS NOT NULL))
	BEGIN
        
		DELETE VCF FROM sRecruitment.tVacancyCustomFieldData VCF 
			INNER JOIN sRecruitment.tCandidateMaster CM ON CM.Id=VCF.CandidateId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId 
		WHERE VCF.VacancyCustomFieldId=@rId
         
		DELETE	FROM sRecruitment.tVacancyCustomFieldMaster WHERE Id=@rId 
		SELECT 1 AS RESULT
	END 

	ELSE
	BEGIN
		SELECT -101 As RESULT
	END
 
END
GO
PRINT N'Creating Procedure [sRecruitment].[pVacancyCustomFieldDetailsGet]...';


GO
CREATE PROCEDURE [sRecruitment].[pVacancyCustomFieldDetailsGet]	 
	@rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		Id,
	    FieldTitle,	
		FieldGroup,	
		FieldTypeId,
		FieldList,
		IsFieldMandatory,
		IsObsolete,
		FieldOrder,
		ISNULL(DataId,0) DataId
	FROM 
		 sRecruitment.tVacancyCustomFieldMaster

	WHERE 
		OrgGroupId = @rOrgGroupId
		
END
GO
PRINT N'Creating Procedure [sRecruitment].[pVacancyCustomFieldUpdate]...';


GO
CREATE PROCEDURE [sRecruitment].[pVacancyCustomFieldUpdate]
		 
	@rId int,
	@rOrgId int,
	--@rFieldTitle nvarchar(500),
	--@rFieldTypeId tinyint,
	--@rFieldList nvarchar(500),
	@rIsFieldMandatory bit,
	--@rFieldGroup nvarchar(200),
	@rFieldOrder smallint,
	--@rCreatedUserId bigint,	
	--@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rIsObsolete int =0
	--@rDataTypeId int = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		BEGIN TRANSACTION	

			DECLARE @lOrgGroupId int=0
			SELECT @lOrgGroupId= OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
 
			--IF(@rId = 0)	
			--BEGIN
				--IF NOT EXISTS(SELECT 2 FROM sHrm.tEmployeeCustomFieldMaster WHERE FieldTitle=@rFieldTitle AND FieldGroup=@rFieldGroup AND DataId=@rDataTypeId AND OrgGroupId=@lOrgGroupId)
				----IF NOT EXISTS(SELECT 2 FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle=@rFieldTitle)
				--BEGIN
	      --DECLARE @lNextNumber int
--	      EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
--Print @lNextNumber
--	      INSERT INTO sHrm.tEmployeeCustomFieldMaster
--	      (
--		    Id
--		   ,FieldTitle
--		   ,FieldTypeId
--		   ,FieldList
--		   ,IsFieldMandatory
--		   ,FieldGroup
--		   ,FieldOrder
--		   ,CreatedUserId
--		   ,CreatedDateTime
--		   ,OrgGroupId
--		   ,IsObsolete
--		   ,DataId
--	      )
--	     VALUES
--	     (
--		   @lNextNumber
--		  ,@rFieldTitle
--		  ,@rFieldTypeId
--		  ,@rFieldList
--		  ,@rIsFieldMandatory
--		  ,@rFieldGroup
--		  ,@rFieldOrder
--		  ,@rCreatedUserId
--		  ,@rCreatedDateTime
--		  ,@lOrgGroupId
--		  ,@rIsObsolete
--		  ,@rDataTypeId
--	     )
--     END
--	 ELSE
--	 SELECT -101 As RESULT
--END
	 	 
--ELSE
--BEGIN
	--SET @lNextNumber = @rId

	
	
			UPDATE sRecruitment.tVacancyCustomFieldMaster
			SET 
				--FieldTitle = @rFieldTitle
				--,FieldTypeId = @rFieldTypeId
				--,FieldList=@rFieldList
				IsFieldMandatory=@rIsFieldMandatory
				,IsObsolete=@rIsObsolete
				--,FieldGroup=@rFieldGroup
				,FieldOrder=@rFieldOrder
				,UpdatedUserId=@rUpdatedUserId
				,UpdatedDateTime=@rUpdatedDateTime
				--,DataId = @rDataTypeId
			WHERE Id = @rId 
	
	
--END  
			SELECT @rId AS Result
	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating Procedure [sSetup].[pCustomFieldAdd]...';


GO
CREATE PROCEDURE [sSetup].[pCustomFieldAdd]
		 
	@rId int,
	@rOrgId int,
	@rFieldTitle nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	@rIsEmployee bit,
	@rFieldGroup nvarchar(200),
	--@rFieldOrder smallint,
	@rCreatedUserId bigint,	
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rIsVacancy int = 0,
	@rDataTypeId int = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	BEGIN TRANSACTION	

		DECLARE @lOrgGroupId int=0
		SELECT @lOrgGroupId= OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
 
		IF(@rId = 0)
		BEGIN
			IF NOT EXISTS(SELECT 2 FROM sSetup.tCustomFieldMaster WHERE FieldTitle=@rFieldTitle AND FieldGroup=@rFieldGroup AND DataId=@rDataTypeId AND OrgGroupId=@lOrgGroupId)
			--IF NOT EXISTS(SELECT 2 FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle=@rFieldTitle)
			BEGIN
				DECLARE @lNextNumber int
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sSetup.tCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				Print @lNextNumber
				INSERT INTO sSetup.tCustomFieldMaster
				(
					Id
					,FieldGroup
					,FieldTitle
					,FieldTypeId
					,FieldList
					,IsEmployee
					,IsVacancy
					--,FieldOrder
					,CreatedUserId
					,CreatedDateTime
					,OrgGroupId
					,DataId
				)
				VALUES
				(
					@lNextNumber
					,@rFieldGroup
					,@rFieldTitle
					,@rFieldTypeId
					,@rFieldList
					,@rIsEmployee
					,@rIsVacancy
					--,@rFieldOrder
					,@rCreatedUserId
					,@rCreatedDateTime
					,@lOrgGroupId
					,@rDataTypeId
				)
			END
			ELSE
			BEGIN
				SELECT -101 As RESULT
			END
		END
	 	 
		ELSE
		BEGIN
			SET @lNextNumber = @rId

			UPDATE sSetup.tCustomFieldMaster
			SET 
				FieldGroup=@rFieldGroup
				,FieldTitle = @rFieldTitle
				,FieldTypeId = @rFieldTypeId
				,FieldList=@rFieldList
				,IsEmployee=@rIsEmployee
				,IsVacancy=@rIsVacancy
				--,FieldOrder=@rFieldOrder
				,UpdatedUserId=@rUpdatedUserId
				,UpdatedDateTime=@rUpdatedDateTime
				,DataId = @rDataTypeId
			WHERE Id = @rId
		END  

	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating Procedure [sSetup].[pCustomFieldDelete]...';


GO
CREATE PROCEDURE [sSetup].[pCustomFieldDelete]

@rId int,
@rOrgId smallint=0,
@rOrgGroupId int=0
AS
BEGIN
	IF EXISTS(Select 1 from sSetup.tCustomFieldMaster CFM
							INNER JOIN sHrm.tEmployeeCustomFieldMaster ECFM ON ECFM.CustomFieldMasterId=CFM.Id
							INNER JOIN sHrm.tEmployeeCustomFieldData ECF ON ECF.EmployeeCustomFieldId=ECFM.Id
							INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=ECF.EmployeeId
							INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId 
						WHERE CFM.Id=@rId AND StatusId=7 AND OM.OrgGroupId=@rOrgGroupId
							AND (ECF.FieldData <> '0' AND ECF.FieldData<>'' AND ECF.FieldData IS NOT NULL))
	BEGIN
		SELECT -101 As RESULT
		RETURN
	END

	IF EXISTS(Select 1 from sSetup.tCustomFieldMaster CFM
							INNER JOIN sRecruitment.tVacancyCustomFieldMaster VCFM ON VCFM.CustomFieldMasterId=CFM.Id
							INNER JOIN sRecruitment.tVacancyCustomFieldData VCF ON VCF.VacancyCustomFieldId=VCFM.Id
							INNER JOIN sRecruitment.tCandidateMaster CM ON CM.Id=VCF.CandidateId
							--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId 
						WHERE CFM.Id=@rId
							AND (VCF.FieldData <> '0' AND VCF.FieldData<>'' AND VCF.FieldData IS NOT NULL))
	BEGIN
		SELECT -102 As RESULT
		RETURN
	END

	DELETE ECF FROM sSetup.tCustomFieldMaster CFM
		INNER JOIN sHrm.tEmployeeCustomFieldMaster ECFM ON ECFM.CustomFieldMasterId=CFM.Id
		INNER JOIN sHrm.tEmployeeCustomFieldData ECF ON ECF.EmployeeCustomFieldId=ECFM.Id
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=ECF.EmployeeId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId 
	WHERE CFM.Id=@rId AND StatusId=1 AND OM.OrgGroupId=@rOrgGroupId

	DELETE VCF FROM sSetup.tCustomFieldMaster CFM
		INNER JOIN sRecruitment.tVacancyCustomFieldMaster VCFM ON VCFM.CustomFieldMasterId=CFM.Id
		INNER JOIN sRecruitment.tVacancyCustomFieldData VCF ON VCF.VacancyCustomFieldId=VCFM.Id
		INNER JOIN sRecruitment.tCandidateMaster CM ON CM.Id=VCF.CandidateId
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId 
	WHERE CFM.Id=@rId

	DELETE FROM sHrm.tEmployeeCustomFieldMaster WHERE CustomFieldMasterId=@rId
	DELETE FROM sRecruitment.tVacancyCustomFieldMaster WHERE CustomFieldMasterId=@rId

	DELETE FROM sSetup.tCustomFieldMaster WHERE Id=@rId
	SELECT 1 AS RESULT
END
GO
PRINT N'Creating Procedure [sSetup].[pCustomFieldDetailsGet]...';


GO
CREATE PROCEDURE [sSetup].[pCustomFieldDetailsGet]
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT
		Id,
		FieldGroup,
		FieldTitle,
		FieldTypeId,
		FieldList,
		IsEmployee,
		IsVacancy,
		ISNULL(DataId,0) AS DataId
	FROM
		sSetup.tCustomFieldMaster
	WHERE
		OrgGroupId = @rOrgGroupId

END
GO
PRINT N'Creating Procedure [sStudent].[pStudentSummaryGet]...';


GO
CREATE PROCEDURE [sStudent].[pStudentSummaryGet]

	@rOrgGroupId int=0,
	@rType nvarchar(100),
	@rCommonOrgGroupBatchId int,
	@rOrgId int =0,
	@rOrgSubGroupId int = 0,
	@rDepartmentId int = 0,
	@rClassId int = 0,
	@rStatusId int  = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	IF(@rType='OrgGroupwiseStudentCount')
	BEGIN
		SELECT 
			OGM.Id AS OrgGroupId,
			OGM.Title As OrgGroupTitle,
			0 As OrgId,
			'' As OrgTitle,
			0 AS DepartmentId,
			'' AS DepartmentTitle,
			[sStudent].[fGetDashboardStudentCount](1,@rCommonOrgGroupBatchId,@rType,0) AS ActiveStudent,
			[sStudent].[fGetDashboardStudentCount](3,@rCommonOrgGroupBatchId,@rType,0) AS LeftStudent,
			[sStudent].[fGetDashboardStudentCount](2,@rCommonOrgGroupBatchId,@rType,0) AS InActiveStudent,
			[sStudent].[fGetDashboardStudentCount](0,@rCommonOrgGroupBatchId,@rType,0) AS TotalStudent
		FROM sSetup.tOrgGroupMaster OGM
		WHERE OGM.Id<>1 AND ISNULL(OGM.IsObsolete,0) = 0 AND ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
	END
	ELSE IF(@rType='OrgwiseStudentCount')
	BEGIN
		SELECT 
			OM.Id As OrgId,
			OM.Title As OrgTitle,
			0 As OrgGroupId,
			'' As OrgGroupTitle,
			0 AS DepartmentId,
			'' AS DepartmentTitle,
			[sStudent].[fGetDashboardStudentCount](1,@rCommonOrgGroupBatchId,@rType,OM.Id) AS ActiveStudent,
			[sStudent].[fGetDashboardStudentCount](3,@rCommonOrgGroupBatchId,@rType,OM.Id) AS LeftStudent,
			[sStudent].[fGetDashboardStudentCount](2,@rCommonOrgGroupBatchId,@rType,OM.Id) AS InActiveStudent,
			[sStudent].[fGetDashboardStudentCount](0,@rCommonOrgGroupBatchId,@rType,OM.Id) AS TotalStudent
		FROM sSetup.tOrganizationMaster OM
		INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
		WHERE OM.Id<>1 AND ISNULL(OM.IsObsolete,0) = 0  AND OM.OrgSubGroupId = @rOrgSubGroupId
	END

	ELSE IF(@rType='OrgSubGroupwiseStudentCount')
	BEGIN
		SELECT 
			OSGM.Id As OrgSubGroupId,
			OSGM.Title As OrgSubGroupTitle,
			OSGM.OrgGroupId As OrgGroupId,
			OGM.Title AS OrgGroupTitle,
			0 AS DepartmentId,
			'' AS DepartmentTitle,
			[sStudent].[fGetDashboardStudentCount](1,@rCommonOrgGroupBatchId,@rType,OSGM.Id) AS ActiveStudent,
			[sStudent].[fGetDashboardStudentCount](3,@rCommonOrgGroupBatchId,@rType,OSGM.Id) AS LeftStudent,
			[sStudent].[fGetDashboardStudentCount](2,@rCommonOrgGroupBatchId,@rType,OSGM.Id) AS InActiveStudent,
			[sStudent].[fGetDashboardStudentCount](0,@rCommonOrgGroupBatchId,@rType,OSGM.Id) AS TotalStudent
		FROM  sSetup.tOrgSubGroupMaster OSGM 
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OSGM.OrgGroupId
		WHERE OSGM.Id<>1 AND ISNULL(OSGM.IsObsolete,0) = 0  AND ((OSGM.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	END

	ELSE IF(@rType='DeptwiseStudentCount')
	BEGIN
		SELECT 
			0 AS OrgGroupId,
			'' As OrgGroupTitle,
			DM.OrgId As OrgId,
			'' As OrgTitle,
			DM.Id AS DepartmentId,
			DM.Title AS DepartmentTitle,
			[sStudent].[fGetDashboardStudentCount](1,@rCommonOrgGroupBatchId,@rType,DM.Id) AS ActiveStudent,
			[sStudent].[fGetDashboardStudentCount](3,@rCommonOrgGroupBatchId,@rType,DM.Id) AS LeftStudent,
			[sStudent].[fGetDashboardStudentCount](2,@rCommonOrgGroupBatchId,@rType,DM.Id) AS InActiveStudent,
			[sStudent].[fGetDashboardStudentCount](0,@rCommonOrgGroupBatchId,@rType,DM.Id) AS TotalStudent
		FROM sSetup.tDepartmentMaster DM 
		WHERE DM.Id <> 1 AND ISNULL(DM.IsObsolete,0) = 0 AND DM.OrgId = @rOrgId 	
	END

	ELSE IF(@rType='ClasswiseStudentCount')
	BEGIN
		SELECT 
			CM.Id AS ClassId,
			CM.Title AS ClassName,
			CM.DepartmentId AS DepartmentId,
			[sStudent].[fGetDashboardStudentCount](1,@rCommonOrgGroupBatchId,@rType,CM.Id) AS ActiveStudent,
			[sStudent].[fGetDashboardStudentCount](3,@rCommonOrgGroupBatchId,@rType,CM.Id) AS LeftStudent,
			[sStudent].[fGetDashboardStudentCount](2,@rCommonOrgGroupBatchId,@rType,CM.Id) AS InActiveStudent,
			[sStudent].[fGetDashboardStudentCount](0,@rCommonOrgGroupBatchId,@rType,CM.Id) AS TotalStudent
		FROM sSetup.tClassMaster CM
		WHERE CM.IsObsolete = 0 AND CM.DepartmentId= @rDepartmentId	
	END

	ELSE IF(@rType='StudentStatusWiseCount')
	BEGIN
		SELECT  SM.Id AS StudentId,
				DM.Id AS DivisionId,
				DM.Code +' - ' + CM.Code AS ClassDivisionName,
				SM.Code As StudentCode,
				[sStudent].[fStudentNameGet](SM.FirstName,SM.MiddleName,SM.LastName,OM.StudentNameFormatId) AS StudentName,
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				CM.DepartmentId
		FROM sStudent.tStudentMaster SM
				 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID 
				 INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId  
				 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				 Left JOIN sStudent.tStudentCommunication SC on SM.Id=SC.StudentId
		WHERE COGBM.Id = @rCommonOrgGroupBatchId AND CM.Id= @rClassId AND BM.IsInContext = 1
			AND (SM.StatusId=@rStatusId OR @rStatusId=0)
		ORDER BY SM.Id	
	END
END
GO
PRINT N'Creating Procedure [sRecruitment].[pVacancyCustomFieldAdd]...';


GO
CREATE PROCEDURE [sRecruitment].[pVacancyCustomFieldAdd]
		 
	--@rId int,
	@rOrgId int,
	@rFieldTitle nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	--@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	--@rFieldOrder smallint,
	@rCreatedUserId bigint,	
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	--@rIsObsolete int =0,
	@rDataTypeId int = 1,
	@rCustomFieldMasterId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
		BEGIN TRANSACTION	

			DECLARE @lOrgGroupId int=0, @lIsVacancy bit = 0
			SELECT @lOrgGroupId= OrgGroupId FROM sSetup.tOrganizationMAster WHERE Id = @rOrgId
			select @lIsVacancy = IsVacancy From sSetup.tCustomFieldMaster WHERE FieldTitle=@rFieldTitle AND FieldGroup=@rFieldGroup AND DataId=@rDataTypeId AND OrgGroupId=@lOrgGroupId
 
			IF(@lIsVacancy=1)	
			BEGIN
				IF NOT EXISTS(SELECT 2 FROM sRecruitment.tVacancyCustomFieldMaster WHERE CustomFieldMasterId=@rCustomFieldMasterId)
				BEGIN
					DECLARE @lNextNumber int
					EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sRecruitment.tVacancyCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
					Print @lNextNumber
					INSERT INTO sRecruitment.tVacancyCustomFieldMaster
					(
						Id
					   ,FieldTitle
					   ,FieldTypeId
					   ,FieldList
					   ,IsFieldMandatory
					   ,FieldGroup
					   ,FieldOrder
					   ,CreatedUserId
					   ,CreatedDateTime
					   ,OrgGroupId
					   ,IsObsolete
					   ,DataId
					   ,CustomFieldMasterId
					)
					VALUES
					(
					   @lNextNumber
					  ,@rFieldTitle
					  ,@rFieldTypeId
					  ,@rFieldList
					  ,0
					  ,@rFieldGroup
					  ,0
					  ,@rCreatedUserId
					  ,@rCreatedDateTime
					  ,@lOrgGroupId
					  ,0
					  ,@rDataTypeId
					  ,@rCustomFieldMasterId
					)
				END
			--ELSE
	--	 SELECT -101 As RESULT
	--END
	 	 
				ELSE
				BEGIN
				--SET @lNextNumber = @rId

					UPDATE sRecruitment.tVacancyCustomFieldMaster
					SET 
						FieldTitle = @rFieldTitle
						,FieldTypeId = @rFieldTypeId
						,FieldList=@rFieldList
						--,IsFieldMandatory=@rIsFieldMandatory
						--,IsObsolete=@rIsObsolete
						,FieldGroup=@rFieldGroup
						--,FieldOrder=@rFieldOrder
						,UpdatedUserId=@rUpdatedUserId
						,UpdatedDateTime=@rUpdatedDateTime
						,DataId = @rDataTypeId
					WHERE CustomFieldMasterId=@rCustomFieldMasterId
	
	
				END  
			END
			ELSE
			BEGIN
				IF EXISTS(SELECT 2 FROM sRecruitment.tVacancyCustomFieldMaster WHERE CustomFieldMasterId=@rCustomFieldMasterId)
				BEGIN
					DECLARE @lVacancyCustomFieldMasterId int=0
					SELECT @lVacancyCustomFieldMasterId = Id FROM sRecruitment.tVacancyCustomFieldMaster WHERE CustomFieldMasterId=@rCustomFieldMasterId

					EXEC sRecruitment.pVacancyCustomFieldDelete @lVacancyCustomFieldMasterId, @rOrgId, @lOrgGroupId
				END
			END	
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO

PRINT N'Update complete.';


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

