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

GO
PRINT N'Altering [sAdmission].[tAdmissionCriteria]...';


GO
ALTER TABLE [sAdmission].[tAdmissionCriteria]
    ADD [IsFatherDetail]       BIT NULL,
        [IsFatherFullDetail]   BIT NULL,
        [IsFatherAcademic]     BIT NULL,
        [IsMotherDetail]       BIT NULL,
        [IsMotherFullDetail]   BIT NULL,
        [IsMotherAcademic]     BIT NULL,
        [IsGuardianDetail]     BIT NULL,
        [IsGuardianFullDetail] BIT NULL,
        [IsGuardianAcademic]   BIT NULL;


GO
PRINT N'Altering [sAdmission].[tAdmissionFormFamilyDetail]...';


GO
ALTER TABLE [sAdmission].[tAdmissionFormFamilyDetail]
    ADD [LiveWithId]          TINYINT       NULL,
        [IsFatherExStudent]   BIT           NULL,
        [FatherPassOutYear]   NVARCHAR (20) NULL,
        [IsMotherExStudent]   BIT           NULL,
        [MotherPassOutYear]   NVARCHAR (20) NULL,
        [IsRelativeExStudent] BIT           NULL,
        [RelativePassOutYear] NVARCHAR (20) NULL;


GO
PRINT N'Altering [sAssessment].[tExamMaster]...';


GO
ALTER TABLE [sAssessment].[tExamMaster]
    ADD [HeaderAdjustment] SMALLINT NULL;


GO
PRINT N'Altering [sCommunication].[tPhotoCategoryMaster]...';


GO
ALTER TABLE [sCommunication].[tPhotoCategoryMaster]
    ADD [Remark] NVARCHAR (300) NULL;


GO
PRINT N'Altering [sErp].[tCustomerMaster]...';


GO
ALTER TABLE [sErp].[tCustomerMaster] ALTER COLUMN [Email] NVARCHAR (300) NULL;

ALTER TABLE [sErp].[tCustomerMaster] ALTER COLUMN [MobileNo] NVARCHAR (200) NULL;


GO
ALTER TABLE [sErp].[tCustomerMaster]
    ADD [AbsolutePath] NVARCHAR (300) NULL,
        [CampusTypeId] TINYINT        NULL;


GO
PRINT N'Altering [sErp].[tProjectMaster]...';


GO
ALTER TABLE [sErp].[tProjectMaster]
    ADD [EstimatedHours] DECIMAL (10, 2) NULL,
        [IsActive]       BIT             NULL,
        [StartDate]      DATE            NULL,
        [EndDate]        DATE            NULL,
        [PMEmployeeId]   BIGINT          NULL;


GO
PRINT N'Creating PK_tProjectMaster...';


GO
ALTER TABLE [sErp].[tProjectMaster]
    ADD CONSTRAINT [PK_tProjectMaster] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO
PRINT N'Altering [sFee].[tReceiptBookMaster]...';


GO
ALTER TABLE [sFee].[tReceiptBookMaster]
    ADD [CGSTPercentage] DECIMAL (5, 2) NULL,
        [SGSTPercentage] DECIMAL (5, 2) NULL;


GO
PRINT N'Altering [sInfrastructure].[tResourceMaster]...';


GO
ALTER TABLE [sInfrastructure].[tResourceMaster]
    ADD [OrgGroupId] SMALLINT NOT NULL;


GO
PRINT N'Altering [sInfrastructure].[tResourceRequest]...';


GO
ALTER TABLE [sInfrastructure].[tResourceRequest]
    ADD [OrgGroupId] SMALLINT NOT NULL;


GO
PRINT N'Altering [sSetup].[tOrganizationOtherDetail]...';


GO
ALTER TABLE [sSetup].[tOrganizationOtherDetail]
    ADD [GSTINNo]    NVARCHAR (50) NULL,
        [HSNSACCode] NVARCHAR (15) NULL;


GO
PRINT N'Altering [sTimetable].[tTimeTableSchema]...';


GO
ALTER TABLE [sTimetable].[tTimeTableSchema]
    ADD [IsPublish] BIT NULL;


GO
PRINT N'Creating [sCanteen].[tGuestRequest]...';


GO
CREATE TABLE [sCanteen].[tGuestRequest] (
    [Id]              INT      NOT NULL,
    [RequestDate]     DATE     NOT NULL,
    [BreakTypeId]     INT      NOT NULL,
    [GuestName]       SMALLINT NOT NULL,
    [Remark]          SMALLINT NOT NULL,
    [NoOfPersons]     SMALLINT NOT NULL,
    [CreatedUserId]   BIGINT   NOT NULL,
    [CreatedDateTime] DATETIME NOT NULL,
    [CanteenId]       INT      NOT NULL
);


GO
PRINT N'Creating PK_tGuestRequest...';


GO
ALTER TABLE [sCanteen].[tGuestRequest]
    ADD CONSTRAINT [PK_tGuestRequest] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO
PRINT N'Creating [sErp].[tCampusTypeMaster]...';


GO
CREATE TABLE [sErp].[tCampusTypeMaster] (
    [Id]         TINYINT        NOT NULL,
    [Code]       NVARCHAR (10)  NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL
);


GO
PRINT N'Creating [sSecurity].[tPermissionUser]...';


GO
CREATE TABLE [sSecurity].[tPermissionUser] (
    [TaskId]          SMALLINT NOT NULL,
    [UserId]          BIGINT   NOT NULL,
    [Permission]      INT      NOT NULL,
    [CreatedUserId]   BIGINT   NOT NULL,
    [CreatedDateTime] DATETIME NULL,
    [UpdatedUserId]   BIGINT   NOT NULL,
    [UpdatedDateTime] DATETIME NULL,
    [IsObsolete]      BIT      NOT NULL,
    [OrgGroupId]      SMALLINT NOT NULL
);


GO
PRINT N'Creating [sSystem].[tLimitLog]...';


GO
CREATE TABLE [sSystem].[tLimitLog] (
    [AutoId]       BIGINT   IDENTITY (1, 1) NOT NULL,
    [LogDate]      DATETIME NOT NULL,
    [StudentCount] SMALLINT NULL,
    [AlertCount]   SMALLINT NULL,
    [OrgGroupId]   SMALLINT NULL
);


GO
PRINT N'Creating [sSystem].[tMobileAppStaticVersion]...';


GO
CREATE TABLE [sSystem].[tMobileAppStaticVersion] (
    [VersionId]     INT           NOT NULL,
    [VersionNumber] NVARCHAR (30) NOT NULL,
    [OSTypeId]      INT           NOT NULL
);


GO
PRINT N'Altering [sFee].[tReceipt]...';


GO
ALTER TABLE [sFee].[tReceipt]
    ADD [AmountAfterDiscount] DECIMAL (12, 2) NULL,
        [CGSTPercentage]      DECIMAL (5, 2)  NULL,
        [SGSTPercentage]      DECIMAL (5, 2)  NULL,
        [CGSTAmount]          DECIMAL (12, 2) NULL,
        [SGSTAmount]          DECIMAL (12, 2) NULL;


GO
PRINT N'Creating PK_tEmployeementType...';


GO
ALTER TABLE [sAlumni].[tEmployeementType]
    ADD CONSTRAINT [PK_tEmployeementType] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO
PRINT N'Creating PK_tUploadResult...';


GO
ALTER TABLE [sCommunication].[tUploadResult]
    ADD CONSTRAINT [PK_tUploadResult] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


 
GO
PRINT N'Altering [sPoliciesForms].[fFolderPathGet]...';


GO

ALTER FUNCTION [sPoliciesForms].[fFolderPathGet] (@FolderId int)
RETURNS nvarchar(max) WITH EXECUTE AS CALLER
AS
BEGIN
    DECLARE @columns varchar(max) = ''
    ;WITH cteReports (id, PerentFolderId, Title, EmpLevel)AS (

	SELECT id, PerentFolderId, case when PerentFolderId=0 then  CAST(CONVERT(varchar,CreatedUserId)  + '\' + ISNULL(Title, '')  AS VARCHAR(8000)) else CAST(ISNULL(Title, '')  AS VARCHAR(8000)) end, 0 AS EmpLevel 
	FROM [sPoliciesForms].[tFolderFile]
    WHERE id = @FolderId      
	UNION ALL
    
	SELECT e.id, e.PerentFolderId,  case when e.PerentFolderId=0 then  CAST(CONVERT(varchar,e.CreatedUserId)  + '\' + ISNULL(e.Title, '')  AS VARCHAR(8000)) else CAST(ISNULL(e.Title, '')  AS VARCHAR(8000)) end, r.EmpLevel + 1
    FROM [sPoliciesForms].[tFolderFile] e
    INNER JOIN cteReports r ON e.id = r.PerentFolderId
    )
    SELECT @columns = COALESCE(@columns + '\', '') + Title
    FROM cteReports
    ORDER BY id

	SELECT @columns=case when len(@columns)>0 then @columns  else @columns end

    RETURN @columns
END
GO
PRINT N'Altering [sAssessment].[vGeneralExamColumnName]...';


GO










/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sAssessment].[vGeneralExamColumnName]  
  
AS  
  
SELECT 	
		 --SA.AcademicId,	  
		 --SA.ClassId,
		 --SA.DivisionId,
		 SA.RollNo,
		 --SA.OrgId,
		 --SA.BatchId,
		 OM.Title AS Organization,
		 BM.Title AS Batch,
		 --SA.StudentId,
		 SA.Code AS [ID No],
		  SA.Code AS [GR No],
		 SA.Number,
		 SA.FirstName,
		 SA.LastName,
		 SA.Name,
		 --SA.DepartmentId,
		 --SA.StatusId,
		 SA.ClassName,
		 SA.DivisionName,
		 SA.StatusName,
		 R.TotalMarks,
		 R.TotalObtain,
		 R.ResultStatus,
		 R.ResultGrade,
		 R.ResultGradePoint,
		 R.RankNumber,
		 R.Percentage,
		 R.Percentile,
		 R.ResultRemark,
		 R.OtherRemark1,
		 ESGM.Code AS ExamCode,
		 ESGM.Title AS ExamName,
		 --EM.Id AS Id,
	     U.DisplayTitle AS CreatedUserName,
	     SR.ExamSeatNo,
	     SR.TotalDays,
	     SR.PresentDays,
	     SR.StudentHeight,
	     SR.StudentWeight,
	     SR.ResultRemark1,
	     SR.ResultRemark2,
	     SR.MyGoal,
	     SR.MyStrength,
	     SR.MyInterestHobby,
	     SR.Achievements,
	     SR.AreaOfInterest,
	     SR.Responsibility,
	     SR.DentalHygiene,
	     SR.VisionLeft,
	     SR.VisionRight,
	     SR.MyActivity,
	     SR.ClassTeacherRemark,
	     SR.HouseRemark,
	     SR.ResultRemark3,
	     SR.GeneralRemark
	    
	     
	     
	  	  	   
FROM 
		sStudent.vStudentAcademic SA
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sAssessment.tResult R ON R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
	INNER JOIN sSecurity.tUser U ON U.Id=R.UpdatedUserId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId=SA.AcademicId
GO
PRINT N'Altering [sFee].[vFeeColumnName]...';


GO





/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sFee].[vFeeColumnName]  
  
AS  
  
SELECT 	
		 --SA.AcademicId,	  
		 --SA.ClassId,
		 --SA.DivisionId,
		 SA.SUId,
		 SA.RollNo,
		 --SA.OrgId,
		 --SA.BatchId,
		 OGBM.Title AS OrgGroupBatch,
		 OM.Title AS Organization,
		 BM.Title AS Batch,
		 --SA.StudentId,
		 SA.Code AS [ID No],
		  SA.Code AS [GR No],
		 SA.Number,
		 SA.FirstName,
		 SA.LastName,
		 SA.Name,
		 --SA.DepartmentId,
		 --SA.StatusId,
		 SA.ClassName,
		 SA.DivisionName,
		 SA.StatusName,
		 --FA.VariableAmount,
		 --FA.DiscountAmount,
   --      FA.AdditionalAmount,
   --      FA.NotApplicable,
   --      FCM.Number AS FeeCategoryNumber,
   --      FCM.Code AS FeeCategoryCode,
   --      FCM.Title AS FeeCategoryName,
	  --   FCM.OrderIndex AS FeeCategoryOrderIndex,
	  --   FHM.Code AS FeeHeadCode,
	  --   FHM.Title AS FeeHeadTitle,
	  --   FM.Code AS FeeCode,
	  --   FM.Number AS FeeNumber,
	  --   FM.Title AS FeeName,
	  --   FM.OrderIndex AS FeeOrderIndex,
	  --   FS.Amount AS FeeSetupAmount,
	  --   FS.StartDate,
	  --   FS.EndDate,
	     R.ReceiptNumber,
	     R.ReceiptDate,
	     R.ReceiptAmount,
	     R.ChequeNo,
	     R.ChequeDate,
	     R.ChequeClearDate,
	     R.BankName,
	     R.Remark,
	     RBM.Code AS ReceiptBookCode,
	     RBM.Title AS ReceiptBookName,
	     RBM.Address1,
	     RBM.Address2,
	     RBM.BankAccountNumber,
	     --RD.Amount AS ReceiptDetailAmount,
	     PTM.Title AS PayType,
	     U.DisplayTitle AS CreatedUserName 
	     
	  	  	   
FROM 
		sStudent.vStudentAcademic SA
	INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=SA.OrgGroupBatchId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	--INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId=SA.AcademicId
	INNER JOIN sFee.tReceipt R ON R.SourceId=SA.AcademicId
	INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
	--INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
	--INNER JOIN sFee.tFeeSetup FS ON FS.Id=RD.FeeSetupId
	--INNER JOIN sFee.tFeeCategoryMaster FCM ON FCM.Id=FS.FeeCategoryId
	--INNER JOIN sFee.tFeeCategoryClass FCC ON FCC.FeeCategoryId=FCM.Id
	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
	--INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
	INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=R.PayTypeId 
	INNER JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId
GO
PRINT N'Altering [sHrm].[vEmployeeColumnName]...';


GO















/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sHrm].[vEmployeeColumnName]  
  
AS  
  
SELECT 	
	   --EM.OrgId
    --  ,EM.Id AS EmployeeId
       EM.Code
      ,EM.FirstName
      ,EM.MiddleName
      ,EM.LastName
      ,ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name
      --,EM.StatusId
      ,SM.Title AS StatusName
      --,EM.IsObsolete
      --,EJD.Id AS EmployeeJobDetailId
      --,EJD.EmployeeDesignationId
      ,EDM.Title AS EmployeeDesignation
      --,EJD.OrganizationDepartmentId
      ,ODM.Title AS OrganizationDepartment
      ,EJD.DateOfJoining
      --,EJD.EPFNumber
      --,EJD.ESINumber
      --,EJD.EmployeeTypeId
      ,ETM.Title AS EmployeeType
      ,EGM.Title AS EmployeeGroup
      ,EJD.DateOfleaving
      ,EJD.ReasonOfleaving
      ,EJD.Subjects
      --,ELM.StreetOne
      --,ELM.StreetTwo
      --,ELM.StreetThree
      --,ELM.CityName
      --,ELM.StateName
      --,ELM.CountryName
      --,ELM.ZipCode
      --,ELM.PhoneNo
      --,ELM.FaxNo
      --,ELM.NameOfOccupier
      --,ELM.AddressOfOccupier
      --,ELM.SmallAddress1
      --,ELM.SmallAddress2
      --,ELM.RegistrationNumber
      --,ELM.LicenceNumber
      --,ELM.EsicNumber
      --,ELM.EsicAddress1
      --,ELM.EsicAddress2
      --,ELM.NatureOfIndustry
      --,ELM.ByProduct
      --,ELM.DangerousOperation
      --,ELM.NatureOfTest
      --,ELM.NatureOfTestNonHazardous
      --,ELM.RowMaterialUsed
      --,ELM.HazardousProcess
      --,ELM.Cmo
      --,ELM.NicNumber
      --,ELM.CountryId
      --,ELM.StateId
      --,EPD.Id AS EmployeePersonalDetailId
      ,EPD.UIDNumber
      ,EPD.DateOfBirth
      ,EPD.Qualification
      ,EPD.FamilyCast
      ,CCM.Title AS CasteCategory
      --,EPD.GenderId
      ,GM.Title AS Gender
      --,EPD.ReligionId
      ,RM.Title AS Religion
      --,EPD.MaritalStatusId
      ,MSM.Title AS MaritalStatus
      ,EPD.IdentificationMark1
      --,EPD.BloodGroupId
      ,BGM.Title AS BloodGroup,
      EC.MobileNumber,
      EC.PersonalEmail
      ,EC.CompanyEmail
      ,EC.PhoneNoCompany
      ,EC.ExtensionNo
      ,EC.PresentStreetOne
      ,Ec.PresentStreetTwo
      ,Ec.PresentStreetThree
      ,Ec.PresentCountry
      ,Ec.PresentState
      ,Ec.PresentCity
      ,Ec.PresentZipCode
      ,Ec.PresentContactNo
      ,Ec.PermanentStreetOne
      ,Ec.PermanentStreetTwo
      ,Ec.PermanentStreetThree
      ,Ec.PermanentCountry
      ,Ec.PermanentState
      ,Ec.PermanentCity
      ,Ec.PermanentZipCode
      ,Ec.PermanentContactNo
      ,ES.EPFNumber
      ,ES.ESINumber
      ,ES.AccountNumber
      ,ES.BankName
      ,ES.Branch
      ,ES.IFSCNumber
      ,ES.PanNumber
      ,ES.BasicPay
      ,ES.IncrementDate
      ,ES.EPFJoinDate
      ,ISNULL(ES.Payscale,'') AS Payscale
      ,ISNULL(EPD.AdhaarNumber,'') AS AdhaarNumber
      
  FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		--LEFT JOIN sHrm.tEmployeeJobTitleMaster EJTM ON EJTM.Id=EJD.EmployeeJobTitleId
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
		INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = EPD.CastCategoryId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=EPD.GenderId
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EPD.ReligionId
		LEFT JOIN sCommon.tMaritalStatusMaster MSM ON MSM.Id=EPD.MaritalStatusId
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=EPD.BloodGroupId
		--LEFT JOIN sHrm.tQualificationMaster QM ON QM.Id=EPD.HigestQualificationId
		INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ES ON ES.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id = EJD.EmployeeGroupId
GO
PRINT N'Altering [sHrm].[vEmployeeCustomSearch]...';


GO














/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sHrm].[vEmployeeCustomSearch]  
  
AS  
  
SELECT 	
	   EM.OrgId
      ,EM.Id AS EmployeeId
      ,EM.Code
      ,EM.FirstName
      ,EM.MiddleName
      ,EM.LastName
      ,ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name
      ,EM.StatusId
      ,SM.Title AS StatusName
      ,EM.IsObsolete
      ,0 AS EmployeeJobDetail
      ,EJD.EmployeeDesignationId
      ,EDM.Title AS EmployeeDesignation
      ,EJD.OrganizationDepartmentId
      ,ODM.Title AS OrganizationDepartment
      ,CONVERT(VARCHAR(10), EJD.DateOfJoining, 111) AS DateOfJoining
      --,EJD.EPFNumber
      --,EJD.ESINumber
      ,EJD.EmployeeTypeId
      ,ETM.Title AS EmployeeType
      ,EGM.Title AS EmployeeGroup
      ,CONVERT(VARCHAR(10), EJD.DateOfleaving, 111) AS DateOfleaving
      ,EJD.ReasonOfleaving
       ,EJD.Subjects
      --,ELM.StreetOne
      --,ELM.StreetTwo
      --,ELM.StreetThree
      --,ELM.CityName
      --,ELM.StateName
      --,ELM.CountryName
      --,ELM.ZipCode
      --,ELM.PhoneNo
      --,ELM.FaxNo
      --,ELM.NameOfOccupier
      --,ELM.AddressOfOccupier
      --,ELM.SmallAddress1
      --,ELM.SmallAddress2
      --,ELM.RegistrationNumber
      --,ELM.LicenceNumber
      --,ELM.EsicNumber
      --,ELM.EsicAddress1
      --,ELM.EsicAddress2
      --,ELM.NatureOfIndustry
      --,ELM.ByProduct
      --,ELM.DangerousOperation
      --,ELM.NatureOfTest
      --,ELM.NatureOfTestNonHazardous
      --,ELM.RowMaterialUsed
      --,ELM.HazardousProcess
      --,ELM.Cmo
      --,ELM.NicNumber
      --,ELM.CountryId
      --,ELM.StateId
      ,0 AS EmployeePersonalDetailId
      ,EPD.UIDNumber
      ,CONVERT(VARCHAR(10), EPD.DateOfBirth, 111) AS DateOfBirth
      ,EPD.GenderId
      ,GM.Title AS Gender
      ,EPD.ReligionId
      ,RM.Title AS Religion
      ,EPD.MaritalStatusId
      ,MSM.Title AS MaritalStatus
      ,EPD.IdentificationMark1
      ,EPD.BloodGroupId
      ,BGM.Title AS BloodGroup
      ,EPD.Qualification
      ,EPD.FamilyCast
      ,CCM.Title AS CastCategory
      ,EJD.EmployeeGroupId
      , EC.MobileNumber
      ,EC.PersonalEmail
      ,EC.CompanyEmail
      ,EC.PhoneNoCompany
      ,EC.ExtensionNo
      ,EC.PresentStreetOne
      ,Ec.PresentStreetTwo
      ,Ec.PresentStreetThree
      ,Ec.PresentCountry
      ,Ec.PresentState
      ,Ec.PresentCity
      ,Ec.PresentZipCode
      ,Ec.PresentContactNo
      ,Ec.PermanentStreetOne
      ,Ec.PermanentStreetTwo
      ,Ec.PermanentStreetThree
      ,Ec.PermanentCountry
      ,Ec.PermanentState
      ,Ec.PermanentCity
      ,Ec.PermanentZipCode
      ,Ec.PermanentContactNo
      ,ES.EPFNumber
      ,ES.ESINumber
      ,ES.AccountNumber
      ,ES.BankName
      ,ES.Branch
      ,ES.IFSCNumber
      ,ES.PanNumber
      ,ES.BasicPay
      ,CONVERT(VARCHAR(10), ES.IncrementDate, 111) AS IncrementDate
      ,CONVERT(VARCHAR(10), ES.EPFJoinDate, 111) AS EPFJoinDate
      ,ISNULL(ES.Payscale,'') AS Payscale
      ,ISNULL(EPD.AdhaarNumber,'') AS AdhaarNumber
      
  FROM 
		sHrm.tEmployeeMaster EM
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
	INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
	INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = EPD.CastCategoryId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=EPD.GenderId
	LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EPD.ReligionId
	LEFT JOIN sCommon.tMaritalStatusMaster MSM ON MSM.Id=EPD.MaritalStatusId
	LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=EPD.BloodGroupId
	INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
	INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4 
	LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ES ON ES.EmployeeId = EM.Id
	LEFT JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id = EJD.EmployeeGroupId
GO
PRINT N'Altering [sStudent].[vStudentColumnName]...';


GO






















/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sStudent].[vStudentColumnName]  
  
AS 
 
 
SELECT 	
	  --SA.AcademicId,	  
	  --SA.ClassId,
	  --SA.DivisionId,
	  SA.RollNo,
	  --SA.OrgId,
	  --SA.BatchId,
	  BM.Title AS Batch,
	  --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,
	  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,
	  --AR.PickupDestinationId AS BusRouteDestinationId,
	  BDM.Title AS BusRouteDestination,
	  SF.FatherName,
	  SF.FatherDateOfBirth,	 
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome,
	  SF.MotherName,
	  SF.MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
      SF.MotherOfficeAddress,
      SF.MotherIncome,      
	  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.LeftDate,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.BankAccountNumber,
	  AD.BankName,
	  AD.BankBranch,
	  AD.BankIFSCCode,
	  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
	  
	  
  FROM sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	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.tNationalityMaster 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
GO

 
GO
PRINT N'Altering [sAccounting].[pLedgerBook]...';


GO
ALTER PROCEDURE [sAccounting].[pLedgerBook]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	@rLedgerGroupId [int],
	 @rAccountId  int=0
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN

    --  SELECT '' AS Builder1,
			 --'' AS Builder2,
    --         '' AS TransactionId,
			 --'' AS CREDIT,
			 --'' AS DEBIT,
			 --'' AS LedgerId,
			 --'' AS TransactionDate,
			 --'' AS VoucherNumber,
			 --'' AS Narration,
			 --'' AS VoucherType,
			 --'' AS TITLE,
			 --'' AS OpeningBalance,
			 --'' AS ClosingBalance,
			 -- '' AS ChequeNo
      
    
    DECLARE @1OpeningBalance DECIMAL(22,2)
    DECLARE @1ClosingBalance DECIMAl(22,2)
     
	CREATE TABLE #tempUpdateClosingBalance
	(	
	    Id INT IDENTITY (1, 1),
		LedgerId int,
		Temp_Op_Balance decimal(12,2),
		Closing_Balance decimal(12,2),
		Transaction_Balance decimal(12,2)	    
	) 
	
	INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
	EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@rLedgerId,''
		
	SELECT @1OpeningBalance = Temp_Op_Balance,@1ClosingBalance = Closing_Balance
	FROM #tempUpdateClosingBalance WHERE LedgerId = @rLedgerId

	SELECT 
	 @rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,
	T.Id AS TransactionId,
	ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * SUM(TD.AMOUNT) END,0) AS CREDIT,
	ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN SUM(TD.AMOUNT) END,0) AS DEBIT,
	TD.LedgerId,T.TransactionDate,T.VoucherNumber,T.Narration,
	VTM.Title As VoucherType,
	T.VoucherTypeId,
	--LEFT(VTM.Title,2) As VoucherType
	L.TITLE,
	ISNULL(@1OpeningBalance,0) AS OpeningBalance,
	ISNULL(@1ClosingBalance,0) AS ClosingBalance,
		AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2,
			T.ChequeNo
	
	from sAccounting.tTransaction T 
	INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id AND (TD.LedgerId <> @rLedgerId)
	INNER JOIN sAccounting.tLedgerMaster L ON L.Id=TD.LedgerId
	INNER JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
	INNER JOIN sAccounting.tLedgerGroupMaster LGM ON LGM.Id = L.LedgerGroupId
	INNER JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
	
	WHERE (T.TransactionDate >= @rStartDate)  AND
	(T.TransactionDate <= @rEndDate) AND 
	(LGM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0) AND
	(LGM.AccountingYearId=@rAccountingYearId or @rAccountingYearId=0) AND	
	(T.AccountingYearId=@rAccountingYearId OR @rAccountingYearId = 0) AND
	(L.LedgerGroupId = @rLedgerGroupId or @rLedgerGroupId = 0) AND L.AccountingYearId=@rAccountingYearId
	AND @rLedgerId IN (SELECT LedgerId FROM sAccounting.tTransactionDetail TD1 WHERE TD1.TRANSACTIONID=T.ID)
AND (T.AccountId=@rAccountId OR @rAccountId=0)  
	GROUP BY 	TD.LedgerId,T.TransactionDate,T.VoucherNumber,T.Id,
				TD.TransactionTypeId,L.Title,T.VoucherTypeId,VTM.Title,T.Narration,AM.ReportOrgTitle,AM.SmallAddress1,AM.SmallAddress2,
				T.ChequeNo
				
				
   order by T.VoucherTypeId,T.TransactionDate,T.VoucherNumber,Credit,Debit
END
GO
PRINT N'Altering [sAccounting].[pTrialBalance]...';


GO
ALTER PROCEDURE [sAccounting].[pTrialBalance]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rOrderBy smallint,
	@rLedgerGroupId int,
	 @rAccountId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

--SELECT '' AS OrgTitle,
--	   '' AS SmallAddress1,
--       '' As SmallAddress2,
-- '' AS Builder1,
--	   '' AS Builder2,
--       '' As Id,
--	   '' As LedgerId,
--	   '' As LedgerName,
--	   '' As LedgerGroup,
--	   '' As LedgerMainGroup,
--	   '' As LedgerTypeId,
--	   '' As CreditBalance,
--	   '' As DebitBalance,
--	   '' As OpeningBalance,
--	   '' As ClosingBalance

Declare @lLedgerId int 
Declare @lCashOpBalance Decimal (12,2)
Declare @lOpeningBalance Decimal (12,2)
Declare @lCreditBalance Decimal (12,2)
Declare @lDebitBalance Decimal (12,2)
Declare @lLOpeningBalance Decimal(12,2)
Declare @lCount int
Declare @lLedgerTypeId int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150)
Declare @ReportOrgTitle Nvarchar(200)
Declare @SmallAddress1  Nvarchar(200)
Declare	@SmallAddress2 Nvarchar(200)
	
	 SELECT @ReportOrgTitle=ReportOrgTitle ,@SmallAddress1=SmallAddress1, @SmallAddress2= SmallAddress2  
  From sAccounting.tAccountMaster AM Where AM.Id= @rAccountId  
	
    CREATE TABLE #tempUpdateClosingBalance
 		(	Id INT IDENTITY (1, 1),
 			LedgerId int,
 			Temp_Op_Balance decimal(12,2),
 			Closing_Balance decimal(12,2),
 			Transaction_Balance decimal(12,2) 			
 		)
 		
	   CREATE TABLE #tTempTrialBalance
 		(	Id INT IDENTITY (1,1),
 			LedgerId int,
 			LedgerName varchar(100),
 			LedgerGroup varchar(100),
			LedgerMainGroup Varchar(100), 			
 			LedgerTypeId int,
 			CreditBalance decimal(12,2),
 			DebitBalance decimal(12,2),
 			OpeningBalance decimal(12,2),
 			ClosingBalance Decimal(12,2)
 		) 
 		INSERT INTO #tTempTrialBalance    
		SELECT L.Id, L.Title,LG.Title AS GName, LGM.Title AS MGName ,L.LedgerTypeId,0,0,L.OpeningBalance,0		
		FROM sAccounting.tLedgerMaster L INNER JOIN sAccounting.tLedgerGroupMaster LG on LG.Id=L.LedgerGroupId
		INNER JOIN sAccounting.tLedgerMainGroupMaster LGM ON LGM.Id = LG.LEDGERMAINGROUPID
		And LG.OrgGroupId= @rOrgGroupId AND L.AccountingYearId=@rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		AND (LG.Id = @rLedgerGroupId or @rLedgerGroupId=0 )
	  
	--select * from #tTemptrialBalance
	 
	SELECT @lCount =  COUNT(Id) FROM #tTempTrialBalance
	WHILE (@lCount > 0)
	BEGIN
		SELECT @lLedgerId=LedgerId,@lCreditBalance=CreditBalance,@lDebitBalance=DebitBalance,
		@lLedgerName=LedgerName,@lLedgerTypeId=LedgerTypeId,@lOpeningBalance=OpeningBalance,@lLedgerGroupName=LedgerGroup,
		@lLedgerMainGroupName=LedgerMainGroup	FROM #tTempTrialBalance WHERE Id= @lCount
	
		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,@lLedgerId,''
		SET @lCount = @lCount - 1
	END	
	
	--select UC.LedgerId,TB.LedgerName,Temp_Op_Balance,Closing_Balance from #tempUpdateClosingBalance UC INNER JOIN #tTemptrialBalance TB ON TB.LedgerId = UC.LedgerId
	
	IF @rOrderBy = 0 
	BEGIN
		SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2,  @rBuilder1 AS Builder1
	    ,@rBuilder2 AS Builder2,TB.LedgerId,TB.LedgerName,TB.LedgerGroup,TB.LedgerMainGroup,T.Temp_Op_Balance AS OpeningBalance,
		ISNULL(CASE WHEN T.Transaction_Balance < 0 THEN -1 * T.Transaction_Balance END,0) AS CreditBalance,
		ISNULL(CASE WHEN T.Transaction_Balance >= 0 THEN T.Transaction_Balance ENd,0) AS DebitBalance,
		
		--ISNULL(CASE WHEN T.Temp_Op_Balance < 0 THEN (-1) * T.Temp_Op_Balance END,0) AS CreditBalance,
		--ISNULL(CASE WHEN T.Temp_Op_Balance >= 0 THEN T.Temp_Op_Balance ENd,0) AS DebitBalance,
		
		T.Closing_Balance AS ClosingBalance
		FROM #tempUpdateClosingBalance T 
		INNER JOIN #tTempTrialBalance TB on T.LedgerId=TB.LedgerId ORDER BY TB.LedgerName
	END
	ELSE
	BEGIN
		SELECT @ReportOrgTitle  AS OrgTitle,
	@SmallAddress1 AS SmallAddress1,
	@SmallAddress2 AS SmallAddress2,  @rBuilder1 AS Builder1
	    ,@rBuilder2 AS Builder2,0 AS LedgerId,'' AS LedgerName,TB.LedgerGroup,TB.LedgerMainGroup,Sum(T.Temp_Op_Balance) AS OpeningBalance,
	    Sum(ISNULL(CASE WHEN T.Transaction_Balance < 0 THEN -1 * T.Transaction_Balance END,0)) AS CreditBalance,
		Sum(ISNULL(CASE WHEN T.Transaction_Balance >= 0 THEN T.Transaction_Balance ENd,0)) AS DebitBalance,
		--ISNULL(CASE WHEN TB.LedgerTypeId =1 THEN T.Transation_Balance END,0) AS CreditBalance,
		--ISNULL(CASE WHEN TB.LedgerTypeId =2 THEN T.Transation_Balance ENd,0) AS DebitBalance,
		Sum(T.Closing_Balance) AS ClosingBalance
		FROM #tempUpdateClosingBalance T inner join #tTempTrialBalance TB on T.LedgerId=TB.LedgerId GRoup BY TB.LedgerGroup,TB.LedgerMainGroup
	END
	
	DROP Table #tempUpdateClosingBalance
	
END
GO
PRINT N'Altering [sActivity].[pXMLEventHoliday]...';


GO


ALTER PROCEDURE [sActivity].[pXMLEventHoliday]
	(
		@rXmlDoc nvarchar(MAX),
		@rOrgId int
	) 
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
			
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	DECLARE @lNextNumber BIGINT    
	DECLARE @lOrgId smallint
	DECLARE @lCount int
	DECLARE @lDivisionId int
	DECLARE @lEventSchduleCount int
	DECLARE @lEventSchduleId int
	
	
	-----------------------  UPDATE EventSchedule
	UPDATE sActivity.tEventSchedule
	SET	
		FromDate = A.FromDate,
		ToDate = A.ToDate,
		Title = A.Title,
		UpdatedUserId = 9999000000003,
		UpdatedDateTime = sCommon.fGetDate() 
	FROM 
	(
	SELECT
		Id,
		FromDate,
		ToDate,
		Title,
		BatchId
	FROM OPENXML (@intDoc, '/Table/Holiday', 1)
	WITH
	(
		Id int '@Id',
		FromDate datetime '@FromDate',
		ToDate datetime '@ToDate',
		Title nvarchar(100) '@Title',
		BatchId int '@BatchId'	
	))A
	 WHERE sCommon.fGetIntIdForOrg(A.Id,@rOrgId) = sActivity.tEventSchedule.Id 
	AND sCommon.fGetIntIdForOrg(A.BatchId,@rOrgId) = sActivity.tEventSchedule.BatchId 
	

	-----------------------  INSERT EventSchedule holiday
	INSERT INTO sActivity.tEventSchedule
	(
		Id,
		BatchId,
		FromDate,
		ToDate,
		Title,
		IsCommonForAll,
		IsEnrollment,
		IsHoliday,
		CreatedUserId,
		CreatedDateTime
	)
	SELECT		
		sCommon.fGetIntIdForOrg(A.Id,@rOrgId),
		A.BatchId,
		A.FromDate,
		A.ToDate,
		A.Title,
		1,
		1,
		1,
		9999000000003,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/Holiday', 1)
	WITH
	(
		Id int '@Id',
		FromDate datetime '@FromDate',
		ToDate datetime '@ToDate',
		Title nvarchar(100) '@Title',
		BatchId int '@BatchId'	
	) A LEFT JOIN sActivity.tEventSchedule ES ON 
	sCommon.fGetIntIdForOrg(A.Id,@rOrgId) = ES.Id AND A.BatchId = ES.BatchId
	WHERE ES.Id IS NULL 
	
	DECLARE @lEvetntTypeId int

	SELECT @lEvetntTypeId= Id FRom sActivity.tEventTypeMaster ET Where EventMainTypeId = 1 AND OrgGroupId IN
	(select OrgGroupId from sSetup.tOrganizationMaster Where Id = @rOrgId)
	
	
	Update ES SET ES.EventTypeId = @lEvetntTypeId From sActivity.tEventSchedule ES inner join 
	(SELECT sCommon.fGetIntIdForOrg(A.Id,@rOrgId) AS Id	,BatchId	
	FROM OPENXML (@intDoc, '/Table/Holiday', 1)
	WITH
	(
		Id int '@Id',
		BatchId int '@BatchId'	
	)A) A1  ON 
	A1.Id = ES.Id AND A1.BatchId = ES.BatchId
	
	
	CREATE Table #EventSchedule (Id Int Identity,EventScheduleId int)
	
	Insert Into #EventSchedule SELECT sCommon.fGetIntIdForOrg(A.Id,@rOrgId)		
	FROM OPENXML (@intDoc, '/Table/Holiday', 1)
	WITH
	(
		Id int '@Id',
		BatchId int '@BatchId'	
	) A INNER JOIN sActivity.tEventSchedule ES ON 
	sCommon.fGetIntIdForOrg(A.Id,@rOrgId) = ES.Id AND A.BatchId = ES.BatchId
	
	
	SELECT @lEventSchduleCount = Max(Id) FROM #EventSchedule
	
	CREATE Table #Division (Id Int Identity,DivId int)
	Insert into #Division Select Id From sSetup.tDivisionMaster Where OrgId = @rOrgId
	
	While @lEventSchduleCount > 0
	BEGIN
		SELECT @lEventSchduleId = EventScheduleId From #EventSchedule Where Id = @lEventSchduleCount		
		Select @lCount = Max(id) From #Division	
		While @lCount > 0 
		BEGIN
			SELECT @lDivisionId = DivId From #Division Where Id = @lCount			
			IF NOT EXISTS (SELECT 1 FROM sActivity.tEventAssign WHERE SourceTypeId = 2005 AND EventScheduleId = @lEventSchduleId AND SourceId = @lDivisionId )
			BEGIN
				Exec [sActivity].[pEventAssignAdd] 0,@lEventSchduleId,2005,@lDivisionId,0,@rOrgId	
			END
			SET @lCount = @lCount - 1
		END
		SET @lEventSchduleCount = @lEventSchduleCount  -1
	END	      
           
	
	Drop Table #Division
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END
GO
PRINT N'Altering [sAdmission].[pAdmissionCriteriaOnlineGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaOnlineGet]
	 @rClassId int = 0,
	 @rBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
	   [ClassId]
      ,[BatchId]
      ,[IsValidateBirthdate]
      ,[FromDateOfBirth]
      ,[ToDateOfBirth]
      ,[IsParentAcademicRequired]
      ,[IsStudentAcademicRequired]
      ,[IsFamilyDetailRequired]
      ,[IsSiblingDetailRequired]
      ,[IsReferenceDetailRequired]
      ,[IsFixStudentAcademic]
      ,[StudentAcademicFor]
      ,[StudentAcademicRemark]
      ,[FamilyDetailRemark]
      ,[IsFixParentAcademic]
      ,[ParentAcademicFor]
      ,[ParentAcademicRemark]
      ,[ConfirmationRemark]
      ,[AdmissionFormRemark]
      ,[Reference1]
      ,[Reference2]
      ,[IsOtherInformationRequired]
      ,[IsPayFormFeeOnline]
      ,[FormFeeName]
      ,[FormFeeAmount]
      ,Isnull(IsHostelDetailRequired,0) As IsHostelDetailRequired
      ,Isnull(IsTransportDetailRequired,0) AS IsTransportDetailRequired
      ,Isnull(IsHealthDetailRequired,0) AS IsHealthDetailRequired
      ,Isnull(IsBirthPlaceDetailRequired,0) aS IsBirthPlaceDetailRequired
      ,Isnull(IsAadhaarDetailRequired,0) As IsAadhaarDetailRequired
      ,Isnull(IsBloodGroupDetailRequired,0) As IsBloodGroupDetailRequired,
      Isnull(IsFatherDetail,0) As IsFatherDetail,
      Isnull(IsFatherFullDetail,0) As IsFatherFullDetail,
       Isnull(IsFatherAcademic,0) As IsFatherAcademic,
       Isnull(IsMotherDetail,0) As IsMotherDetail,
        Isnull(IsMotherFullDetail,0) As IsMotherFullDetail,
         Isnull(IsMotherAcademic,0) As IsMotherAcademic,
          Isnull(IsGuardianDetail,0) As IsGuardianDetail,
        Isnull(IsGuardianFullDetail,0) As IsGuardianFullDetail   ,
        Isnull(IsGuardianAcademic,0) As IsGuardianAcademic
  FROM sAdmission.tAdmissionCriteria
  WHERE 
		 ((ClassId=@rClassId) OR (@rClassId=0))
		AND BatchId=@rBatchId
END
GO
PRINT N'Altering [sAdmission].[pAdmissionCriteriaSetupAdd]...';


GO

ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaSetupAdd]
		@rClassId int
		,@rBatchId int
		,@rIsValidateBirthdate bit
		,@rFromDateOfBirth date
		,@rToDateOfBirth date
		,@rIsParentAcademicRequired bit
		,@rIsStudentAcademicRequired bit
		,@rIsFamilyDetailRequired bit
		,@rIsSiblingDetailRequired bit
		,@rIsReferenceDetailRequired bit
		
		,@rIsFixStudentAcademic bit
		,@rStudentAcademicFor nvarchar(300)
		,@rStudentAcademicRemark nvarchar(max)
		,@rFamilyDetailRemark nvarchar(max)
		,@rIsFixParentAcademic bit
		,@rParentAcademicFor nvarchar(300)
		,@rParentAcademicRemark nvarchar(max)
		,@rConfirmationRemark nvarchar(max)
		,@rAdmissionFormRemark nvarchar(max),
		@rReference1 nvarchar(150),
		@rReference2 nvarchar(150),
		@rIsOtherInformationRequired bit,
		@rIsPayFormFeeOnline bit = NULL,
		@rFormFeeName nvarchar(100)=NULL,
		@rFormFeeAmount decimal(12,2)=NULL,
		@rIsHostelDetailRequired	bit	,
		@rIsTransportDetailRequired	bit	,
		@rIsHealthDetailRequired	bit	,
		@rIsBirthPlaceDetailRequired	bit	,
		@rIsAadhaarDetailRequired	bit	,
		@rIsBloodGroupDetailRequired	bit,
		@rReceiptBookId int = NULL	,
		@rIsFatherDetail bit=0,
		@rIsFatherFullDetail bit=0,
		@rIsFatherAcademic bit=0,
		@rIsMotherDetail bit=0,
		@rIsMotherFullDetail bit=0,
		@rIsMotherAcademic bit=0,
		@rIsGuardianDetail bit=0,
		@rIsGuardianFullDetail bit=0,
		@rIsGuardianAcademic bit=0
		
		
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	

	
 BEGIN TRANSACTION	
	
	IF(@rFormFeeAmount=0)
		SET @rFormFeeAmount=NULL
	
	Delete from sAdmission.tAdmissionCriteria where ClassId=@rClassId AND BatchId=@rBatchId

	INSERT INTO sAdmission.tAdmissionCriteria
		(
			 ClassId
			 ,BatchId
			 ,IsValidateBirthdate
			 ,FromDateOfBirth
			,ToDateOfBirth
			,IsParentAcademicRequired
			,IsStudentAcademicRequired
			,IsFamilyDetailRequired
			,IsSiblingDetailRequired
			,IsReferenceDetailRequired
			
			,IsFixStudentAcademic
			,StudentAcademicFor
			,StudentAcademicRemark
			,FamilyDetailRemark
			,IsFixParentAcademic
			,ParentAcademicFor
			,ParentAcademicRemark
			,ConfirmationRemark
			,AdmissionFormRemark,
			Reference1,
			Reference2,
			IsOtherInformationRequired,
			IsPayFormFeeOnline,
			FormFeeName,
			FormFeeAmount,
			IsHostelDetailRequired,
			IsTransportDetailRequired,
			IsHealthDetailRequired,
			IsBirthPlaceDetailRequired,
			IsAadhaarDetailRequired,
			IsBloodGroupDetailRequired,
			ReceiptBookId	,
			IsFatherDetail,
			IsFatherFullDetail,
			IsFatherAcademic,
			IsMotherDetail,
			IsMotherFullDetail,
			IsMotherAcademic,
			IsGuardianDetail,
			IsGuardianFullDetail,
			IsGuardianAcademic
		)
	VALUES
		(
			 @rClassId
			,@rBatchId
			,@rIsValidateBirthdate
			,@rFromDateOfBirth
			,@rToDateOfBirth
			,@rIsParentAcademicRequired
			,@rIsStudentAcademicRequired
			,@rIsFamilyDetailRequired
			,@rIsSiblingDetailRequired
			,@rIsReferenceDetailRequired
			
			,@rIsFixStudentAcademic
			,@rStudentAcademicFor
			,@rStudentAcademicRemark
			,@rFamilyDetailRemark
			,@rIsFixParentAcademic
			,@rParentAcademicFor
			,@rParentAcademicRemark
			,@rConfirmationRemark
			,@rAdmissionFormRemark,
			@rReference1,
			@rReference2,
			@rIsOtherInformationRequired,
			@rIsPayFormFeeOnline,
			@rFormFeeName,
			@rFormFeeAmount,
			@rIsHostelDetailRequired,
			@rIsTransportDetailRequired,
			@rIsHealthDetailRequired,
			@rIsBirthPlaceDetailRequired,
			@rIsAadhaarDetailRequired,
			@rIsBloodGroupDetailRequired,	
			@rReceiptBookId,
			@rIsFatherDetail,
			@rIsFatherFullDetail,
			@rIsFatherAcademic,
			@rIsMotherDetail,
			@rIsMotherFullDetail,
			@rIsMotherAcademic,
			@rIsGuardianDetail,
			@rIsGuardianFullDetail,
			@rIsGuardianAcademic
			
		)
		     SELECT 103 AS Result
	
		COMMIT TRANSACTION
	
			
END
GO
PRINT N'Altering [sAdmission].[pAdmissionCriteriaSetupGet]...';


GO


ALTER PROCEDURE [sAdmission].[pAdmissionCriteriaSetupGet]
	 
	 @rClassId int=0,
	 @rBatchId int=0
	 
	  

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	 

BEGIN 
	 
	 
	
	SELECT 
		
		ClassId,
		BatchId,
		ISNULL(IsValidateBirthdate,'') AS IsValidateBirthdate,
		ISNULL(FromDateOfBirth,'') AS FromDateOfBirth,
		ISNULL(ToDateOfBirth,'')AS ToDateOfBirth,
		ISNULL(IsParentAcademicRequired,'') AS IsParentAcademicRequired,
		ISNULL(IsStudentAcademicRequired,'') AS IsStudentAcademicRequired,
		ISNULL(IsFamilyDetailRequired,'') AS IsFamilyDetailRequired,
		ISNULL(IsSiblingDetailRequired,'') AS IsSiblingDetailRequired,
		ISNULL(IsReferenceDetailRequired,'') AS IsReferenceDetailRequired,
		
		ISNULL(IsFixStudentAcademic,'') AS IsFixStudentAcademic,
		StudentAcademicFor,
		StudentAcademicRemark,
		FamilyDetailRemark,
		ISNULL(IsFixParentAcademic,'') AS IsFixParentAcademic,
		ParentAcademicFor,
		ParentAcademicRemark,
		ConfirmationRemark,
		AdmissionFormRemark,
		ISNULL(Reference1,'') AS Reference1,
		ISNULL(Reference2,'')AS Reference2,
		ISNULL(IsOtherInformationRequired,0) As IsOtherInformationRequired,
		ISNULL(IsPayFormFeeOnline,0) AS IsPayFormFeeOnline,
		ISNULL(FormFeeName,'') AS FormFeeName,
		ISNULL(FormFeeAmount,0) AS FormFeeAmount,
		ISNULL(IsHostelDetailRequired,0) AS IsHostelDetailRequired,
		ISNULL(IsTransportDetailRequired,0) AS IsTransportDetailRequired,
		ISNULL(IsHealthDetailRequired,0) AS IsHealthDetailRequired,
		ISNULL(IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired,
		ISNULL(IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired,
		ISNULL(IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
		ISNULL(ReceiptBookId,0) AS ReceiptBookId,
		ISNULL(IsFatherDetail,0) AS IsFatherDetail,
		ISNULL(IsFatherFullDetail,0) AS IsFatherFullDetail,
		ISNULL(IsFatherAcademic,0) AS IsFatherAcademic,
		ISNULL(IsMotherDetail,0) AS IsMotherDetail,
		ISNULL(IsMotherFullDetail,0) AS IsMotherFullDetail,
		ISNULL(IsMotherAcademic,0) AS IsMotherAcademic,
		ISNULL(IsGuardianDetail,0) AS IsGuardianDetail,
		ISNULL(IsGuardianFullDetail,0) AS IsGuardianFullDetail,
		ISNULL(IsGuardianAcademic,0) AS IsGuardianAcademic
  FROM 
            sAdmission.tAdmissionCriteria
			 
  WHERE 
   (ClassId=@rClassId)
   AND BatchId=@rBatchId
	
END
GO
PRINT N'Altering [sAdmission].[pAdmissionFormFamilyDetailAdd]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionFormFamilyDetailAdd]
		 @rId bigint,
		 @rFatherName nvarchar(100),
		 @rFatherDateOfBirth date,
		 @rFatherOccupation nvarchar(50),
		 @rFatherQualification nvarchar(50),
		 @rFatherContactNo nvarchar(50),
		 @rFatherMail nvarchar(50),
		 @rFatherOfficeAddress nvarchar(300),
		 @rFatherIncome int,
		 
		 @rMotherName nvarchar(100),
		 @rMotherDateOfBirth date,
		 @rMotherOccupation nvarchar(50),
		 @rMotherQualification nvarchar(50),
		 @rMotherContactNo nvarchar(50),
		 @rMotherMail nvarchar(50),
		 @rMotherOfficeAddress nvarchar(300),
		 @rMotherIncome int,
		
		 @rRelationshipName nvarchar(100),
		 @rGuardianName nvarchar(100),
		 @rGuardianDateOfBirth date,
		 @rGuardianOccupation nvarchar(50),
		 @rGuardianQualification nvarchar(50),
		 @rGuardianContactNo nvarchar(50),
		 @rGuardianMail nvarchar(50),
		 @rGuardianOfficeAddress nvarchar(300),
		 @rGuardianIncome int,
		 @rCreatedUserId bigint,
		 @rCreatedDateTime date,
		 --@rUpdatedUserId bigint,
		 --@rUpdatedDateTime date,
		 @rFatherPhoto varbinary(max)=0,
		  @rMotherPhoto varbinary(max)=0,
		 @rGuardianPhoto varbinary(max)=0,
		 @rFatherOrganization nvarchar(200)='',
		 @rFatherDesignation nvarchar(100)='',
		 @rFatherOfficePhone nvarchar(100)='',
		 @rMotherOrganization nvarchar(200)='',
		 @rMotherDesignation nvarchar(100)='',
		 @rMotherOfficePhone nvarchar(100)='',
		 @rRelativeOrganization nvarchar(200)='',
		 @rRelativeDesignation nvarchar(100)='',
		 @rRelativeOfficePhone nvarchar(100)='',
		 @rLiveWithId smallint=0,
		 @rIsFatherExStudent bit=0,
		 @rFatherPassOutYear nvarchar(50)='',
		 @rIsMotherExStudent bit=0,
		 @rMotherPassOutYear nvarchar(50)='',
		 @rIsRelativeExStudent bit=0,
		 @rRelativePassOutYear nvarchar(50)=''
		 
		 
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	

	
 BEGIN TRANSACTION	
	
	IF NOT EXISTS (Select AdmissionFormId from sAdmission.tAdmissionFormFamilyDetail where AdmissionFormId = @rId)
	BEGIN
	INSERT INTO sAdmission.tAdmissionFormFamilyDetail
		(
		AdmissionFormId,
		 FatherName,
		 FatherDateOfBirth,
		 FatherOccupation,
		 FatherQualification,
		 FatherContactNo,
		 FatherMail,
		 FatherOfficeAddress,
		 FatherIncome,
		 MotherName,
		 MotherDateOfBirth,
		 MotherOccupation,
		 MotherQualification,
		 MotherContactNo,
		 MotherMail,
		 MotherOfficeAddress,
		 MotherIncome,
		 
		 RelationshipName,
		 RelativeName,
		 RelativeDateOfBirth,
		 RelativeOccupation,
		 RelativeQualification,
		 RelativeContactNo,
		 RelativeMail,
		 RelativeOfficeAddress,
		 RelativeIncome,
		 CreatedUserId,
		 CreatedDateTime,
		 FatherPhoto,
		 MotherPhoto,
		 RelativePhoto,
		 FatherOrganization,
		 FatherDesignation,
		 FatherOfficePhone,
		 MotherOrganization,
		 MotherDesignation,
		 MotherOfficePhone,
		 RelativeOrganization,
		 RelativeDesignation,
		 RelativeOfficePhone,
		 LiveWithId,
		 IsFatherExStudent,
		 FatherPassOutYear,
		 IsMotherExStudent,
		 MotherPassOutYear,
		 IsRelativeExStudent,
		 RelativePassOutYear
		 
		)
	VALUES
		(
	     @rId,
		 @rFatherName,
		 @rFatherDateOfBirth,
		 @rFatherOccupation,
		 @rFatherQualification,
		 @rFatherContactNo,
		 @rFatherMail,
		 @rFatherOfficeAddress,
		 @rFatherIncome,
		 
		 @rMotherName,
		 @rMotherDateOfBirth,
		 @rMotherOccupation,
		 @rMotherQualification,
		 @rMotherContactNo,
		 @rMotherMail,
		 @rMotherOfficeAddress,
		 @rMotherIncome,
		 
		 @rRelationshipName,
		 @rGuardianName,
		 @rGuardianDateOfBirth,
		 @rGuardianOccupation,
		 @rGuardianQualification,
		 @rGuardianContactNo,
		 @rGuardianMail,
		 @rGuardianOfficeAddress,
		 @rGuardianIncome,
		 
		 @rCreatedUserId,
		 @rCreatedDateTime,
		 
		 @rFatherPhoto,
		 @rMotherPhoto,
		 @rGuardianPhoto,
		 @rFatherOrganization,
		 @rFatherDesignation,
		 @rFatherOfficePhone,
		 @rMotherOrganization,
		 @rMotherDesignation,
		 @rMotherOfficePhone,
		 @rRelativeOrganization,
		 @rRelativeDesignation,
		  @rRelativeOfficePhone,
		  @rLiveWithId,
		  @rIsFatherExStudent,
		  @rFatherPassOutYear,
		  @rIsMotherExStudent,
		  @rMotherPassOutYear,
		  @rIsRelativeExStudent,
		  @rRelativePassOutYear
		  
		)
		             
	END	 
	 ELSE
	 BEGIN

	    UPDATE  sAdmission.tAdmissionFormFamilyDetail
	    SET

	     AdmissionFormId = @rId,
		 FatherName = @rFatherName,
		 FatherDateOfBirth = @rFatherDateOfBirth,
		 FatherOccupation = @rFatherOccupation,
		 FatherQualification = @rFatherQualification,
		 FatherContactNo = @rFatherContactNo,
		 FatherMail = @rFatherMail,
		 FatherOfficeAddress = @rFatherOfficeAddress,
		 FatherIncome = @rFatherIncome,
		 MotherName = @rMotherName,
		 MotherDateOfBirth = @rMotherDateOfBirth,
		 MotherOccupation = @rMotherOccupation,
		 MotherQualification = @rMotherQualification,
		 MotherContactNo = @rMotherContactNo,
		 MotherMail = @rMotherMail,
		 MotherOfficeAddress = @rMotherOfficeAddress,
		 MotherIncome = @rMotherIncome,
		 RelationshipName = @rRelationshipName,
		 RelativeName = @rGuardianName,
		 RelativeDateOfBirth = @rGuardianDateOfBirth,
		 RelativeOccupation = @rGuardianOccupation,
		 RelativeQualification = @rGuardianQualification,
		 RelativeContactNo = @rGuardianContactNo,
		 RelativeMail = @rGuardianMail,
		 RelativeOfficeAddress = @rGuardianOfficeAddress,
		 RelativeIncome = @rGuardianIncome,
		 UpdatedUserId = @rCreatedUserId,
		 UpdatedDateTime = sCommon.fGetDate(),
		 FatherPhoto = @rFatherPhoto,
		 MotherPhoto = @rMotherPhoto,
		 RelativePhoto = @rGuardianPhoto,
		 FatherOrganization=@rFatherOrganization,
	      FatherDesignation =@rFatherDesignation,
	      FatherOfficePhone=@rFatherOfficePhone,
	      MotherOrganization=@rMotherOrganization,
	      MotherDesignation=@rMotherDesignation,
	    MotherOfficePhone=@rMotherOfficePhone,
	    RelativeOrganization=@rRelativeOrganization,
	    RelativeDesignation=@rRelativeDesignation,
	    RelativeOfficePhone=@rRelativeOfficePhone ,
	    LiveWithId=@rLiveWithId,
	    IsFatherExStudent =@rIsFatherExStudent ,
	    FatherPassOutYear = @rFatherPassOutYear,
	    MotherPassOutYear = @rMotherPassOutYear,
	    IsRelativeExStudent =@rIsRelativeExStudent,
	    RelativePassOutYear = @rRelativePassOutYear
	    
	    
			
	      WHERE AdmissionFormId = @rId 	   
	 END  
		SELECT @rId AS Result
	
		COMMIT TRANSACTION
		
	
	
		
END
GO
PRINT N'Altering [sAdmission].[pAdmissionInquiryGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionInquiryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rId bigint = 0,
	 
	 @rForClassId int = 0,
	 @rClassId int = 0,
	 @rBatchId int = 0,
	 @rStatusId int =0,
	-- @rStatusId smallint,
	 @rInquiryStatusMasterId int = 0,
	 @rOrgId int,
	 @rFirstName nvarchar(100) = '',
	 @rLastName nvarchar(100) = '',
	 @rFromDate datetime='',
	 @rToDate datetime='',
	 @rForBatchId int = 0,
	 @rDepartmentId int,
	 @rFromMeritMarks decimal(10,2) = 0,
	 @rToMeritMarks decimal(10,2)=0,
	 @rInquiryModeId smallint=0,
	 @rInquiryReferenceId int=0,
	 @rNumber bigint=0,
	 @rOrgGroupBatchId int = 0,
	 @rFollowUpdate datetime='',
	 @rIsTransportRequired int=0,
	 @rIsHostelRequired int=0,
	 @rOrderBy int =0
	 
	 
	 --@rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	 SET @rToDate = DATEADD(d,1,@rToDate)
	 --IF @rIsSearch = 1
		BEGIN
			SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName= sCommon.fSearchStringGet(@rLastName)
		END
	
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 AI.Id
			,AI.ForBatchId
			,AI.ForClassId
			,AI.StatusId
			,ISNULL(SM.Id,0) AS InquiryStatusMasterId
			,ISNULL(AI.GenderId,0) AS GenderId
			,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
			,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		    ,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		    ,AI.OrgId
		    ,ISNULL(AI.Number,0) AS InquiryNumber
		    ,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		    ,OM.DisplayTitle AS OrgName
		    ,BM.Title AS ForBatch
			,ISNULL(CM.Title,'') AS ClassName	
			,AI.FirstName
			,AI.MiddleName
			,AI.LastName
			,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
			,AI.DateOfBirth
			,ISNULL(GM.Title,'') As Gender			
			,AI.ContactNo
			,AI.ContactEmail			
			,AI.StreetOne
			,AI.StreetTwo
			,AI.StreetThree
			,AI.Country
			,AI.State
			,AI.City
			,AI.ZipCode
			,ISNULL(AI.Remark,'') AS Remark						
		    ,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
			,ISNULL(AI.MeritMarks,0) AS MeritMarks
			,ISNULL(AI.MeritGrade,'') AS MeritGrade
			,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
			,SM.Title as StatusName			
			,ISNULL(AI.FollowupDate,'') As FollowupDate
			,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
			,ISNULL(IRM.Title ,'') AS InquiryReference	
			,ISNULL(SCM.Title,'') AS AdmissionCategory		
			,ISNULL(AI.HandledBy,'') AS HandledBy
			,AI.CreatedDateTime
			,ISNULL(AI.StudentId,0) AS StudentId,
			ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
			ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
			ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
			ISNULL(SM.HighlightColor,'') AS HighlightColor,
			ISNULL(SA.PreviousStandard,'') As PreviousStandard
  FROM 
            sAdmission.tAdmissionInquiry AI
           --INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AI.StatusId AND StatusTypeId=104
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  --AND ((AI.StatusId=@rStatusId) OR (@rStatusId=0))
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (@rNumber=0))
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
	  AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN AI.IsTransportRequired
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	  
	  AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN AI.IsHostelRequired
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	  --AND ((AI.IsTransportRequired=@rIsTransportRequired) OR (@rIsTransportRequired=0))	   
	    --AND ((AI.IsHostelRequired =@rIsHostelRequired) OR (@rIsHostelRequired=0))
	  Order by Case @rOrderBy When 1 then AI.MeritMarks END desc ,
			    Case @rOrderBy when 0 then AI.Number Else 
			    AI.Number  END  
END
GO
PRINT N'Altering [sAdmission].[pExportAllAdmissionFormDetail]...';


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

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


	 
	

)
INsert into #tempStudentAcademic
(AdmissionFormId, 
StudentAcademicYear1  ,	StudentAdmissionClass1  ,	StudentInstituteName1  ,	StudentInstituteCity1  ,	StudentInstituteAffiliaton1   ,	StudentLanguage1  ,	StudentResult1  ,
	StudentAcademicYear2  ,	StudentAdmissionClass2  ,	StudentInstituteName2  ,	StudentInstituteCity2  ,	StudentInstituteAffiliaton2  ,	StudentLanguage2  ,	StudentResult2   ,
	StudentAcademicYear3   ,	StudentAdmissionClass3  ,	StudentInstituteName3  ,	StudentInstituteCity3  ,	StudentInstituteAffiliaton3  ,	StudentLanguage3  ,	StudentResult3  ,
	StudentAcademicYear4  ,	StudentAdmissionClass4  ,	StudentInstituteName4  ,	StudentInstituteCity4  ,	StudentInstituteAffiliaton4  ,	StudentLanguage4   ,	StudentResult4  ,
	StudentAcademicYear5  ,	StudentAdmissionClass5  ,	StudentInstituteName5  ,	StudentInstituteCity5  ,	StudentInstituteAffiliaton5  ,	StudentLanguage5  ,	StudentResult5  ,
	StudentAcademicYear6  ,	StudentAdmissionClass6  ,	StudentInstituteName6  ,	StudentInstituteCity6  ,	StudentInstituteAffiliaton6  ,	StudentLanguage6  ,	StudentResult6  ,
	StudentAcademicYear7  ,	StudentAdmissionClass7  ,	StudentInstituteName7  ,	StudentInstituteCity7  ,	StudentInstituteAffiliaton7  ,	StudentLanguage7   ,	StudentResult7  ,
	StudentAcademicYear8  ,	StudentAdmissionClass8  ,	StudentInstituteName8  ,	StudentInstituteCity8  ,	StudentInstituteAffiliaton8  ,	StudentLanguage8  ,	StudentResult8  ,
	StudentAcademicYear9  ,	StudentAdmissionClass9  ,	StudentInstituteName9  ,	StudentInstituteCity9  ,	StudentInstituteAffiliaton9  ,	StudentLanguage9  ,	StudentResult9  ,
	StudentAcademicYear10  ,	StudentAdmissionClass10  ,	StudentInstituteName10  ,	StudentInstituteCity10  ,	StudentInstituteAffiliaton10  ,	StudentLanguage10  ,	StudentResult10  
	
)

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

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

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


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

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

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

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


 

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

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

SELECT * from #tempAdmissionForm tempAF
LEFT JOIN #tempStudentAcademic tempSA ON tempSA.AdmissionFormId = tempAF.AdmissionFormId
LEFT JOIN #tempFatherAcademic tempFA ON tempFA.AdmissionFormId=tempAF.AdmissionFormId
LEFT JOIN #tempReference tempRF on tempRF.AdmissionFormId=tempAF.AdmissionFormId
LEFT JOIN #TempSibling tempSB ON tempSB.AdmissionFormId = tempAF.AdmissionFormId
 
Order by tempAF.Formno

END
GO
PRINT N'Altering [sAlert].[pAppRegisteredUserGet]...';


GO
ALTER PROCEDURE [sAlert].[pAppRegisteredUserGet]
	@rOrgId int,
	@rOSTypeId tinyint=0,	
	@rFromDate date,
	@rToDate date,
	@rDepartmentId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rCode nvarchar(20)='',
	@rUserSourceTypeId smallint	,
	@rOrgGroupId int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
if(@rUserSourceTypeId=2003)
BEGIN
SELECT 
	OM.Title AS OrganizationName,
	RU.UserSourceId AS UserSourceId,
	RU.UserSourceTypeId AS UserSourceTypeId,
	'Student' AS UserTypeName,
	SA.Code AS Code,
	SA.ClassName + ' ' + SA.DivisionName AS Class,
	SA.Name AS Name,
	RU.CreatedDateTime AS Date,
	OT.Title AS OSType,
	SA.DepartmentName AS Department,
	CONVERT(bit,CASE WHEN ISNULL(RU.DeviceToken,'') = '' THEN 0 ELSE 1 END) AS IsDeviceToken
	FROM		
		sCommunication.tRegisteredUsers RU
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=RU.OrgId				
		INNER JOIN sAlert.tOSType OT ON OT.ID =RU.OSTypeId											
		INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId = RU.UserSourceId AND RU.UserSourceTypeId=2003	
	WHERE
	((RU.OrgId = @rOrgId) OR (@rOrgId=0))
		AND((RU.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))		
		AND((SA.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
	AND ((SA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CONVERT(date,RU.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,RU.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))	
		AND OM.OrgGroupId =@rOrgGroupId
	ORDER BY RU.OrgId,RU.OSTypeId,RU.UserId ASC,RU.CreatedDateTime DESC	
END
ELSE
BEGIN
SELECT 
	OM.Title AS OrganizationName,
	RU.UserSourceId AS UserSourceId,
	RU.UserSourceTypeId AS UserSourceTypeId,
	'Employee' AS UserTypeName,
	Emp.Code  AS Code,
	Emp.DepartmentName As Department,	
	Emp.FirstName +  ' ' + Emp.LastName AS Name,
	RU.CreatedDateTime AS Date,
	OT.Title AS OSType	,
	'' AS Class,
	CONVERT(bit,CASE WHEN ISNULL(RU.DeviceToken,'') = '' THEN 0 ELSE 1 END) AS IsDeviceToken
	FROM		
		sCommunication.tRegisteredUsers RU
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=RU.OrgId				
		INNER JOIN sAlert.tOSType OT ON OT.ID =RU.OSTypeId			
		
	    INNER JOIN sHrm.vExtEmployeeMaster Emp ON Emp.Id = RU.UserSourceId AND RU.UserSourceTypeId=95	    												
	WHERE
	((RU.OrgId = @rOrgId) OR (@rOrgId=0))
		AND((RU.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))	
	    AND((Emp.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND ((Emp.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((CONVERT(date,RU.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,RU.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND((RU.UserSourceTypeId=@rUserSourceTypeId) OR (@rUserSourceTypeId=0))	
		AND OM.OrgGroupId =@rOrgGroupId
		ORDER BY RU.OrgId,RU.OSTypeId,RU.UserId ASC,RU.CreatedDateTime DESC	
END
END
GO
PRINT N'Altering [sAlert].[pNotificationLogGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pNotificationLogGet]

		@rOSTypeId tinyint,
		@rUserId bigint,
		@rUserSourceTypeId smallint,
		@rUserSourceId bigint,
		@rSyncedNotificationId bigint
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lAcademicId bigint
	DECLARE @lEmployeeId bigint
	DECLARE @lStudentId bigint
	DECLARE @lDivisionId int
	DECLARE @lClassId int
	DECLARE @lDepartmentId int
	DECLARE @lOrgId int
	
	IF(@rUserSourceTypeId=2003)
	BEGIN
		SELECT 
		@lAcademicId=AcademicId,
		@lStudentId=StudentId,
		@lDivisionId=DivisionId,
		@lClassId=ClassId,
		@lDepartmentId=DepartmentId,
		@lOrgId=OrgId
		FROM sStudent.vStudentAcademic WHERE StudentId = @rUserSourceId AND IsActiveBatch=1
	
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
		FROM 
			sAlert.tNotificationLog NL
		WHERE 
		(
		(NL.SourceId=@lAcademicId) AND (NL.SourceTypeId=2001)
		OR (NL.SourceId=@lStudentId) AND (NL.SourceTypeId=2003)
		OR (NL.SourceId=@lDivisionId) AND (NL.SourceTypeId=2005)
		OR (NL.SourceId=@lClassId) AND (NL.SourceTypeId=2016)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
	END
		
	IF(@rUserSourceTypeId=95)
	BEGIN
	
		SELECT 
		@lEmployeeId=EmployeeId,
		@lDepartmentId=OrganizationDepartmentId,
		@lOrgId=OrgId
		FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId
		SELECT 
				NL.Id AS NotificationId,
				NL.EventId,
				NL.DocumentId,
				NL.MessageTitle,
				NL.NotificationMessage AS 'Message',
				CONVERT(VARCHAR,NL.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,NL.CreatedDateTime,100),8)),7),2) AS CreatedDateTime
				--CONVERT(VARCHAR(25), NL.CreatedDateTime, 100) AS CreatedDateTime
		FROM 
			sAlert.tNotificationLog NL
		WHERE 
		(
		(NL.SourceId=@lEmployeeId) AND (NL.SourceTypeId=95)
		OR (NL.SourceId=@lDepartmentId) AND (NL.SourceTypeId=2017)
		OR (NL.SourceId=@lOrgId) AND (NL.SourceTypeId=2021)	
		) AND Id > @rSyncedNotificationId AND OSTypeId=@rOSTypeId
	END
	
END
GO
PRINT N'Altering [sAlumni].[pRegistrationAdd]...';


GO

ALTER PROCEDURE [sAlumni].[pRegistrationAdd] 
	
		@rFirstName nvarchar(100),
		@rMiddleName nvarchar(100),
		@rLastName nvarchar(100),
		@rGenderId tinyint,
		@rRegistrationDate date,
		@rEmailId nvarchar(150),
		@rMobileNo nvarchar(11),
		@rOrgId int,
		@rPassingBatchId int,
		@rPassingClassId int,
		@rMappedStudentId bigint=0,
		@rEmployeementTypeId int,
		@rEmployerName nvarchar(150),
		@rDesignation nvarchar(150),
		@rEmployeementCountry nvarchar(150),
		@rEmployeementState nvarchar(150),
		@rEmployeementCity nvarchar(150),
		@rSpecialAchievement nvarchar(500),
		@rUniversityName nvarchar(200),
		@rHigherStudyCountry nvarchar(150),
		@rHigherStudyState nvarchar(150),
		@rHigherStudyCity nvarchar(150),
		@rResidentialCountry nvarchar(150),
		@rResidentialState nvarchar(150),
		@rResidentialCity nvarchar(150),
		@rOfficePhone nvarchar(150),
		@rResidentialPhone nvarchar(150),
		
		@rCreatedUserId bigint=0  
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY
	  BEGIN TRANSACTION		
	--if exists(select 1 from sAlumni.tRegistration where MobileNo=@rMobileNo)
	--BEGIN
	--	Select -101 As Result
	--	COMMIT TRANSACTION		
	--	Return
	--END
	
	--if exists(select 1 from sAlumni.tRegistration where EmailId=@rEmailId)
	--BEGIN
	--	Select -102 As Result
	--	COMMIT TRANSACTION		
	--	Return
	--END
	
	INSERT INTO sAlumni.tRegistration
		(
			 
			FirstName,
			MiddleName,
			LastName,
			GenderId,
			RegistrationDate ,
			EmailId,
			MobileNo,
			OrgId,
			PassingBatchId,
			PassingClassId,
			MappedStudentId,
			EmployeementTypeId,
			EmployerName,
			Designation,
			EmployeementCountry,
			EmployeementState,
			EmployeementCity,
			SpecialAchievement,
			UniversityName,
			HigherStudyCountry,
			HigherStudyState,
			HigherStudyCity,
			ResidentialCountry,
			ResidentialState,
			ResidentialCity,
			OfficePhone,
			ResidentialPhone,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
	VALUES
		(
			@rFirstName,
			@rMiddleName,
			@rLastName,
			@rGenderId,
			@rRegistrationDate,
			@rEmailId,
			@rMobileNo,
			@rOrgId,
			@rPassingBatchId,
			@rPassingClassId,
			@rMappedStudentId,
			@rEmployeementTypeId,
			@rEmployerName,
			@rDesignation,
			@rEmployeementCountry,
			@rEmployeementState,
			@rEmployeementCity,
			@rSpecialAchievement,
			@rUniversityName,
			@rHigherStudyCountry,
			@rHigherStudyState,
			@rHigherStudyCity,
			@rResidentialCountry,
			@rResidentialState,
			@rResidentialCity,
			@rOfficePhone,
			@rResidentialPhone,
			@rCreatedUserId,
			sCommon.fGetDate() ,
			 @rCreatedUserId,
			 sCommon.fGetDate()
		)
		    SELECT 1 AS Result
	 	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAlumni].[pRegistrationGet]...';


GO

ALTER PROCEDURE [sAlumni].[pRegistrationGet] 
	
		@rFirstName nvarchar(100),
		@rLastName nvarchar(100),
		@rMobileNo nvarchar(11),
		@rOrgId int ,
		@rOrgGroupId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 Select 
		FirstName,
		MiddleName,
		LastName,
		RegistrationDate,
		MobileNo,
		CM.DisplayTitle As ClassName
	From sAlumni.tRegistration R
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=R.PassingClassId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=R.OrgId
	Where ((FirstName like '%'+@rFirstName+'%') OR (@rFirstName=''))
	AND ((LastName like '%'+@rLastName+'%') OR (@rLastName=''))
	AND ((MobileNo=@rMobileNo) OR (@rMobileNo=''))
	And ((R.OrgId=@rOrgId) OR (@rOrgId=0))
	AND OM.OrgGroupId=@rOrgGroupId
END
GO
PRINT N'Altering [sAssessment].[pGeneralExamCustomSearchGet]...';


GO
ALTER PROCEDURE [sAssessment].[pGeneralExamCustomSearchGet]
(
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rExamId nvarchar(max) = '',
	@rFromMarks decimal(5,2),
	@rToMarks decimal(5,2),
	@rFromGradePoint decimal(6,2),
	@rToGradePoint decimal(6,2),
	@rFromRankNumber int,
	@rToRankNumber int,
	@rFromPercentage decimal(5,2),
	@rToPercentage decimal(5,2),
	@rFromPercentile decimal(5,2),
	@rToPercentile decimal(5,2),
	@rResultGrade nvarchar(10),
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownExamSubGroupId int,
	@rDepartmentId int=0
 )
AS
SET NOCOUNT ON

BEGIN
		if @rOrderBy='Id No'
		BEGIN
			Set @rOrderBy='Code'
		END
		if @rOrderBy='GR No'
		BEGIN
			Set @rOrderBy='Code'
		END
		DECLARE @Sql nvarchar(MAX)
		
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rResultGrade = sCommon.fSearchStringGet(@rResultGrade)
		
		SELECT 
				  *
		into sAssessment.tTempGeneralExam1
		FROM sAssessment.vGeneralExamCustomSearch ECS
		
		WHERE 
				(ECS.OrgId = @rOrgId)
			AND (ECS.BatchId = @rBatchId)
			AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ECS.TotalObtain >= @rFromMarks) OR (@rFromMarks=0))
			AND ((ECS.TotalObtain <= @rToMarks) OR (@rToMarks=0))
			AND ((ECS.ResultGradePoint >= @rFromGradePoint) OR (@rFromGradePoint=0))
			AND ((ECS.ResultGradePoint <= @rToGradePoint) OR (@rToGradePoint=0))
			AND ((ECS.RankNumber >= @rFromRankNumber) OR (@rFromRankNumber=0))
			AND ((ECS.RankNumber <= @rToRankNumber) OR (@rToRankNumber=0))
			AND ((ECS.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
			AND ((ECS.Percentage <= @rToPercentage) OR (@rToPercentage=0))
			AND ((ECS.Percentile >= @rFromPercentile) OR (@rFromPercentile=0))
			AND ((ECS.Percentile <= @rToPercentile) OR (@rToPercentile=0))
			AND ((ECS.ResultGrade Like @rResultGrade + '%')OR(@rResultGrade = ''))	
		    
		    AND (ECS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (ECS.ExamId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamId,','))OR @rExamId='')	
	       
	        AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((ECS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((ECS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	        AND ((ECS.ExamSubGroupId = @rDropDownExamSubGroupId) OR (@rDropDownExamSubGroupId=0))
	         AND ((ECS.DepartmentId =@rDepartmentId) OR (@rDepartmentId =0))
		SET @sql=
		'SELECT 
				Code AS Code,
				Name,
				ClassName,
				RollNo,
				TotalMarks,
				TotalObtain,
				ResultStatus,
				ResultGrade,
				ResultGradePoint,
				RankNumber,
				Percentage,
				Percentile,
				ResultReMark,
				OtherRemark1,
				ExamName
		FROM sAssessment.tTempGeneralExam1 ORDER BY ' + @rOrderBy
		exec(@Sql)
		
		DROP Table sAssessment.tTempGeneralExam1
END
GO
PRINT N'Altering [sAssessment].[pGeneralExamGenerateReport]...';


GO
ALTER PROCEDURE [sAssessment].[pGeneralExamGenerateReport]
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rBatchId int,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rExamId nvarchar(max) = '',
	@rFromMarks decimal(5,2),
	@rToMarks decimal(5,2),
	@rFromGradePoint decimal(6,2),
	@rToGradePoint decimal(6,2),
	@rFromRankNumber int,
	@rToRankNumber int,
	@rFromPercentage decimal(5,2),
	@rToPercentage decimal(5,2),
	@rFromPercentile decimal(5,2),
	@rToPercentile decimal(5,2),
	@rResultGrade nvarchar(10),
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownExamSubGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tGeneralExamCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sAssessment.tGeneralExamCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgId,
			BatchId,
			Code,
			FirstName,	
			LastName,
			DivisionId,
			ExamId,
			FromMarks,
			ToMarks,
			FromGradePoint,
			ToGradePoint,
			FromRankNumber,
			ToRankNumber,
			FromPercentage,
			ToPercentage,
			FromPercentile,
			ToPercentile,
			ResultGrade,
			IsCommon,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgId,
			@rBatchId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rDivisionId,
			@rExamId,
			@rFromMarks,
			@rToMarks,
			@rFromGradePoint,
			@rToGradePoint,
			@rFromRankNumber,
			@rToRankNumber,
			@rFromPercentage,
			@rToPercentage,
			@rFromPercentile,
			@rToPercentile,
			@rResultGrade,
			@rIsCommon,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		--SELECT @lNextNumber AS Result
	END
	if(@rColumnName='ID No')
	BEGIN
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
	END
	if(@rOrderBy='ID No')
	BEGIN
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	END
	
	if(@rColumnName='GR No')
	BEGIN
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
	END
	
	if(@rOrderBy='GR No')
	BEGIN
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	END
	 
	 
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rDivisionId=DivisionId,
				@rExamId=ExamId,
				@rFromMarks=FromMarks,
				@rToMarks=ToMarks,
				@rFromGradePoint=FromGradePoint,
				@rToGradePoint=ToGradePoint,
				@rFromRankNumber=FromRankNumber,
				@rToRankNumber=ToRankNumber,
				@rFromPercentage=FromPercentage,
				@rToPercentage=ToPercentage,
				@rFromPercentile=FromPercentile,
				@rToPercentile=ToPercentile,
				@rResultGrade=ResultGrade
		FROM
			sAssessment.tGeneralExamCustomSearch
		WHERE
			Id=@rId
	END
	if(@rColumnName='ID No')
	BEGIN
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
	END
	if(@rOrderBy='ID No')
	BEGIN
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	END
	if(@rColumnName='GR No')
	BEGIN
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
	END
	if(@rOrderBy='GR No')
	BEGIN
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	END
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rResultGrade = sCommon.fSearchStringGet(@rResultGrade)
	
	DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
	SELECT @cols = STUFF((SELECT ',' + QUOTENAME(Title,'[]'), '' AS AcademicId, '' AS ExamSubGroupId
					FROM sAssessment.tExamMaster EM 
					INNER JOIN sAssessment.tExamDetail ED ON EM.Id = ED.ExamId
                    INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id AND RD.ExamDetailId = ED.Id
					INNER JOIN sSetup.tClassSubject CS ON CS.ClassId = EM.ClassId
					INNER JOIN sSetup.tSubjectMaster CM ON CM.Id = CS.SubjectId
					WHERE EM.ExamSubGroupId = @rDropDownExamSubGroupId AND EM.BatchId = @rBatchId
					group by CM.Title
                    order by CM.Title	
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
	   set @query = 'SELECT ExamSubGroupId AS ExamSubGroupId1, AcademicId AS AcademicId1 ,' + @cols + ' into sAssessment.tTempGeneralExam1 FROM 
             (
                    SELECT EM.ExamSubGroupId,R.AcademicId,RD.Obtain,CM.Title
                    FROM 
                    sAssessment.tExamMaster EM 
					INNER JOIN sAssessment.tExamDetail ED ON EM.Id = ED.ExamId
                    INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id AND RD.ExamDetailId = ED.Id
					INNER JOIN sSetup.tClassSubject CS ON CS.ClassId = EM.ClassId AND ED.ClassSubjectId = CS.Id
					INNER JOIN sSetup.tSubjectMaster CM ON CM.Id = CS.SubjectId
					WHERE EM.ExamSubGroupId = '+CONVERT(nvarchar,@rDropDownExamSubGroupId)+' AND EM.BatchId = '+CONVERT(nvarchar,@rBatchId)+'
            ) x 
            pivot 
            (
                SUM(Obtain)
                for  Title in (' +@cols  + ')
            ) p '
            
	 
	    execute(@query)
	    

	
		SELECT 
				*
		into sAssessment.tTempGeneralExam
		FROM sAssessment.vGeneralExamCustomSearch ECS
		INNER JOIN sAssessment.tTempGeneralExam1 T ON ECS.AcademicId = T.AcademicId1 AND ECS.ExamSubGroupId =  T.ExamSubGroupId1 
		WHERE 
				(ECS.OrgId = @rOrgId)
			AND (ECS.BatchId = @rBatchId)
			AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    AND ((ECS.TotalObtain >= @rFromMarks) OR (@rFromMarks=0))
			AND ((ECS.TotalObtain <= @rToMarks) OR (@rToMarks=0))
			AND ((ECS.ResultGradePoint >= @rFromGradePoint) OR (@rFromGradePoint=0))
			AND ((ECS.ResultGradePoint <= @rToGradePoint) OR (@rToGradePoint=0))
			AND ((ECS.RankNumber >= @rFromRankNumber) OR (@rFromRankNumber=0))
			AND ((ECS.RankNumber <= @rToRankNumber) OR (@rToRankNumber=0))
			AND ((ECS.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
			AND ((ECS.Percentage <= @rToPercentage) OR (@rToPercentage=0))
			AND ((ECS.Percentile >= @rFromPercentile) OR (@rFromPercentile=0))
			AND ((ECS.Percentile <= @rToPercentile) OR (@rToPercentile=0))
			AND ((ECS.ResultGrade Like @rResultGrade + '%')OR(@rResultGrade = ''))
			
		    AND (ECS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (ECS.ExamId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamId,','))OR @rExamId='')	
	        --AND ((ECS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	        AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((ECS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((ECS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND ((ECS.ExamSubGroupId = @rDropDownExamSubGroupId) OR (@rDropDownExamSubGroupId=0))
	     
	    if(@rColumnName='ID No')
	    BEGIN
			 SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [ID No]')
	    END
	    if(@rOrderBy='ID No')
	    BEGIN
			 SET @rOrderBy=Replace(@rOrderBy,',Code',',Code AS [ID No]')
	    END
	    if(@rColumnName='GR No')
	    BEGIN
			 SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [GR No]')
	    END
	    if(@rOrderBy='GR No')
	    BEGIN
			 SET @rOrderBy=Replace(@rOrderBy,',Code',',Code AS [GR No]')
	    END
		SET @sql=
		'SELECT '+ @rColumnName+' FROM sAssessment.tTempGeneralExam ORDER BY '+@rOrderBy
		exec(@Sql)
		
		DROP Table sAssessment.tTempGeneralExam
		DROP Table sAssessment.tTempGeneralExam1
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pMarkEntrySubjectGradeUpdate]...';


GO
ALTER PROCEDURE [sAssessment].[pMarkEntrySubjectGradeUpdate]

	 @rExamId int,
	 @rDataSetId int,
	 @rDivisionId int,
	 @rBatchId int,
	 @rClassSubjectId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
BEGIN TRY
 BEGIN TRANSACTION	
 
 
 	 DECLARE @lIsExcludeAbsentTotal bit
	 
	 SELECT @lIsExcludeAbsentTotal = ISNULL(IsExcludeAbsentTotal,0) FROM sAssessment.tExamMaster EM
	 WHERE EM.Id = @rExamId AND BatchId = @rBatchId
 	
DECLARE @MinimumScore decimal(5,2)
DECLARE @Grade nvarchar(10)
DECLARE @GradePoint Decimal(6,2)
DECLARE @lCount int

begin
	CREATE TABLE #tempGradeSetDetail
 		(
 			Id INT IDENTITY (1, 1),
 			MinimumScore decimal(5,2),
 			Grade nvarchar(10),
 			GradePoint Decimal(6,2)						 
 		) 
 		INSERT INTO #tempGradeSetDetail
 		SELECT MinimumScore,GradeCode,GradePoint		
		FROM sAssessment.tGradeSetDetail where GradesetId=@rDataSetID
		--order by Id Asc
 	order by MinimumScore desc
SELECT @lCount =  COUNT(Id) FROM #tempGradeSetDetail
while (@lCount > 0)
BEGIN
	SELECT
		@MinimumScore =MinimumScore,
		@Grade= Grade,
		@GradePoint = GradePoint
		FROM #tempGradeSetDetail WHERE Id = @lCount
		select * from #tempGradeSetDetail
IF ( @lIsExcludeAbsentTotal	= 0)
BEGIN	
    Update RD Set SubjectGrade=@Grade,SubjectGradePoint=@GradePoint FROM sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id= RD.ResultId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND IsShowSubjectGrade = 1
		WHERE RD.Obtain >= @MinimumScore
		--AND (ISNULL(RD.SubjectGrade,'') = '')
		AND R.ExamId= @rExamId AND ED.GradeSetId = @rDataSetId
		AND ED.ClassSubjectId = @rClassSubjectId
		AND R.AcademicId IN (SELECT AcademicID from sStudent.vStudentAcademic WHERE DivisionId=@rDivisionId AND BatchId = @rBatchId AND StatusId=1)
	END
ELSE
BEGIN	
    Update RD Set SubjectGrade=@Grade,SubjectGradePoint=@GradePoint FROM sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id= RD.ResultId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId AND IsShowSubjectGrade = 1
		WHERE RD.Obtain >= @MinimumScore
		AND ED.ClassSubjectId = @rClassSubjectId
		--AND (ISNULL(RD.SubjectGrade,'') = '')
		AND RD.IsPresent = 1
		AND R.ExamId= @rExamId AND ED.GradeSetId = @rDataSetId
		AND R.AcademicId IN (SELECT AcademicID from sStudent.vStudentAcademic WHERE DivisionId=@rDivisionId AND BatchId = @rBatchId AND StatusId=1)
	END
	SET @lCount = @lCount - 1
 END	
END
SELECT 1 AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sAssessment].[pMyResultGet]...';


GO


ALTER PROCEDURE [sAssessment].[pMyResultGet]
	 
	@rExamSubGroupId int = 0,
	@rStudentId bigint =0,
	@rAcademicId bigint = 0,
	@rBatchId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT
		R.Id AS ResultId, 
		R.ExamId,
		ISNULL(E.ReportId,0) AS ReportId,
		ESGM.Title AS ExamName,
		StuM.FirstName+' '+StuM.LastName AS StudentName,
		StuM.Id AS StudentId,
		A.RollNo,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain AS Obtain,
		R.ResultStatus,
		R.ResultGrade,
		R.RankNumber,
		R.Percentage,
		R.Percentile,	
		ESGM.Id AS ExamSubGroupId,
		BM.Id AS BatchId,
		BM.Title AS BatchName
		
		
FROM 
			sAssessment.tResult R 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		
			
	WHERE 
	
			(ESGM.Id=@rExamSubGroupId OR @rExamSubGroupId=0)
		--AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId =0))
		AND  StuM.Id = @rStudentId 
		AND ((A.Id = @rAcademicId) OR (@rAcademicId =0))
		AND ((BM.Id = @rBatchId) OR (@rBatchId =0))
		AND (E.IsPublished = 1)  AND ISNULL(E.ReportId,0)  > 0
	
		 order by ESGM.OrderIndex asc
		
		
		 
		 
		
	
	
		
END
GO
PRINT N'Altering [sAssessment].[pResultGenerateFlush]...';


GO
ALTER PROCEDURE [sAssessment].[pResultGenerateFlush]
	 @rExamId int
	,@rDivisionId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	
		BEGIN 		
			
			UPDATE RD SET	SubjectGrade='',
							SubjectGradePoint=0,
							Percentile=0.00 
							--Remark=''
			FROM sAssessment.tResultDetail RD  
			INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
			INNER JOIN sStudent.tAcademic SA ON SA.Id = R.AcademicId 
			AND R.ExamId = @rExamId AND SA.DivisionId=@rDivisionId 
			
			UPDATE R SET	TotalMarks=0,
							TotalObtain=0,
							ResultStatus='',
							ResultGrade='',
							ResultGradePoint = 0,
							RankNumber =0,
							Percentage = 0.00,
							Percentile =0.00,
							resultRemark=''			
			FROM sAssessment.tResult R 
			INNER JOIN sStudent.tAcademic  SA ON SA.Id=R.AcademicId 
			AND ExamId = @rExamId 
			AND DivisionId=@rDivisionId
			
			
			UPDATE sAssessment.tExamStatus SET  STATUSID=503 WHERE ExamId = @rExamId AND DivisionId = @rDivisionId
			
			SELECT 1 AS RESULT
			
		END
END TRY
BEGIN CATCH
		SELECT -1 AS RESULT
END CATCH
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetCoScholasticSubCombineGet]...';


GO




ALTER PROCEDURE [sAssessment].[pRptResultSheetCoScholasticSubCombineGet]
	 
	 

	 --@rAcademicIdTextText bigint,
	 --@rExamIdTextText bigint
	  @rAcademicIdText nvarchar(20),
	 @rExamIdText nvarchar(20) ,
	 @rCoScholasticScopeId int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--DECLARE
--@rAcademicIdText bigint,
--@rExamIdText int
--SET @rAcademicIdText = convert(bigint, @rAcademicIdTextText)
--SET @rExamIdText = convert(bigint, @rExamIdTextText)
DECLARE
@lIsCoScholasticGrade	bit,
@lIsCoScholasticGradeIndicator bit, 
@lIsCoScholasticGradeDesIndicator bit,
@lIsCoScholasticCombine bit	 	 

--@lCoScholasticScopeId tinyint

SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator,
@lIsCoScholasticCombine = IsCoScholasticCombine 
FROM sAssessment.tExamMaster WHERE Id = @rExamIdText
 

DECLARE 
@Exam1 int,
@Exam2 int


--@Grade2 nvarchar(50),
--@GradeIndicator1 nvarchar(50),
--@Grade2 nvarchar(50),
--@CategoryID int,
--@BrandID int



 
SELECT @Exam1 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamIdText AND ExamOrder = 1
SELECT @Exam2 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamIdText AND ExamOrder = 2

SELECT
Convert(nvarchar(10),@rExamIdText) AS ExamIdText,
Convert(nvarchar(20),@rAcademicIdText) AS   AcademicIdText,
  
@rAcademicIdText AS AcademicId,
--(CASE Term1.AcademicId  WHEN  null THEN Convert(nvarchar(10),Term2.AcademicId)
--ELSE Convert(nvarchar(10),Term1.AcademicId) END) AS   AcademicIdText,
@rExamIdText AS ExamId, 
Convert(nvarchar(20), @rCoScholasticScopeId ) AS CoScholasticScopeIdText,

--(CASE Term1.AcademicId  WHEN  null THEN Term2.AcademicId
--ELSE Term1.AcademicId END) AS   AcademicId ,
(CASE Term1.CoSubject  WHEN  null THEN Term2.CoSubject
ELSE Term1.CoSubject END) AS   CoSubject ,
(CASE Term1.CoSubjectGroup  WHEN  null THEN Term2.CoSubjectGroup
ELSE Term1.CoSubjectGroup END) AS   CoSubjectGroup ,
(CASE Term1.CoSubjectGroupOrder  WHEN  null THEN Term2.CoSubjectGroupOrder
ELSE Term1.CoSubjectGroupOrder END) AS   CoSubjectGroupOrder ,
(CASE Term1.CoSubjectOrder  WHEN  null THEN Term2.CoSubjectOrder
ELSE Term1.CoSubjectOrder END) AS   CoSubjectOrder , 
ISNULL(Term1.Grade,'') AS Grade1,
ISNULL(Term1.GradeIndicator,'') AS GradeIndicator1,
ISNULL(Term1.DescriptiveIndicator,'') AS DescriptiveIndicator1,
ISNULL(Term2.Grade,'') AS Grade2,
ISNULL(Term2.GradeIndicator,'') AS GradeIndicator2,
ISNULL(Term2.DescriptiveIndicator,'') AS DescriptiveIndicator2,
@lIsCoScholasticGrade AS IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
ISNULL(Term1.GroupTypeId,0) AS GroupTypeId,
ISNULL(Term1.GroupType,0) AS GroupType ,
Term1.ExamName AS ExamTerm1,
Term2.ExamName AS ExamTerm2,
Term1.CoScholasticTitle AS CoScholasticTitle


 

FROM 

	(SELECT			
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.Id AS CoSubjectId,
			cceCSM.OrderIndex AS CoSubjectOrder,
			cceCSGM.OrderIndex AS CoSubjectGroupOrder,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType ,
			 ESM.Title AS ExamName,
			 EM.CoScholasticTitle 
			
	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 
	WHERE 
		     cceCSS.ExamId=@Exam1		     
		     AND cceCSS.AcademicId=@rAcademicIdText	) Term1
		     
		     FULL OUTER JOIN
		 	(SELECT			
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.Id AS CoSubjectId,
			cceCSM.OrderIndex AS CoSubjectOrder,
			cceCSGM.OrderIndex AS CoSubjectGroupOrder,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType,
			ESM.Title AS ExamName 
			 --EM.CoScholasticTitle 
			
			 
			
			
			    
	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 
	WHERE 
		     cceCSS.ExamId=@Exam2		     
		     AND cceCSS.AcademicId=@rAcademicIdText	) Term2
		     ON Term1.CoSubjectId = Term2.CoSubjectId    
		     
		     
		     
END
GO
PRINT N'Altering [sAssessment].[pRptSubjectResultListFloating]...';


GO


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

BEGIN 
 --Select * from dbo.Float
 --Select
 --           ''  AS AcademicIdText,
	--		'' AS ExamIdText,
	--		'' AS IsDisplayMonthlyAttendanceText,
	--		'' AS Exam,
	--		'' AS Builder1,
	--		'' Code,
	--		'' AS Name,
	--		0 RollNo,
	--		0 AcademicId,			
	--		'' ResultStatus,
	--		'' AS Class,
	--		'' AS Division,
	--		0.0 TotalMarks,
	--		0.0 TotalObtain,
	--		0.0 Percentage,
	--		0 RankNumber,
	--		'' ResultGrade,
	--		0.0 Percentile,			
	--		0 AS ResultDetailId,		
	--		0 IsDisplayInMarksheet,
	--		0 IsShowSubjectGrade,
	--		0 IsIncludeInTotal,
	--		0.0 AS SubjectObtain,
	--		0.0 AS SubjectMinimum,
	--		0.0 AS SubjectMaximum,			
	--		'' AS SubjectCode,
	--		'' AS SubjectName,
	--		0 AS SubjectOrderIndex,
	--		0 AS ResultId,
	--		0 AS SubjectId,			 	
	--		0 IsMarksInDecimal,
			
	--		 '' AS Remark1,
	--		'' AS Remark2,
	--		'' AS Remark3,
	--		'' DisplayTitle,
	--		 0 IsRankNo, 
	--		0 IsGrade,
	--		0 IsPercentile,
	--		0 IsPercentage,
	--		0 IsSubjectPercentile,
	--		0 IsProcessResult,
			 
	--		0 IsNegativeMarks,
	--		 0 IsIncludeCoScholastic,
	--		0 IsOnPrePrinted,
	--		0 IsDisplayPhoto,
	--		0 IsDisplayBirthDate,
	--		0 IsLockForEdit,
	--		0 IsDisplaySchoolName,			
	--		0 IsDisplayAttendance,
	--		0 IsDisplayHeightWeight,
	--		0 IsResultStatus,
	--		'' AS FooterAdjustmentText,
	--		'' AS DetailAdjustmentText,
	--		0 FooterAdjustment,
	--		0 DetailAdjustment,
		 		 
	--		0 TermScopeId,
		 
	--		0 IsPresent,
	--		'' AS GradeString,
	--		0 IsDisplayGradeString,
	--		 ''  AS HighestDivisionGrade,			
	--		'' SmallAddress1,
	--		0 IsDisplayParentName,
			 
	--		0 AS IsShowSubjectMark,
			
	--		0 IsDisplayTeacherSign,
	--		0 IsDisplayPrincipalSign,
		 
	--		0 AS IsDisplayMonthlyAttendance,
			 
	--		0 AS IsImageHeader,
			 
	--		0 SubExamId,
	--		0 ExamOrderIndex,
	--		0 AnnualExamId ,
	--		'' DecimalFormat,
	--		0 TermExamId,
	--		'' AS ExamNAme, 			 
	--		'' AS AnnualSubjectGrade,
	--		0.00 As AnnualSubjectObtain,
	--		'' AS TermSubjectGrade,
	--		0.0 As TermSubjectObtain ,
	--		'' AS SubjectGrade
			
 
 
 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int 
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  

CREATE TABLE #TempExam
(
	SubExamId int, 
	ExamOrderIndex int,
	TermExamId int,
	AnnualExamId int, 
	Exam nvarchar(50) 
)
--INSERT INTO #TempExam
--(
--	SubExamId,	 
--	ExamOrderIndex,
--	ExamId,
--	Exam 
--)
--Select 
	 
--	EC.SubExamId,
--	EC.ExamOrder,
--	EM.Id As ExamId,
--	ES.Title AS Exam
--	from sAssessment.tExamMaster EM 
--	INNER JOIN sAssessment.tExamCombine EC ON EC.ExamId = EM.Id 
--	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = EM.ExamSubGroupId 
--	WHERE EM.Id=@rExamId 

INSERT INTO #TempExam
(
	 SubExamId,
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam 
	
)
Select  
	EC.SubExamId,
	EC.ExamOrder,
	EC.ExamId AS TermExamId,
	@rExamId AS AnnualExamId,
	ES.Title AS Exam	
	from  sAssessment.tExamCombine EC 
	INNER JOIN sAssessment.tExamMaster EM  ON EC.ExamId = EM.Id 
	 INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = EM.ExamSubGroupId
	 INNER JOIN (select SubExamId from sAssessment.tExamCombine where examId = @rExamId) AS SE
	 ON EC.ExamId = SE.SubExamId  
	--WHere EC.ExamId  in  (select SubExamId from sAssessment.tExamCombine where examId = @rExamId  )
	
	
 
		
	
	
	
--INSERT INTO #TempExam
--(
--	ExamId, 
--	ExamOrderIndex
--)
--Select 
	 
--	@rExamId,
--	999 
	 --Select * from #TempExam
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			 @rBuilder1 AS Builder1,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			 
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
		 		 
			EM.TermScopeId,
		 
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
		 
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			 
			EC.SubExamId,
			EC.ExamOrderIndex,
			EC.AnnualExamId ,
			EM.DecimalFormat,
			EC.TermExamId,
			EC.Exam AS ExamNAme, 			 
			ARD.SubjectGrade AS AnnualSubjectGrade,
			ARD.Obtain As AnnualSubjectObtain,
			TRD.SubjectGrade AS TermSubjectGrade,
			TRD.Obtain As TermSubjectObtain ,
			RD.SubjectGrade AS SubjectGrade
			
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.SubExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId			
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			INNER JOIN sAssessment.tResult AR ON AR.AcademicId = A.Id AND AR.ExamId = EC.AnnualExamId 
			INNER JOIN sAssessment.tResultDetail ARD ON AR.Id = ARD.ResultId 
			INNER JOIN sAssessment.tExamDetail AED ON ARD.EXamDetailId = AED.Id 
			INNER JOIN sSetup.tClassSubject ACS ON AED.ClassSubjectId = ACS.Id AND ACS.SubjectId = @rSubjectId  
			INNER JOIN sAssessment.tResult TR ON TR.AcademicId = A.Id AND TR.ExamId = EC.TermExamId 
			INNER JOIN sAssessment.tResultDetail TRD ON TR.Id = TRD.ResultId 
			INNER JOIN sAssessment.tExamDetail TED ON TRD.EXamDetailId = TED.Id 
			INNER JOIN sSetup.tClassSubject TCS ON TED.ClassSubjectId = TCS.Id AND TCS.SubjectId = @rSubjectId 
			
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			--LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			--LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			--LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
			--LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		--AND (R.ExamId = @rExamId)
	 
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		order by A.RollNo,CS.OrderIndex 
		
	 drop table #TempExam
		
END
GO
PRINT N'Altering [sAttendance].[pRptDailyAttendanceList]...';


GO
ALTER PROCEDURE [sAttendance].[pRptDailyAttendanceList]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		 @rBatchId int,
		@rClassId int,
		@rDivisionId int,
		@rDepartmentId int ,
		--@rOrgMainGroupId int,
		--@rOrgSubGroupId int,
		 @rOrgId smallint,
		 @rAttendanceTypeId int,
		 @rDate date,
		 
		 @rDivisionGroup bit=0
		--@rOrgGroupBatchId int,
		--@rFromDate Date,
		--@rToDate Date 
		--@rStrOrgMainGroupId nvarchar(max),
		--@rStrOrgSubGroupId nvarchar(max),
		--@rStrOrgId nvarchar(max),
		--@rStrDepartmentId nvarchar(max),
		--@rStrClassId nvarchar(max),
		--@rIsTestMainGroup bit =0,
		--@rIsTestSubGroup bit =0,
		--@rIsTestOrg bit=0,
		--@rIsTestClass bit=0,
		--@rIsTestDepartment bit=0,
		--@rOrgGroupId int,
		--@rIsDisplayOrgGroup bit=0
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			 
			@rDivisionGroup AS DivisionGroup,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex  ,
			DM.Id AS DivisionId,
			DM.Title AS DivisionName,
			DM.OrderIndex AS DivisionOrderIndex,
			
		 --   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			--ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			--WHERE BM.IsActive = 1 AND  SA.AdmissionDate= Convert(DATE,GETDATE()-1)
			--AND A.ClassId =CM.Id AND A.DivisionId = DM.Id  ) AS OpeningStrength,
			
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			WHERE BM.IsActive = 1 AND SA.AdmissionDate = @rDate 
			AND A.ClassId =CM.Id AND A.DivisionId = DM.Id AND A.OrgId = @rOrgId  ) AS NewJoinedStudent,
			
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			 ON SA.StudentId = A.StudentId INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			 WHERE BM.IsActive = 1 AND SA.LeftDate = @rDate 
			 AND A.ClassId =CM.Id AND A.DivisionId = DM.Id AND A.OrgId = @rOrgId ) AS LeftStudent,
			 
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId 
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			WHERE BM.IsActive = 1 AND SM.StatusId = 1
			AND A.ClassId =CM.Id AND A.DivisionId = DM.Id AND A.OrgId = @rOrgId ) AS ClosingStrength,
			
			
			(SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			WHERE 
			 SA.AdmissionDate < @rDate
			 AND  ((SA.LeftDate >= @rDate) OR ISNULL(SA.LeftDate,'')= '')
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id  
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId AND A.DivisionId = DM.Id AND A.OrgId = @rOrgId ) AS PreviousDay,
			
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =1 AND A.OrgId = @rOrgId ) AS Present,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =1 AND A.OrgId = @rOrgId AND SO.GenderId=1 ) AS PresentBoys,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =1 AND A.OrgId = @rOrgId AND SO.GenderId=2 ) AS PresentGirls,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =0 AND A.OrgId = @rOrgId ) AS AbsentStudent,
			
			 (select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =0 AND A.OrgId = @rOrgId AND SO.GenderId=1 ) AS AbsentBoys,
			
			(select count(A.Id) FROM sStudent.tAcademic A
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			INNER JOIN sStudent.tStudentOther SO
			ON SO.StudentId=A.StudentId
	        WHERE A.BatchId = @rBatchId  
	        AND SR.AttendanceDate=@rDate
	        AND A.ClassId =CM.Id 
			AND A.DivisionId=DM.Id  AND  CM.DepartmentId =Dept.Id 
			AND SR.AttendanceTypeId =@rAttendanceTypeId AND SR.IsPresent =0 AND A.OrgId = @rOrgId AND SO.GenderId=2) AS AbsentGirls,
			
			0 as WithLeave,
			0 as SeekLeave,
			 0 AS TotalStudent,
			 '' AS Remark 
	FROM 
			sSetup.tDivisionMaster DM  
			 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
			 INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
			--AND DM.Id=A.DivisionId AND CM.Id=A.ClassId
			--sSetup.tClassMaster CM			
			 
			--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
		 
	WHERE 
		  DM.OrgId=@rOrgId
	 
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
		
		  -- ((CM.Id=@rClassId) OR (@rClassId=0))
			 --AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		 
			 
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering [sAttendance].[pRptStudentMonthlyRegisterGet]...';


GO

ALTER PROCEDURE [sAttendance].[pRptStudentMonthlyRegisterGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAttendanceTypeId tinyint=0,
	 @rSubjectId int=0,
	 @rForYear smallint,
	 @rForMonth tinyint,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int,
	 @rFromAverage decimal=0,
	 @rToAverage decimal=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			MR.ForMonth,
			MR.ForYear,
			M.Code +' - '+Convert(nvarchar(4),MR.ForYear) AS ForMonthYear,
			MR.TotalCount,
			ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
			MR.PresentCount,
			MR.AbsentCount,
			MR.AveragePresence,
			MR.AbsentDays,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SM.Title AS SubjectName,
			SA.DivisionOrder
			
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
		INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SA.AcademicId
		LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=MR.SubjectId
		INNER JOIN sCommon.tMonthMaster M ON MR.ForMonth = M.Id
		INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((MR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((MR.ForYear=@rForYear) OR (@rForYear=0))
		AND ((MR.ForMonth=@rForMonth) OR (@rForMonth=0))
		AND (SA.StatusId != 3)
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((MR.AveragePresence >= @rFromAverage) OR (@rFromAverage=0))
		AND ((MR.AveragePresence <= @rToAverage) OR (@rToAverage=0))
END
GO
PRINT N'Altering [sAttendance].[pStudentAttendanceGet]...';


GO
ALTER PROCEDURE [sAttendance].[pStudentAttendanceGet]
	 	 
	 	 @rUserSourceId bigint,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rAttendanceTypeId int=1,
	 	  @rForMonth int=0,
	 	 @rForYear int=0
	 	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN  
	 
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			SR.RepeatCount,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			Day(SR.AttendanceDate) AS AttendanceDay,
			MOnth(SR.AttendanceDate) AS AttendanceMonth,
			YEar(SR.AttendanceDate) AS AttendanceYear
  FROM   
			sStudent.vStudentAcademic SA 
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			 
			--AND (SR.AttendanceDate=@rAttendanceDate)
			--AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			--AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
		 
  WHERE 
		 -- ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  --AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
        (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      AND SA.StudentId=@rUserSourceId
      AND SR.AttendanceTypeId=@rAttendanceTypeId
      AND Month(SR.AttendanceDate)=@rForMonth
      AND Year(SR.AttendanceDate)=@rForYear
      --AND (SA.StatusId != 3)
      --AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      --AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
   
END
GO
PRINT N'Altering [sAttendance].[pStudentLeaveRequestGet]...';


GO
ALTER PROCEDURE [sAttendance].[pStudentLeaveRequestGet] 
	 
	 	@rAcademicId bigint,
        @rLeaveFromDate date='',
        @rLeaveToDate date='' ,
        @rOrgID int=0,
        @rBatchId int=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	Select
		SL.AcademicId,
		ISNULL(SL.LeaveFromDate,'')AS LeaveFromDate,
		ISNULL(SL.LeaveToDate,'')AS LeaveToDate,
		SL.LeaveReason,
		SM.Code As IdNo,
		SM.FirstName+' ' +SM.MiddleName+' ' +SM.LastName As Name
		
	from sAttendance.tStudentLeaveRequest SL
	INNER JOIN sStudent.tAcademic A ON A.Id=SL.AcademicId
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
	
	Where ((AcademicId=@rAcademicId) OR (@rAcademicId=0))
	AND ((LeaveFromDate=@rLeaveFromDate) OR (ISNULL(@rLeaveFromDate,'')=''))
	AND ((LeaveToDate=@rLeaveToDate) OR (ISNULL(@rLeaveToDate,'')=''))
	AND SM.OrgId=@rOrgID	
	AND A.BatchId=@rBatchId	
	
END
GO
PRINT N'Altering [sAttendance].[pYearlyRegisterGet]...';


GO



ALTER PROCEDURE [sAttendance].[pYearlyRegisterGet]

	 
	 @rAcademicId bigint=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int=0,
	 @rAttendanceTypeId tinyint=1,
	 @rStatus int=0,
	 @rDepartmentId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

SELECT 
	A.Id AS AcademicId,
	A.RollNo,
	SM.Code,
	YR.AvergeAttendance,
	YR.TotalDays,
	YR.PresentDays,
	
	YR.Month1,
	YR.PresentDays1,
	YR.TotalDays1,
	
	YR.Month2,
	YR.PresentDays2,
	YR.TotalDays2,
	
	YR.Month3,
	YR.PresentDays3,
	YR.TotalDays3,
	
	YR.Month4,
	YR.PresentDays4,
	YR.TotalDays4,
	
	YR.Month5,
	YR.PresentDays5,
	YR.TotalDays5,
	
	YR.Month6,
	YR.PresentDays6,
	YR.TotalDays6,
	
	YR.Month7,
	YR.PresentDays7,
	YR.TotalDays7,
	
	YR.Month8,
	YR.PresentDays8,
	YR.TotalDays8,
	
	YR.Month9,
	YR.PresentDays9,
	YR.TotalDays9,
	
	YR.Month10,
	YR.PresentDays10,
	YR.TotalDays10,
	
	YR.Month11,
	YR.PresentDays11,
	YR.TotalDays11,
	
	YR.Month12,
	YR.PresentDays12,
	YR.TotalDays12,
	
	SM.FirstName + ' ' + SM.LastName As Name,
	SM.StatusID
	
from
	sAttendance.tYearlyRegister YR
	INNER JOIN sStudent.tAcademic A ON A.Id=YR.AcademicId
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId 
where 


	((YR.AcademicId=@rAcademicId) OR (@rAcademicId=0))
	AND(A.BatchId=@rBatchId)
	AND((A.ClassId=@rClassId) OR (@rClassId=0))
	AND((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((Sm.StatusId=@rStatus) OR (@rStatus=0))
	order by A.RollNo 
 
	 END
GO
PRINT N'Altering [sAttendance].[pYearlyRegisterUpdate]...';


GO



ALTER PROCEDURE [sAttendance].[pYearlyRegisterUpdate]

     @rOrgId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

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



SET @lQuery = 'UPDATE YR    
    SET Month' +   convert(nvarchar(15),@lCounter)+  ' = MM.Code,
    TotalDays' +   convert(nvarchar(15),@lCounter)+  ' = MR.TotalCount,
    PresentDays' +   convert(nvarchar(15),@lCounter)+  ' = MR.PresentCount 
    from sAttendance.tYearlyRegister YR
    INNER JOIN sAttendance.tMonthlyRegister MR
    ON YR.AcademicId = MR.AcademicId
    AND MR.ForMonth = '  + convert(nvarchar(15),@lForMonth)  + ' AND MR.ForYear = ' + convert(nvarchar(15),@lForYear)  +
    ' INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
    INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
    AND A.BatchId = ' +  convert(nvarchar(15),@rBatchId)  + ' AND A.ClassId = ' + convert(nvarchar(15),@lClassId) 
    

    
 print @lQuery
execute(@lQuery)
	
	--IF 	(@lCounter = 1)
	--BEGIN
 
	--UPDATE YR    
 --   SET Month1  = MM.Title,TotalDays1 = MR.TotalCount,PresentDays1 = MR.PresentCount 
 --   from sAttendance.tYearlyRegister YR
 --   INNER JOIN sAttendance.tMonthlyRegister MR
 --   ON YR.AcademicId = MR.AcademicId
 --   AND MR.ForMonth = @lForMonth AND MR.ForYear = @lForYear
 --   INNER JOIN sCommon.tMonthMaster MM ON MM.Id = MR.ForMonth
 --   INNER JOIN sStudent.tAcademic A ON A.Id = MR.AcademicId 
 --   AND A.BatchId = @rBatchId AND A.ClassId = @lClassId
    
	--END
	--ELSE IF (@lCounter = 2)
	--BEGIN

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

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


GO
ALTER PROCEDURE [sBiometric].[pMonthlyPresenceSummaryGet]	 
	 @rCode nvarchar(20)='',
	 @rForYear int,
	 @rForMonth int,
	 @rOrgId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	DECLARE @rFromDate date
	DECLARE @rToDate date
	
	SET @rFromDate = CONVERT(date,CONVERT(nvarchar(10), @rForYear) + '-' + CONVERT(nvarchar(10), @rForMonth) + '-' + '01')
	SET @rToDate = DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rFromDate) + 1, 0))
	
	CREATE TABLE #TempMonthTrans
	(
	Id int Identity,
	EmployeeId bigint,	
	PresentStatus nvarchar(5),
	LateBy decimal(10,2),
	Duration decimal(10,2),
	EarlyBy nvarchar(10),
	Attn_dt date,
	FirstIn nvarchar(10)
	)
	
	INSERT INTO #TempMonthTrans
	
	SELECT EmployeeId,D01,Replace(D01_L,':','.'),Replace(D01_T,':','.'),D01_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),D01_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D02,Replace(D02_L,':','.'),Replace(D02_T,':','.'),D02_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 2) as datetime),D02_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D03,Replace(D03_L,':','.'),Replace(D03_T,':','.'),D03_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 3) as datetime),D03_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D04,Replace(D04_L,':','.'),Replace(D04_T,':','.'),D04_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 4) as datetime),D04_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D05,Replace(D05_L,':','.'),Replace(D05_T,':','.'),D05_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 5) as datetime),D05_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D06,Replace(D06_L,':','.'),Replace(D06_T,':','.'),D06_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 6) as datetime),D06_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D07,Replace(D07_L,':','.'),Replace(D07_T,':','.'),D07_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 7) as datetime),D07_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D08,Replace(D08_L,':','.'),Replace(D08_T,':','.'),D08_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 8) as datetime),D08_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D09,Replace(D09_L,':','.'),Replace(D09_T,':','.'),D09_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 9) as datetime),D09_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D10,Replace(D10_L,':','.'),Replace(D10_T,':','.'),D10_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D11,Replace(D11_L,':','.'),Replace(D11_T,':','.'),D11_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D12,Replace(D12_L,':','.'),Replace(D12_T,':','.'),D12_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D13,Replace(D13_L,':','.'),Replace(D13_T,':','.'),D13_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D14,Replace(D14_L,':','.'),Replace(D14_T,':','.'),D14_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D15,Replace(D15_L,':','.'),Replace(D15_T,':','.'),D15_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D16,Replace(D16_L,':','.'),Replace(D16_T,':','.'),D16_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D17,Replace(D17_L,':','.'),Replace(D17_T,':','.'),D17_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D18,Replace(D18_L,':','.'),Replace(D18_T,':','.'),D18_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D19,Replace(D19_L,':','.'),Replace(D19_T,':','.'),D19_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D20,Replace(D20_L,':','.'),Replace(D20_T,':','.'),D20_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D21,Replace(D21_L,':','.'),Replace(D21_T,':','.'),D21_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D22,Replace(D22_L,':','.'),Replace(D22_T,':','.'),D22_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D23,Replace(D23_L,':','.'),Replace(D23_T,':','.'),D23_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D24,Replace(D24_L,':','.'),Replace(D24_T,':','.'),D24_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D25,Replace(D25_L,':','.'),Replace(D25_T,':','.'),D25_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D26,Replace(D26_L,':','.'),Replace(D26_T,':','.'),D26_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D27,Replace(D27_L,':','.'),Replace(D27_T,':','.'),D27_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL
	SELECT EmployeeId,D28,Replace(D28_L,':','.'),Replace(D28_T,':','.'),D28_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,D29,Replace(D29_L,':','.'),Replace(D29_T,':','.'),D29_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29_IN FROM sBiometric.tMonthTrans WHERE 1=1 
		AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,D30,Replace(D30_L,':','.'),Replace(D30_T,':','.'),D30_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,D31,Replace(D31_L,':','.'),Replace(D31_T,':','.'),D31_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31_IN FROM sBiometric.tMonthTrans WHERE 1=1 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	DECLARE @lAttendanceDate AS nvarchar(20)
	SET @lAttendanceDate = CONVERT(nvarchar(10), @rForYear) + '-' + CONVERT(nvarchar(10), @rForMonth) + '-' + '01'

	DECLARE @lOrgGroupId int=0
	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
		
	DECLARE @lItemValue nvarchar(20) = ''
	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 204

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

	

	SELECT
	
		
		ROW_NUMBER() OVER (ORDER BY EM.Code ASC) AS SrNo,
		EM.Code,
		EM.FirstName + ' ' + EM.Lastname AS Name,					
									
		Tot_Abs -(ISNULL(LateStatus,0) * 0.5) - isnull(A4.AbsentStatusApr,0)  - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHCountApproved.LHCount,0)    AS Absent,	-- 		
		--Tot_Abs,
		--(ISNULL(LateStatus,0) * 0.5),
		--isnull(A4.AbsentStatusApr,0),
		--isnull(A5.HDStatusApr,0) * 0.5,
		--isnull(LHApproved.LHCount,0),	-- 		
		
		
		ISNULL(TotalLate,0) + ISNULL(ELValidCount,0) AS ELTotal, -- Number of EL Case
		ISNULL(LateStatusApr,0) + ISNULL(ELValidApproveCount,0) AS ELApprove,  -- Approved EL Case
		
		
		isnull(V_StatusApprove.VstatusLatecount,0) AS ELValidCount,
		isnull(V_Status.VstatusLatecount,0) AS ELValidApprove,
		
	    Count_Late - ISNULL(LateValidCount.LateValid,0) - ISNULL(LateCountAprooved.LateAprooved,0) AS Late,
	   -- Count_Late , ISNULL(LateValidCount.LateValid,0),

		ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
		UNPIVOT
		(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
		WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS DinnerAllowance,

		Comp.Compoff AS CompOff,	
		
		--sBiometric.fcalcMINI(Tot_Early)		-- Total Early		
		--,isnull(PW.PWHrs,0)										
		--,isnull(LateValid1.EarlyBy,0)								-- 1st HD so early -
		--,isnull(LH.EarlyBy,0)		
		--,isnull(LateEL.LateBy,0)									-- EL Late
		--,ISNULL(V_Status.EarlyLateMin,0)
		--,isnull(LateValid.EarlyBy,0)								-- Valid case Approve Early/Late Min
		--,ISNULL(ELLateValid.LateBy,0)								-- Not Attain Fullday and Late Duration< 9.15 and Late< 0.30
		--,sBiometric.fcalcMINI(replace(isnull(A.EarlyHrs,0.0),'.',':')),
		
		 
		case when convert(decimal(10,2),replace(sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_Early)		-- Total Early
		- isnull(PW.PWHrs,0)										-- Presence On WeekOff
		- isnull(LateValid1.EarlyBy,0)								-- 1st HD so early -
		- isnull(LH.EarlyBy,0)										-- LH Early By
		+ isnull(LateEL.LateBy,0)									-- EL Late
		- ISNULL(V_Status.EarlyLateMin,0)
		+ isnull(LateValid.EarlyBy,0)								-- Valid case Approve Early/Late Min
		- ISNULL(ELLateValid.LateBy,0)								-- Not Attain Fullday and Late Duration< 9.15 and Late< 0.30
		-sBiometric.fcalcMINI(replace(isnull(A.EarlyHrs,0.0),'.',':'))),':','.'))  < 0 then '00:00' else 
		
		
		sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_Early)		-- Total Early
		- isnull(PW.PWHrs,0)										-- Presence On WeekOff
		- isnull(LateValid1.EarlyBy,0)								-- 1st HD so early -
		- isnull(LH.EarlyBy,0)										-- LH Early By
		+ isnull(LateEL.LateBy,0)									-- EL Late
		+ isnull(LateValid.EarlyBy,0)
		- ISNULL(V_Status.EarlyLateMin,0)							-- Valid case Approve Early/Late Min
		- ISNULL(ELLateValid.LateBy,0)								-- Not Attain Fullday and Late Duration< 9.15 and Late< 0.30		
		-sBiometric.fcalcMINI(replace(isnull(A.EarlyHrs,0.0),'.',':'))) 		
		end
		AS EarlyLeave,  		
		--   After 10 & attn full day      
		0 AS Tot_Late,	
		--sBiometric.fcalcHour(sBiometric.fcalcMINI(replace(ISNULL(LHApproved.LHHrs,0.0),'.',':'))),
		sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_OT) + sBiometric.fcalcMINI(replace(ISNULL(LHApproved.LHHrs,0.0),'.',':'))) AS Tot_OT,	


		

		case when convert(decimal(10,2),replace(sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_Early)		-- Total Early
		- isnull(PW.PWHrs,0)										-- Presence On WeekOff
		- isnull(LateValid1.EarlyBy,0)								-- 1st HD so early -
		- isnull(LH.EarlyBy,0)										-- LH Early By
		+ isnull(LateEL.LateBy,0)									-- EL Late
		+ isnull(LateValid.EarlyBy,0)
		- ISNULL(V_Status.EarlyLateMin,0)							-- Valid case Approve Early/Late Min
		- ISNULL(ELLateValid.LateBy,0)								-- Not Attain Fullday and Late Duration< 9.15 and Late< 0.30		
		-sBiometric.fcalcMINI(replace(isnull(A.EarlyHrs,0.0),'.',':'))),':','.'))  < 0 then 
		 sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_OT) + sBiometric.fcalcMINI(replace(ISNULL(LHApproved.LHHrs,0.0),'.',':')))
		 else 
		sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_OT) + sBiometric.fcalcMINI(replace(ISNULL(LHApproved.LHHrs,0.0),'.',':')) - 
		((sBiometric.fcalcMINI(Tot_Early)		-- Total Early
		- isnull(PW.PWHrs,0)										-- Presence On WeekOff
		- isnull(LateValid1.EarlyBy,0)								-- 1st HD so early -
		- isnull(LH.EarlyBy,0)										-- LH Early By
		+ isnull(LateEL.LateBy,0)									-- EL Late
		+ isnull(LateValid.EarlyBy,0)
		- ISNULL(V_Status.EarlyLateMin,0)							-- Valid case Approve Early/Late Min
		- ISNULL(ELLateValid.LateBy,0)								-- Not Attain Fullday and Late Duration< 9.15 and Late< 0.30		
		-sBiometric.fcalcMINI(replace(isnull(A.EarlyHrs,0.0),'.',':'))))) END AS Tot_OT_EL,
	--	LWP.NoOfLeave,
		Tot_Abs - isnull(lwp.NoOfleave,0)
		--(SELECT ISNULL(SUM(NoOfLeave),0) FROM sHrm.tLeaveTypeMaster Lt inner join sHrm.tLeave L ON L.LeaveTypeId = LT.Id AND LT.IsLWP =  0 WHERE EmployeeId = EM.Id AND StatusId=550 AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))) 
		- (ISNULL(LateStatus,0) * 0.5) - isnull(A4.AbsentStatusApr,0) - isnull(A5.HDStatusApr,0) * 0.5 - isnull(LHCountApproved.LHCount,0)
		AS LWP,		--   +  isnull(LH.LHCount,0)
		ISNULL(EC.CompanyEmail,'')+','+ISNULL(vEM.CompanyEmail,'') AS CompanyEmail
	FROM 
		sBiometric.tMonthTrans MT
		INNER JOIN sHrm.tEmployeeMaster EM ON MT.EMployeeId = EM.Id AND MT.attn_dt = @lAttendanceDate
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		LEFT JOIN sHrm.vEmployeeCommonDetail vEM  ON  vEM.EmployeeId = EJD.EmployeeManagerId	
		
		LEFT Join
		(
			SELECT ISNULL(SUM(NoOfLeave),0) NoOfLeave,L.EmployeeId FROM sHrm.tLeaveTypeMaster Lt 
		  inner join sHrm.tLeave L ON L.LeaveTypeId = LT.Id AND LT.IsLWP =  0
			inner jOIN #TempMonthTrans TT on L.EmployeeId = TT.EmployeeId 
			AND TT.PresentStatus NOT IN ('W') 
			WHERE StatusId=550 AND TT.attn_dt = L.FromDate
			AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))
		 Group By L.EmployeeId
		)LWP ON LWP.EmployeeId = MT.EmployeeId
		
		LEFT JOIN  -- early or first half day early 
		(	Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateValid
		    From sBiometric.tMonthTrans MT
			leFT jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND ((TT.PresentStatus ='HD' AND TT.LateBy > '4.0')
			Or (TT.LateBy > 0.30)) 			
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LateValidCount ON LateValidCount.EmployeeId = MT.EmployeeId
		
		LEFT JOIN  -- Late Approve entry count Less then 30 min late
		(	Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateAprooved
		    From sBiometric.tMonthTrans MT
			INNER JOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.LateBy <= 0.30 AND TT.LateBy > 0 
			INNER JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TT.EmployeeId AND ELS.StatusId = 550 
			--and ELS.LateStatus='V'
			AND CONVERT(DATE,ELS.LateDate) = TT.Attn_Dt
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LateCountAprooved ON LateCountAprooved.EmployeeId = MT.EmployeeId
				
		LEFT JOIN  -- early or first half day early 
		(	Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateValid,0 AS EarlyBy,  --
			 sum(sBiometric.fcalcMINI(Replace(Isnull(Tt.lATEbY,0.0),'.',':'))) AS LateBy
		     From
			sBiometric.tMonthTrans MT
			INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND ((TT.PresentStatus ='HD' AND TT.LateBy > '4.0')
			Or (TT.LateBy > 0.30)) AND TT.PresentStatus <> 'E' AND TT.PresentStatus <> 'PW'			--AND TT.Duration <9.15
			
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LateValid ON LateValid.EmployeeId = MT.EmployeeId
		LEFT JOIN  -- Duration <= 9.15  AND Late <= 30
		(	Select TT.EmployeeID, 0  AS LateBy   --  SUM(sBiometric.fcalcMINI(Replace(Isnull(Tt.lATEbY,0.0),'.',':')))
		    From sBiometric.tMonthTrans MT
			INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  
			AND TT.LateBy <= 0.30  
			AND TT.Duration < 9.30 WHERE MT.attn_dt = @lAttendanceDate AND TT.PresentStatus <> 'LH' 
			GRoup By TT.EmployeeId
		)ELLateValid ON ELLateValid.EmployeeId = MT.EmployeeId
		LEFT JOIN  -- Late arrive and attain full day > 9.15
		(	Select TT.EmployeeID, sum(sBiometric.fcalcMINI(isnull(Replace(TT.LateBy,'.',':'),'0:0'))) AS LateBy From
			sBiometric.tMonthTrans MT
			leFT jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND (TT.PresentStatus ='HD' AND TT.LateBy <= 0.30 
			AND TT.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))
			AND TT.Duration <= Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4)))			
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LateNotEL ON LateNotEL.EmployeeId = MT.EmployeeId
		LEFT JOIN -- Half Day Early
		(	Select TT.EmployeeID, sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS EarlyBy From
			sBiometric.tMonthTrans MT
			inner jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  
			AND (((TT.PresentStatus ='HD' AND convert(decimal(10,2),Replace(TT.Duration,':','.')) > 4.0 AND convert(decimal(10,2),Replace(TT.Duration,':','.')) < 6.15)) Or TT.PresentStatus  in ('E') )
			AND TT.Attn_Dt Not in (Select Latedate from sBiometric.tEmployeeLateStatus Where StatusId <> 550 AND LateStatus='EL' AND EmployeeId=MT.EmployeeId )
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LateValid1 ON LateValid1.EmployeeId = MT.EmployeeId
		LEFT JOIN -- Less Hour
		(	Select TT.EmployeeID, Count(TT.EmployeeID) LHCount, sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS EarlyBy ,sum(isnull(TT.Duration,0)) AS LHHrs From
			sBiometric.tMonthTrans MT
			inner jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus ='LH' 
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LH ON LH.EmployeeId = MT.EmployeeId
		LEFT JOIN -- Less Hour Approved
		(	
		Select MT.EmployeeID, Count(MT.EmployeeID) LHCount,sBiometric.fcalcHour(sum(sBiometric.fcalcMINI(Replace(ISNULL(TT.Duration,0),'.',':'))))
		--sum(isnull(TT.Duration,0.00)) 
		AS LHHrs 
		From
			sBiometric.tMonthTrans MT
			INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus ='LH' 
			where MT.attn_dt = @lAttendanceDate AND
			TT.Attn_DT 
			not in (select LateDate from sBiometric.tEmployeeLateStatus Where StatusId = 550 AND LateStatus='LH' AND EmployeeId=MT.EmployeeId )
			GRoup By MT.EmployeeId
		--SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) as LHCount,SUM(ELS1.EarlyHrs) AS LHHrs FROM sBiometric.tEmployeeLateStatus ELS1
		--WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate) AND ELS1.StatusId = 550  AND ElS1.LateStatus = 'LH'
		--AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		--GROUP BY ELS1.EmployeeId
		)LHApproved ON LHApproved.EmployeeId = MT.EmployeeId
		Left Join (
		SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) as LHCount FROM sBiometric.tEmployeeLateStatus ELS1
		WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate) AND ELS1.StatusId = 550  AND ElS1.LateStatus = 'LH'
		AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS1.EmployeeId
		)LHCountApproved ON LHCountApproved.EmployeeId = MT.EmployeeId
		LEFT JOIN -- PW
		(	Select TT.EmployeeID,sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS PWHrs From
			sBiometric.tMonthTrans MT
			leFT jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus like '%PW%' 
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)PW ON PW.EmployeeId = MT.EmployeeId
		LEFT JOIN -- Aproved EL Time
		(
		SELECT 
		sBiometric.fcalcHour(sum(case when TM.LateBy <=0.30 then sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))-TM.lateBy*100
		else sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))end ))
		AS EarlyHrs,ELS.EmployeeId 
		FROM sBiometric.tEmployeeLateStatus ELS 
		INNER JOIN #TempMonthTrans TM ON TM.EmployeeId = ELS.EmployeeId and TM.ATTN_DT = ELS.LateDate AND (TM.LateBy >.30 OR TM.EarlyBy <> '00:00' )
		WHERE ELS.StatusId = 550 AND ELS.LateStatus <> 'HD' AND ELS.LateStatus <> 'LH' AND ELS.LateStatus <> 'V' AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate) 
		AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS.EmployeeId
		) A ON A.EMployeeId = MT.EMployeeId 
		LEFT JOIN -- Aproved EL Time
		(
		SELECT sum(sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))) AS EarlyLateMin,ELS.EmployeeId ,COUNT(ELS.EmployeeId ) VstatusLatecount
		FROM sBiometric.tEmployeeLateStatus ELS 
		INNER JOIN #TempMonthTrans TM ON TM.EmployeeId = ELS.EmployeeId and TM.ATTN_DT = ELS.LateDate 
		AND (TM.LateBy >.30 OR sBiometric.fcalcMINI(isnull(TM.EarlyBy,'0:0')) > 0  )
		WHERE ELS.StatusId = 550 AND ELS.LateStatus = 'V' AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate) 
		AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS.EmployeeId
		) V_Status ON V_Status.EMployeeId = MT.EMployeeId 
		LEFT JOIN  -- EL Approved Count
		(
		SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS LateStatusApr FROM sBiometric.tEmployeeLateStatus ELS1
		LEFT JOIN sHRM.tLeave L on L.EmployeeId = ELS1.EmployeeId AND L.LeavePeriodId = 2 
		AND L.StatusId = 550 
		AND L.FromDate = ELS1.LateDate 
		WHERE ELS1.StatusId = 550 AND L.Id IS NULL and  (LateStatus = 'EL') AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)
		AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS1.EmployeeId
		)A3 ON A3.EMployeeId = MT.EMployeeId 
		LEFT JOIN  -- EL Approved Count
		(
		SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS ELValidApproveCount FROM sBiometric.tEmployeeLateStatus ELS1
		INNER JOIN sHRM.tLeave L on L.EmployeeId = ELS1.EmployeeId AND L.LeavePeriodId = 1 
		AND L.StatusId = 550 
		AND L.FromDate = ELS1.LateDate 
		WHERE ELS1.StatusId = 550 AND L.Id IS NULL and  (LateStatus = 'V') AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)
		AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS1.EmployeeId
		)ELValidApproveCount ON ELValidApproveCount.EMployeeId = MT.EMployeeId 
		LEFT JOIN -- EL Entry AND Approved  Absent Case
		(
		SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS AbsentStatusApr FROM sBiometric.tEmployeeLateStatus ELS1
		INNER JOIN #TempMonthTrans TM ON TM.EmployeeId = ELS1.EmployeeId 
		AND ELS1.StatusId = 550  AND ELS1.LateDate = TM.Attn_dt
		WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)
		AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		AND ELS1.LateStatus = 'A'
		GROUP BY ELS1.EmployeeId
		)A4 ON A4.EMployeeId = MT.EMployeeId 
		LEFT JOIN -- EL Entry AND Approved  HD Case
		(
		SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS HDStatusApr FROM sBiometric.tEmployeeLateStatus ELS1
		WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate) AND ELS1.StatusId = 550  AND ElS1.LateStatus = 'HD'
		AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		GROUP BY ELS1.EmployeeId
		)A5 ON A5.EMployeeId = MT.EMployeeId
		Left Join -- EL Case 
		(
		SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS LateStatus FROM #TempMonthTrans TM
		WHERE 1=1 
		AND TM.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))
		AND TM.Duration <= Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4))
		AND TM.PresentStatus not like '%PW%' AND (sBiometric.fcalcMINI(TM.FirstIn) < 720 AND PresentStatus = 'HD')	
		GROUP BY TM.EmployeeId
		) A1 ON A1.EMployeeId = MT.EMployeeId 
		LEFT JOIN
		(		
		SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS TotalLate FROM #TempMonthTrans TM
		LEFT JOIN sHRM.tLeave L on L.EmployeeId = TM.EmployeeId AND L.LeavePeriodId = 2 
		AND L.StatusId = 550 
		AND L.FromDate = TM.Attn_dt 
		WHERE 1=1 AND L.Id IS NULL  AND sBiometric.fcalcMINI(TM.FirstIn) < 720  AND (TM.LateBy > 0.30 or TM.EarlyBy <> '00:00')
		AND TM.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))
		AND TM.Duration <= Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4))
		GROUP BY TM.EmployeeId
		) A2 ON A2.EMployeeId = MT.EMployeeId 
		LEFT JOIN
		(		
		SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS ELValidCount FROM #TempMonthTrans TM
		INNER JOIN sHRM.tLeave L on L.EmployeeId = TM.EmployeeId AND L.LeavePeriodId = 1 
		AND L.StatusId = 550 
		AND L.FromDate = TM.Attn_dt 
		WHERE 1=1 AND L.Id IS NULL  AND  (TM.LateBy > 0.30 or TM.EarlyBy <> '00:00')
		GROUP BY TM.EmployeeId
		) ELValidCount ON ELValidCount.EMployeeId = MT.EMployeeId 
		LEFT Join
		(
		select Sum(isnull(AddRequestBalance,0)) AS Compoff,LV.EmployeeId from shrm.tLeaveBalanceAddRequest LV
		inner join sHrm.tLeaveTypeMaster LT ON LV.LeaveTypeId=LT.Id AND MainLeaveTypeId = 3 AND ReportDate >= CONVERT(DATE,@lAttendanceDate)
		AND ReportDate <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
		AND LV.StatusId = 550
		GRoup by LV.EmployeeId
		)Comp ON Comp.EmployeeId = MT.EMployeeId 
		LEFT JOIN  -- EL and Late 
		(	Select TT.EmployeeID,sum(sBiometric.fcalcMINI(Replace(Isnull(Tt.LateBy,0.0),'.',':'))) AS LateBy
		     From sBiometric.tMonthTrans MT		     
			INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  and TT.LateBy > 0.30
			--AND ((TT.PresentStatus ='HD' AND TT.Duration > '6.15')
			AND (TT.PresentStatus IN ('EL','V','P')
			OR (TT.PresentStatus ='HD' AND TT.LateBy < '2.30'))
			AND TT.LateBy > 0 
			LEFT JOIN sBiometric.tEmployeeLateStatus ELS1  ON TT.EmployeeId = ELS1.EmployeeId 
			AND ISNULL(ELS1.StatusId,0) <> 550  
			AND ELS1.LateDate = TT.Attn_dt
			and CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate) 
			AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))
			where MT.attn_dt = @lAttendanceDate 
			GRoup By TT.EmployeeId
		)LateEL ON LateEL.EmployeeId = MT.EmployeeId
		LEFT JOIN -- Aproved EL Time
		(
		SELECT COUNT(TM.EmployeeId ) VstatusLatecount,EMployeeId
		FROM #TempMonthTrans TM 
		WHERE (TM.LateBy >.30 OR sBiometric.fcalcMINI(isnull(TM.EarlyBy,'0:0')) > 0  )	AND TM.Duration >= 9.30	
		GROUP BY TM.EmployeeId
		) V_StatusApprove ON V_StatusApprove.EMployeeId = MT.EMployeeId AND MT.attn_dt = @lAttendanceDate  
	
	WHERE (EM.Code = @rCode OR ISNULL(@rCode,'') = '')
	ORDER BY EM.Code

	TRUNCATE TABLE #TempMonthTrans
END
GO
PRINT N'Altering [sCertificate].[pRptBonafiedCertificateGet]...';


GO


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

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


	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	if (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 177 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	
	Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	
	
	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			B.Id,
			B.Number,
			B.AcademicId,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			B.BonafideDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			--OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			--OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			ATM.Title AS AffiliationType,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			@lIsShowPhoto AS IsShowPhoto,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			B.Remark AS ReceiptNo,
			SF.FatherName,
			SA.AdmissionDate,
			DP.Title AS DepartmentName,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4,
			REPLICATE(',',OM.LetterHeadMargin)    AS LetterHeadMargin,
			ISNULL(B.BonafiedReason,'') AS BonafiedReason,
			CT.Title AS Category,
			SF.MotherName,
			C.PermanentStreetOne,
			C.PermanentStreetTwo,
			C.PermanentStreetThree,
			C.PermanentCountry,
			C.PermanentState,
			C.PermanentCity,
			C.PermanentZipCode,
			C.PermanentContactNo,
			C.PresentStreetOne,
			C.PresentStreetTwo,
			C.PresentStreetThree,
			C.PresentCountry,
			C.PresentState,
			C.PresentCity,
			C.PresentContactNo,
			C.PresentZipCode,
			SM.SUId,
			SO.AdhaarNumber,
			CM.DisplayTitle AS ClassName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			OM.PrincipalSignature,
			ISnull(AR.SourceId,0) AS StudentidForhostel,
			DM.DisplayTitle AS Divisionname,
			@lIDConfigValue AS ItemValue ,
			SM.RecordStatusId 
			
	FROM 
			sCertificate.tBonafide B
			INNER JOIN sStudent.tAcademic A ON B.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN SHostel.tAssignRoom Ar On Ar.SourceId=A.StudentId AND Ar.OrgGroupBatchId=@rOrgGroupBatchId 
			
			
			--INNER JOIN sSetup.tTermMaster TM ON  TM.ID=
	WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			--AND ((B.BonafideDate=@rBonafiedDate) OR (ISNULL(@rBonafiedDate,'')=''))
			AND ((B.Number=@rNumber) OR (@rNumber=''))
			AND ((B.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((B.Number <= @rToNo) OR (@rToNo=''))
			AND ((B.BonafideDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((B.BonafideDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--Group By B.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
			--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,B.BonafideDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,
			--OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering [sCertificate].[pRptCharacterCertificateGet]...';


GO



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

DECLARE @lConfigValue nvarchar(50)

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

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

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 180 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	SELECT 
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			C.Id,
			C.AcademicId,
			SM.Code,
			SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			BM.Title AS Batch,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			C.characterDate,
			C.Number,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgName,
			OM.StateName+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4  ,
			SA.AdmissionDate,
			SF.FatherName,
			@lIDConfigValue AS ItemValue 
	FROM 
			sCertificate.tCharacter C
			INNER JOIN sStudent.tAcademic A ON C.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
	WHERE  
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((C.Number=@rNumber) OR (@rNumber=''))
		AND ((C.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((C.Number <= @rToNo) OR (@rToNo=''))
		AND ((C.characterDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((C.characterDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--Group By C.AcademicId,C.Number,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
		--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,C.characterDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,OM.OrgLogo,OM.Title,
		--OM.StreetOne,OM.StreetThree,OM.StreetTwo,OM.PhoneNo
	END
GO
PRINT N'Altering [sCertificate].[pRptFirstTrialCertificateGet]...';


GO
 


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

DECLARE @lIsDisplayImageHeader bit = 0

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

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

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

	SELECT 
	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			FT.Id,
			FT.Number,
			FT.AcademicId,
			FT.FirstTrialDate,
			FT.ExamCentre,
			FT.ExamYear,
			FT.SeatNo,
			FT.Trial,
			SM.Code,
			SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			SO.GenderId,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SM.StatusId,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4  ,
			(CASE WHEN CGM.Title='10' THEN  'SSC'
			WHEN  CGM.Title='12'  THEN 'HSC'  ElSE CGM.Title + ' '+'std'
			 END) AS Exam,
			 FT.Remark AS Remark,
			 ISNULL(SF.FatherName,'') As FatherName,
			 SA.AdmissionDate,
			 SO.BirthDateInWord ,
			 SI.StudentPhoto,
			 @lIDConfigValue AS ItemValue 
			
			
	FROM 
			sCertificate.tFirstTrial FT
			INNER JOIN sStudent.tAcademic A ON FT.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId 
			Left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sSetup.tClassGroupMaster CGM ON CGM.Id = CM.ClassGroupId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			
	WHERE 
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((FT.FirstTrialDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((FT.FirstTrialDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((FT.Number=@rNumber) OR (@rNumber=''))
		AND ((FT.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((FT.Number <= @rToNo) OR (@rToNo=''))
		--Group By FT.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,FT.SeatNo,FT.Trial,SM.Code,SM.FirstName,OM.StateName,SO.GenderId,
		--OM.CityName,OM.StateName,FT.FirstTrialDate,FT.ExamCentre,FT.ExamYear,SM.MiddleName,SM.LastName,OM.CityName,SM.StatusId
		--,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering [sCertificate].[pRptLeavingCertificateGet]...';


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

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

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


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


SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 178 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	
	
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--MR.PresentCount AS PresentDays ,
			--MR.TotalCount AS TotalDays ,
			L.Id,
			--(SELECT SUM(MR.PresentCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS PresentDaysSum ,
			--(SELECT SUM(MR.TotalCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS TotalDaysSum ,
			SM.Code,
			L.AcademicId,
			SM.FirstName,SM.MiddleName,SM.LastName,
			SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			--0 As CastCategoryId,
			--ISNULL(SO.CastCategoryId,0) As CastCategoryId,
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			SA.PreviousSchool,
			SA.AdmissionDate,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			SO.GenderId,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			CM.DisplayTitle AS AdmissionStandard,
			CMS.DisplayTitle AS CurrentStandard,
			CMS.Title AS CurrentStandardTitle,
			--'' AS CurrentStandardInWords,
			SM.StatusId,
			L.LastExamName AS Result,
			L.LastExamResult AS FailOrPass,
			L.SubjectStudied AS SubjectNAme,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			'' AS PromotedorNot,
			L.PromoteToClass  AS PromotedToClass,
			L.FeeDetail AS LastFeesPaid,
			L.FeeConcessionDetail AS AnyConcession,
			L.NCCScoutDetail  AS NCCScoutDetail,
			L.ExtraCurricularActivities AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			AD.PresentDaysAnnual AS PresentDaysSum,
			AD.TotalDaysAnnual AS TotalDaysSum,
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4  ,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(L.ToCollege,'') AS ToCollege ,
			ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
			ISNULL(OM.University,'')AS University,
			@lSchoolRemark1 AS SchoolRemark1 ,
			@lSchoolRemark2 AS SchoolRemark2 ,
			@lSchoolRemark3 AS SchoolRemark3 ,
			@lSchoolRequiredSignature AS SchoolRequiredSignature,
			ISNULL(CSG.Inword,'')AS CurrentStandardInWords,
			SO.MotherTongue,
			SO.AdhaarNumber,
			vSA.SUId,
			CASE WHEN isnull(BM.FromDate,'')>Isnull(SA.AdmissionDate,'') THEN BM.FromDate ELSE SA.AdmissionDate END AS BatchDate,
			SO.BirthState,
			SO.BirthCountry,
			SD.BankAccountNumber,
			SO.UIDNumber,
			SD.BankName,
			SD.BankIFSCCode,
			SA.PreviousStandard 
			,L.TermsInInstitute,
			@lIDConfigValue AS ItemValue 
		--sFinanceCommon.fNumberToWords(ISNULL(CM.ClassGroupId,0),'',OM.OrgGroupId) AS CurrentStandardInWords
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.PresentCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.PresentCount,0))
		--END AS Presentdays,
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.TotalCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.TotalCount,0))
		--END AS TotalCount
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			--INNER JOIN sStudent.tAcademic A ON L.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			--LEFT JOIN  sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id 
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			--AND BM.OrgGroupBatchId=vSA.OrgGroupBatchId
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId

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


GO


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

BEGIN 
DECLARE @lIsOnPrePrinted bit = 0,@lIsDisplayReligion bit=0,@lConfigValue nvarchar(50),@lIsDisplayImageHeader bit = 0,@lOrgId smallint
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0
Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId

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

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

	SELECT  
		T.Number,
		T.TCDate AS TransferDate,
		T.ExamName,
		T.ExamSeatNo,
		T.ExamYear,
		T.ExamResult,
		T.PromotedClass,
		T.TransferConduct,
		T.OptionalSubject,
		T.Remark,
		A.Name,
		A.OrganiZationName,
	    SO.GenderId,
	    SO.DateOfBirth,
	    A.ClassName AS ClassName,
		A.DivisionName AS DivisionName,
		A.Code As StudentCode,
		SO.AdhaarNumber,
		T.SemesterDuration,
		A.StudentId,
		@lIsOnPrePrinted AS IsOnPrePrinted,
		@lIsDisplayImageHeader AS IsDisplayImageHeader,
		OM.OrgLogo,
		OM.ReportOrgTitle AS OrgTitle,
		OM.SmallAddress1,
		OM.SmallAddress2,
		OM.RegistrationDetail,
		OI.CertificateHeaderA4,
		@lIDConfigValue AS ItemValue 
		
	From sCertificate.tTransfer T 
	INNER JOIN sStudent.vStudentAcademic A On A.AcademicId=T.AcademicId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId  
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId 
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	WHERE 
		T.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((A.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((T.TCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((T.TCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((A.ClassId=@rClassId) OR(@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((T.Number=@rNumber) OR (@rNumber=''))
		AND ((T.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((T.Number <= @rToNo) OR (@rToNo=''))
	
END
GO
PRINT N'Altering [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(TempCircularId, 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


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

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


GO

ALTER PROCEDURE [sCommon].[pStockItemUpdateGet]
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rLocationId bigint,
	 @rIsBlank bit,
	 @rStockItemCategoryId bigint,
	 @rItemSubGroupId bigint,
	 @rItemMainGroupId bigint
	
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		
		
		IF(@rSubCategory = 'ItemSubGroup' OR @rSubCategory = 'IssueStockUom' OR @rSubCategory = 'StockItemCategory' OR @rSubCategory = 'Bin')
		BEGIN
			SET @rSubCategory = @rSubCategory + 'Id' 
		END
		
		 Declare @Sql nvarchar(max)=''
		 
		 SET @Sql = 'Select SA.Id,SA.Code,SA.Title,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SA.'+@rSubCategory+',0) 
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SA.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SA.'+@rSubCategory+',''False'') 
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SA.'+@rSubCategory+',''0001/01/01'') 
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SA.'+@rSubCategory+',''0'') 
						END AS SubCategory
							FROM 
							sIp.tStockItemMaster  SA
							inner join sIp.tItemSubGroupMaster ISGM on ISGM.id = SA.ItemSubGroupId
							Where SA.OrgGroupId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.LocationId='+CAST(@rLocationId AS nvarchar(15))+')
							AND (ISGM.ItemMainGroupId = ' + convert(varchar,@rItemMainGroupId) + ' or ' + convert(varchar,@rItemMainGroupId) + '= 0)
							AND (ISGM.Id = ' + convert(varchar,@rItemSubGroupId) + ' or ' + convert(varchar,@rItemSubGroupId) + '= 0)
							AND (SA.StockItemCategoryId = ' + convert(varchar,@rStockItemCategoryId) + ' or ' + convert(varchar,@rStockItemCategoryId) + '= 0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SA.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SA.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SA.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SA.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'	
								
									
	 
	   Exec sp_executesql @sql
END
GO
PRINT N'Altering [sCommunication].[pPhotoCategoryMaster_Get]...';


GO
 
ALTER PROCEDURE [sCommunication].[pPhotoCategoryMaster_Get]
	 
	 @rScopeSourceId bigint=0,
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 --@rOrgGroupId smallint,
	 @rSourcetypeId smallint,
	 --@rOrgGroupBatchID int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

  declare @lOrgGroupId smallint,@lOrgGroupBatchID int,@lOrgId smallint
  
  if @rSourcetypeId=2003
  BEGIN
  
	  Select @lOrgGroupId=Om.OrgGroupId,@lOrgId=OM.Id ,@lOrgGroupBatchID=BM.OrgGroupBatchId  from 
	  sSetup.tOrganizationMaster OM
	  INNER JOIN sStudent.tAcademic A ON A.OrgId=OM.Id
	  INNER JOIN sSetup.tBatchMaster BM ON  BM.Id=A.BatchId
	  where A.BatchId= @rBatchId AND A.Id=@rScopeSourceId 
	  
  END
  
 else if @rSourcetypeId=95
  BEGIN
	 Select @lOrgId=OrgId From 
	 sSetup.tOrganizationMaster OM
	 INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgID=OM.Id
	 Where Em.Id=@rScopeSourceId
  END
  else
  BEGIN
	Select @lOrgGroupId=OM.OrgGRoupId from sSetup.tOrganizationMaster OM
	INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id
	Where Bm.Id=@rBatchId
  END
 
  if @rSourcetypeId=2003
  BEGIN
		
  SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete],
          ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,Remark
          
  from [sCommunication].[tPhotoCategoryMaster] PCM 
	INNER join sCommunication.tPhotoCategoryScope PCS  ON PCM.Id = PCS.PhotoCateGoryId AND
	(PCS.ScopeSourceId = Case  When PCM.ScopeSourceTypeId = 2005 Then
	(Select DivisionId From sStudent.tAcademic Where DivisionId = PCS.ScopeSourceId And Id = @rScopeSourceId)
	When PCM.ScopeSourceTypeId = 2016 Then
    (Select ClassId From sStudent.tAcademic Where DivisionId = PCS.ScopeSourceId And Id = @rScopeSourceId)
	when PCM.ScopeSourceTypeId = 2017 Then
	(select D.Id from sSetup.tDepartmentMaster D INNER JOIN sSetup.tClassMaster CA ON CA.DepartmentId=D.Id 
	INNER JOIN sStudent.tAcademic A ON A.ClassID=CA.Id Where A.Id =@rScopeSourceId)
	When PCM.ScopeSourceTypeId =2021 Then
	(Select OM.Id from sSetup.tOrganizationMaster OM INNER JOIN sStudent.tAcademic A ON A.OrgId =OM.Id Where A.Id=@rScopeSourceId)
	When PCM.ScopeSourceTypeId =2014 Then
	(Select Hm.Id from sHostel.tHostelMaster Hm INNER JOIN  sHostel.tRoomMaster RA ON RA.HostelId=HM.Id 
	INNER JOIN sHostel.tAssignRoom AR ON AR.RoomId=RA.Id
	INNER JOIN sStudent.tAcademic A ON A.StudentId=AR.SourceId 
	Where AR.OrgGroupBatchId = @lOrgGroupBatchID AND HM.OrgGroupId=@lOrgGroupId AND A.Id=@rScopeSourceId)
	When PCM.ScopeSourceTypeId =2029 Then
	(select HO.Id from sActivity.tHouseMaster HO
	INNER JOIN sStudent.tStudentOther SO ON SO.HouseId=HO.Id 
	INNER JOIN sStudent.tAcademic A ON A.StudentId=SO.StudentId
	Where HO.OrgId=@lOrgId AND A.Id=@rScopeSourceId)
	ENd)
	where PCM.Id=@rId
	 
      END
  else if @rSourcetypeId=95
  BEGIN 
		SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete],
          ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,Remark
        From [sCommunication].[tPhotoCategoryMaster] PCM 
        INNER join sCommunication.tPhotoCategoryScope PCS  ON PCM.Id = PCS.PhotoCateGoryId AND
        (PCS.ScopeSourceId = Case when PCM.ScopeSourceTypeId = 2017 Then
        (Select D.Id from sSetup.tDepartmentMaster D 
        INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.OrganizationDepartmentId=D.Id
        Where EJ.EmployeeId=@rScopeSourceId AND EJ.OrgId=@lOrgId)
        when PCM.ScopeSourceTypeId=2021 Then
        (Select OM.Id from sSetup.tOrganizationMaster OM 
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.OrgId=OM.Id
        Where EM.OrgId=@lOrgId and Em.Id=@rScopeSourceId)
        END)
        where PCM.Id = @rId
        
  END
  else
  BEGIN
  SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete],
          ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId,Remark
          
  FROM    [sCommunication].[tPhotoCategoryMaster]  PCM 
            
  WHERE   
      PCM.IsObsolete = 0
      AND ((PCM.Id = @rId) OR (@rId = 0))
      AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
      --AND PCM.ScopeSourceTypeId=@rScopeSourceId
      AND OrgGroupId=@lOrgGroupId
      ORDER BY PCM.CreatedDateTime DESC
   END   
      
END
GO
PRINT N'Altering [sCommunication].[pPhotoCategoryMasterAdd]...';


GO
ALTER PROCEDURE [sCommunication].[pPhotoCategoryMasterAdd]
	 
	 @rId int,
	 @rOrgGroupId int,
	 @rTitle nvarchar(100),
	 @rIsObsolete bit,
	 @rCreatedUserId bigint,
	 @rScopeSourceTypeId smallint=0,
	 @rRemark nvarchar(300)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
IF(@rId = 0)	
BEGIN
	IF EXISTS(Select 1 FROM sCommunication.tPhotoCategoryMaster Where Title = @rTitle AND IsObsolete = 0 AND OrgGroupId=@rOrgGroupId)
	BEGIN 
		SELECT -101 AS Result
		RETURN
	END 
END
ELSE 
BEGIN 
	IF EXISTS(Select 1 FROM sCommunication.tPhotoCategoryMaster Where Title = @rTitle AND OrgGroupId=@rOrgGroupId AND IsObsolete = 0 AND Id!=@rId)
	BEGIN 
		SELECT -101 AS Result
		RETURN
	END 
END
	
BEGIN TRY

BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN
  
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tPhotoCategoryMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO [sCommunication].[tPhotoCategoryMaster]
           (
            [Id]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId],
           ScopeSourceTypeId,
           Remark)
     VALUES
		(
			@lNextNumber,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
		    sCommon.fGetDate(),
			@rCreatedUserId,	 
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rScopeSourceTypeId,
			@rRemark
		)
		             
	END	 
	 ELSE
	  BEGIN
	 SET @lNextNumber = @rId
	    UPDATE [sCommunication].[tPhotoCategoryMaster]
	    SET
			Title = @rTitle,
			IsObsolete = @rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ScopeSourceTypeId=@rScopeSourceTypeId,
			Remark=@rRemark
	      
	      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'Altering [sCommunication].[pQueryListv2Get]...';


GO

ALTER PROCEDURE [sCommunication].[pQueryListv2Get]
	 
	 
	 @rOrgGroupBatchId int,
	 @rCreatedUserId bigint	
	  	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	 
	  
	SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			CONVERT(VARCHAR,QM.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,QM.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,QM.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
			--CONVERT(VARCHAR(25), QM.CreatedDateTime, 100) AS CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
  WHERE 
			QM.OrgGroupBatchId=@rOrgGroupBatchId
		AND QM.CreatedUserId=@rCreatedUserId
		
		order by QM.Id desc
        
END
GO
PRINT N'Altering [sCommunication].[pStudentResultGet]...';


GO
ALTER PROCEDURE [sCommunication].[pStudentResultGet]
	 
	 --@rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rDivisionId int,
	 @rBatchId int,
	 @rSyncedUploadResultId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF (@rSourceId!=0)
	BEGIN
		SELECT @rDivisionId=DivisionId FROM sStudent.tAcademic		
		 WHERE StudentId=@rSourceId AND BatchId = @rBatchId
	END
		SELECT 
			@rSourceId AS SourceId,
			UR.Id,
			UR.Title,
			UR.ExamDate,
			S.Code 
			 
		FROM 
			sCommunication.tUploadResult UR  
			INNER JOIN sStudent.vStudentAcademic S ON S.DivisionId = UR.DivisionId AND UR.BatchId = S.BatchId 
			AND S.StudentId = @rSourceId AND S.BatchId = @rBatchId
		WHERE 
			UR.DivisionId=@rDivisionId
			AND UR.BatchId=@rBatchId
			AND UR.IsObsolete=0
			AND ( UR.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
			and UR.ExamDate <= replace(convert(varchar, sCommon.fGetDate(), 111), '/','-') 
				order by UR.ExamDate,S.RollNo,S.Code DESC
END
GO
PRINT N'Altering [sCommunication].[pViewQueryRemarkv2Get]...';


GO
 

ALTER PROCEDURE [sCommunication].[pViewQueryRemarkv2Get]
	 
	 @rQueryId bigint,
	 @rUserId bigint
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	
	DECLARE	@lUserSourceTypeId smallint

	SELECT  @lUserSourceTypeId = SourceTypeId FROM sSecurity.tUser WHERE Id = @rUserId

		
	IF @lUserSourceTypeId = 2003
	 BEGIN
	  UPDATE sCommunication.tQuery SET IsUserView = 1	WHERE Id = @rQueryId
	 END
	ELSE IF @lUserSourceTypeId = 95
	 BEGIN
	  UPDATE sCommunication.tQuery SET IsAssigneeView = 1	WHERE Id = @rQueryId
	 END
	 
	SELECT 
			QC.Id,
			QC.QueryId,
			QC.Remark,
			U.DisplayTitle AS UserName,
			CONVERT(VARCHAR,QC.CreatedDateTime,103)+' '+ left(right('0'+LTRIM(RIGHT(CONVERT(varchar,QC.CreatedDateTime,100),8)),7),5)+ ' ' + right(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,QC.CreatedDateTime,100),8)),7),2) AS CreatedDateTime,
			--CONVERT(VARCHAR(25), QC.CreatedDateTime, 100) AS CreatedDateTime,
			QC.CreatedUserId AS CommentCreatedUserId,
			Q.CreatedUserId AS QueryCreatedUserId
	FROM 
			sCommunication.tQueryComment QC
		INNER JOIN sCommunication.tQuery Q ON Q.Id=QC.QueryId
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON Q.QueryCategoryId=QCM.Id AND QCM.IsObsolete=0
		INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId
		
	WHERE 
			QC.QueryId = @rQueryId
			--AND Q.CreatedUserId = @rUserId 
			order by QC.Id desc
END
GO
PRINT N'Altering [sCommunication].[pXMLCircularAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pXMLCircularAdd]
	
	@rXML nvarchar(max),
	@rOrgId smallint
	
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
	 
	SET @rXML=REPLACE(@rXML,'&','AND')
	DECLARE @lCount INT
	DECLARE @lInterrorCode INT,
			@intDoc INT
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXML
	
	DECLARE @lNextNumber BIGINT  
	DECLARE @lFromNextNumber BIGINT  
	EXECUTE sCommon.pTableRowIdGet @lOrgGroupId, 'sCommunication.tCircular', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	SET @lFromNextNumber=@lNextNumber-1
	INSERT INTO sCommunication.tCircular
		(
			Id,
			Title,
			Remark,
			StartDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			OrgGroupBatchId,
			AssigneeId,
			CircularTypeId
		)
	SELECT
			@lFromNextNumber + ROW_NUMBER() OVER(ORDER BY SourceId),
			Title,
			Remark,
			sCommon.fGetDate(), 
			CreatedUserId,
			sCommon.fGetDate(), 
			OrgGroupId,
			OrgGroupBatchId,
			AssigneeId,
			sCommon.fGetIntIdForOrg(2,@lOrgGroupId)
		
	FROM OPENXML (@intDoc, '/Table/Circular', 1)
	WITH
	(
		SourceId bigint 'SourceId',
		Title nvarchar(100) 'Title',
		Remark nvarchar(200) 'Remark',
		CreatedUserId bigint 'CreatedUserId',
		OrgGroupId smallint 'OrgGroupId',
		OrgGroupBatchId int 'OrgGroupBatchId',
		AssigneeId tinyint 'AssigneeId',
		SourceTypeId smallint 'SourceTypeId'
	)
	
	
	INSERT INTO sCommunication.tCircularScope
		(
			CircularId,
			SourceTypeId,
			SourceId
		)
	SELECT
			@lFromNextNumber + ROW_NUMBER() OVER(ORDER BY SourceId),
			SourceTypeId,
			SourceId
					
	FROM OPENXML (@intDoc, '/Table/Circular', 1)
	WITH
	(
		SourceId bigint 'SourceId',
		SourceTypeId smallint 'SourceTypeId'
	)
	
	
	SELECT @lCount = COUNT(1) FROM OPENXML (@intDoc, '/Table/Circular', 1)
				 WITH ( AcademicId bigint)
		SET @lNextNumber  = @lCount + @lFromNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @lOrgGroupId, @rTableTitle = 'sCommunication.tCircular', @rCurrentNumber = @lNextNumber 
		
		EXEC sp_xml_removedocument @intDoc
		
		SELECT 1 AS Result,@lFromNextNumber+1 AS FromId,@lNextNumber AS ToId
	
		--COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
END
GO
PRINT N'Altering [sErp].[pCustomerMasterAdd]...';


GO
ALTER PROCEDURE [sErp].[pCustomerMasterAdd]  	 	 
			@rId int, 
			@rOrgId smallint, 
			@rOrgGroupId smallint, 
			@rCRMLicenceId int, 
			@rTitle nvarchar(200), 
			@rShortTitle nvarchar(100), 
			@rStreetOne nvarchar(50), 
			@rStreetTwo nvarchar(50), 
			@rStreetThree nvarchar(50), 
			@rCityName nvarchar(100), 
			@rZipCode nvarchar(20),	
			@rHomePage nvarchar(100), 
			@rPhoneNo nvarchar(50), 
			@rMobileNo nvarchar(50), 
			@rContactPerson nvarchar(100),
			@rCreatedUserId bigint,       
			--@rUpdatedUserId bigint, 
			@rIsObsolete bit,
			@rCustomerStatusId tinyint,
			@rChannelId int, 
			@rInstallationTypeId tinyint,
			@rStateId int, 
			@rCountryId int, 
			@rDomain  nvarchar(200),
			@rDb nvarchar(100), 
			@rInstallationDate date,
			@rEmail nvarchar(100),
			@rAbsolutePath nvarchar(300)='',
			@rCampusType  int=0
    	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--BEGIN
--	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sErp.tCustomerMaster where OrgGroupId=@rOrgGroupId AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	
		If Exists(select Id from sErp.tCustomerMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where ShortTitle=@rShortTitle AND OrgId=@rOrgId)
			BEGIN
			select -102 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where CRMLicenceId=@rCRMLicenceId AND OrgId=@rOrgId)
			BEGIN
			select -101 as Result
			RETURN
		END 
			If Exists(select Id from sErp.tCustomerMaster where Domain=@rDomain AND OrgId=@rOrgId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
			BEGIN
			select -105 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where Db=@rDb AND OrgId=@rOrgId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
			BEGIN
			select -106 as Result
			RETURN
		END 
		
	END
	ELSE
	BEGIN
		If Exists(select Id from sErp.tCustomerMaster where OrgGroupId=@rOrgGroupId AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End
		If  Exists(select Id from sErp.tCustomerMaster where Title=@rTitle  AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
        If Exists(select Id from sErp.tCustomerMaster where ShortTitle=@rShortTitle AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			select -102 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where CRMLicenceId=@rCRMLicenceId AND OrgId=@rOrgId AND Id<>@rId)
			BEGIN
			select -101 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where Domain=@rDomain AND OrgId=@rOrgId AND Id<>@rId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
			BEGIN
			select -105 as Result
			RETURN
		END 
		If Exists(select Id from sErp.tCustomerMaster where Db=@rDb AND OrgId=@rOrgId AND Id<>@rId AND (@rInstallationTypeId=1 OR @rInstallationTypeId=2))
			BEGIN
			select -106 as Result
			RETURN
		END 
	END
	
	 --BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tCustomerMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tCustomerMaster
		(
			Id ,
			OrgId ,
			OrgGroupId ,
			CRMLicenceId ,
			Title ,
			ShortTitle ,
			StreetOne,
			StreetTwo ,
			StreetThree ,
			CityName ,
			ZipCode,
			HomePage ,
			PhoneNo ,
			MobileNo ,
			ContactPerson ,
			CreatedUserId , 
			CreatedDateTime, 
			UpdatedUserId, 
			UpdatedDateTime,
			IsObsolete,
			CustomerStatusId ,
			ChannelId ,
			InstallationTypeId,
			StateId ,
			CountryId ,
			Domain ,
			Db ,
			InstallationDate ,
			Email,
			AbsolutePath,
			CampusTypeId
        )
	VALUES
		(
			@lNextNumber , 
			@rOrgId,
			@rOrgGroupId , 
			@rCRMLicenceId , 
			@rTitle , 
			@rShortTitle, 
			@rStreetOne , 
			@rStreetTwo , 
			@rStreetThree , 
			@rCityName,
			@rZipCode,
			@rHomePage,
			@rPhoneNo,
			@rMobileNo,
			@rContactPerson,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rCustomerStatusId,
			@rChannelId,
			@rInstallationTypeId,
			@rStateId,
			@rCountryId,
			@rDomain,
			@rDb,
			@rInstallationDate,
			@rEmail,
			@rAbsolutePath,
			@rCampusType
			  			  			
		)
		INSERT INTO sErp.tCustomerActivationLog
			(
			OrgGroupId,
			LogDate,
			StatusRemark,
			CreatedUserId,
			CreatedDateTime,
			CustomerStatusId
			)
			VALUES
			(
			@rOrgGroupID , 
			sCommon.fGetDate(),
			'',
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rCustomerStatusId
			
			)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tCustomerMaster
	    SET		
			OrgGroupId= @rOrgGroupId,
			CRMLicenceId =@rCRMLicenceId,
			Title=@rTitle ,
			ShortTitle=@rShortTitle ,
			StreetOne=@rStreetOne,
			StreetTwo=@rStreetTwo ,
			StreetThree=@rStreetThree ,
			CityName= @rCityName,
			ZipCode=@rZipCode,
			HomePage= @rHomePage,
			PhoneNo=@rPhoneNo ,
			MobileNo= @rMobileNo,
			ContactPerson =@rContactPerson,

			UpdatedUserId=@rCreatedUserId, 
			UpdatedDateTime=sCommon.fGetDate(),
			IsObsolete=@rIsObsolete,
			CustomerStatusId= @rCustomerStatusId,
			ChannelId=@rChannelId ,
			InstallationTypeId=@rInstallationTypeId,
			StateId=@rStateId ,
			CountryId =@rCountryId,
			Domain =@rDomain,
			Db =@rDb,
			InstallationDate =@rInstallationDate,
			Email=@rEmail,
			AbsolutePath=@rAbsolutePath,
			CampusTypeId=@rCampusType
	      
	      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 [sErp].[pCustomerMasterGet]...';


GO
ALTER PROCEDURE [sErp].[pCustomerMasterGet]

	  @rId int,
	  @rOrgId smallint=0,
	  @rOrgGroupId smallint=0,
	  @rTitle nvarchar(100),
	  @rShortTitle nvarchar(100),
	  @rCRMLicenceId int=0, 
	  @rCustomerStatusId tinyint,
      @rChannelId int, 
      @rInstallationTypeId tinyint
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rShortTitle = sCommon.fSearchStringGet(@rShortTitle)
	END
	
	SELECT 
			CM.Id,
			CM.OrgId,
			CM.OrgGroupId,				
			CM.Title,
			CM.ShortTitle,
			CM.CRMLicenceId,
			CM.StreetOne,
			CM.StreetTwo,
			CM.StreetThree,
			ISNULL(CM.CountryId,0) AS CountryId,
			CM.StateId,
			CM.CityName,
			CM.ZipCode,
			CM.HomePage,
			CM.MobileNo,
			CM.PhoneNo,
			CM.ContactPerson,
			CM.CustomerStatusId AS CustomerStatusTypeId,
			CS.Title AS CustomerStatus,
			CM.ChannelId AS ChannelTypeId,
			CC.Title AS ChannelName,
			CM.InstallationTypeId AS InstallationId,
			IT.Title AS InstallationType,	
			CM.Domain,
			CM.Db,
			CM.InstallationDate,
			--CS.Id AS CustomerStatusTypeId,
			--CS.Title AS CustomerStatus,
			--CC.Id AS ChannelTypeId,
			--CC.Title AS ChannelName,
			--IT.Id AS InstallationId,
			--IT.Title AS InstallationType,	
			CM.IsObsolete ,
			Isnull(CM.Email,'') As Email,
			ISNULL(AbsolutePath,'') AS AbsolutePath,
			ISNULL(CampusTypeID,0) As CampusTypeID,
			ISNULL(CA.Title,'') As CampusType
	FROM 
			 sErp.tCustomerMaster CM
			 LEFT JOIN  sErp.tCustomerStatusMaster CS ON CM.CustomerStatusId=CS.Id
			 LEFT JOIN sErp.tChannelMaster CC ON CM.ChannelId=CC.Id
			 LEFT JOIN sErp.tInstallationTypeMaster IT ON CM.InstallationTypeId=IT.Id
			 LEFT JOIN sErp.tCampusTypeMaster CA ON CA.Id= CM.CampusTypeId
	WHERE 
	((CM.OrgId = @rOrgId)OR (@rOrgId=0))
		AND((CM.OrgGroupId = @rOrgGroupId)OR (@rOrgGroupId=0))
		AND	((CM.Id = @rId) OR (@rId = 0))
		AND ((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))		
		AND	((CM.CRMLicenceId = @rCRMLicenceId) OR (@rCRMLicenceId = 0))
		AND ((CM.ShortTitle like @rShortTitle) OR (ISNULL(@rShortTitle,'') = ''))
		AND ((CM.CustomerStatusId like @rCustomerStatusId) OR (@rCustomerStatusId=0))
		AND ((CM.ChannelId like @rChannelId) OR (@rChannelId=0))
		AND ((CM.InstallationTypeId like @rInstallationTypeId) OR (@rInstallationTypeId=0))
		ORDER BY CM.OrgGroupId DESC
END
GO
PRINT N'Altering [sErp].[pStudentStrengthGet]...';


GO

ALTER PROCEDURE [sErp].[pStudentStrengthGet]
	 	  @rOrgId smallint,
		@rCRMLicenceId int,
		@rOrgGroupId smallint,
		@rOrgGroupName nvarchar(200),
		@rCustomerStatusId tinyint,
		@rInstallationTypeId tinyint,
		@rChannelId int
		
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

		BEGIN
			SET @rOrgGroupName = sCommon.fSearchStringGet(@rOrgGroupName)
		END
		SELECT 
			CM.CRMLicenceId,
			CSM.Title AS CustomerStatus,
			CM.OrgGroupId,
			CM.Title AS OrgGroupName,
			CM.Db AS DatabaseName,
			CM.InstallationTypeId,
			IM.Title AS InstallationType,
			CM.ChannelId,
			HM.Title AS Channel,
			ISNULL(CA.Title,'') As CampusType
		FROM 
			sErp.tCustomerMaster CM
			INNER JOIN sErp.tCustomerStatusMaster CSM ON CSM.Id = CM.CustomerStatusId AND CM.InstallationTypeId NOT IN (3,5)
			INNER JOIN sErp.tInstallationTypeMaster IM ON IM.Id = CM.InstallationTypeId
			INNER JOIN sErp.tChannelMaster HM ON HM.Id = CM.ChannelId
			LEFT JOIN sErp.tCampusTypeMaster CA ON CA.Id=CM.CampusTypeId
		WHERE 
			(CM.CRMLicenceId = @rCRMLicenceId OR @rCRMLicenceId=0)
			AND (CM.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
			AND (CM.Title LIKE @rOrgGroupName OR ISNULL(@rOrgGroupName,'') = '')		
			AND (CM.CustomerStatusId = @rCustomerStatusId OR @rCustomerStatusId=0)
			AND (CM.InstallationTypeId = @rInstallationTypeId OR @rInstallationTypeId=0)
			AND (CM.ChannelId = @rChannelId OR @rChannelId=0)
			 AND((CM.OrgId = @rOrgId)OR (@rOrgId=0))
END
GO
PRINT N'Altering [sFee].[pChargeAccountMappingGet]...';


GO

ALTER PROCEDURE [sFee].[pChargeAccountMappingGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		 
           --@rChargeCategoryId int,
		   --@rBatchId int,
		   @rOrgGroupId int, 
		   @rChargeCategoryId int
		   
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 ISNULL(CM.Id,0)AS ChargeId,
			ISNULL(AM.ChargeId,0)AS AMChargeId,
			--ISNULL(FS.ClassId,0)AS ClassId,
			 
			ISNULL(CM.ChargeCategoryId,0) AS ChargeCategoryId,
			--ISNULL(CR.BatchId,0)AS BatchId,
			 
			ISNULL(AYM.AccountId,0) AS AccountId,
			ISNULL(AM.CreditLedgerId,0) AS CreditLedgerId,
			ISNULL(AM.DebitLedgerId,0) AS DebitLedgerId,
			ISNULL(AM.AccountingYearId,0) AS AccountingYearId,
			ISNULL(AM.PayTypeId,0) AS AMPayTypeId,
			ISNULL(PTM.Id,0) AS PayTypeId,
			ISNULL(PTM.Title,'') AS PayTypeName,
			ISNULL(RB.TItle,'') AS ReceiptBookTitle,
			ISNULL(RB.Id,0) AS ReceiptBookId ,
			CM.Title AS ChargeTitle
  FROM 
		  sFee.tChargeMaster CM
		  inner join  sFee.tChargeCategoryMaster CCM ON CCM.Id = CM.ChargeCategoryId AND CM.ChargeCategoryId=@rChargeCategoryId
		 --INNER JOIN sFee.tChargeReceiptDetail CE ON CE.ChargeId = CM.Id AND CM.ChargeCategoryId=@rChargeCategoryId
		 --INNER JOIN sFee.tChargeReceipt CR ON CR.Id=CE.ChargeReceiptId
		INNER JOIN  sFee.tChargeReceiptBookMaster RB ON CCM.ChargeReceiptBookId = RB.Id
		Cross JOIN sFinanceCommon.tPayTypeMaster PTM 
		LEFT JOIN sFee.tChargeAccountMapping AM ON AM.ChargeId=CM.Id AND AM.PayTypeId=PTM.Id	
		LEFT JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=CLM.AccountingYearId AND AYM.Id=DLM.AccountingYearId
WHERE 
		CM.OrgGroupId=@rOrgGroupId

ORDER BY  PTM.Id

END
GO
PRINT N'Altering [sFee].[pChargePostingAdd]...';


GO

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


GO

ALTER PROCEDURE [sFee].[pChargePostingGet]
				
		   --@rClassId int,
           @rReceiptBookId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptDate date,
		   @rReceiptDateTo date,
		   @rChequePosting nvarchar(50),
		   @rOrgGroupBatchID int=0
           
	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,
					'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,0 AS PayTypeId,
					ISNULL(AYM.ISLocked,0) AS ISLocked				
			FROM 
					sFee.tChargeAccountMapping AM
					INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
					INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
						AND R.PayTypeId = AM.PayTypeId
						AND R.ReceiptDate >= @rReceiptDate 
						AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
					--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.ChargeId 
					----AND (FS.ClassId=@rClassId) 
					--	AND (FS.ReceiptBookId=@rReceiptBookId) 
					--	AND (R.OrgGroupBatchId=@rBatchId)
					INNER JOIN sFee.tChargeMaster FM ON FM.Id=AM.ChargeId 
					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
					INNER JOIN sStudent.tAcademic A On A.Id=R.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId	AND BM.OrgGroupBatchId=@rOrgGroupBatchID		 
					GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked
	 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,0 AS PayTypeId,
			ISNULL(AYM.ISLocked,0) AS ISLocked				
		FROM 
			sFee.tChargeAccountMapping AM
			INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
			INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate 
				AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.ChargeId 
			--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
             INNER JOIN sStudent.tAcademic A On A.Id=R.SourceId
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  
		WHERE 
			AMast.OrgGroupId=@rOrgGroupId AND R.PayTypeId = 1 AND BM.OrgGroupBatchId=@rOrgGroupBatchID
			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.PayTypeId AS PayTypeId,
			ISNULL(AYM.ISLocked,0) AS ISLocked	
						
		FROM 
			sFee.tChargeAccountMapping AM
			INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
			INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate  
				AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			--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
            INNER JOIN sStudent.tAcademic A On A.Id=R.SourceId
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  
		WHERE  R.PayTypeId <> 1 AND	 AMast.OrgGroupId=@rOrgGroupId	  AND BM.OrgGroupBatchId=@rOrgGroupBatchID		
		GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ChequeNo,R.ChequeDate,R.BankName,R.PayTypeId 
		END
END
GO
PRINT N'Altering [sFee].[pDepositePostingAdd]...';


GO

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


GO

ALTER PROCEDURE [sFee].[pDepositPostingGet]
				
		   --@rClassId int,
           --@rReceiptBookId int,
           @rDepositHead int,
		   --@rBatchId int,
		   @rOrgGroupId int,
		   @rFromDate date='',
		   @rToDate date='',
		   @rDepositePosting nvarchar(50),
		   @rOrgGroupBatchID int=0
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

	IF @rDepositePosting = 'Single'
	BEGIN
			SELECT  
					 
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId AS CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					--AM.CreditLedgerId As DebitLedgerId,
					DLM.Title AS DebitLedgerName ,
					 
					--'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,
					AM.PayTypeId AS PayTypeId,
					ISNULL(AYM.ISLocked,0) AS ISLocked	,	
					SUM(DA.Amount) AS Amount,
					DA.DepositDate AS DepositDate,
					'' AS ChequeNo  	 ,
					AcademicId,
					SM.FirstName+' ' +MiddleName+' ' +LastName As Name
			FROM 
					sFee.tDepositeAccountMapping AM
					--INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
					--INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
					--	AND R.PayTypeId = AM.PayTypeId
					--	AND R.ReceiptDate >= @rReceiptDate 
					--	AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
					 
					INNER JOIN  sFee.tDepositHeadMaster HM ON HM.Id=AM.DepositeHeadId AND AM.DepositeHeadId=@rDepositHead	
					INNER JOIN sFee.tDepositAdd DA ON DA.DepositHeadId = HM.Id AND DA.PayTypeId = AM.PayTypeId	
						 
						AND DA.DepositDate >= @rFromDate 
						AND DA.DepositDate <= @rToDate  
					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
					INNER JOIN sStudent.tAcademic A On A.Id=DA.AcademicId
					INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId	   AND BM.OrgGroupBatchId=@rOrgGroupBatchID
					GROUP BY  AMast.Title,AYM.Title,AM.CreditLedgerId,CLM.Title, DLM.Title,AM.PayTypeId,AYM.ISLocked,DA.DepositDate,AcademicId,
					SM.FirstName,MiddleName,LastName
	 END
	 ELSE
		BEGIN		
		SELECT  
			 
			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,
			AM.PayTypeId AS PayTypeId,	
			ISNULL(AYM.ISLocked,0) AS ISLocked	,
			SUM(DA.Amount) Amount,
			DA.DepositDate,
			DA.ChequeNo ,
			AcademicId,
			SM.FirstName+' ' +MiddleName+' ' +LastName As Name
		FROM 
			sFee.tDepositeAccountMapping AM
			--INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.DepositeHeadId  
			--INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeReceiptId 
			--	AND R.PayTypeId = AM.PayTypeId
			--	AND R.ReceiptDate >= @rReceiptDate 
			--	AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			
			--INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.ChargeId 
			--AND (FS.ClassId=@rClassId) 
			--	AND (FS.ReceiptBookId=@rReceiptBookId) 
				--AND (R.OrgGroupBatchId=@rBatchId)
				
			INNER JOIN  sFee.tDepositHeadMaster HM ON HM.Id=AM.DepositeHeadId   
					AND AM.DepositeHeadId=@rDepositHead		
			INNER JOIN sFee.tDepositAdd DA ON DA.DepositHeadId = HM.Id AND DA.PayTypeId = AM.PayTypeId
					AND DA.DepositDate >=@rFromDate
					AND DA.DepositDate <=@rToDate
            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
            INNER JOIN sStudent.tAcademic A On A.Id=DA.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
		WHERE 
			AMast.OrgGroupId=@rOrgGroupId AND DA.PayTypeId=1  AND BM.OrgGroupBatchId=@rOrgGroupBatchID
			 GROUP BY AMast.Title,AYM.Title,AM.CreditLedgerId,CLM.Title,AM.DebitLedgerId,DLM.Title,AM.PayTypeId,AYM.ISLocked,DA.DepositDate,DA.ChequeNo,AcademicId,
					SM.FirstName,MiddleName,LastName
			
		UNION ALL
		
		SELECT  
			 
			AMast.Title AS AccountName,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			 AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName ,
			 
			--R.ChequeNo,R.ChequeDate,R.BankName,
			AM.PayTypeId AS PayTypeId,
			ISNULL(AYM.ISLocked,0) AS ISLocked	,
			
			 	SUM(DA.Amount) Amount,
			DA.DepositDate,
			DA.ChequeNo,
			AcademicId,
			SM.FirstName+' ' +MiddleName+' ' +LastName As Name
						
		FROM 
			sFee.tDepositeAccountMapping AM
			--INNER JOIN sFee.tChargeReceiptDetail RD ON RD.ChargeId = AM.ChargeId  
			--INNER JOIN sFee.tChargeReceipt R ON R.Id = RD.ChargeId 
			--	AND R.PayTypeId = AM.PayTypeId
			--	AND R.ReceiptDate >= @rReceiptDate  
			--	AND R.ReceiptDate <= @rReceiptDateTo AND R.IsObsolete = 0
			 INNER JOIN  sFee.tDepositHeadMaster HM ON HM.Id=AM.DepositeHeadId AND AM.DepositeHeadId=@rDepositHead	
			 INNER JOIN sFee.tDepositAdd DA ON DA.DepositHeadId = HM.Id AND DA.PayTypeId = AM.PayTypeId	
					AND DA.DepositDate >= @rFromDate
					AND DA.DepositDate <= @rToDate
            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
            INNER JOIN sStudent.tAcademic A On A.Id=DA.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  
		WHERE    AMast.OrgGroupId=@rOrgGroupId AND DA.PayTypeId=2   AND BM.OrgGroupBatchId=@rOrgGroupBatchID
		 GROUP BY AMast.Title,AYM.Title,AM.CreditLedgerId,CLM.Title, AM.DebitLedgerId,AM.PayTypeId,AYM.ISLocked,DA.DepositDate,DA.ChequeNo,AcademicId,
					SM.FirstName,MiddleName,LastName,DLM.Title 
			
		END
END
GO
PRINT N'Altering [sFee].[pFeecancelReceiptListviewGet]...';


GO

ALTER PROCEDURE [sFee].[pFeecancelReceiptListviewGet]
		
		@rOrgId smallint,
		@rBatchId int,
		@rAcademicId bigint
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
			
BEGIN 	
DECLARE @lcancellist nvarchar(max)	=''
	SELECT @lcancellist=@lcancellist+'<tr>
	<td align="left" scope="col">'+ convert(varchar,Isnull(R.ReceiptNumber,0)) +'</td>
	<td align="left" scope="col">'+convert(varchar,ISNULL(R.ReceiptDate,'01/01/0001'),103)+'</td>
    <td align="left" scope="col">'+Convert(varchar,ISNULL(R.ReceiptAmount,0))+'</td>
    <td align="left" scope="col">'+ISNULL(PTM.Title,'')+'</td>
    <td align="left" scope="col">'+ISNULL(R.ChequeNo,'')+'</td>
    <td align="left" scope="col">'+ISNULL(R.BankName,'')+'</td>
    <td align="left" scope="col">'+ISNULL(RBM.Title,'')+'</td>
    <td align="left" scope="col">'+convert(varchar,ISNULL(FI.InvoiceNumber,0))+'</td>
     <td align="left" scope="col">'+convert(varchar,ISNULL(R.Remark,''))+'</td>
    <tr>'
  FROM 
		sFee.tReceipt R
		INNER JOIN sStudent.vStudentAcademic A
			ON A.AcademicId=R.SourceId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
		ON PTM.Id=R.PayTypeId
		INNER JOIN sFee.tReceiptBookMaster RBM
			ON RBM.Id=R.ReceiptBookId
		LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId
WHERE 
	    R.SourceTypeId=2001 AND R.IsObsolete=1
		AND A.OrgId=@rOrgId AND R.BatchId=@rBatchId
		AND A.AcademicId=@rAcademicId
	   ORDER BY R.ReceiptNumber DESC
	   
		SELECT ISNULL(@lcancellist,'') AS cancellist
END

--
--    
--    
--    
--    
--    
--    
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeCustomSearchGet]
(
	@rOrgGroupBatchId int,
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'ReceiptNumber',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rReceiptBookId nvarchar(max) = '',
	@rFromReceiptDate Date = '0001-01-01',
	@rToReceiptDate Date = '9999-12-31',
	@rFromReceiptNo int,
	@rToReceiptNo int,
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownReceiptBookId int,
	@rDepartmentId int=0
	
 )
AS
SET NOCOUNT ON

BEGIN
		DECLARE @Sql nvarchar(MAX)
		
		IF(@rFromReceiptDate IS NULL)
			SET @rFromReceiptDate='0001-01-01'
		IF(@rToReceiptDate IS NULL)
			SET @rToReceiptDate='9999-12-31'
		
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		
		SELECT 
				      FCS.AcademicId, FCS.ClassId, FCS.DivisionId, FCS.RollNo, FCS.OrgGroupBatchId, FCS.OrgId, FCS.BatchId, FCS.OrgGroupBatch , 
				      FCS.Organization, FCS.Batch, FCS.StudentId, FCS.Code, FCS.Number, FCS.FirstName, FCS.LastName, FCS.Name, FCS.StatusId, FCS.ClassName,
				       FCS.DivisionName, FCS.StatusName, FCS.ReceiptId , FCS.ReceiptNumber, FCS.ReceiptDate, FCS.ReceiptAmount, FCS.ChequeNo, FCS.BankName,
					FCS.Remark, FCS.IsObsolete, FCS.FeeReceiptBookId , 
                      FCS.ReceiptBookCode , FCS.ReceiptBookName , FCS.Address1, FCS.Address2, FCS.BankAccountNumber, FCS.PayTypeId , 
                      FCS.PayType , FCS.CreatedUserId , FCS.CreatedUserName

		into sFee.tTempFee1
		FROM sFee.vFeeCustomSearch FCS
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = FCS.ClassId  
		WHERE 
				(FCS.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((FCS.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((FCS.BatchId = @rBatchId) OR (@rBatchId=0))
			AND ((FCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((FCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((FCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((FCS.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
			AND ((FCS.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
			AND ((ISNULL(FCS.ReceiptDate,'0001-01-01') >= @rFromReceiptDate) OR (ISNULL(@rFromReceiptDate,'') = ''))
			AND ((ISNULL(FCS.ReceiptDate,'9999-12-31') <= @rToReceiptDate) OR (ISNULL(@rToReceiptDate,'') = ''))
			--AND ((ISNULL(FCS.EndDate,'9999-12-31') <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    
		    AND (FCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (FCS.FeeReceiptBookId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookId,','))OR @rReceiptBookId='')	
	        AND ((FCS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	        AND (FCS.IsObsolete=@rIsObsolete)
	        AND ((FCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((FCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((FCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND ((FCS.FeeReceiptBookId = @rDropDownReceiptBookId) OR (@rDropDownReceiptBookId=0))
			AND ((Cm.DepartmentId =@rDepartmentId ) OR (@rDepartmentId=0))
	
	if(@rOrderBy='ID No')
	BEGIN
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code') 
	END
	
	if(@rOrderBy='GR No')
	BEGIN
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code') 
	END
		SET @sql=
		'SELECT 
				Code AS Code,
				Name,
				ReceiptNumber,
				ReceiptDate,
				ReceiptAmount,
				PayType,
				ChequeNo,
				BankName,
				ReceiptBookName,
				Remark,
				OrgId,
				BatchId
		FROM sFee.tTempFee1 ORDER BY '+@rOrderBy
		exec(@Sql)
		
		DROP Table sFee.tTempFee1
END
GO
PRINT N'Altering [sFee].[pFeeFollowupGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeFollowupGet]
	
	@rId bigint = 0,
	@rFromDate date='',
	@rToDate date='',
	@rOrgId Smallint=0,
	@rOrgGroupBatchId int = 0,
	@rReceiptBookId int=0,
	@rCode nvarchar(20)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
		FF.Id,
		vSA.Code,
		FF.ReceiptBookId,
		ISNULL(FF.FollowupDate,'') AS  FollowupDate,
		FF.FollowupRemark,
		FF.HandledBy,
		vSA.Name,
		ISNULL(FF.FollowupDate,'0001/01/01') AS NextFollowupDate,
		vSA.OrgId,
		OM.DisplayTitle AS OrgName
	FROM 
		sFee.tFeeFollowup FF
		INNER JOIN sStudent.vStudentAllDetail vSA ON  vSA.AcademicId = FF.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId
	WHERE  
		(FF.Id = @rId OR @rId = 0)
		AND (FF.FollowupDate>= @rFromDate OR ISNULL(@rFromDate,'')='')
		AND (FF.FollowupDate<= @rToDate OR ISNULL(@rToDate,'')='')
		AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (FF.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
		AND (vSA.Code=@rCode OR ISNULL(@rCode,'')='')
	ORDER BY FF.FollowupDate  
END
GO
PRINT N'Altering [sFee].[pFeeGenerateReport]...';


GO
ALTER PROCEDURE [sFee].[pFeeGenerateReport]
	
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'ReceiptNumber',
	@rOrgGroupBatchId int,
	@rOrgId smallint,
	@rBatchId int,
	@rCurrentOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rReceiptBookId nvarchar(max) = '',
	@rFromReceiptDate Date = '0001-01-01',
	@rToReceiptDate Date = '9999-12-31',
	@rFromReceiptNo int,
	@rToReceiptNo int,
	@rIsObsolete bit,
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rInsertUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownReceiptBookId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rFromReceiptDate IS NULL)
			SET @rFromReceiptDate='0001-01-01'
	IF(@rToReceiptDate IS NULL)
		SET @rToReceiptDate='9999-12-31'
	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rCurrentOrgId, 'sFee.tFeeCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sFee.tFeeCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgGroupBatchId,
			OrgId,
			BatchId,
			Code,
			FirstName,	
			LastName,
			DivisionId,
			ReceiptBookId,
			FromReceiptDate,
			ToReceiptDate,
			FromReceiptNo,
			ToReceiptNo,
			IsObsolete,
			IsCommon,
			UserId,
			CreatedUserId,
			CreatedDateTime
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgGroupBatchId,
			@rOrgId,
			@rBatchId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rDivisionId,
			@rReceiptBookId,
			@rFromReceiptDate,
			@rToReceiptDate,
			@rFromReceiptNo,
			@rToReceiptNo,
			@rIsObsolete,
			@rIsCommon,
			@rCreatedUserId,
			@rInsertUserId,
			sCommon.fGetDate()
		)
		--SELECT @lNextNumber AS Result
	END
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgGroupBatchId=OrgGroupBatchId,
				@rOrgId=OrgId,
				@rBatchId=BatchId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rDivisionId=DivisionId,
				@rReceiptBookId=ReceiptBookId,
				@rFromReceiptDate=FromReceiptDate,
				@rToReceiptDate=ToReceiptDate,
				@rFromReceiptNo=FromReceiptNo,
				@rToReceiptNo=ToReceiptNo,
				@rIsObsolete=IsObsolete,
				@rCreatedUserId=UserId
		FROM
			sFee.tFeeCustomSearch
		WHERE
			Id=@rId
	END
	if(@rColumnName='ID No')
	BEGIN
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
	END
	if(@rOrderBy='ID No')
	BEGIN
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	END
	
	if(@rColumnName='GR No')
	BEGIN
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
	END
	if(@rOrderBy='GR No')
	BEGIN
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	END
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	
		SELECT 
				*
		into sFee.tTempFee
		FROM sFee.vFeeCustomSearch FCS
		WHERE 
				(FCS.OrgGroupBatchId = @rOrgGroupBatchId)
			AND	((FCS.OrgId = @rOrgId) OR (@rOrgId=0))
			AND ((FCS.BatchId = @rBatchId) OR (@rBatchId=0))
			AND ((FCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((FCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((FCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((FCS.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo=0))
			AND ((FCS.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
			AND ((ISNULL(FCS.ReceiptDate,'0001-01-01') >= @rFromReceiptDate) OR (ISNULL(@rFromReceiptDate,'') = ''))
			AND ((ISNULL(FCS.ReceiptDate,'9999-12-31') <= @rToReceiptDate) OR (ISNULL(@rToReceiptDate,'') = ''))
			--AND ((ISNULL(FCS.EndDate,'9999-12-31') <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			--AND (FCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    
		    AND (FCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (FCS.FeeReceiptBookId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookId,','))OR @rReceiptBookId='')	
	        AND ((FCS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	        AND (FCS.IsObsolete=@rIsObsolete)
	        AND ((FCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((FCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((FCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND ((FCS.FeeReceiptBookId = @rDropDownReceiptBookId) OR (@rDropDownReceiptBookId=0))
	     
	    if(@rColumnName='ID No')
	    BEGIN
			SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [ID No]')
	    END
	    if(@rColumnName='GR No')
	    BEGIN
			SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [GR No]')
		END
		--SET @rOrderBy=Replace(@rOrderBy,',Code',',Code AS [ID No]')    
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sFee.tTempFee ORDER BY '+@rOrderBy
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		exec(@Sql)
		
		DROP Table sFee.tTempFee
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		--SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeeReceiptListGet]...';


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


GO

ALTER PROCEDURE [sFee].[pReceiptBookMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rFullTitle nvarchar(200)
           ,@rAddress1 nvarchar(200)
           ,@rAddress2 nvarchar(200)
           ,@rBankAccountNumber nvarchar(50)
           ,@rIsObsolete bit
           ,@rRemark1 nvarchar(500)
           ,@rRemark2 nvarchar(500)
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
           ,@rIsOnPrePrinted bit
           ,@rReportId int
           ,@rIsSupressLogo bit
           ,@rOrderIndex int
           ,@rIsDisplaySchoolName bit
           ,@rIsMonthDetailOnly bit
           ,@rIsServiceTaxApplicable bit
           ,@rServiceTaxPercentage decimal(6,2)
           ,@rBankName nvarchar(150)=''
           ,@rIsFeeInvoiceHeadwise bit = 0
           ,@rGroupTitle nvarchar(200)=''
           ,@rIsSuppressFeeDetail bit=0
		   ,@rReceiptLogo varbinary(max)=NULL
		   ,@rHeaderDisplayId tinyint
		   ,@rReceiptBookHeader varbinary(max)=NULL
		   ,@rFeeInvoiceHeaderDisplayId tinyint
		   ,@rFeeInvoiceHeader varbinary(max)=NULL
		   ,@rCGSTPercentage decimal(5,2) = 0 
		   ,@rSGSTPercentage decimal(5,2) = 0
		   
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
If Exists(select top(1)* from sFee.tReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId) 
BEGIN
	If NOT Exists(select top(1)* from sFee.tReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id=@rId)
	BEGIN
		select -101 as Result
	END
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete      
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo   
             ,OrderIndex=@rOrderIndex
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,IsMonthDetailOnly=@rIsMonthDetailOnly
             ,IsServiceTaxApplicable=@rIsServiceTaxApplicable
			 ,ServiceTaxPercentage=@rServiceTaxPercentage
			 ,BankName=@rBankName
			 ,IsFeeInvoiceHeadwise=@rIsFeeInvoiceHeadwise
			 ,GroupTitle =@rGroupTitle
			 ,IsSuppressFeeDetail=@rIsSuppressFeeDetail
			 ,ReceiptLogo = @rReceiptLogo
			 ,ReceiptBookHeader=@rReceiptBookHeader
			 ,HeaderDisplayId=@rHeaderDisplayId
			 ,FeeInvoiceHeader=@rFeeInvoiceHeader
			 ,FeeInvoiceHeaderDisplayId=@rFeeInvoiceHeaderDisplayId
			 ,CGSTPercentage=@rCGSTPercentage
			 ,SGSTPercentage=@rSGSTPercentage
			 
             
	      WHERE Id = @rId 	 
	      SELECT @lNextNumber AS Result
	 END  
END
ELSE
BEGIN
IF(@rId = 0)	
BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tReceiptBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sFee].[tReceiptBookMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[FullTitle]
			   ,[Address1] 
			   ,[Address2] 
			   ,[BankAccountNumber] 
			   ,[IsObsolete]
			   ,[Remark1] 
			   ,[Remark2] 
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[OrgGroupId]
			   ,IsOnPrePrinted
			   ,ReportId
			   ,IsSupressLogo
			   ,OrderIndex
			   ,IsDisplaySchoolName
			   ,IsMonthDetailOnly
			   ,IsServiceTaxApplicable
			   ,ServiceTaxPercentage
			   ,BankName
			   ,IsFeeInvoiceHeadwise
			   ,GroupTitle
			   ,IsSuppressFeeDetail
			   ,ReceiptLogo
			   ,HeaderDisplayId
			   ,ReceiptBookHeader
			   ,FeeInvoiceHeader
			   ,FeeInvoiceHeaderDisplayId
			   ,CGSTPercentage
			   ,SGSTPercentage
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFullTitle
			   ,@rAddress1
			   ,@rAddress2
			   ,@rBankAccountNumber
			   ,@rIsObsolete
			   ,@rRemark1
			   ,@rRemark2
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rIsOnPrePrinted
			   ,@rReportId
			   ,@rIsSupressLogo
			   ,@rOrderIndex
			   ,@rIsDisplaySchoolName
			   ,@rIsMonthDetailOnly
			   ,@rIsServiceTaxApplicable
			   ,@rServiceTaxPercentage
			   ,@rBankName
			   ,@rIsFeeInvoiceHeadwise
			   ,@rGroupTitle
			   ,@rIsSuppressFeeDetail
			   ,@rReceiptLogo
			   ,@rHeaderDisplayId
			   ,@rReceiptBookHeader
			   ,@rFeeInvoiceHeader
			   ,@rFeeInvoiceHeaderDisplayId
			   ,@rCGSTPercentage
			   ,@rSGSTPercentage
			   
			   )
			   
 
INSERT INTO sSecurity.tUserAccess
           (
            SourceTypeId
            ,SourceId
           ,[UserId]
           
           )
SELECT 
		   2013
		   ,@lNextNumber
		  ,@rCreatedUserId
			   
			   
		    SELECT @lNextNumber AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete          
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2                     
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()   
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo
             ,OrderIndex=@rOrderIndex              
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,IsMonthDetailOnly=@rIsMonthDetailOnly
             ,IsServiceTaxApplicable=@rIsServiceTaxApplicable
			 ,ServiceTaxPercentage=@rServiceTaxPercentage
			 ,BankName=@rBankName
			 ,IsFeeInvoiceHeadwise=@rIsFeeInvoiceHeadwise
			 ,GroupTitle =@rGroupTitle
			 ,IsSuppressFeeDetail=@rIsSuppressFeeDetail
			 ,ReceiptLogo = @rReceiptLogo
			 ,HeaderDisplayId=@rHeaderDisplayId
			 ,ReceiptBookHeader=@rReceiptBookHeader
              ,FeeInvoiceHeaderDisplayId=@rFeeInvoiceHeaderDisplayId
			 ,FeeInvoiceHeader=@rFeeInvoiceHeader
			 ,CGSTPercentage=@rCGSTPercentage
			 ,SGSTPercentage=@rSGSTPercentage
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	 END  
		
	
	END
	If Not Exists(Select 1 from sSystem.tPortalSync where OrgGRoupId=@rOrgGroupId)
	BEGIN
	Insert into sSystem.tPortalSync
	(
		OrgGroupId,
		FeeChange
	)
	Values
	(
		@rOrgGroupId,
		1
	)
	 
	END
	
	Else
	BEGIN
		Update sSystem.tPortalSync 
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
	END
	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pReceiptBookMasterGet]...';


GO

ALTER PROCEDURE [sFee].[pReceiptBookMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId int,
           @rIsWildCardSearch bit
 
AS
SET NOCOUNT ON

		IF @rIsWildCardSearch = 1
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END

BEGIN
SELECT RBM.Id 
	  ,RBM.Code
      ,RBM.Title
      ,RBM.FullTitle
      ,RBM.Address1
      ,RBM.Address2
      ,RBM.BankAccountNumber
      ,RBM.IsObsolete
      ,RBM.Remark1
      ,RBM.Remark2
      ,ISNULL(RBM.IsOnPrePrinted ,0) AS IsOnPrePrinted
      ,ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo
      ,RBM.ReportId  
       --,RBM.OrderIndex  
      ,ISNULL(RBM.OrderIndex,0) AS OrderIndex
      ,ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName
      ,ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly
      ,ISNULL(RBM.IsServiceTaxApplicable,0) AS IsServiceTaxApplicable
	  ,ISNULL(RBM.ServiceTaxPercentage,0) AS ServiceTaxPercentage
	  ,ISNULL(RBM.BankName,'') AS BankName
	  ,ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise
	  ,ISNULL(RBM.GroupTitle,'') AS GroupTitle
	  ,ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail
	  ,RBM.ReceiptLogo
	  ,ISNULL(RBM.HeaderDisplayId,1) AS HeaderDisplayId
	  ,RBM.ReceiptBookHeader
	  ,ISNULL(RBM.FeeInvoiceHeaderDisplayId,1) AS FeeInvoiceHeaderDisplayId
	  ,RBM.FeeInvoiceHeader
	  ,ISNULL(RBM.CGSTPercentage,0) AS CGSTPercentage
	  ,ISNULL(RBM.SGSTPercentage,0) AS SGSTPercentage
      
     
  FROM [sFee].[tReceiptBookMaster] RBM  
        
  WHERE 
		 RBM.Id = @rId OR @rId = 0
	AND ((RBM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((RBM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND  RBM.OrgGroupId = @rOrgGroupId 
	--AND  QM.IsObsolete = 0
         
END
GO
PRINT N'Altering [sFee].[pRptChargeReceiptListGet]...';


GO
ALTER PROCEDURE [sFee].[pRptChargeReceiptListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSourceTypeId smallint,
	 @rSourceCode nvarchar(20),
	 @rGuestName nvarchar(200)='',
	 @rFromDate date,
	 @rToDate date,
	 @rFromNo int,
	 @rToNo int,
	 @rReceiptBookId int,
	 @rChargeCategoryId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rOrgGroupBatchId int,
	 @rDepartmentId int = 0,
	 @rStudentCode nvarchar(20) = '',
	 @rIsDetail bit=0,
	 @rCreatedUserName nvarchar(100)='',
	 @rPayTypeId int=0,
	 @rOrgGroupId int=0,
	 @rStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 		

Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0
Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			CR.ReceiptNumber,
			CR.ReceiptDate,
		    -- For Type 
			(CASE WHEN CR.SourceTypeId = 95 THEN	'Employee'
			 WHEN CR.SourceTypeId = 2001 THEN	'Student'
			 ELSE 'Other' END) AS TypeName,
			-- For Name
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Name 
			WHEN CR.SourceTypeId = 3 THEN CR.GuestName
			WHEN CR.SourceTypeId = 95 THEN EM.EmployeeName
			END ) AS Name, 
			-- For Code
			(CASE WHEN CR.SourceTypeId = 2001 THEN SA.Code 
			WHEN CR.SourceTypeId = 95 THEN EM.Code
			END ) AS Code,
			-- For Class Department
			(CASE WHEN CR.SourceTypeId = 95 THEN EM.DepartmentName
			WHEN CR.SourceTypeId = 2001 THEN (SA.ClassName + ' - '+ SA.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
			SA.RollNo,
			PTM.Title AS PayType,
			ISNULL(CR.ChequeNo,'') AS ChequeNo,
			ISNULL(CR.BankName,'') AS BankName,
			CR.Remark,
			CR.CreatedUserId,
			U.DisplayTitle AS UserName,
			CR.SourceTypeId,
			ISNULL(RBM.Id,0) AS ChargeReceiptBookId,
			ISNULL(RBM.Title,'') AS ChargeReceiptBookName,
			ISNULL(OM.Title,'') AS OrganizationName,
			CR.ReceiptAmount,
			@lIDConfigValue AS ItemValue 
			
	FROM 
			sFee.tChargeReceipt CR
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=CR.PayTypeId
			INNER JOIN sFee.tChargeReceiptBookMaster RBM 
				ON RBM.Id=CR.ChargeReceiptBookId
			INNER JOIN sSecurity.tUser U
				ON U.Id=CR.CreatedUserId
			LEFT JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId = 2001	
			LEFT JOIN sHrm.vExtEmployeeMaster EM
				ON EM.Id=CR.SourceId AND CR.SourceTypeId = 95	
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=SA.OrgId				
	WHERE 
			((CR.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
			--AND (((@rSourceTypeId =2001 OR(@rSourceTypeId=0)) AND SA.Name like @rGuestName) 
			--	OR (ISNULL(@rGuestName,'')='') OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND EM.EmployeeName LIKE @rGuestName) OR (ISNULL(@rGuestName,'')='') 
			--	OR ((@rSourceTypeId =3 OR (@rSourceTypeId=0)) AND CR.GuestName LIKE @rGuestName) OR (ISNULL(@rGuestName,'')=''))
            AND (((@rSourceTypeId =2001 OR(@rSourceTypeId=0)) AND SA.Code LIKE @rStudentCode) OR (ISNULL(@rStudentCode,'')='') 
				OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND EM.Code LIKE @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,'')=''))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			And (CR.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CR.PayTypeId = @rPaytypeId OR @rPaytypeId=0)
			AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
			ORDER BY CR.ReceiptNumber
END
GO
PRINT N'Altering [sFee].[pRptFeePendingDetailListOtherGet]...';


GO

 
ALTER PROCEDURE [sFee].[pRptFeePendingDetailListOtherGet]
		@rReportId int=0,
		@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,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rIsReceiptBookGroup bit=0,
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeId,
		FS.FeeName,
		FS.FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	FS.ReceiptBookId
			 END) AS ReceiptBookId,	
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.Title,'')
			 END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.OrderIndex,0)
			 END) AS ReceiptOrderIndex,	 
		--FS.ReceiptBookId,
		--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND SM.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SM.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    BM.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=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 ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				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 SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (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 ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				
		) 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.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				--AND (R.ReceiptDate <= @rUptoDate)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
				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='')
				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
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId	
	 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	
			 SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND (
				 (@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)))
			     ) 	
			Order by SA.RollNo
 
END
GO
PRINT N'Altering [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=''

	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 = @lOrgGroup_Id
	
	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

	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.Title AS PayType,
			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 @lAmountInWord 
				  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,
			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)	
				
			WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  THEN				
				 [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Month name in detail
	
			ELSE '' END) AS MonthDetail,    
			
			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 
	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 sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=FR.PayTypeId
			--LEFT JOIN sFee.tFeeAllocation FA
			--	ON FA.FeeSetupId=FS.Id
			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
	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,'') = ''))
	  
ORDER BY FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC

END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptListGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptListGet]
		
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rFromDate date='',
		@rToDate date='',
		@rFromReceiptNo int=0,
		@rToReceiptNo int=0,
		@rBatchId int,
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)=0,
		@rBuilder2 nvarchar(max)=0,
		@rIsDetail bit=0,
		@rIsCancel bit=0,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int=0,
		@rPaytypeId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20),
	    @rIsFilter bit=0,
	    @rIsHeader bit=0,
	    @rCreatedUserName nvarchar(100)='',
	    @rFeeHeadId nvarchar(max) = '',
	    @rIsDisplayOrgGroup bit=0,
	    @rIsDiscount bit = 0,
	    @rFeeId nvarchar(max) = '',
	    @rFilterId int=0,
	    @rCustomGroupId smallint = 0
	    
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsCancel AS IsCancel,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		R.Id AS ReceiptId,
		R.ReceiptNumber,
		SA.ClassId,
		--SA.ClassName,
		SA.DivisionId,
		--SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.Code,
		SA.Name,
		ISNULL(PTM.Title,'') AS PayType,
		ISNULL(R.ChequeNo,'') AS ChequeNo,
		ISNULL(R.BankName,'') AS BankName,
		R.ReceiptAmount,
		R.ReceiptDate,
		R.CreatedUserId,
		ISNULL(U.LoginTitle,'') AS UserName,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.BankName,'') AS ReceiptBookBank,
		ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
		ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
		ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)
		 ELSE '' END),'') AS FeeDetail,
		 R.Remark,
		 R.DiscountAmount,
		 ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,
		 SA.OrgId,
		 SA.OrganizationName,
		 ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,
		 ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,
		 ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,
		 ISNULL(R.CGSTAmount,0) AS CGSTAmount,
		 ISNULL(R.SGSTAmount,0) AS SGSTAmount,
		 @rCustomGroupId AS CustomGroupId
  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 SA
			ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
			ON PTM.Id=R.PayTypeId
		LEFT JOIN sSecurity.tUser U
			ON U.Id=R.CreatedUserId
		INNER JOIN sFee.tReceiptBookMaster RBM 
			ON RBM.Id=R.ReceiptBookId
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId 
    AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
    AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)
WHERE 
	R.SourceTypeId = 2001
	AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
	AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
	AND	((SA.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	AND (R.IsObsolete = @rIsCancel) 
	AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)
	AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
	AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))
	--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	 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)))
   )
	ORDER BY R.ReceiptNumber
--	UNION ALL
	
--	SELECT 
--		R.Id AS ReceiptId,
--		0 AS ClassId,
--		--SA.ClassName,
--		0 AS DivisionId,
--		--SA.DivisionName,
--		EM.DepartmentId,
--		EM.DepartmentName AS ClassDept,
--		0 AS RollNo,
--		EM.Code,
--		EM.EmployeeName,
--		PTM.Title AS PayType,
--		R.ReceiptAmount
			
--  FROM 
--			sFee.tReceipt R
--		INNER JOIN sCommon.tSourceTypeMaster STM
--			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95
--		INNER JOIN sHrm.vExtEmployeeMaster EM
--			ON EM.EmployeeId=R.SourceId
--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
--			ON PTM.Id=R.PayTypeId
			
--WHERE 
--		((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
--	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
--	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
--	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--	AND (R.BatchId = @rBatchId)
END
GO
PRINT N'Altering [sFee].[pRptFeeSummaryGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeSummaryGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@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
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		@rFeeGroupId As FeeGroup
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		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='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
					sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (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='')
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM
			ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )	
			Order by SA.RollNo
				
				
--	UNION ALL
	
--	SELECT 
--		R.Id AS ReceiptId,
--		0 AS ClassId,
--		--SA.ClassName,
--		0 AS DivisionId,
--		--SA.DivisionName,
--		EM.DepartmentId,
--		EM.DepartmentName AS ClassDept,
--		0 AS RollNo,
--		EM.Code,
--		EM.EmployeeName,
--		PTM.Title AS PayType,
--		R.ReceiptAmount
			
--  FROM 
--			sFee.tReceipt R
--		INNER JOIN sCommon.tSourceTypeMaster STM
--			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95
--		INNER JOIN sHrm.vExtEmployeeMaster EM
--			ON EM.EmployeeId=R.SourceId
--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
--			ON PTM.Id=R.PayTypeId
			
--WHERE 
--		((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
--	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
--	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
--	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--	AND (R.BatchId = @rBatchId)
END
GO
PRINT N'Altering [sHostel].[pRptHostelDepositRefundGet]...';


GO

ALTER PROCEDURE [sHostel].[pRptHostelDepositRefundGet]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int=0,
           @rFromRefundAmount decimal(12,2)=0,
           @rToRefundAmount decimal(12,2)=0,
           @rFromRefundDate date='',
           @rToRefundDate date='',
           @rHostelId int,
           @rCode nvarchar(20)='',
           @rRoomId int=0,
           @rStudentName nvarchar(100)='',
		   @rStudentCode nvarchar(100)='',
		   @rClassId int=0,
		   @rDivisionId int=0,
		   @rIsBasedOnSUId bit = 0,
		   @rDepartmentId int=0,
		   @rSUId nvarchar(20)='',
		   @rOrgGroupBatchId int,
		   @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='',
	       @rFromAllocateDate date=null,
	       @rToAllocateDate Date=null
          
AS
SET NOCOUNT ON

BEGIN
SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			DHM.Title AS DepositHeadName,
			DR.HostelDepositHeadId,
			DR.StudentId AS StudentId,
			vSA.AcademicId AS AcademicId,
			DR.RefundDate,
			DR.PayTypeId,
			DR.ChequeNo,
			DR.BankName,
			DR.Remark,
			DR.CreatedDateTime,
			vSA.Code,
			vSA.Name AS StudentName,        
			vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,

			CASE  WHEN ISNULL(DR.RefundAmount,0) <> 0 THEN ISNULL(DR.RefundAmount,0) ELSE
			(SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
			INNER JOIN sHostel.tHostelDepositRefund DR1 ON DR1.HostelDepositHeadId=D.HostelDepositHeadId AND DR1.StudentId=D.StudentId AND D.StudentId = DR.StudentId AND DR1.OrgGroupBatchId=@rOrgGroupBatchId
			WHERE D.HostelDepositHeadId = DR1.HostelDepositHeadId AND D.StudentId=DR1.StudentId AND D.OrgGroupBatchId=@rOrgGroupBatchId)         
			- (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sHostel.tHostelDepositAdjustment DA 
			INNER JOIN sHostel.tHostelDepositRefund DR2 ON DR2.HostelDepositHeadId=DA.HostelDepositHeadId AND DR2.StudentId=DA.StudentId AND DA.StudentId= DR.StudentId AND DA.OrgGroupBatchId=@rOrgGroupBatchId
			WHERE DA.HostelDepositHeadId = DR2.HostelDepositHeadId AND DA.StudentId=DR2.StudentId  AND  DR2.OrgGroupBatchId=@rOrgGroupBatchId) END AS RefundAmount,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrganizationName,
			HM.ReportOrgTitle,
			HM.SmallAddress1,
			HM.SmallAddress2,
			RM.Id AS RoomId,
			RM.Title AS RoomName,
			CASE WHEN @rIsBasedOnSUId=0 THEN  vSA.Code Else ISNULL(vSA.suid,'') END AS SUId,
			U.Id As UserId,
			U.DisplayTitle AS Username
		
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DR.HostelDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DR.HostelId
		LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=DR.StudentId  AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	    LEFT JOIN sHostel.tRoomMaster RM ON RM.Id= AR.RoomId   
	    LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sSecurity.tUser U ON U.Id=DR.CreatedUserId
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DR.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DR.RefundAmount >= @rFromRefundAmount) OR (@rFromRefundAmount = 0))
		AND ((DR.RefundAmount <= @rToRefundAmount) OR (@rToRefundAmount = 0))
		AND ((DR.RefundDate >= @rFromRefundDate) OR (ISNULL(@rFromRefundDate,'') = ''))
		AND ((DR.RefundDate <= @rToRefundDate) OR (ISNULL(@rToRefundDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DR.HostelId=@rHostelId)
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((vSA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vSA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((vSA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((vSA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((vSA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (vSA.SUId like @rSUId OR ISNULL(@rSUId,'')='') 
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (DR.OrgGroupBatchId=@rOrgGroupBatchId)
		   AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
		GROUP BY
		DHM.Title,DR.HostelDepositHeadId,DR.StudentId,vSA.AcademicId,DR.RefundAmount,DR.RefundDate,DR.PayTypeId,
		DR.ChequeNo,DR.BankName,DR.Remark,DR.CreatedDateTime,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName,OM.Id,OM.DisplayTitle ,HM.ReportOrgTitle,HM.SmallAddress1,HM.SmallAddress2,RM.Id ,RM.Title,vSA.SUId,U.Id,U.DisplayTitle
		Order By DR.RefundDate
END
GO
PRINT N'Altering [sHrm].[pEmployeeJobDetailAdd]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeJobDetailAdd]
    
    @rOrgId smallint,
	@rEmployeeId [bigint], 
	@rEmployeeDesignationId [int],
	@rOrganizationDepartmentId [int],
	@rDateOfJoining Date,
	@rCreatedUserId [bigint],
	@rEmployeeTypeId int,
	@rEmployeeGradeId int,
	@rEmployeeGroupId int,
	@rJobRemark nvarchar(200) = '',
	@rEmployeeManagerId bigint=0,
	@rProbationDays smallint = NULL,
	@rSubjects nvarchar(200) = NULL
	
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	BEGIN TRY
	BEGIN TRANSACTION
	
			IF (@rEmployeeDesignationId <= 0)
			SET @rEmployeeDesignationId = NULL		
			
			IF(@rEmployeeTypeId <= 0)
			SET @rEmployeeTypeId = NULL			
			
			IF(@rEmployeeGradeId <= 0) 
			SET @rEmployeeGradeId = NULL
			
			IF(@rEmployeeGroupId <= 0)
			SET @rEmployeeGroupId = NULL
			
			IF(@rEmployeeManagerId <= 0)
			SET @rEmployeeManagerId = NULL
			
	INSERT INTO sHrm.tEmployeeJobDetail
		(
			EmployeeId,	
			EmployeeDesignationId,
			OrganizationDepartmentId,
			DateOfJoining,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId,
			EmployeeTypeId,
			EmployeeGradeId,
			EmployeeGroupId,
			JobRemark,
			EmployeeManagerId,
			ProbationDays,
			Subjects
		)
	VALUES
		(
			@rEmployeeId, 			 
			@rEmployeeDesignationId,
			@rOrganizationDepartmentId,
			@rDateOfJoining,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			@rEmployeeTypeId,
			@rEmployeeGradeId,
			@rEmployeeGroupId,
			@rJobRemark,
			@rEmployeeManagerId,
			@rProbationDays,
			@rSubjects
		)
	
	SELECT @rEmployeeId AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	RAISERROR ('Error Creating Job Detail', -- Message text.
               16, -- Severity.
               1 -- State.
               );
	--SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Altering [sHrm].[pEmployeeJobDetailGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeJobDetailGet]
	
	@rOrgId smallint,
	@rEmployeeId [bigint] = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			JD.EmployeeId,			 
			ISNULL(JD.EmployeeDesignationId,0) AS EmployeeDesignationId,
			ISNULL(DM.Title,'') AS EmployeeDesignation,
			JD.OrganizationDepartmentId,
			ODM.Title AS OrganizationDepartment, 
			JD.DateOfJoining,
			JD.UpdatedUserId,
			JD.UpdatedDateTime,
			ISNULL(JD.EmployeeTypeId,0) AS EmployeeTypeId,
			ISNULL(JD.DateOfleaving,'01-01-0001') AS DateOfLeaving,
			ISNULL(JD.ReasonOfleaving,'') AS ReasonOfLeaving,
			ISNULL(JD.JobRemark,'') AS JobRemark,
			ISNULL(JD.EmployeeGradeId,0) AS EmployeeGradeId,
			ISNULL(JD.EmployeeGroupId,0) AS EmployeeGroupId,
			ISNULL(JD.EmployeeManagerId,0) AS EmployeeManagerId,
			ISNULL(JD.ReferenceRemark,'') AS ReferenceRemark,
			ISNULL(JD.ProbationDays,'') AS ProbationDays,
			JD.OrgId,
			ISNULL(JD.Subjects,'') AS Subjects
	   FROM 
			sHrm.tEmployeeJobDetail JD
	   INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = JD.OrganizationDepartmentId	
	   LEFT JOIN sHrm.tEmployeeDesignationMaster DM ON DM.Id  = JD.EmployeeDesignationId
	   WHERE 
			((EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		AND JD.OrgId = @rOrgId
END
GO
PRINT N'Altering [sHrm].[pEmployeeJobDetailModify]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeJobDetailModify]
 
	@rEmployeeId [bigint], 
	@rEmployeeDesignationId [int],
	@rOrganizationDepartmentId [int],
	@rDateOfJoining Date,
	@rUpdatedUserId [bigint],
	@rEmployeeTypeId int,
	@rDateOfLeaving Date = null,
	@rReasonOfLeaving nvarchar(200) = null,
	@rEmployeeGradeId int,
	@rEmployeeGroupId int,
	@rJobRemark nvarchar(200),
	@rEmployeeManagerId bigint,
	@rReferenceRemark nvarchar(200)='',
	@rProbationDays smallint=NULL,
	@rSubjects nvarchar(200) = NULL
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
			IF (@rEmployeeDesignationId <= 0)
			SET @rEmployeeDesignationId = NULL
			
	 UPDATE sHrm.tEmployeeJobDetail
		SET  
			EmployeeDesignationId = @rEmployeeDesignationId,			 
			OrganizationDepartmentId = @rOrganizationDepartmentId,
			DateOfJoining =	@rDateOfJoining,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			EmployeeTypeId = @rEmployeeTypeId,
			DateOfleaving = @rDateOfLeaving,
			ReasonOfleaving = @rReasonOfLeaving,
			EmployeeGradeId = @rEmployeeGradeId,
			EmployeeGroupId = @rEmployeeGroupId,
			JobRemark=@rJobRemark,
			EmployeeManagerId=@rEmployeeManagerId,
			ReferenceRemark = @rReferenceRemark,
			ProbationDays = @rProbationDays,
			Subjects = @rSubjects
	  WHERE 
			EmployeeId = @rEmployeeId
	
	  SELECT 1 AS JobDetailId From sHrm.tEmployeeJobDetail where EmployeeId = @rEmployeeId
END
GO
PRINT N'Altering [sHrm].[pEmployeeProfileFullGet]...';


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


GO
ALTER PROCEDURE [sHrm].[pEmployeeProfileGet]
 
	@rOrgId int,
	@rDepartmentId int = 0,
	@rEmployeeId bigint,
	@rGroupId int
 
AS
SET NOCOUNT ON

BEGIN
		SELECT 
				EM.Id AS EmployeeId,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				EC.CompanyEmail AS EmailId,
				DM.Id AS DepartmentId,
				DM.Title AS DepartmentName,
				CONVERT(date,EJD.DateOfJoining) AS DateOfJoining,
				EM.Code AS Code,
				ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS EmployeePhoto,
				GrpM.Id AS EmployeeGroupId,
				GrpM.Title AS GroupName,
				[sHrm].[fEmployeeSubjectGet](EM.Id) AS Subjects,
				ISNULL(EC.MobileNumber,'') AS MobileNumber,
				CONVERT(nvarchar(10), ROW_NUMBER() OVER ( ORDER BY EM.Id )) AS SrNo
		FROM 
				sHrm.tEmployeeMaster EM
				INNER JOIN  sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
				LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EM.Id
				LEFT JOIN sHrm.tEmployeeGroupMaster GrpM ON GrpM.Id=EJD.EmployeeGroupId
		WHERE 
				EM.OrgId = @rOrgId 
				AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
				AND ((EM.Id=@rEmployeeId) OR (@rEmployeeId=0))
				AND ((EJD.EmployeeGroupId = @rGroupId) OR (@rGroupId = 0))	
				AND EM.StatusId = 7
END
GO
PRINT N'Altering [sHrm].[pImportUser]...';


GO
ALTER PROCEDURE [sHrm].[pImportUser]
    
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rCreatedUserId bigint 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @loXML XML,@lCount int,
			@lUserType nvarchar(100),
			@lEmployeeCode nvarchar(100),
			@lUserName nvarchar(100),
			@lDisplayName nvarchar(100),
			@lPassword nvarchar(500),
			@lRole nvarchar(100),
			@lRoleId bigint
	
	SET @loXML = CAST(@rXmldoc AS XML)
	
	CREATE TABLE #tTable1 (
	Id bigint identity,
	UserType nvarchar(50) collate SQL_Latin1_General_CP1_CI_AS ,
	EmployeeCode nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	UserName nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	DisplayName nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	[Password] nvarchar(500) collate SQL_Latin1_General_CP1_CI_AS ,
	[Role] nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS ,
	RoleId bigint)
	
	INSERT INTO #tTable1(
		UserType,
		EmployeeCode,
		UserName,
		DisplayName, 
		[Password],
		[Role],
		RoleId)      
	SELECT
		 T.c.value('@UserType','nvarchar(50)') AS UserType,
		 T.c.value('@EmployeeCode','nvarchar(100)') AS EmployeeCode,
		 T.c.value('@UserName','nvarchar(100)') AS UserName,
		 T.c.value('@DisplayName','nvarchar(100)') AS DisplayName,
		 T.c.value('@Password','nvarchar(500)') AS [Password],
		 T.c.value('@Role','nvarchar(100)') AS [Role],
		 T.c.value('@RolId','nvarchar(100)') AS RoleId
	FROM @loXML.nodes('/Table/ImportUser')T(c)
  			
BEGIN

	DECLARE @rUserSourceId bigint = NULL, @rUserSourceTypeId bigInt = NULL, @EmployeeId bigint = NULL, @tmp varchar(500)

	SET @tmp = ''
	
	SELECT @tmp = @tmp + T.EmployeeCode  + ', '  from #tTable1 T 
	LEFT JOIN  sHrm.tEmployeeMaster EM ON T.EmployeeCode  = EM.Code 
	AND EM.OrgId = @rOrgId AND upper(T.UserType) = 'EMPLOYEE' 
	WHERE EM.ID IS NULL AND T.EmployeeCode <> ''
 
	IF @tmp <> ''
	BEGIN
		SELECT -101 AS Result, SUBSTRING(@tmp, 0, LEN(@tmp)) AS ResultDetail
		RETURN
	END

	SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
	BEGIN		
		SELECT         
			@lUserType = UserType ,
			@lEmployeeCode = EmployeeCode,
			@lUserName = UserName,
			@lDisplayName = DisplayName,
			@lPassword = [Password],
			@lRole = [Role],
			@lRoleId = RoleId
		FROM #tTable1 WHERE Id = @lCount    
	     
		IF UPPER(@lUserType) = 'EMPLOYEE'
		BEGIN
		 SELECT @rUserSourceId = Id FROM sHrm.tEmployeeMaster WHERE Code = @lEmployeeCode AND OrgID=@rOrgId
		 SELECT @rUserSourceTypeId = 95
		END
		ELSE
		BEGIN
			 SELECT @rUserSourceId = 0
			 SELECT @rUserSourceTypeId = 1
		END
							
		IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @lUserName AND OrgId=@rOrgId)
		BEGIN
			UPDATE sSecurity.tUser
			SET	
				LoginPassword = @lPassword,				
				IsObsolete = 0,			
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				LoginTitle = @lUserName,
				DisplayTitle = @lDisplayName
			WHERE 
				LoginTitle = @lUserName AND OrgId=@rOrgId			
		END
		ELSE
		BEGIN
			DECLARE @lNextNumber BIGINT	
			EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 101, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sSecurity.tUser
				(
					Id,		
					DisplayTitle,
					LoginTitle,
					LoginPassword,
					LastLockOutDate,
					NumberOfLogonAttempt,
					IsObsolete,
					CreatedUserId,
					CreatedDateTime,
					UpdatedUserId,
					UpdatedDateTime,
					OrgId,
					SourceId,
					SourceTypeId	
				)
			VALUES
				(
					@lNextNumber,
					@lDisplayName,					
					@lUserName,
					@lPassword,
					sCommon.fGetDate(),
					0,
					0,
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rCreatedUserId,
					sCommon.fGetDate(),
					@rOrgId,
					@rUserSourceId,
					@rUserSourceTypeId
				)
				
			IF NOT EXISTS(Select 1 From [sSecurity].[tUserRole]  WHERE RoleId = @lRoleId AND UserId=@lNextNumber)
			BEGIN
				INSERT INTO 
				[sSecurity].[tUserRole] (RoleId, UserId, IsObsolete, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsPrimary)
				VALUES
				(@lRoleId,@lNextNumber,0,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),1)
			END
		END
		SET @lCount = @lCount-1
	  END 
	SELECT 1 AS Result, '' AS ResultDetail
 END
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeAllDetailList]...';


GO
ALTER PROCEDURE [sHrm].[pRptEmployeeAllDetailList]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int=0,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint
									
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
DECLARE @lIsOnPrePrinted bit = 0

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

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 129 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsOnPrePrinted = 0
	ELSE
	SET @lIsOnPrePrinted = 1
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayImageHeader = 0
	ELSE
	SET @lIsDisplayImageHeader = 1	
	
	
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
		    EM.Id,
	        EM.Id AS EmployeeId,
	        EM.Code,
	        EM.EmployeeName,
	       	EM.FirstName,
			EM.MiddleName,
			EM.LastName,	
			EM.ShortName,
			EM.OrgID,
			EM.GenderId,
			EM.DateOfBirth,
			EM.DateOfJoining,
			EM.DateOfleaving,
			EM.ReasonOfleaving,
			EM.JobRemark,
			EM.StatusId,
			EM.CreatedUserId,
			EM.CreatedDateTime,
			EM.UpdatedUserId,
			EM.UpdatedDateTime,
			EM.IsObsolete,
			EM.PhoneNoCompany,
			EM.CompanyEmail,
			EM.ExtensionNo,
			EM.UserId,
			EM.DepartmentId,
			EM.DepartmentCode,  
			EM.DepartmentName,
		    EM.MobileNumber,
			EM.EmployeeTypeId,
			EM.DesignationId,
			EM.Designation,
			EM.ParticipantSourceTypeId,
			EM.EmployeeGroup,
			EM.EmployeeGroupId,
			EM.EmployeePhoto,
			EC.PresentStreetOne,
			EC.PresentStreetTwo,
			EC.PresentStreetThree,
			EC.PresentCity,
			EC.PresentState,
			EC.PresentCountry,
			EC.PresentZipCode,
			EC.PresentContactNo,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			GM.Title AS Gender,
			EM.EmployeeType,
			EM.Qualification,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			OI.CertificateHeaderA4 ,
			--[sHrm].[fTeachingSubjectGet] (EM.Id) AS TeachingSubject,
			EJD.Subjects AS TeachingSubject,
			ISNULL(ESO.EPFNumber,'') AS EPFNumber,
			ISNULL(EP.AdhaarNumber,'') AS AdhaarNumber
	FROM 
			[sHrm].[vExtEmployeeMaster] EM
			INNER JOIN sHrm.tEmployeeCommunications EC ON EM.Id=EC.EmployeeId
			INNER JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.Id		
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EM.GenderId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId 
	WHERE
			((EM.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(EM.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (EM.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (EM.StatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (EM.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (EM.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (EM.DesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (EM.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,EM.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  EM.OrgId = @rOrgId
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeAttendanceGet]...';


GO
ALTER PROCEDURE [sHrm].[pRptEmployeeAttendanceGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rEmployeeName nvarchar(200),
	@rEmployeeCode nvarchar (200),
	@rEmployeeId bigint,
	@rDepartmentId int,
	@rEmployeeGradeId int,
	@rForYear  smallint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int,
	@rEmployeeStatusId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT 
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2, 
			 EM.Code AS EmployeeCode,
			 EM.EmployeeName,   
			 EM.EmployeeId,
			 EM.DepartmentName,
			 EM.EmployeeGrade,      
			 ISNULL(WD.TotalDays,ISNULL(AT.TotalWorkingDays,0)) As TotalDays,
			 ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays, 
			 ISNULL(AT.LWP,0) AS LWP,
			 CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
			 MM.Title AS MonthName,
			 AT.ForYear As YearName
			 --L.LeaveReason,
			 --L.NoOfLeave,
			 --L.ReportDate,
			 --L.FromDate,
			 --L.ToDate,
			 --LPM.Title As LeavePeriod,
			 --LTM.Title As LeaveType,
			 --LTM.IsCarryForward,
			 --LTM.IsLWP
        FROM 
				sHrm.vEmployeeCommonDetail EM 
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			LEFT JOIN sCommon.tMonthMaster MM ON MM.Id=AT.ForMonth
			LEFT JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
				AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
			--INNER JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId
			--INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id=L.LeavePeriodId
			--INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id=L.LeaveTypeId
    	WHERE 
    			EM.OrgID = @rOrgId 
    		AND (AT.BatchId=@rBatchId)
    		AND ((AT.ForMonth=@rForMonth) OR (@rForMonth=0))
    		AND ((AT.ForYear=@rForYear) OR (@rForYear=0))
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		--AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    		--AND ((L.ToDate>=@rToDate) OR (ISNULL(@rToDate,'')=''))
    		
    		ORDER BY AT.ForYear,AT.ForMonth
    		
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeAttendanceRegisterGet]...';


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

BEGIN 
       SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			EM.Code AS EmployeeCode,
			EM.EmployeeId,
			EM.EmployeeName,   
			EM.DepartmentName,
			EM.EmployeeGrade,      
		   	sCommon.fGetDaysInMonth (@rForMonth,@rForYear) AS DaysInMonth,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,1 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P1,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,2 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P2,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,3 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P3,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,4 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P4,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,5 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P5,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,6 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P6,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,7 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P7,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,8 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P8,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,9 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P9,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,10 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P10,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,11 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P11,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,12 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P12,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,13 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P13,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,14 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P14,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,15 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P15,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,16 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P16,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,17 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P17,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,18 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P18,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,19 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P19,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,20 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P20,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,21 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P21,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,22 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P22,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,23 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P23,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,24 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P24,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,25 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P25,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,26 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P26,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,27 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P27,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,28 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P28,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,29 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P29,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,30 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P30,
		   	[sHrm].[fWeekHOffHolidayGet](EM.EmployeeId,@rForYear ,@rForMonth ,31 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P31
        FROM
			sHrm.vEmployeeCommonDetail EM
			INNER JOIN sHrm.tEmployeeMaster E ON E.Id = EM.EmployeeId
    	WHERE
    		EM.OrgID = @rOrgId 
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((E.StatusId=@rStatusId) OR (@rStatusId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		ORDER BY EM.Code
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeDetailWithExpenseGet]...';


GO
ALTER PROCEDURE [sHrm].[pRptEmployeeDetailWithExpenseGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rEmployeeCode nvarchar (200),
	@rDepartmentId int,
	@rEmployeeGradeId int,
	@rForYear  smallint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int,
	@rEmployeeStatusId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT 
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2, 
			 EM.Code AS EmployeeCode,
			 EM.EmployeeName,   
			 EM.EmployeeId,
			 EM.DepartmentName,
			 EM.EmployeeGrade,      
			 ISNULL(WD.TotalDays,ISNULL(AT.TotalWorkingDays,0)) As TotalDays,
			 ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays, 
			 ISNULL(AT.LWP,0) AS LWP,
			 CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
			 MM.Title AS MonthName,
			 AT.ForYear As YearName,
			 ISNULL(E.Amount,0) AS Amount
        FROM 
			sHrm.vEmployeeCommonDetail EM 
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			LEFT JOIN sCommon.tMonthMaster MM ON MM.Id=AT.ForMonth
			LEFT JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
			AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
			LEFT JOIN sAccounting.tExpense E ON EM.EmployeeId = E.EmployeeId AND DATEPART(MONTH,E.ExpenseDate)=AT.ForMonth
    	WHERE 
    		EM.OrgID = @rOrgId AND AT.BatchId=@rBatchId 
    		AND ((AT.ForMonth=@rForMonth) OR (@rForMonth=0))
    		AND ((AT.ForYear=@rForYear) OR (@rForYear=0))
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code LIKE @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		ORDER BY  EM.EmployeeId,AT.ForYear,AT.ForMonth
    		
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeLeaveDetailsGet]...';


GO


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

BEGIN 
       SELECT 
				 @rBuilder1 AS Builder1,
				 @rBuilder2 AS Builder2, 
				 EM.Code AS EmployeeCode,
				 EM.EmployeeName,   
				 EM.EmployeeId,
				 EM.DepartmentName,
				 EM.EmployeeGrade,      
				 --ISNULL(AT.LWP,0) AS LWP,
				 --CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
				 --MM.Title AS MonthName,
		   --      (SELECT  t1.MonthTitle FROM (SELECT MonthTitle,MonthNumber FROM [sSetup].[fMonthYearForBatchGet] (100100001))  AS T1
				 --WHERE MonthNumber = 4) AS MonthName,
				 --(SELECT  t2.YearNumber FROM (SELECT YearNumber,MonthNumber FROM [sSetup].[fMonthYearForBatchGet] (100100001))  AS T2
				 --WHERE YearNumber = 2014 AND MonthNumber = 4 ) AS YearName,
				 --AT.ForYear As YearName,
				 L.LeaveReason,
				 L.NoOfLeave,
				 L.ReportDate,
				 L.FromDate,
				 L.ToDate,
				 LPM.Title As LeavePeriod,
				 LTM.Title As LeaveType,
				 LTM.IsCarryForward,
				 LTM.IsLWP,
				 ISNULL(SM.Title,'') AS StatusName
        FROM 
				sHrm.vEmployeeCommonDetail EM 
		--LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
		--LEFT JOIN sCommon.tMonthMaster MM ON MM.Id=AT.ForMonth
		INNER JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id=L.LeavePeriodId
		INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id=L.LeaveTypeId
		LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId
    	WHERE 
    	EM.OrgID = @rOrgId 
    	AND L.BatchId=@rBatchId
    	AND (YEAR(L.FromDate) = @rForYear OR @rForYear='') 
    	AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth='') 
    	AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    	AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    	AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    	AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    	AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    	AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    	AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
    	AND ((L.LeaveReason Like '%'+@rLeaveReson+'%' ) OR (ISNULL(@rLeaveReson,'')=''))
    	AND ((L.StatusId=@rStatusId) OR (@rStatusId=0))
    	AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
END
GO
PRINT N'Altering [sHrm].[pRptLeaveDeductionGet]...';


GO
ALTER PROCEDURE [sHrm].[pRptLeaveDeductionGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rEmployeeName nvarchar(200),
		@rEmployeeCode nvarchar (200),
		@rEmployeeId bigint,
		@rDepartmentId int,
		@rEmployeeGradeId int,
		@rForYear  smallint,
		@rForMonth tinyint,
		@rBatchId int,
		@rOrgId int,
		@rIsDetail bit=0,
		@rEmployeeStatusId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT 
			
			
				
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			@rIsDetail AS IsDetail,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,   
			EM.EmployeeId,
			EM.DepartmentName,
			EM.EmployeeGrade,      
			ISNULL(LB.BalanceLeave,0) AS BalanceLeave,
			LTM.Id AS LeaveTypeId,	
			LTM.Title AS LeaveType,
			(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
		   	) AS NoOfLeave,
	   		(
			SELECT ISNULL(SUM(L.NoOfLeave),0)				 
			FROM 
				sHrm.tLeave L
				INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
				AND IsLWP = 1 AND StatusId=550
			WHERE 
				L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
				AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
				AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
				AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
	   	    ) AS LWPNoOfLeave,
		   	ISNULL(LTM.IsLWP,0) AS IsLWP,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) < @rForMonth OR @rForMonth=0) 
		   	) AS UptoNoOfLeave,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 1 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) < @rForMonth OR @rForMonth=0) 
		   	) AS LWPUptoNoOfLeave,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 0 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
		   	) AS CurrentNoOfLeave,
		   	(
				SELECT ISNULL(SUM(L.NoOfLeave),0)				 
				FROM 
					sHrm.tLeave L
					INNER JOIN sHrm.tLeaveTypeMaster LTM1 ON L.LeaveTypeId = LTM1.Id 
					AND IsLWP = 1 AND StatusId=550
				WHERE 
					L.BatchId=@rBatchId AND L.OrgId = @rOrgId 
					AND EM.EmployeeId = L.EmployeeId AND LTM.Id = L.LeaveTypeId
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
		   	) AS LWPCurrentNoOfLeave
        FROM
			sHrm.vEmployeeCommonDetail EM
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0
			LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EM.EmployeeId AND LTM.Id = LB.LeaveTypeId AND LB.BatchId=@rBatchId
    	WHERE
    		EM.OrgID = @rOrgId 
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		ORDER BY EM.Code
END
GO
PRINT N'Altering [sInfrastructure].[pResourceMasterAdd]...';


GO

ALTER PROCEDURE [sInfrastructure].[pResourceMasterAdd] 
	 
        @rId int,
		@rTitle nvarchar(100),
		@rCode nvarchar(20),
		@rIsObsolete bit,
		@rCreatedUserId bigint ,
		@rOrgId int,
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sInfrastructure.tResourceMaster where Code=@rCode AND OrgGroupId =@rOrgGroupId)
			BEGIN
			select -102 as Result
			RETURN
		END 
	
		If Exists(select Id from sInfrastructure.tResourceMaster where Title=@rTitle AND OrgGroupId =@rOrgGroupId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sInfrastructure.tResourceMaster where Code=@rCode  AND Id<>@rId AND OrgGroupId =@rOrgGroupId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from sInfrastructure.tResourceMaster where Title=@rTitle AND Id<>@rId AND OrgGroupId =@rOrgGroupId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sInfrastructure.tResourceMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sInfrastructure.tResourceMaster
		(
			Id,
			Code,
			Title,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime ,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate() ,
			@rOrgGroupId
		)
		    SELECT 1 AS Result
	
 COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sInfrastructure.tResourceMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			IsObsolete=@rIsObsolete, 
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      
	      WHERE Id = @rId AND OrgGroupId=@rOrgGroupId
	      SELECT 11 AS Result
	
		 COMMIT TRANSACTION
	 END  	

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


GO

ALTER PROCEDURE [sInfrastructure].[pResourceMasterGet] 
	 
        @rId int,
		@rTitle nvarchar(100),
		@rCode nvarchar(100),
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRANSACTION
	BEGIN TRY
		Select Id,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime
		From sInfrastructure.tResourceMaster 
		Where
		((Id=@rId) OR (@rId=0))
		AND ((Code like '%'+@rCode+'%') OR (ISNULL(@rCode,'')=''))
		AND ((Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
		AND  OrgGroupId=@rOrgGroupId
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sInfrastructure].[pResourceRequestAdd]...';


GO

ALTER PROCEDURE [sInfrastructure].[pResourceRequestAdd] 
	 
        @rId bigint,
		@rRequestDate datetime,
		@rRequestFromTime datetime,
		@rRequestToTime datetime,
		@rResourceId int,
		@rRequestedBy nvarchar(100),
		@rRequestedRemark nvarchar(250),
		@rStatusId smallint=704,
		@rCreatedUserId bigint ,
		@rOrgId int,
		@rOrgGRoupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sInfrastructure.tResourceRequest', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sInfrastructure.tResourceRequest
		(
			Id,
			RequestDate,
			RequestFromTime,
			RequestToTime,
			ResourceId,
			RequestedBy,
			RequestedRemark,
			StatusId,
			CreatedUserId,
			CreatedDateTime ,
			OrgGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rRequestDate,
			@rRequestFromTime,
			@rRequestToTime,
			@rResourceId,
			@rRequestedBy,
			@rRequestedRemark,
			@rStatusId,
			@rCreatedUserId,
			sCommon.fGetDate() ,
			@rOrgGRoupId
		)
		    SELECT 1 AS Result
	
 
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sInfrastructure.tResourceRequest
	    SET
			RequestDate=@rRequestDate,
			RequestFromTime=@rRequestFromTime,
			RequestToTime=@rRequestToTime, 
			ResourceId=@rResourceId,
			RequestedBy=@rRequestedBy,
			RequestedRemark=@rRequestedRemark,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      
	      WHERE Id = @rId AND OrgGroupId=@rOrgGRoupId
	      SELECT 11 AS Result
	
		 
	 END  	

	 
		
END
GO
PRINT N'Altering [sInfrastructure].[pResourceRequestGet]...';


GO

ALTER PROCEDURE [sInfrastructure].[pResourceRequestGet] 
	 
        @rId bigint,
		@rRequestFromTime date='',
		@rRequestToTime date='',
		@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRANSACTION
	BEGIN TRY
		Select 
			RR.Id,ISNULL(RR.RequestDate,'') AS RequestDate,ISNULL(RR.RequestFromTime,'') AS RequestFromTime,ISNULL(RR.RequestToTime,'') As RequestToTime,ISNULL(RR.ResourceId,0) AS ResourceId,RR.RequestedBy,
			RR.RequestedRemark,ISNULL(RR.StatusId,0) AS StatusId,SM.Title As Status
		From sInfrastructure.tResourceRequest RR
		INNER JOIN sInfrastructure.tResourceMaster R ON R.Id =RR.ResourceId  
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id =RR.StatusId
		
		Where
		((RR.Id=@rId) OR (@rId=0))
		AND ((RequestFromTime=@rRequestFromTime) OR (ISNULL(@rRequestFromTime,'')=''))
		AND ((RequestToTime=@rRequestToTime) OR (ISNULL(@rRequestToTime,'')=''))
		AND RR.OrgGroupId =@rOrgGroupId
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sLibrary].[pRptMagazineMonthlyCount]...';


GO


ALTER PROCEDURE [sLibrary].[pRptMagazineMonthlyCount]

	 
	@rLibraryId int ,
	@rFromLogDate date='',
	@rToLogDate date='',
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rMagazineTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


	CREATE Table #table
	(
		NoOfCopies int,
		Id bigint 
	)
	Insert Into #table
		
	Select  M.NoOfCopies,M.Id
	From sLibrary.tMagazineMaster M
	WHere M.LibraryId =@rLibraryId
	AND (M.MagazineTypeId=@rMagazineTypeId)
  
	Select 
		MM.Code,
		MM.Title,
		MM.NoOfCopies,
		ISNULL(MM.Currency,'') AS Currency,
		MM.Price,
		MR.Id,
		MR.VolumeNumber,
		MR.MagazineAmount,
		MR.IssueNumber,
		CONVERT(date,ReceiveDate) ReceiveDate,
		@rBuilder1 As Builder1,
		@rBuilder2 As Builder2 ,
		(Select Sum(NoOfCopies) from #table) AS Total 
		 
	From sLibrary.tMagazineMaster MM
	INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId=MM.Id
	WHere MM.LibraryId =@rLibraryId
	AND  (MR.ReceiveDate>=@rFromLogDate) 
	AND (MR.ReceiveDate<=@rToLogDate)
	AND  (MM.MagazineTypeId=@rMagazineTypeId) 
	 
	ORder by ReceiveDate
	
END
GO
PRINT N'Altering [sMis].[pRptAverageAttendanceGet]...';


GO
ALTER PROCEDURE [sMis].[pRptAverageAttendanceGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rOrgGroupBatchId int,
		@rFromDate Date,
		@rToDate Date,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0,
		@rIsDisplayOrgGroup bit=0,
		@rBatchGroupId int=0,
		@rStatusId int=0,
		@rStudentStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = 1	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId	
			LEFT JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=Bm.batchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			WHERE CM.Id = A.ClassId
			AND AttendanceTypeId = 1
			--AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND SR.IsPresent=1
			AND SR.AttendanceDate >= @rFromDate
			AND SR.AttendanceDate <= @rToDate	
			 --AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			 AND   BM.IsActive =@rStatusId
			 AND ((SM.StatusID =@rStudentStatusId) OR (@rStudentStatusId=0))
			 ) PresentCount,
			(select ISNULL(count(1),0) from sAttendance.tStudentRegister SR
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId AND BM.IsActive = @rStatusId		
			INNER JOIN 	sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			WHERE CM.Id = A.ClassId
			AND AttendanceTypeId = 1
			--AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			AND SR.IsPresent=0
			AND SR.AttendanceDate >= @rFromDate
			AND SR.AttendanceDate <= @rToDate
			 --AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			 AND   BM.IsActive=@rStatusId
			 AND ((SM.StatusID=@rStudentStatusId) OR (@rStudentStatusId=0))
			) AbsentCount
			 
		   
	FROM 
			sSetup.tClassMaster CM			
			--INNER JOIN sSetup.tBatchClass BC ON BC.ClassId= CM.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
	WHERE 
			--BC.BatchId = @rBatchId
		   ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			 
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering [sMis].[pRptCastCategorywiseStudentGet]...';


GO


 
ALTER PROCEDURE [sMis].[pRptCastCategorywiseStudentGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rClassId int,
	@rDivisionId int,
	@rDepartmentId int,
	@rOrgMainGroupId int,
	@rOrgSubGroupId int,
	@rOrgId smallint,
	@rOrgGroupBatchId int,
	@rStrOrgMainGroupId nvarchar(max),
	@rStrOrgSubGroupId nvarchar(max),
	@rStrOrgId nvarchar(max),
	@rStrDepartmentId nvarchar(max),
	@rStrClassId nvarchar(max),
	@rOrgGroupId int,
	@rIsTestMainGroup bit =0,
	@rIsTestSubGroup bit =0,	
	@rIsTestOrg bit=0,
	@rIsTestDepartment bit=0,
	@rIsTestClass bit=0,
	@rIsTestDivision bit=0,
	@rReportId int =0,
	@rIsDisplayOrgGroup bit=0,
	@rIsDisplayGender bit=0,
	@rBatchGroupId int =0,
	@rStatusId int=0,
	@rStudentStatusId int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsTestClass AS IsTestClass,
			@rIsTestDivision AS IsTestDivision ,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			@rIsDisplayGender AS IsDisplayGender,
			DV.Id AS DivisionId,
			CM.Id AS ClassId,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Department,
			CM.DisplayTitle+' '+DV.DisplayTitle AS ClassDivision,
			
			ISNULL(GM.Title,'') As Gender,
			A.Id AS AcademicId,
			--OBM.Title,
			
			DV.DisplayTitle AS Division,
		
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			CASE WHEN  @rReportId=20621	 -- Caste Category wise Summary
			THEN ISNULL(CCM.Title,'') 
		    WHEN  @rReportId=20623 -- Religionwise Summary
			THEN ISNULL(RM.Title,'')
			END AS Head,
			DV.OrderIndex AS DivisionOrder
			FROM 
			
			
			sStudent.tAcademic A	
			INNER JOIN	sSetup.tClassMaster CM	ON CM.Id=A.ClassId	
			INNER JOIN sSetup.tDivisionMaster DV ON DV.Id=A.DivisionId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId	
				
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId		
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId = OG.Id
			INNER JOIN sSetup.tBatchMaster BM ON  BM.Id=A.BatchId 
			--AND	BM.IsActive = 1 
			AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			AND BM.OrgGroupBatchId=OBM.Id
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId 	AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			
	WHERE 
		
		((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			--AND ((BM.Id=@rBatchId) OR (@rBatchId=0))			 
			AND  (BM.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((OM.OrgGroupId = @rOrgGroupId))
			 AND ((SM.StatusId=@rStudentStatusId) OR (@rStudentStatusId=0))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			
			 	
END
GO
PRINT N'Altering [sMis].[pRptClassCapacityGet]...';


GO
ALTER PROCEDURE [sMis].[pRptClassCapacityGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		@rOrgGroupBatchId int,
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0,
		@rIsDisplayOrgGroup bit=0,
		@rBatchGroupId int=0,
		@rStatusId int=0,
		@rStudentStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			ISNULL(CM.Capacity,0) AS Capacity,
			(SELECT ISNULL(count(1),0)  FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM 
			ON A.StudentId = SM.Id INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id = BM.BatchGroupId AND ( (BGM.Id = @rBatchGroupId) OR (@rBatchGroupId = 0))   
			WHERE A.ClassId = CM.Id AND SM.StatusId = 1 						
			AND BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END			
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SM.StatusId = @rStudentStatusId) OR (@rStudentStatusId=0))
			) AS CurrentStrength,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle
			
	FROM 
			sSetup.tClassMaster CM			
			--INNER JOIN sSetup.tBatchClass BC ON BC.ClassId= CM.Id
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			
			
			 
	WHERE 
			--((BC.BatchId = @rBatchId)
			  ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			 
			 
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering [sMis].[pRptDivisionCapacityGet]...';


GO
ALTER PROCEDURE [sMis].[pRptDivisionCapacityGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rDepartmentId int,
		@rClassId int,
		@rDivisionId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rOrgGroupId int,
		@rOrgGroupBatchId int,
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestDepartment bit=0,
		@rIsTestClass bit=0,
		@rIsDisplayOrgGroup bit=0,
		@rBatchGroupId int=0,
		@rStatusId int=0,
		@rStudentStatusId int=0
		
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

  SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsTestClass AS IsTestClass,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			DM.Id AS DivisionId,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			DM.DisplayTitle AS DivisionName,
			CM.DisplayTitle+'-'+DM.DisplayTitle AS ClassDivisionName,
			DM.OrderIndex,
			ISNULL(DM.Capacity,0) AS Capacity,
			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.ID=BM.BatchgroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			WHERE A.DivisionId = DM.Id AND SM.StatusId = 1 			
			AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SM.StatusId = @rStudentStatusId) OR (@rStudentStatusId=0))
			) AS CurrentStrength,
			CM.DepartmentId,
			DeptM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle
  FROM 
			sSetup.tDivisionMaster DM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			--INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId
			INNER JOIN sSetup.tDepartmentMaster DeptM ON DeptM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
  WHERE 
			--BC.BatchId = @rBatchId
			((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((CM.Id=@rClassId) OR (@rClassId=0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering [sMis].[pRptStudentStrengthGet]...';


GO
 
ALTER PROCEDURE [sMis].[pRptStudentStrengthGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		--@rBatchId int,
		@rClassId int,
		@rDepartmentId int,
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId smallint,
		@rOrgGroupBatchId int,
		@rFromDate Date,
		@rToDate Date,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max),
		@rIsTestMainGroup bit =0,
		@rIsTestSubGroup bit =0,
		@rIsTestOrg bit=0,
		@rIsTestClass bit=0,
		@rIsTestDepartment bit=0,
		@rOrgGroupId int,
		@rIsDisplayOrgGroup bit=0,
		@rBatchgroupId int =0,
		@rStatusID int =0,
		@rStudentStatusId int=0
		
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
		 
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
						
		    (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id = BM.batchGroupId ANd ((BGM.ID=@rBatchgroupId) OR (@rBatchGroupId=0))
			--WHERE BM.IsActive = 1 
			WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			AND SA.AdmissionDate < @rFromDate
			AND A.ClassId =CM.Id   
			AND ((SM.StatusID = @rStudentStatusId) OR (@rStudentStatusId=0))
			) AS OpeningStrength,
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.batchGroupId AND ((BGm.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			--WHERE BM.IsActive = 1 
			WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			AND SA.AdmissionDate >= @rFromDate AND SA.AdmissionDate <= @rToDate
			AND A.ClassId =CM.Id 
			 AND ((SM.StatusID = @rStudentStatusId) OR (@rStudentStatusId=0))
			 ) AS NewJoinedStudent,
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupid AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			--WHERE BM.IsActive = 1 
			WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			AND SA.LeftDate >= @rFromDate AND SA.LeftDate <= @rToDate
			AND A.ClassId =CM.Id
			AND ((SM.StatusID = @rStudentStatusId) OR (@rStudentStatusId=0))
			    ) AS LeftStudent,
		   (select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			ON SA.StudentId = A.StudentId 
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tBatchGroupMaster BGM on BGM.Id=BM.BatchGroupId AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			--WHERE BM.IsActive = 1
			WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId AND   BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			 --AND SM.StatusId = 1
			 AND ( SA.LeftDate > @rToDate OR SA.LeftDate IS NULL)
			AND A.ClassId =CM.Id  
			 AND ((SM.StatusId=@rStudentStatusId) OR (@rStudentStatusId=0))
			) AS ClosingStrength
 
 
	FROM 
			sSetup.tClassMaster CM			 
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId AND DM.IsObsolete = 0
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId AND DM.IsObsolete = 0
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
	WHERE 
		 
		   ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			 
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering [sPoliciesForms].[pFolderFileGet]...';


GO
/******************************
** Name:  [sPoliciesForms].[pFolderFileGet]
** Desc:  get Record From FolderFile Table
** Auth:  Savan Vaghela
** Date:  3-April-2017
** Page:  /Pages/Hrm/PoliciesForms/FormsMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    3-April-2017      Savan Vaghela       
************************************************************/
--EXEC [sPoliciesForms].[pFolderFileGet] 1001,1001000000003,0,1
ALTER PROCEDURE [sPoliciesForms].[pFolderFileGet] @rOrgId smallint,
@rCreatedUserId bigint,
@rPerentFolderId int,
@rIsForms bit 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

    DECLARE @rRoleId int
    SELECT @rRoleId = RoleId FROM [sSecurity].[tUserRole] WHERE UserID = @rCreatedUserId AND IsObsolete = 0

    SELECT 
		UFF.Id, UFF.Title, CASE WHEN UFF.IsFolder = 1 THEN 'Folder' ELSE 'File' END AS Type, 
		CASE WHEN UFF.IsFolder = 1 THEN 1 ELSE 0 END AS TypeId,
		CASE WHEN UFF.IsFolder = 1 THEN [sPoliciesForms].[fFileFolderSizeGet]([sPoliciesForms].[fFolderSizeGet](UFF.Id)) ELSE [sPoliciesForms].[fFileFolderSizeGet](ISNULL(UFF.Size, 0)) END AS Size,
		USR.DisplayTitle AS CreatedUser,
		CONVERT(varchar(20), UFF.CreatedDateTime, 113) AS CreateDate,
		CONVERT(bit, 1) AS IsAccess,
		CONVERT(bit, 1) AS IsView,
		CONVERT(bit, 1) AS IsUpload,
		CONVERT(bit, 1) AS IsEdit,
		CONVERT(bit, 1) AS IsDelete,
		FolderPath = [sPoliciesForms].[fFolderPathGet](UFF.Id)
    FROM [sPoliciesForms].[tFolderFile] AS UFF
    LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id = UFF.CreatedUserId
    WHERE UFF.OrgId = @rOrgId
    AND UFF.CreatedUserId = @rCreatedUserId
    AND UFF.PerentFolderId = @rPerentFolderId
    AND UFF.IsForms = @rIsForms

    UNION ALL

    SELECT
        UFF.Id, UFF.Title,
        CASE WHEN UFF.IsFolder = 1 THEN 'Folder' ELSE 'File' END AS Type,
        CASE WHEN UFF.IsFolder = 1 THEN 1 ELSE 0 END AS TypeId,
        CASE WHEN UFF.IsFolder = 1 THEN [sPoliciesForms].[fFileFolderSizeGet]([sPoliciesForms].[fFolderSizeGet](UFF.Id)) ELSE [sPoliciesForms].[fFileFolderSizeGet](ISNULL(UFF.Size, 0)) END AS Size,
        USR.DisplayTitle AS CreatedUser,
       CONVERT(varchar(20), UFF.CreatedDateTime, 113) AS CreateDate,
        FFP.IsAccess,
        FFP.IsView,
        FFP.IsUpload,
        FFP.IsEdit,
        FFP.IsDelete,
        FolderPath = [sPoliciesForms].[fFolderPathGet](UFF.Id)
    FROM [sPoliciesForms].[tFolderFile] AS UFF
    LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id = UFF.CreatedUserId
    LEFT JOIN [sPoliciesForms].[tFolderFilePermission] AS FFP ON FFP.FolderFileId = UFF.Id
    WHERE UFF.OrgId = @rOrgId
    AND UFF.CreatedUserId <> @rCreatedUserId
    AND UFF.PerentFolderId = @rPerentFolderId
    AND UFF.IsForms = @rIsForms
    AND UFF.Id IN (SELECT FolderFileId FROM [sPoliciesForms].[tFolderFilePermission] WHERE FolderFileId = UFF.Id
    AND RoleId = @rRoleId AND IsView = 1)
    AND FFP.RoleId = @rRoleId


    SELECT UFF.Id, UFF.Title,FolderPath = [sPoliciesForms].[fFolderPathGet](UFF.Id)
    FROM [sPoliciesForms].[tFolderFile] AS UFF
    LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id = UFF.CreatedUserId
    WHERE UFF.OrgId = @rOrgId
    AND UFF.CreatedUserId = @rCreatedUserId
    AND UFF.PerentFolderId = @rPerentFolderId
    AND UFF.IsFolder = 1
    AND UFF.IsForms = @rIsForms

    UNION ALL

    SELECT UFF.Id, UFF.Title,FolderPath = [sPoliciesForms].[fFolderPathGet](UFF.Id) 
    FROM [sPoliciesForms].[tFolderFile] AS UFF
    LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id = UFF.CreatedUserId
    LEFT JOIN [sPoliciesForms].[tFolderFilePermission] AS FFP ON FFP.FolderFileId = UFF.Id
    WHERE UFF.OrgId = @rOrgId
    AND UFF.CreatedUserId <> @rCreatedUserId
    AND UFF.PerentFolderId = @rPerentFolderId
    AND UFF.IsForms = @rIsForms
    AND UFF.IsFolder = 1
    AND UFF.Id IN (SELECT FolderFileId FROM [sPoliciesForms].[tFolderFilePermission]
    WHERE FolderFileId = UFF.Id
    AND RoleId = @rRoleId AND IsView = 1)
    AND FFP.RoleId = @rRoleId


    SELECT UFF.Id, UFF.Title, ISNULL(Exe.ImageName, 'unknown.png') AS ImageName
    FROM [sPoliciesForms].[tFolderFile] AS UFF
    LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id = UFF.CreatedUserId
    LEFT JOIN ( SELECT * FROM [sPoliciesForms].[tFolderImageName]) AS Exe ON LOWER(Exe.Extension) = LOWER(REVERSE(LEFT(REVERSE(UFF.Title), CHARINDEX('.', REVERSE(UFF.Title)) - 1)))
    WHERE UFF.OrgId = @rOrgId
    AND UFF.CreatedUserId = @rCreatedUserId
    AND UFF.PerentFolderId = @rPerentFolderId
    AND UFF.IsFolder = 0
    AND UFF.IsForms = @rIsForms


    UNION ALL

    SELECT UFF.Id, UFF.Title, ISNULL(Exe.ImageName, 'unknown.png') AS ImageName
    FROM [sPoliciesForms].[tFolderFile] AS UFF
    LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id = UFF.CreatedUserId
    LEFT JOIN (SELECT * FROM [sPoliciesForms].[tFolderImageName]) AS Exe ON LOWER(Exe.Extension) = LOWER(REVERSE(LEFT(REVERSE(UFF.Title), CHARINDEX('.', REVERSE(UFF.Title)) - 1)))
    LEFT JOIN [sPoliciesForms].[tFolderFilePermission] AS FFP ON FFP.FolderFileId = UFF.Id
    WHERE UFF.OrgId = @rOrgId
    AND UFF.CreatedUserId <> @rCreatedUserId
    AND UFF.PerentFolderId = @rPerentFolderId
    AND UFF.IsForms = @rIsForms
    AND UFF.IsFolder = 0
    AND UFF.Id IN (SELECT FolderFileId
    FROM [sPoliciesForms].[tFolderFilePermission]
    WHERE FolderFileId = UFF.Id
    AND RoleId = @rRoleId
    AND IsView = 1)
    AND FFP.RoleId = @rRoleId


    IF (@rPerentFolderId = 0)
    BEGIN
        SELECT
            CONVERT(bit, 1) AS IsAccess,
            CONVERT(bit, 1) IsView,
            CONVERT(bit, 1) IsUpload,
            CONVERT(bit, 1) AS IsEdit,
            CONVERT(bit, 1) AS IsDelete
    END
    ELSE
    BEGIN
        SELECT
            CASE WHEN FOL.CreatedUserId = @rCreatedUserId THEN CONVERT(bit, 1) ELSE IsAccess END AS IsAccess,
            CASE WHEN FOL.CreatedUserId = @rCreatedUserId THEN CONVERT(bit, 1) ELSE IsView END AS IsView,
            CASE WHEN FOL.CreatedUserId = @rCreatedUserId THEN CONVERT(bit, 1) ELSE IsUpload END AS IsUpload,
            CASE WHEN FOL.CreatedUserId = @rCreatedUserId THEN CONVERT(bit, 1) ELSE IsEdit END AS IsEdit,
            CASE WHEN FOL.CreatedUserId = @rCreatedUserId THEN CONVERT(bit, 1) ELSE IsDelete END AS IsDelete
        FROM [sPoliciesForms].[tFolderFile] AS FOL
        INNER JOIN [sPoliciesForms].[tFolderFilePermission] AS PER ON PER.FolderFileId = FOL.Id
        WHERE FOL.OrgId = @rOrgId
        AND FOL.Id = @rPerentFolderId
        AND FOL.IsForms = @rIsForms
        AND PER.RoleId = @rRoleId
    END
END
GO
PRINT N'Altering [sPoliciesForms].[pFolderFileGetByID]...';


GO
/******************************
** Name:  [sPoliciesForms].[pFolderFileGet]
** Desc:  get Record From FolderFile Table
** Auth:  Savan Vaghela
** Date:  10-April-2017
** Page:  /Pages/Hrm/PoliciesForms/FormsMaster.aspx
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    10-April-2017      Savan Vaghela       
************************************************************/
--EXEC [sPoliciesForms].[pFolderFileGetByID] 100100334
ALTER PROCEDURE [sPoliciesForms].[pFolderFileGetByID]
	@rFileFolderId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	SELECT
		UFF.Id 
		,UFF.Title
		,ISNULL(UFF.Remark,'') Description
		,CASE When UFF.PerentFolderId=0 THEN 'Root' ELSE  UPF.Title END AS ParentFolder 
		,CASE WHEN UFF.IsFolder=1 THEN 'Folder' ELSE 'File' END AS Type
		,CASE WHEN UFF.IsFolder=1 THEN 1 ELSE 0  END AS TypeId
		,CASE WHEN UFF.IsFolder=1 THEN     [sPoliciesForms].[fFileFolderSizeGet]([sPoliciesForms].[fFolderSizeGet](UFF.Id)) ELSE [sPoliciesForms].[fFileFolderSizeGet](ISNULL(UFF.Size,0))  END AS Size
		,USR.DisplayTitle AS CreatedUser
		,CONVERT(VARCHAR(20), USR.CreatedDateTime, 113) AS CreateDate
		,ISNULL(UFF.ContentType,'')ContentType
		, CASE WHEN UFF.IsForms=1 THEN 'Forms' ELSE 'Policies' END  + [sPoliciesForms].[fFolderPathGet](@rFileFolderId)AS FilePath 
	FROM   
		[sPoliciesForms].[tFolderFile] AS UFF
		LEFT JOIN [sPoliciesForms].[tFolderFile]  AS UPF ON UPF.Id=UFF.PerentFolderId
		LEFT JOIN [sSecurity].[tUser] AS USR ON USR.id=UFF.CreatedUserId
	WHERE UFF.Id=@rFileFolderId
END
GO
PRINT N'Altering [sProcurement].[pRptStockItemWiseTransaction]...';


GO
ALTER PROCEDURE [sProcurement].[pRptStockItemWiseTransaction]
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rFilterId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rId int=0,
	@rItemCode nvarchar(100)='',
	@rItemName nvarchar(100)='',
	@rOrgId smallint,
	@rFromDate datetime = '1900/1/1',
	@rToDate datetime = '1900/1/1'
								
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN
 
  SET @rItemName = sCommon.fSearchStringGet(@rItemName)

	  
	SELECT
	WAC.Id,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SIM.Id AS StockItemId,
		
		 SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Good Reciept Note' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE
	   SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 46)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 7) OR (ISNULL(@rFilterId,  0) = 0))
		
		
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Good Return Note' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 47)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 8) OR (ISNULL(@rFilterId,  0) = 0))
		
		
		
				
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Adjustment' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 50)
		AND WAC.StoreLocationId= @rStoreLocationId
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 9) OR (ISNULL(@rFilterId,  0) = 0))
		
		
			
				
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Inward' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 1010)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 11) OR (ISNULL(@rFilterId,  0) = 0))
		
		
					
				
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Issue' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 51)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 1) OR (ISNULL(@rFilterId,  0) = 0))
		
		
					
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Transfer' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 52)
	    AND WAC.StoreLocationId= @rStoreLocationId 
	    AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')
		
		AND ((@rFilterId = 2) OR (ISNULL(@rFilterId,  0) = 0))
		
		
						
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Freeze Adjustmnet' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 104)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 10) OR (ISNULL(@rFilterId,  0) = 0))
		
		
		
							
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Dispense' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 48)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 3) OR (ISNULL(@rFilterId,  0) = 0))
		
		UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Inward Return' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 1013)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 12) OR (ISNULL(@rFilterId,  0) = 0))

		
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Issue Return' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		---(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 1012)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 5) OR (ISNULL(@rFilterId,  0) = 0))

	Order by WAC.Id	desc	
END

 




/****** Object:  StoredProcedure [sIp].[pWeightedAverageCostLogGet]    Script Date: 07/09/2013 16:23:45 ******/
SET ANSI_NULLS ON
GO
PRINT N'Altering [sProcurement].[pStockInward]...';


GO
ALTER PROCEDURE [sProcurement].[pStockInward]
	@rOrgGroupId int,
	 
	@rNumber [nvarchar](20) = '',
	@rStoreLocationId int,
	@rFromDate date='',
	@rToDate date='',
	@rVendorId int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
SELECT		SI.Id,
			SI.Number,
			isnull(SI.StockInwardRequestId,0) as StockInwardRequestId,
			isnull(SI.InwardByName,'') as InwardByName,
		  
			 
			SI.CreatedDateTime			AS InwardDate,
			SLM.Code					AS ToStoreLocationCode,
			--ODM.Title					AS ToOrganizationDepartmentCode,
			--ISNULL(FAM.Title,'')        AS FirstAid,
			SIReq.Number				AS RequestNumber,			
			isnull(SIReq.CreatedDateTime,'') AS RequestedDate,
			SI.VendorId
			
FROM		sProcurement.tStockInward SI
INNER JOIN	sIp.tStoreLocationMaster SLM
			ON SLM.Id = SI.ToStoreLocationId 		
LEFT JOIN	sProcurement.tStockInwardRequest SIReq
			ON SIReq.Id = SI.StockInwardRequestId

WHERE		
		((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = '*'))
		AND        SI.OrgGroupId = @rOrgGroupId	
		AND ((SI.CreatedDateTime>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SI.CreatedDateTime<=DateAdd(Day,1,@rToDate)) OR (ISNULL(@rToDate,'')=''))
		AND SI.ToStoreLocationId =@rStoreLocationId
		AND ((SI.VendorId=@rVendorId) or (@rVendorId=0))
		order by SI.Number desc

 
END
GO
PRINT N'Altering [sSecurity].[pMenuGet]...';


GO
ALTER PROCEDURE [sSecurity].[pMenuGet]
	@rUserId [bigint],
	@rMenuId int = 0,
	@rResourceTypeId int= 0 
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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
					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

   --SELECT DISTINCT Menu.Id AS MenuID, 
	--		ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID, 
	--		Menu.Title AS MenuTitle, 
	--		Menu.TitleResourceKeyId AS MenuResourceKey, 
	--		Screen.Title AS ScreenTitle,
	--		Screen.TitleResourceKeyId AS ScreenResourceKey,
	--		Screen.Page AS PageURL
	--FROM sSecurity.tMenu Menu
	--LEFT OUTER JOIN sSecurity.tScreen Screen
	--	ON Menu.ScreenId = Screen.Id
	--LEFT OUTER JOIN sSecurity.tPermission Permission
	--	ON Screen.TaskId = Permission.TaskId
	--WHERE	Menu.IsObsolete = 0 AND
	--		Screen.IsObsolete = 0 AND
	--		Permission.RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE UserId = @rUserId) AND
	--		(Permission.Permission & 2) = 2
	--ORDER BY ParentMenuID
END
	
END
GO
PRINT N'Altering [sSecurity].[pMobileAppTaskGet]...';


GO
ALTER PROCEDURE [sSecurity].[pMobileAppTaskGet]
		@rRoleId bigint,		
		@rOrgGroupId int,
		@rUserId bigint = 0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

    DECLARE @lRoleTitle nvarchar(100)=''
	
	IF(@rUserId=0)
	BEGIN
		SELECT @lRoleTitle = Title FROM sSecurity.tRole WHERE Id=@rRoleId
		IF(@lRoleTitle = 'Student')
		BEGIN
				SELECT  
					T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
				FROM sSecurity.tTask T
					INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
					INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id AND RDM.RoleId =@rRoleId
					INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.Id=T.ResourceTypeId
					INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
					LEFT OUTER JOIN sSecurity.tPermission P ON T.Id = P.TaskId AND (P.RoleId = @rRoleId OR P.RoleId IS NULL)
				WHERE 
				T.IsObsolete = 0 AND T.RoleScopeId IN(0,2)
				ORDER BY T.ModuleId,RTM.Id
		END
		ELSE
		BEGIN
				SELECT  
					T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
				FROM sSecurity.tTask T
					INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
					INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id AND RDM.RoleId =@rRoleId
					INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.Id=T.ResourceTypeId 
					INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
					LEFT OUTER JOIN sSecurity.tPermission P ON T.Id = P.TaskId AND (P.RoleId = @rRoleId OR P.RoleId IS NULL)
				WHERE 
				T.IsObsolete = 0 AND T.RoleScopeId IN(0,1)
				ORDER BY T.ModuleId,RTM.Id
		END
	END
	ELSE
	BEGIN
		
		SELECT @lRoleTitle = Title FROM sSecurity.tRole R
		INNER JOIN sSecurity.tUserRole UR ON R.Id = UR.RoleId 
		WHERE UR.UserId=@rUserId
		
		IF(@lRoleTitle = 'Student')
		BEGIN
				SELECT  
					T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
				FROM sSecurity.tTask T
					INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
					--INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id AND RDM.RoleId =@rRoleId
					INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.Id=T.ResourceTypeId
					INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
					LEFT OUTER JOIN sSecurity.tPermissionUser P ON T.Id = P.TaskId AND (P.UserId = @rUserId OR P.UserId IS NULL)
				WHERE 
				T.IsObsolete = 0 AND T.RoleScopeId IN(0,2)
				ORDER BY T.ModuleId,RTM.Id
		END
		ELSE
		BEGIN
				SELECT  
					T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
				FROM sSecurity.tTask T
					INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
					--INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id AND RDM.RoleId =@rRoleId
					INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.Id=T.ResourceTypeId 
					INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
					LEFT OUTER JOIN sSecurity.tPermissionUser P ON T.Id = P.TaskId AND (P.UserId = @rUserId OR P.UserId IS NULL)
				WHERE 
				T.IsObsolete = 0 AND T.RoleScopeId IN(0,1)
				ORDER BY T.ModuleId,RTM.Id
		END
	END
	
	
	
END
GO
PRINT N'Altering [sSecurity].[pPageTaskPermissionsGet]...';


GO
ALTER PROCEDURE [sSecurity].[pPageTaskPermissionsGet]
	@rUserId [int],
	@rPageURL [nvarchar](50)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
	BEGIN
		SELECT	TP.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 	TaskId,
				UserId,
				(Permission & 1) AS C,
				(Permission & 2)/2 AS R,
				(Permission & 4)/4 AS U,
				(Permission & 8)/8 AS D,
				(Permission & 16)/16 AS S,
				(Permission & 32)/32 AS P,
				(Permission & 64)/64 AS X
		FROM sSecurity.tPermissionUser
		WHERE TaskId IN (SELECT TaskId FROM tScreen WHERE Page = @rPageURL) AND 
			  UserId IN (SELECT UserId FROM sSecurity.tUserRole WHERE UserId = @rUserId)
		) TP
		GROUP BY TP.TaskId
	END
	ELSE
	BEGIN
		SELECT	TP.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 	TaskId,
				RoleId,
				(Permission & 1) AS C,
				(Permission & 2)/2 AS R,
				(Permission & 4)/4 AS U,
				(Permission & 8)/8 AS D,
				(Permission & 16)/16 AS S,
				(Permission & 32)/32 AS P,
				(Permission & 64)/64 AS X
		FROM sSecurity.tPermission
		WHERE TaskId IN (SELECT TaskId FROM tScreen WHERE Page = @rPageURL) AND 
			  RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE UserId = @rUserId)
		) TP
		GROUP BY TP.TaskId
	END
	
	
END
GO
PRINT N'Altering [sSecurity].[pPermissionGet]...';


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

	
IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser 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 
	) 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
	--RoleId 
	
	--IN
	-- (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId )
	) TP 
	GROUP BY TP.TaskId
	
	--SELECT	CAST(MAX(TP.C) AS BIT) AS [Create],
	--		CAST(MAX(TP.R) AS BIT) AS [Read],
	--		CAST(MAX(TP.U) AS BIT) AS [Update],
	--		CAST(MAX(TP.D) AS BIT) AS [Delete],
	--		CAST(MAX(TP.S) AS BIT) AS [Search],
	--		CAST(MAX(TP.P) AS BIT) AS [Print],
	--		CAST(MAX(TP.X) AS BIT) AS [Execute]
	--FROM
	--(
	--	SELECT 	(Permission & 1) AS C,
	--			(Permission & 2)/2 AS R,
	--			(Permission & 4)/4 AS U,
	--			(Permission & 8)/8 AS D,
	--			(Permission & 16)/16 AS S,
	--			(Permission & 32)/32 AS P,
	--			(Permission & 64)/64 AS X
	--	FROM sSecurity.tPermission
	--	WHERE TaskId = @rTaskId AND 
	--		  RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId)
	--) TP
END


END
GO
PRINT N'Altering [sSecurity].[pPermissionModify]...';


GO
ALTER PROCEDURE [sSecurity].[pPermissionModify]
	@rRoleID [bigint] = 0,
	@rXML nvarchar(max),
	@rUpdatedUserId [bigint],
	@rOrgGroupId smallint,
	@rUserId bigint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
DECLARE @loDoc INT

EXEC sp_xml_preparedocument @loDoc OUTPUT, @rXML
BEGIN
	BEGIN TRANSACTION	
	
	IF(@rUserId=0)
	BEGIN 
		UPDATE sSecurity.tPermission
		SET Permission = A.Permission, 
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM
			(
			SELECT TaskID, Permission FROM
			OPENXML (@loDoc, '/Tasks/Task', 2)
			WITH (
				TaskID INT, 
				Permission INT)
			) A
		WHERE	sSecurity.tPermission.TaskId = A.TaskID AND
				sSecurity.tPermission.RoleId = @rRoleID 
			
		INSERT INTO sSecurity.tPermission (TaskId, RoleId, Permission, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsObsolete,OrgGroupId)
		SELECT  A.TaskID, 
				@rRoleID, 
				A.Permission, 
				@rUpdatedUserId, 
				sCommon.fGetDate(), 
				@rUpdatedUserId, 
				sCommon.fGetDate(), 
				0,
				@rOrgGroupId
		FROM(
			SELECT TaskID, Permission FROM
			OPENXML (@loDoc, '/Tasks/Task', 2)
			WITH (
				TaskID SMALLINT, 
				Permission INT)
			) A
		WHERE NOT EXISTS(SELECT TaskId FROM sSecurity.tPermission WHERE TaskId = A.TaskID AND RoleId = @rRoleID)

		DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId AND RoleId = @rRoleID AND Permission = 0
	END
	ELSE
	BEGIN
		UPDATE sSecurity.tPermissionUser
		SET Permission = A.Permission, 
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM
			(
			SELECT TaskID, Permission FROM
			OPENXML (@loDoc, '/Tasks/Task', 2)
			WITH (
				TaskID INT, 
				Permission INT)
			) A
		WHERE	sSecurity.tPermissionUser.TaskId = A.TaskID AND
				sSecurity.tPermissionUser.UserId = @rUserId 
			
		INSERT INTO sSecurity.tPermissionUser (TaskId, UserId, Permission, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, IsObsolete,OrgGroupId)
		SELECT  A.TaskID, 
				@rUserId, 
				A.Permission, 
				@rUpdatedUserId, 
				sCommon.fGetDate(), 
				@rUpdatedUserId, 
				sCommon.fGetDate(), 
				0,
				@rOrgGroupId
		FROM(
			SELECT TaskID, Permission FROM
			OPENXML (@loDoc, '/Tasks/Task', 2)
			WITH (
				TaskID SMALLINT, 
				Permission INT)
			) A
		WHERE NOT EXISTS(SELECT TaskId FROM sSecurity.tPermissionUser WHERE TaskId = A.TaskID AND UserId = @rUserId)

		DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId AND UserId = @rUserId AND Permission = 0
	END
	
	COMMIT TRANSACTION
	
END
EXEC sp_xml_removedocument @loDoc
GO
PRINT N'Altering [sSecurity].[pReportGet]...';


GO
ALTER PROCEDURE [sSecurity].[pReportGet]
	@rUserId [bigint],
	@rReportGroupId [int] 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN


IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
BEGIN
	SELECT
		ISNULL(ReportId,0) AS ReportId,
		ReportTitle,
		ReportGroup,
		OrderIndex,
		OrgGroupId
		
 
	FROM
(SELECT	 
			Report.Id AS ReportId, 			
			Report.Title AS ReportTitle,
			Report.ReportGroup,	 
 			ISNULL(PermissionValue, 0) AS Permission,
 			Report.OrderIndex,
 			Report.OrgGroupId
 			 	 
	FROM sCommon.tReport Report	
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue 
					FROM 
						sSecurity.tPermissionUser p INNER JOIN sSecurity.tTask t ON  p.TaskId = t.Id
					WHERE 
						T.IsObsolete = 0 AND UserId  IN (SELECT UserId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0)
					GROUP BY 
						TaskId  ) TBL2
					ON 
						Report.TaskId = TBL2.TaskId
						--Report.Id = TBL2.TaskId 
						 AND Report.IsObsolete = 0	
						 --AND Report.OrgGroupId IS NULL
						
					 ) 
					ReportTable
	WHERE 
		 ReportTable.Permission >= 2	
		 AND ReportTable.ReportGroup=@rReportGroupId
		 
		
		
	ORDER BY 
		ReportTable.orderindex
END
ELSE
BEGIN
	SELECT
		ISNULL(ReportId,0) AS ReportId,
		ReportTitle,
		ReportGroup,
		OrderIndex,
		OrgGroupId
		
 
	FROM
(SELECT	 
			Report.Id AS ReportId, 			
			Report.Title AS ReportTitle,
			Report.ReportGroup,	 
 			ISNULL(PermissionValue, 0) AS Permission,
 			Report.OrderIndex,
 			Report.OrgGroupId
 			 	 
	FROM sCommon.tReport Report	
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue 
					FROM 
						sSecurity.tPermission p INNER JOIN sSecurity.tTask t ON  p.TaskId = t.Id
					WHERE 
						T.IsObsolete = 0 AND RoleId  IN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0)
					GROUP BY 
						TaskId  ) TBL2
					ON 
						Report.TaskId = TBL2.TaskId
						--Report.Id = TBL2.TaskId 
						 AND Report.IsObsolete = 0	
						 --AND Report.OrgGroupId IS NULL
						
					 ) 
					ReportTable
	WHERE 
		 ReportTable.Permission >= 2	
		 AND ReportTable.ReportGroup=@rReportGroupId
		 
		
		
	ORDER BY 
		ReportTable.orderindex
END



	

END
GO
PRINT N'Altering [sSecurity].[pReportOrgScopeGet]...';


GO
 
ALTER PROCEDURE [sSecurity].[pReportOrgScopeGet]
	
	@rUserId [bigint],
	@rReportGroupId [int],
	@rScopeSourceId smallint,
	@rScopeSourceTypeId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
BEGIN
	SELECT
		ISNULL(ReportId,0) AS ReportId,
		ReportTitle,
		ReportGroup,
		OrderIndex,
		OrgGroupId
	FROM
(SELECT	 
			Report.Id AS ReportId, 			
			Report.Title AS ReportTitle,
			Report.ReportGroup,	 
 			ISNULL(PermissionValue, 0) AS Permission,
 			Report.OrderIndex,
 			Report.OrgGroupId
 			 	 
	FROM sCommon.tReport Report	
	INNER JOIN sCommon.tReportOrg RG ON Report.Id = RG.ReportId AND (RG.ScopeSourceId=@rScopeSourceId) AND (RG.ScopeSourceTypeId=@rScopeSourceTypeId)
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue 
					FROM 
						sSecurity.tPermissionUser p INNER JOIN sSecurity.tTask t ON  p.TaskId = t.Id
					WHERE 
						T.IsObsolete = 0 AND UserId  IN (SELECT UserId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0)
					GROUP BY 
						TaskId  ) TBL2
					ON 
						Report.TaskId = TBL2.TaskId
						 AND Report.IsObsolete = 0	
					 ) 
					ReportTable
	WHERE 
		 ReportTable.Permission >= 2	
		 AND ReportTable.ReportGroup=@rReportGroupId
	ORDER BY 
		ReportTable.orderindex
END
ELSE
BEGIN
	SELECT
		ISNULL(ReportId,0) AS ReportId,
		ReportTitle,
		ReportGroup,
		OrderIndex,
		OrgGroupId
	FROM
(SELECT	 
			Report.Id AS ReportId, 			
			Report.Title AS ReportTitle,
			Report.ReportGroup,	 
 			ISNULL(PermissionValue, 0) AS Permission,
 			Report.OrderIndex,
 			Report.OrgGroupId
 			 	 
	FROM sCommon.tReport Report	
	INNER JOIN sCommon.tReportOrg RG ON Report.Id = RG.ReportId AND (RG.ScopeSourceId=@rScopeSourceId) AND (RG.ScopeSourceTypeId=@rScopeSourceTypeId)
	LEFT OUTER JOIN ( 
					SELECT 
						TaskId, 
						SUM(Permission & 2) PermissionValue 
					FROM 
						sSecurity.tPermission p INNER JOIN sSecurity.tTask t ON  p.TaskId = t.Id
					WHERE 
						T.IsObsolete = 0 AND RoleId  IN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0)
					GROUP BY 
						TaskId  ) TBL2
					ON 
						Report.TaskId = TBL2.TaskId
						 AND Report.IsObsolete = 0	
					 ) 
					ReportTable
	WHERE 
		 ReportTable.Permission >= 2	
		 AND ReportTable.ReportGroup=@rReportGroupId
	ORDER BY 
		ReportTable.orderindex
END

	

END
GO
PRINT N'Altering [sSecurity].[pRoleModulePermissionGet]...';


GO
ALTER PROCEDURE [sSecurity].[pRoleModulePermissionGet]
	  
	 @rOrgGroupId smallint,
	 @rRoleId int 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	DECLARE @lDefaultRoleId int=0
	DECLARE @lModuleId int=0
	
	SET @lDefaultRoleId = RIGHT(@rRoleId, 2)
	
	-- Employee
	IF(@lDefaultRoleId = 10) SET @lModuleId = 233
	
	-- Student
	IF(@lDefaultRoleId = 22) SET @lModuleId = 234
	
	SELECT 
		MP.ModuleId,
		MM.Title AS ModuleName,
		MP.OrgGroupId,
		CASE WHEN RDM.ModuleId IS NULL THEN Convert(bit,0) ELSE Convert(bit,1) END AS IsChecked
	FROM 
		sSecurity.tModulePermission MP
		INNER JOIN  sCommon.tModuleMaster MM ON MP.ModuleId=MM.Id AND MM.Id!=@lModuleId
		LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId
  WHERE 
		MP.OrgGroupId =@rOrgGroupId
END
GO
PRINT N'Altering [sSecurity].[pTaskGet]...';


GO
ALTER PROCEDURE [sSecurity].[pTaskGet]
	@rModuleID [smallint],
	@rRoleID [bigint],		
	@rResourceTypeId smallint,
	@rOrgGroupId int,
	@rUserId bigint=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

IF(@rUserId=0)
BEGIN
		SELECT  T.Id,
				T.Title,
				MM.Title AS ModuleName,
				RTM.Title AS ResourceTypeName, 			
				CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
				CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
				CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
				CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
				CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
				CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
				CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
				CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
				CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
				CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
				CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
				CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
				CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
				CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM sSecurity.tTask T
		INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
		INNER JOIN sSecurity.tResourceTypeMaster RTM
		ON RTM.Id=T.ResourceTypeId
		INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
		LEFT OUTER JOIN sSecurity.tPermission P
			ON T.Id = P.TaskId AND (P.RoleId = @rRoleID OR P.RoleId IS NULL)
		INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId	
		WHERE	((T.ModuleId = @rModuleID) OR (@rModuleID = 0)) AND
				T.IsObsolete = 0 
				AND ((T.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
				ORDER BY T.ModuleId,RTM.Id
END
ELSE
BEGIN
	
		SELECT  T.Id,
				T.Title,
				MM.Title AS ModuleName,
				RTM.Title AS ResourceTypeName, 			
				CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
				CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
				CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
				CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
				CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
				CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
				CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
				CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
				CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
				CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
				CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
				CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
				CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
				CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM sSecurity.tTask T
		INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
		INNER JOIN sSecurity.tResourceTypeMaster RTM
		ON RTM.Id=T.ResourceTypeId
		INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
		LEFT OUTER JOIN sSecurity.tPermissionUser P
			ON T.Id = P.TaskId AND (P.UserId = @rUserId OR P.UserId IS NULL)
		WHERE	((T.ModuleId = @rModuleID) OR (@rModuleID = 0)) AND
				T.IsObsolete = 0 
				AND ((T.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
				ORDER BY T.ModuleId,RTM.Id
		END
END
GO
PRINT N'Altering [sSetup].[pOrganizationMasterAdd]...';


GO
ALTER PROCEDURE [sSetup].[pOrganizationMasterAdd]
	 
	@rId int,
	@rCode nvarchar(20),
	@rTitle nvarchar(100),
	@rDisplayTitle nvarchar(100),
	@rAffiliationId smallint,
	@rLanguageId smallint,
	--@rInstituteTypeId smallint,
	--@rInstituteSubTypeId smallint,
	@rStreetOne nvarchar(50),
	@rStreetTwo nvarchar(50),
	@rStreetThree nvarchar(50),
	@rCityName nvarchar(100),
	@rStateName nvarchar(100),
	@rCountryName nvarchar(100),
	@rZipCode nvarchar(20),
	@rHomePage nvarchar(100),
	@rPhoneNo nvarchar(50),
	@rFaxNo nvarchar(50),
	@rReportOrgTitle nvarchar(200),
	@rSmallAddress1 nvarchar(100),
	@rSmallAddress2 nvarchar(100),
	@rRegistrationDetail nvarchar(200),
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rIsObsolete bit,
	@rOrgGroupId smallint,
	@rOrgLogo varbinary(max),
	@rIsLogo bit,
	@rEmployeeId bigint,
	@rOrderIndex int,
	--@rIcardOrgTitle nvarchar(200),
	--@rIcardAddress1 nvarchar(200),
	--@rIcardAddress2 nvarchar(200),
	--@rICardAddress3 nvarchar(200),
	--@rLabelColor nvarchar(20),
	--@rDetailColor nvarchar(20),
	--@rHeaderColor nvarchar(20),
	@rOrgSubGroupId int=0,
	@rTermPatternId int=0,
	@rNameFormateId tinyint = 1,
	@rWeekOffs nvarchar(20),
	@rReportOrgGroupTitle nvarchar(200)='',
	@rDegreeAwarded nvarchar(100) = '',
	@rShortCode nvarchar(20) = '',
	@rNoOfTerm tinyint=0,
	@rHeadMargin int=0,
	@rUniversity nvarchar(100)='',
	@rFooterSignature nvarchar(500)='',
	@rEmail nvarchar(150) = null,
	@rTaxOfficeDetail nvarchar(500) = null,
	@rTANNumber nvarchar(40) = null,
	@rPANNumber nvarchar(40)=null,
	@rTaxCertifyAuthorityName        nvarchar(100)=null,
	@rTaxCertifyAuthorityFatherName  nvarchar(100)=null,
	@rTaxCertifyAuthorityRelation    nvarchar(100)=null,
	@rTaxCertifyAuthorityDesignation nvarchar(100)=null,
	@rOrgTypeCaption nvarchar(100)='',
	@rAccountNumber nvarchar(50)='',
	@rGSTINNo nvarchar(50)='',
	@rHSNSACCode nvarchar(15)=''
	
	
	
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF EXISTS (SELECT 1 FROM sSetup.tOrganizationMaster WHERE @rId = 0 AND Code=@rCode)
	BEGIN
		SELECT -100 AS RESULT
		RETURN
	END

	BEGIN TRY
	
	BEGIN TRANSACTION	
	
	
	IF(@rId=0)
	BEGIN
	SET @rId=@rCode
		 
	INSERT INTO sSetup.tOrganizationMaster
		(
			Id,
			Code,
			Title,
			DisplayTitle,
			AffiliationId,
			LanguageId,
			--InstituteTypeId,
			--InstituteSubTypeId,
			StreetOne,
			StreetTwo,
			StreetThree,
			CityName,
			StateName,
			CountryName,
			ZipCode,
			HomePage,
			PhoneNo,
			FaxNo,
			ReportOrgTitle,
			SmallAddress1,
			SmallAddress2,
			RegistrationDetail,
			CreatedUserId,
			CreatedDateTime,
			IsObsolete,
			OrgGroupId,
			EmployeeId,
			OrderIndex,
			--,
			--IcardOrgTitle,
		



	--IcardAddress1,
			--IcardAddress2,
			--ICardAddress3,
			--LabelColor,
			--DetailColor,
			--HeaderColor,
			OrgSubGroupId,
			TermPatternId,
			StudentNameFormatId,
			WeekOffs,
			ReportOrgGroupTitle,
			DegreeAwarded,
			ShortCode,
			NoOfTerm,
			LetterHeadMargin,
			University,
			FooterSignature,
			Email,
			OrgTypeCaption
			--OrgLogo
		)
	VALUES
		(
			@rCode,
			@rCode,
			@rTitle,
			@rDisplayTitle,
			@rAffiliationId,
			@rLanguageId,
			--@rInstituteTypeId,
			--@rInstituteSubTypeId,
			@rStreetOne,
			@rStreetTwo,
			@rStreetThree,
			@rCityName,
			@rStateName,
			@rCountryName,
			@rZipCode,
			@rHomePage,
			@rPhoneNo,
			@rFaxNo,
			--@rReportOrgTitle,
			@rTitle,
			@rSmallAddress1,
			@rSmallAddress2,
			@rRegistrationDetail,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rIsObsolete,
			@rOrgGroupId,
			@rEmployeeId,
			@rOrderIndex,
			--,
			--@rIcardOrgTitle,
			--@rIcardAddress1,
			--@rIcardAddress2,
			--@rIcardAddress3,
			--@rLabelColor,
			--@rDetailColor,
			--@rHeaderColor,
			@rOrgSubGroupId,
			@rTermPatternId,
			1,
			ISNULL(@rWeekOffs,'0'),
			@rReportOrgGroupTitle,
			@rDegreeAwarded,
			@rShortCode,
			@rNoOfTerm,
			@rHeadMargin,
			@rUniversity,
			@rFooterSignature,
			@rEmail,
			@rOrgTypeCaption
			--@rOrgLogo
		)
		 EXECUTE [sCommon].[pOrganizationSetupAdd] @rId
		 --print @rId
		 
		 
		 DECLARE @lIsCommonToAll bit = 0
	     DECLARE @lConfigValue nvarchar(50)
	     SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 139 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	     
	     IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
			SET @lIsCommonToAll = 0
		 ELSE
			SET @lIsCommonToAll = 1
		 
		 -- For SMS Configuration
		 
		 DECLARE @lCountSMS int=0, @lOrgIdSMS int
		 
		 SELECT @lCountSMS = COUNT(OrgId) FROM sAlert.tSMSConfiguration
		 
		 IF(@lCountSMS!=0 AND @lIsCommonToAll = 1)
		 BEGIN
			SELECT TOP 1 @lOrgIdSMS = OrgId FROM sAlert.tSMSConfiguration
			
			INSERT INTO sAlert.tSMSConfiguration
			SELECT 
				@rCode,
				SMSURL,
				SMSCreditURL,
				LoginId,
				LoginPassword,
				LoginSenderId,
				SMSXMLURL,
				VendorId,
				SMSUnicodeURL
			FROM sAlert.tSMSConfiguration SMS
			INNER JOIN sSetup.tOrganizationMaster OM ON SMS.OrgId = OM.Id
			WHERE OrgId = @lOrgIdSMS AND OM.OrgGroupId = @rOrgGroupId
			
		 END
		 
		 -- For Email Configuration
		 
		 DECLARE @lCountEmail int=0, @lOrgIdEmail int
		 SELECT @lCountEmail = COUNT(OrgId) FROM sAlert.tEmailConfiguration
		 
		 IF(@lCountEmail!=0 AND @lIsCommonToAll = 1)
		 BEGIN
			SELECT TOP 1 @lOrgIdEmail = OrgId FROM sAlert.tEmailConfiguration
			
			INSERT INTO sAlert.tEmailConfiguration
			SELECT 
				@rCode,
				MailTypeId,
				SMTPServer,
				SMTPPort,
				EnableSSL,
				SendUserName,
				SendPassword,
				FromMail
			FROM sAlert.tEmailConfiguration Email
			INNER JOIN sSetup.tOrganizationMaster OM ON Email.OrgId = OM.Id
			WHERE OrgId = @lOrgIdEmail AND OM.OrgGroupId = @rOrgGroupId
		 END
		
		 
		 SELECT @rCode AS Result
		             
	END	 
	 ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	    UPDATE  sSetup.tOrganizationMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			DisplayTitle=@rDisplayTitle,
			AffiliationId=@rAffiliationId,
			LanguageId=@rLanguageId,
			--InstituteTypeId=@rInstituteTypeId,
			--InstituteSubTypeId=@rInstituteSubTypeId,
			StreetOne=@rStreetOne,
			StreetTwo=@rStreetTwo,
			StreetThree=@rStreetThree,
			CityName=@rCityName,
			StateName=@rStateName,
			CountryName=@rCountryName,
			ZipCode=@rZipCode,
			HomePage=@rHomePage,
			PhoneNo=@rPhoneNo,
			FaxNo=@rFaxNo,
			ReportOrgTitle=@rReportOrgTitle,
			SmallAddress1=@rSmallAddress1,
			SmallAddress2=@rSmallAddress2,
			RegistrationDetail=@rRegistrationDetail,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate(), 
			IsObsolete=@rIsObsolete,
			OrgGroupId=@rOrgGroupId,
			EmployeeId=@rEmployeeId,
			OrderIndex=@rOrderIndex,	 
			--IcardOrgTitle=@rIcardOrgTitle,
			--IcardAddress1=@rIcardAddress1,
			--IcardAddress2=@rIcardAddress2,
			--IcardAddress3=@rIcardAddress3,
			--LabelColor=@rLabelColor,
			--DetailColor=@rDetailColor,
			--HeaderColor=@rHeaderColor,
			OrgSubGroupId=@rOrgSubGroupId,
			TermPatternId=@rTermPatternId,
			StudentNameFormatId= @rNameFormateId,
			WeekOffs=@rWeekOffs,
			ReportOrgGroupTitle=@rReportOrgGroupTitle,
			DegreeAwarded=@rDegreeAwarded,
			ShortCode =@rShortCode,
			NoOfTerm = @rNoOfTerm,
			LetterHeadMargin = @rHeadMargin,
			University = @rUniversity,
			Footersignature= @rFooterSignature,
			Email=@rEmail,
			OrgTypeCaption=@rOrgTypeCaption
			--OrgLogo=@rOrgLogo
	      
	      
	      WHERE Id = @rId 
	      
		  UPDATE  sHrm.tEmployeeJobDetail  SET EmployeeBusinessHeadId=@rEmployeeId  where OrgId=@rId

		  IF NOT EXISTS (SELECT 1 FROM sSetup.tOrganizationOtherDetail WHERE OrgId = @rId )
			  BEGIN
				INSERT INTO sSetup.tOrganizationOtherDetail  (OrgId,PANNumber,TANNumber,TaxOfficeDetail,TaxCertifyAuthorityName,TaxCertifyAuthorityFatherName,TaxCertifyAuthorityRelation,TaxCertifyAuthorityDesignation,AccountNumber,GSTINNo,HSNSACCode)
				VALUES (@rId,@rPANNumber,@rTANNumber,@rTaxOfficeDetail,@rTaxCertifyAuthorityName,@rTaxCertifyAuthorityFatherName,@rTaxCertifyAuthorityRelation,@rTaxCertifyAuthorityDesignation,@rAccountNumber,@rGSTINNo,@rHSNSACCode)
			  END
		 ELSE 
		 BEGIN
			 UPDATE sSetup.tOrganizationOtherDetail SET TaxOfficeDetail=@rTaxOfficeDetail,
				TANNumber=@rTANNumber,
				PANNumber=@rPANNumber,
				TaxCertifyAuthorityName=@rTaxCertifyAuthorityName,
				TaxCertifyAuthorityFatherName=@rTaxCertifyAuthorityFatherName,
				TaxCertifyAuthorityRelation=@rTaxCertifyAuthorityRelation,
				TaxCertifyAuthorityDesignation=@rTaxCertifyAuthorityDesignation,
				AccountNumber=@rAccountNumber,
				GSTINNo=@rGSTINNo,
				HSNSACCode=@rHSNSACCode
			 Where OrgId=@rId
		 END



		  



	      IF(@rIsLogo = 1)
	      BEGIN
			UPDATE  sSetup.tOrganizationMaster
				SET
					OrgLogo=@rOrgLogo
			WHERE Id = @rId 
	      END
	      
	      SELECT @rId AS Result	   
	 END  
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pOrganizationMasterGet]...';


GO
ALTER PROCEDURE [sSetup].[pOrganizationMasterGet]
	 
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rOrgGroupId smallint,
	 @rIsSearch bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF(@rIsSearch=1)
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	 
	SELECT 
	
			OM.Id,
			OM.Code,
			OM.Title,
			OM.DisplayTitle,
			OM.AffiliationId,
			AM.Title AS AffiliationTitle,
			OM.LanguageId,
			LM.Title AS LanguageTitle,
			--OM.InstituteTypeId,
			--ITM.Title AS InstituteTypeTitle,
			--OM.InstituteSubTypeId,
			--ISTM.Title AS InstituteSubTypeTitle,
			OM.StreetOne,
			OM.StreetTwo,			 
			OM.StreetThree,
			OM.CityName,
			OM.StateName,
			OM.CountryName,
			OM.ZipCode,
			OM.HomePage,
			OM.PhoneNo,
			OM.FaxNo,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,			 
			OM.CreatedUserId,
			OM.CreatedDateTime,
			OM.UpdatedUserId,
			OM.UpdatedDateTime,
			OM.IsObsolete,
			OM.OrgGroupId,
			OM.OrgLogo,
			ISNULL(OM.WeekOffs,0) AS WeekOffs ,
			--OM.IcardOrgTitle,
			--OM.IcardAddress1,
			--OM.ICardAddress2,
			--OM.ICardAddress3,
			--OM.LabelColor,
			--OM.DetailColor,
			--OM.HeaderColor,
			ISNULL(OM.OrgSubGroupId,0) AS OrgSubGroupId, 
			--OB.Code AS BatchName,
			--OB.FromDate,
			--OB.ToDate,
			ISNULL(OM.EmployeeId,0) AS EmployeeId,
		    ISNULL(EM.Code,'') AS EmployeeCode,
		    ISNULL(EM.FirstName,'')+ ' ' + ISNULL(EM.MiddleName,'')+ ' ' + ISNULL(EM.LastName,'') AS EmployeeName,
			ISNULL(OM.OrderIndex,0) AS OrderIndex,
			ISNULL(OM.TermPatternId,0) AS TermPatternId,
			ISNULL(OM.StudentNameFormatId,0) AS NameFormateId,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			ISNULL(OM.ShortCode,'') AS ShortCode,
			ISNULL(OM.NoOfTerm,'') AS NoOfTerm,
			ISNULL(OM.LetterHeadMargin,0) AS LetterHeadMargin,
			ISNULL(OM.University,'') AS University,
			ISNULL(OM.FooterSignature,'') AS FooterSignature,
			ISNULL(om.Email,'') AS  Email,
			ISNULL(OOD.TaxOfficeDetail,'') AS TaxOfficeDetail,
			ISNULL(OOD.TANNumber,'')TANNumber,
			ISNULL(OOD.PANNumber,'')PANNumber,
			ISNULL(OOD.TaxCertifyAuthorityName,'')TaxCertifyAuthorityName,
			ISNULL(OOD.TaxCertifyAuthorityFatherName,'')TaxCertifyAuthorityFatherName,
			ISNULL(OOD.TaxCertifyAuthorityRelation,'')TaxCertifyAuthorityRelation,
			ISNULL(OOD.TaxCertifyAuthorityDesignation,'')TaxCertifyAuthorityDesignation,
			ISNULL(OM.OrgTypeCaption,'') AS  OrgTypeCaption,
			ISNULL(OOD.AccountNumber,'') As AccountNumber,
			ISNULL(OOD.GSTINNo,'') As GSTINNo,
			ISNULL(OOD.HSNSACCode,'') As HSNSACCode


      
  FROM 
            sSetup.tOrganizationMaster OM
           INNER JOIN sSetup.tAffiliationMaster AM
				ON AM.Id=OM.AffiliationId
		  -- INNER JOIN sSetup.tInstituteTypeMaster ITM
				--ON ITM.Id=OM.InstituteTypeId
		  -- INNER JOIN sSetup.tInstituteSubTypeMaster ISTM
				--ON ISTM.Id=OM.InstituteSubTypeId
		   INNER JOIN sSetup.tLanguageMaster LM
				ON LM.Id=OM.LanguageId
		  -- INNER JOIN sSetup.tOrgGroupBatchMaster OB 
				--ON OB.OrgGroupId=OM.OrgGroupId 
		   LEFT JOIN sHrm.tEmployeeMaster EM 
				ON EM.Id = OM.EmployeeId AND EM.IsObsolete = 0
			LEFT JOIN sSetup.tOrganizationOtherDetail AS OOD on OOD.OrgId=OM.id
  WHERE 
  
        ((OM.Id = @rId) OR (@rId = 0))
	AND ((OM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((OM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
	AND (OM.Id != 1)
 ORDER BY OM.OrderIndex
END
GO
PRINT N'Altering [sSetup].[pReportInfoGet]...';


GO


ALTER PROCEDURE [sSetup].[pReportInfoGet]

	@rReportId [int] = 0,	
	@rOrgId [smallint] = 0,
	@rUserId [bigint] = 0 ,
	@rUserTitle nvarchar(100) = '',
	@rScopeId [int] = 0,
	@rStoreLocationId [int] = 0 
	
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

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

Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId

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


SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 181 AND SourceTypeId = 1016 AND SourceId = @rOrgId
 
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF(@lConfigValue = 'Image')
	BEGIN
	SET @lIsDisplayImageHeader = 1
	END
	ELSE IF(@lConfigValue = 'Compact')
	BEGIN
	SET @lIsCompact = 1
	END
 --  SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 176 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1
	
IF @rScopeId = 3
	BEGIN
	SELECT 
	
			OM.ID AS OrgId,
			OM.Code AS OrgCode,
			OM.ReportOrgTitle,
			OM.SmallAddress1 AS ReportAddress1,
			OM.SmallAddress2 AS ReportAddress2,			
			OM.OrgLogo AS ReportOrgLogo,
			(SELECT Title FROM sCommon.tReport WHERE Id = @rReportId) AS ReportTitle,
			@rUserId AS PrintedByUserId,
			@rUserTitle AS PrintedByUserDisplayTitle,
			LM.Title AS LanguageTitle,
			OM.PrincipalSignature,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.RegistrationDetail,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			(CASE @lIsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4
			ELSE NULL END ) AS CertificateHeaderA4,
			@lIsCompact AS Compact,
			REPLICATE(',',OM.LetterHeadMargin) AS LetterHeadMargin,
			@lIDConfigValue AS ItemValue 
				--RC.DetailBackgroundColor,	 
			--RC.Group1BackgroundColor,
			--RC.Group2BackgroundColor,
			--RC.Group3BackgroundColor,
			--RC.Group4BackgroundColor,
			--CC.ShortDatePattern,
			--CC.ShortTimePattern,
		 --   CC.LongDatePattern,
		 --   CC.LongTimePattern,
		 --   CC.NumberGroupSeparator,
		 --   CC.NumberNegativePattern,
		 --   CC.NumberGroupSizes      
  FROM 
		   sSetup.tOrganizationMaster OM    
		   INNER JOIN sSetup.tLanguageMaster LM ON LM.Id = OM.LanguageId  
		   LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id          
  WHERE  
       OM.Id = @rOrgId 
 
  order by OM.OrderIndex
END
ELSE
BEGIN
	SELECT 
	
			OM.ID AS OrgId,
			OM.Code AS OrgCode,
			OM.ReportOrgTitle,
			OM.SmallAddress1 AS ReportAddress1,
			OM.SmallAddress2 AS ReportAddress2,			
			OM.OrgLogo AS ReportOrgLogo,		
			(SELECT Title FROM sCommon.tReport WHERE Id = @rReportId) AS ReportTitle,
			@rUserId AS PrintedByUserId,
			@rUserTitle AS PrintedByUserDisplayTitle,
			LM.Title AS LanguageTitle,
			OM.PrincipalSignature,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.RegistrationDetail,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			(CASE @lIsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4
			ELSE NULL END ) AS CertificateHeaderA4,
			@lIsCompact AS Compact,
			REPLICATE(',',OM.LetterHeadMargin) AS LetterHeadMargin,
			@lIDConfigValue AS ItemValue 
				--RC.DetailBackgroundColor,	 
			--RC.Group1BackgroundColor,
			--RC.Group2BackgroundColor,
			--RC.Group3BackgroundColor,
			--RC.Group4BackgroundColor,
			--CC.ShortDatePattern,
			--CC.ShortTimePattern,
		 --   CC.LongDatePattern,
		 --   CC.LongTimePattern,
		 --   CC.NumberGroupSeparator,
		 --   CC.NumberNegativePattern,
		 --   CC.NumberGroupSizes      
  FROM 
		   sSetup.tOrganizationMaster OM 
		   INNER JOIN sSetup.tLanguageMaster LM ON LM.Id = OM.LanguageId 
		   LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id         
  WHERE  
       OM.Id = @rOrgId 
 
  order by OM.OrderIndex

END
END
GO
PRINT N'Altering [sStudent].[pChangeBatchStatusGet]...';


GO
ALTER PROCEDURE [sStudent].[pChangeBatchStatusGet]
	 @rAcademicId bigint = 0,
	 @rStatus smallint=0 , 
	  @rBatchId int=0,
	  @rOrgId int=0,
	  @rDepartmentId int=0,
	  @rClassId int=0,
	  @rDivisionId int=0,
	  @rOrgGroupId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
	SELECT 
		SBS.AcademicId,
		SBS.BatchStatusId,
		SBS.Remark,
		SM.FIrstName + ' ' + SM.LastName As Name,
		BSM.Title AS BatchStatus,
		ISNULL(SBS.StatusDate,'') AS StatusDate,
		A.RollNo,
		A.Code,
		A.ClassName,
		A.DivisionName,
		A.DivisionId,
		A.BatchId,
		A.ClassId,
		A.OrgId,
		A.DepartmentId,
		OM.DisplayTitle AS Organization,
		Dm.Title AS Department,
		BM.Title AS Batch
		
		
			 
			
			
  FROM 
           sStudent.tStudentBatchStatus SBS
           INNER JOIN sStudent.vStudentFull A ON A.AcademicId = SBS.AcademicId 
            
           INNER JOIN sStudent.tStudentMaster Sm On Sm.Id = A.StudentId	
           
           INNER JOIN sStudent.tBatchStatusMaster BSM ON BSM.Id =SBS.BatchStatusId
           INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
           INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
           INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = A.DepartmentId
  WHERE 
		((SBS.AcademicId = @rAcademicId) OR (@rAcademicId =0))
		AND((SBS.BatchStatusId=@rStatus) OR (@rStatus=0)) 
		AND ((A.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((A.BatchId = @rBatchId) OR (@rbatchId=0))
		AND ((A.DepartmentId = @rDepartmentId) or (@rDepartmentId=0))
		AND((A.ClassId = @rClassId) OR (@rClassId =0))
		AND ((A.DivisionId =@rDivisionId) OR (@rDivisionId=0))
		AND OM.OrgGroupId= @rOrgGroupId
END
GO
PRINT N'Altering [sStudent].[pRptAddressLabelGet]...';


GO


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

BEGIN 

	SELECT 
			 
			SD.AcademicId,
			SD.StudentId,			
			SD.Code,
			SD.Number AS StudentNumber,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,	
			SD.ClassName,
			SD.DivisionId,
			SD.DivisionName,
			SD.DivisionOrder,
			SD.StatusName,
			SD.StatusId,			
			SI.StudentPhoto,			 			
			OM.Title AS OrgName,		
			BM.Title AS Batch,				
			CD.PresentStreetOne AS Address1,
			CD.PresentStreetTwo AS Address2,
			CD.PresentStreetThree AS Address3,
			CD.PresentCountry AS AddressCountry,
			CD.PresentState AS AddressState,
			CD.PresentCity AS AddressCity,
			CD.PresentZipCode AS AddressZipCode,
			CD.PresentContactNo AS ContactNo,
			CD.ParentContactNo ,
			CD.StudentContactNo,
			CD.ParentEmail,
			CD.StudentEmail
			
			
	FROM 
			sStudent.vStudentAcademic SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			INNER JOIN sStudent.tStudentCommunication CD ON SD.StudentId = CD.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SD.StudentId = SI.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON SD.BatchId = BM.Id 
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassId and BC.BatchId= @rBatchId
			--LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
	WHERE 
			SD.OrgId=@rOrgId
		AND	SD.BatchId = @rBatchId 
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		 
END
GO
PRINT N'Altering [sStudent].[pRptCountCategorywiseStudentGet]...';


GO
 

 
ALTER PROCEDURE [sStudent].[pRptCountCategorywiseStudentGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAsOnDate date,
	 @rReportId int,
	 @rDepartmentId int,
	 @rStudentCode varchar(20),
	 @rCasteCategoryIds nvarchar(max) = '',
	 @rReligionIds nvarchar(max) = '',
	 @rGenderIds nvarchar(max) = '',
	 @rAdmissionCatgoryIds nvarchar(max) = '',
	 @rClassGroup bit=0,
	 @rDivisionGroup bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
  
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(GM.Title,'') As Gender,
			A.ClassId,
			A.DivisionId,
			A.Id AS AcademicId,
			A.RollNo,
			SO.DateOfBirth,
			SA.AdmissionDate,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassDivision,
			SM.FirstName +' '+ SM.MiddleName +' '+ SM.LastName AS Name,
			SM.Code,
			CASE WHEN  @rReportId=10135 OR @rReportId=20702-- Caste Category
			THEN ISNULL(CCM.Title,'') 
		    WHEN  @rReportId=10136 OR @rReportId=20703 -- Religion
			THEN ISNULL(RM.Title,'') 
			WHEN  @rReportId=20704 -- Gender
			THEN ISNULL(GM.Title,'') 
			WHEN @rReportId=20328 OR @rReportId=20705 -- Admission Catgory 
			THEN ISNULL(SCM.Title,'')
			WHEN  @rReportId=10152 -- BloodGroupwise Summary
			THEN ISNULL(BGM.Title,'') 
			WHEN  @rReportId=20329 OR @rReportId=20706--Agegroupwise
			THEN  ([sStudent].[fStudentAgeGroupGet](SO.DateOfBirth,@rAsOnDate,@rOrgId))
			--WHEN  @rReportId=20426 OR @rReportId=20707  --Age wise
			--THEN  ([sStudent].[fStudentAgeGet](SO.DateOfBirth,@rAsOnDate,@rOrgId) + ' Y')
			WHEN    @rReportId = 20866 OR @rReportId=20426 OR @rReportId=20707
			
			THEN RIGHT('00'+ CAST([sStudent].[fStudentAgeGet](SO.DateOfBirth,@rAsOnDate,@rOrgId) AS VARCHAR(2)), 2)+' Year '
			
			WHen @rReportId=30236
			THEN
				ISNULL(HM.Title,'')
			
			END AS Head,
			DM.OrderIndex AS DivisionOrder,
			@rClassGroup As ClassGroup,
			@rDivisionGroup As DivisionGroup,
			Cm.OrderINdex AS ClassOrderIndex  
			FROM 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			LEFT JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=SM.AdmissionCategoryId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseID
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
	WHERE 
		A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND SM.StatusId = 1
		AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	    AND (ISNULL(CCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rCasteCategoryIds,','))OR @rCasteCategoryIds='')
	    AND (ISNULL(RM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionIds,','))OR @rReligionIds='')
	    AND (ISNULL(GM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderIds,','))OR @rGenderIds='')
	    AND (ISNULL(SCM.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCatgoryIds,','))OR @rAdmissionCatgoryIds='')
	    AND SA.AdmissionDate<=@rAsOnDate
END

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


GO


ALTER PROCEDURE [sStudent].[pRptGenderwiseStudentStrengthGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromDate date='',
	 @rToDate date='',
	 @rReportId int=0,
	 @rDepartmentId int,
	 @rOrgGroupBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			Dept.Id AS DepartmentId,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId			 
			WHERE SA.AdmissionDate >= @rFromDate AND SA.AdmissionDate <= @rToDate 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=2 
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId 
			)AS NewGirls,

			(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId			 
			WHERE SA.AdmissionDate >= @rFromDate AND SA.AdmissionDate <= @rToDate
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=1 
			AND CM.DepartmentId=Dept.Id	AND A.BatchId = @rBatchId 
			) AS NewBoys,

			(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 
			WHERE SA.LeftDate >= @rFromDate AND SA.LeftDate <= @rToDate
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=2 
			AND CM.DepartmentId=Dept.Id AND A.BatchId = @rBatchId 
			) AS LeftGirls,

			(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 
			WHERE SA.LeftDate >= @rFromDate AND SA.LeftDate <= @rToDate
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=1 
			AND CM.DepartmentId=Dept.Id AND A.BatchId = @rBatchId 
			) AS LeftBoys,

			(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId 
			WHERE SA.AdmissionDate < @rFromDate 
			AND (SA.LeftDate > @rFromDate OR ISNULL(SA.LeftDate,'')= '')
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=2 
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId 
			) AS TotalGirls,
			
			(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			WHERE SA.AdmissionDate < @rFromDate 
			AND ( SA.LeftDate > @rFromDate OR ISNULL(SA.LeftDate,'')= '')
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND GM.Id=1 
			AND CM.DepartmentId = Dept.Id AND A.BatchId = @rBatchId 
			) AS TotalBoys,	

			Dept.Title AS DepartmentName,
			CM.Id AS ClassId,
			CM.Title AS ClassName,
			DM.Id AS DivId,
			DM.Title AS DivisionName
			
			FROM 
			 
			sSetup.tDivisionMaster DM  	 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
	WHERE 
		DM.OrgId=@rOrgId		
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
END


 

--select AD.* from sStudent.tStudentMaster SM INNER JOIN sStudent.tAcademic A
--ON A.StudentId = SM.Id 
--INNER JOIN sStudent.tStudentAdmission AD ON SM.Id = Ad.StudentId 
--WHERE A.divisionId = 100100028
GO
PRINT N'Altering [sStudent].[pRptincopleteFieldGet]...';


GO

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

BEGIN 

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.AcademicId,
		SA.StudentId, 
		SA.ClassId,
		SA.DivisionId,
		SA.Code,
		SA.RollNo AS RollNo,
		SA.Name,		
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		--M.FieldName,
		--M.Id AS MandatoryFeildId,
		SA.MiddleName AS FatherName,
		ISNULL(SA.Religion,'') AS Religion,
		ISNULL(SA.BloodGroup,'') AS BloodGroup,
		ISNULL(SA.BirthPlace,'') AS BirthPlace,	
		ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
		SA.BirthState,
		SA.BirthCountry,
		ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
		ISNULL(SA.FamilyCast,'') AS FamilyCast,
		ISNULL(SA.FamilySubCast,'') AS FamilySubCast,
		ISNULL(SA.Nationality,'') AS Nationality,
		ISNULL(CT.Title,'') AS CasteCategory,
		ISNULL(HM.Title,'-') AS House,
		ISNULL(SF.MotherName,'') AS MotherName,
		SO.ReferenceRemark,
		ISNULL(SA.ParentEmail,'') AS ParentEmail,
		ISNULL(SA.ParentContactNo,'') As ParentContactNo,
		ISNULL(SA.StudentEmail,'') AS StudentEmail,
		ISNULL(SA.StudentContactNo,'') AS StudentContactNo,
		ISNULL(SA.PresentStreetone,'') AS LocalAddress1,
		ISNULL(SA.PresentStreetTwo,'') AS LocalAddress2,
		ISNULL(SA.PresentStreetThree,'') AS LocalAddress3,
		ISNULL(SA.PresentCity,'') AS PresentCity,
		ISNULL(SA.PresentState,'') AS PresentState,
		ISNULL(SA.PresentCountry,'') AS PresentCountry,
		ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
		ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
		ISNULL(SO.MotherTongue,'') As MotherTongue,
		ISNUll(MF.IsDisplayFatherName,0)  AS IsDisplayFatherName,
		ISNUll(MF.IsDisplayReligion,0)  AS IsDisplayReligion,
		ISNUll(MF.IsDisplayBloodGroup,0)  AS IsDisplayBloodGroup,
		ISNUll(MF.IsDisplayBirthPlace,0)  AS IsDisplayBirthPlace,
		ISNUll(MF.IsDisplayBirthTaluka,0)  AS IsDisplayBirthTaluka,
		ISNUll(MF.IsDisplayBirthDistrict,0)  AS IsDisplayBirthDistrict,
		ISNUll(MF.IsDisplayBirthState,0)  AS IsDisplayBirthState,
		ISNUll(MF.IsDisplayBirthCountry,0)  AS IsDisplayBirthCountry,
		ISNUll(MF.IsDisplayFamilyCaste,0)  AS IsDisplayFamilyCaste,
		ISNUll(MF.IsDisplayFamilySubCaste,0)  AS IsDisplayFamilySubCaste,
		ISNUll(MF.IsDisplayCasteCategory,0)  AS IsDisplayCasteCategory,
		ISNUll(MF.IsDisplayHouse,0)  AS IsDisplayHouse,
		ISNUll(MF.IsDisplayMotherTongue,0)  AS IsDisplayMotherTongue,
		ISNUll(MF.IsDisplayNationality,0)  AS IsDisplayNationality,
		ISNUll(MF.IsDisplayReferenceRemark,0)  AS IsDisplayReferenceRemark,
		ISNUll(MF.IsDisplayParentContactNo,0)  AS IsDisplayParentContactNo,
		ISNUll(MF.IsDisplayParentEmail,0)  AS IsDisplayParentEmail,
		ISNUll(MF.IsDisplayStudentContactNo,0)  AS IsDisplayStudentContactNo,
		ISNUll(MF.IsDisplayStudentEmail,0)  AS IsDisplayStudentEmail,
		ISNUll(MF.IsDisplayLocalAddress1,0)  AS IsDisplayLocalAddress1,
		ISNUll(MF.IsDisplayLocalAddress2,0)  AS IsDisplayLocalAddress2,
		ISNUll(MF.IsDisplayLocalAddress3,0)  AS IsDisplayLocalAddress3,
		ISNUll(MF.IsDisplayLocalAddressCity,0)  AS IsDisplayLocalAddressCity,
		ISNUll(MF.IsDisplayLocalAddressState,0)  AS IsDisplayLocalAddressState,
		ISNUll(MF.IsDisplayLocalAddressCountry,0)  AS IsDisplayLocalAddressCountry,
		ISNUll(MF.IsDisplayLocalAddressPINCode,0)  AS IsDisplayLocalAddressPINCode,
		ISNUll(MF.IsDisplayLocalAddressContactNo,0)  AS IsDisplayLocalAddressContactNo

	FROM 
		sStudent.vStudentAllDetail SA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
		LEFT JOIN sActivity.tHouseMaster HM ON HM.ID = SA.HouseId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId 
		INNER JOIN  [sStudent].[fMandatoryFieldGet](@rOrgGroupId,@rStrMandatoryFeildId) MF ON  MF.OrgGroupId=OM.OrgGroupId
		 INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassId and BC.BatchId= @rBatchId
		 
	WHERE 
		SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND (ISNULL(SA.StudentId,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId=0) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((HM.HouseGroupId=@rHouseGroupId) OR (@rHouseGroupId=0))

END
GO
PRINT N'Altering [sStudent].[pRptStudentBarcodeListGet]...';


GO

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

BEGIN 

  DECLARE @lSUIdBarcode nvarchar(50)
  DECLARE @lOrgGroupId int = 0

  SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
  SELECT @lSUIdBarcode = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 168 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId

   
	SELECT 
			--@rBuilder1 AS Builder1,
			--@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId,
			SA.SUId,
			SA.Code,
			CASE WHEN @lSUIdBarcode = 'True' THEN SA.SUId  ELSE SA.Code END AS BarcodeNumber,
			SA.RollNo 
			
			
	FROM 
		 	sStudent.vStudentAcademic SA
		 	INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
		 	--LEFT JOIN sStudent.tStudentOther SO
		 	--	ON SA.StudentId = SO.StudentId
		
	WHERE 
	
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		order by SA.Code 
END
GO
PRINT N'Altering [sStudent].[pRptStudentDetailListGet]...';


GO

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

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,
			SA.Code,
			SA.RollNo AS RollNo,			
			SA.FirstName,			
			SA.LastName,
			SA.Name,		
			SA.ClassName,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber,
			SO.DateOfBirth,
			SC.ParentContactNo,
			GM.Title AS Gender,
			SO.FamilyCast,
			CCM.Title AS CastCategory,
			HM.Title AS HouseName
	FROM 
		 	sStudent.vStudentAcademic SA
		 	LEFT JOIN sStudent.tStudentOther SO
		 		ON SA.StudentId = SO.StudentId
		 	LEFT JOIN sStudent.tStudentCommunication SC
		 		ON SA.StudentId = SC.StudentId
		 	LEFT JOIN sActivity.tHouseMaster HM 
		 		ON SO.HouseId = HM.Id 
		 	LEFT JOIN sCommon.tGenderMaster GM 
		 		ON SO.GenderId = GM.Id
		 	LEFT JOIN sCommon.tCastCategoryMaster CCM
		 		ON SO.CastCategoryId = CCM.Id	
		 	INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassId and BC.BatchId= @rBatchId
	WHERE 
	
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Altering [sStudent].[pRptStudentIcardGet]...';


GO


ALTER PROCEDURE [sStudent].[pRptStudentIcardGet]
	 
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rHouseGroupId int=0,
	 @rIsShowBarcode bit=0,
	 @rOrgGroupBatchId int
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @lIcardBorder nvarchar(10)
DECLARE @lSUIdBarcode nvarchar(50)
--DECLARE @lIsBarcodeBasedOnSUId bit = 0
DECLARE @lOrgGroupId int = 0
Declare @lIDConfigValue nvarchar(50)=''
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId

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

SELECT @lIcardBorder = ItemValue FROM sConfig.tConfigurationSetup WHERE configurationId = 130 AND SourceTypeId = 1016 AND SourceId = @rOrgId --ItemKey = 'sConfig.tConfigurationSetup' 
SELECT @lSUIdBarcode = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 168 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	
	--IF (@lSUIdBarcode IS NULL) OR (@lSUIdBarcode = 'False')
	--SET @lIsBarcodeBasedOnSUId = 0
	--ELSE
	--SET @lIsBarcodeBasedOnSUId = 1	
	
	SELECT			 
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassName,
			SD.DivisionName,
			SD.ClassDivision,
			SD.Batch,
			SD.Code,
			SD.Number AS StudentNumber,
			SD.RegistrationNumber,	
			SD.RollNo,				
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.FirstName + ' ' + SD.MiddleName + ' ' + SD.LastName As Name,		 
			SD.StatusId,
			SD.DateOfBirth,		
			SD.BloodGroup,
			ISNULL(SD.PresentStreetone,'') AS PresentStreetone,
			ISNULL(SD.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(SD.PresentStreetThree,'') AS PresentStreetThree,
		    ISNULL(SD.PresentCity,'') AS PresentCity,
		    ISNULL(SD.PresentZipCode,'') AS PresentZipCode,
			SD.PresentContactNo,						 
			SD.ParentContactNo AS ParentContactNo,
			SD.StudentContactNo,			
			SD.StudentPhoto,
			SD.AdmissionCategory, 
			SD.DivisionOrder,		 
			OM.Title AS OrgName,	
			ISNULL(HM.Title,'') AS HouseName,	
			OM.PrincipalSignature,
			ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,
			ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,
			ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,
			ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,			
			OM.OrgLogo AS ICardLogo,
			
			--ISNULL(ICO.ICardBackground,0) AS ICardBackground,	
			--ISNULL(ICO.ICardBackBackground,0) AS ICardBackBackground,	
			
			 ICO.ICardBackground  AS ICardBackground,	
			 ICO.ICardBackBackground  AS ICardBackBackground,						
			  
			ISNULL(ICO.LabelColor,'Black') AS LabelColor,
			ISNULL(ICO.DetailColor,'Black') AS DetailColor,
			ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(RT.RouteName,'') AS RouteName,
			ISNULL(RT.PickupPoint,'') AS PickupPoint,
			@lIcardBorder AS IcardBorder,
			HM.ColorCode,
			OM.OrgLogo,
			OM.SmallAddress1,
			--@lSUIdBarcode AS IsBarcodeBasedOnSUId,
			CASE WHEN @lSUIdBarcode = 'True' THEN SD.SUId  ELSE SD.Code END AS BarcodeNumber,
			 ISNULL(SD.EmergencyStreetOne,'') AS EmergencyStreetOne,
	         ISNULL(SD.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
	        ISNULL(SD.EmergencyStreetThree,'') AS EmergencyStreetThree,
	        ISNULL(SD.EmergencyCountry,'') AS EmergencyCountry,
	        ISNULL(SD.EmergencyState,'') As EmergencyState,
	        ISNULL(SD.EmergencyCity,'') AS EmergencyCity,
	        ISNULL(SD.EmergencyZipCode,'') as EmergencyZipCode,
	        SD.EmergencyContactNo AS EmergencyContactNo,
			ISNULL(SD.SUId,'') As SUId,
			ISNULL(RT.RouteNumber,0) AS RouteNumber,
			@rIsShowBarcode As IsShowBarcode,
			SD.Name,
			SM.Title AS Stream,
			SD.AdmissionDate,
			ISNULL(DM.Title,'') AS DepartmentName,
			SD.FatherPhoto,
			SD.MotherPhoto,
			SD.RelativePhoto,
			@lIDConfigValue AS ItemValue 
			
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			--INNER JOIN sStudent.tStudentOther SO ON SD.StudentId = So.StudentId 			
			LEFT JOIN sActivity.tHouseMaster HM ON SD.HouseId = HM.Id 
			LEFT JOIN sActivity.tHouseGroupMaster HGM ON HGM.Id=HM.HouseGroupId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SD.StudentId 
			 LEFT JOIN
			(SELECT AT.SourceId,BRM.Title As RouteName,BRDM.Title As PickupPoint,ISNULL(BRM.RouteNumber,0) AS RouteNumber FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND  AT.SourceTypeId=2003 AND ((BRM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SD.StudentId AND ((SD.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		 
			--LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId =SD.StudentId 
			--LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id =AR.PickupDestinationId 
			--LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id =BRDM.BusRouteId  AND(( BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			LEFT JOIN sStudent.tICardOrg ICO ON SD.OrgId = ICO.OrgId
			LEFT JOIN sSetup.tStreamMaster SM ON SM.Id=SD.StreamId
			LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id=SD.DepartmentId
			
	
			--LEFT JOIN sSetup.tOrganizationConfiguration OC ON OM.Id = OC.OrgId 
			
	WHERE 
		SD.OrgId=@rOrgId
		AND	SD.BatchId = @rBatchId 
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((HGM.Id=@rHouseGroupId)OR(@rHouseGroupId=0))
END
GO
PRINT N'Altering [sStudent].[pRptStudentInformationFormGet]...';


GO

ALTER PROCEDURE [sStudent].[pRptStudentInformationFormGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrStudentId nvarchar(max),
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rRemark nvarchar(500),
	 @rNote nvarchar(500)

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rRemark AS Remark,
			@rNote AS Note,
			SA.AcademicId,
			SA.StudentId, 			
			SA.Code,						
			SA.Name,		
			SA.ClassDivision AS ClassDiv,	
			SA.ParentEmail,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SA.Religion,'') AS Religion,
			ISNULL(SA.Gender,'') AS Gender,
			SA.DateOfBirth AS DateOfBirth,
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			
			SF.FatherIncome AS FatherIncome,
			SF.MotherIncome AS MotherIncome,
			SD.BankAccountNumber AS BankAccountNo,
			SD.BankName AS BankName,
			SD.BankBranch AS BranchName,
			SD.BankIFSCCode AS BankIFSCCode,
			CM.Id AS CategoryId,
			CM.Title AS Category,
			SA.FamilyCast AS Cast,
			 CASE WHEN EXISTS (SELECT StudentId FROM sStudent.tStudentSibling AS SS WHERE SS.StudentId = SA.StudentId)
				THEN 'No' 
					ELSE 'Yes'
				 END AS OnlyOneChild
			
	FROM 
		 	 sStudent.vStudentAllDetail SA
		 	 --LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
		 	 LEFT JOIN sCommon.tCastCategoryMaster CM ON CM.Id=SA.CastCategoryId
		 	 -- LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 	  LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
		 	  LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=SA.StudentId 
		 	INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassId and BC.BatchId= @rBatchId
	WHERE 
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Altering [sStudent].[pRptStudentListGet]...';


GO

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

BEGIN 

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


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


GO


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

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassDivision,
			SD.Code,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,		
			SD.ClassName,
			SD.DivisionName,
			SD.StatusName,
			SD.StatusId,
			SD.LCProgress,
			SD.Religion,
			SD.FamilyCast,
			SD.FamilySubCast,
			SD.LCConduct,
			SD.BirthPlace,
			SD.BirthTaluka,
			SD.BirthDistrict,
			SD.LeftDate,
			SD.PreviousSchool,
			SD.DateOfBirth,
			SD.BirthDateInWord,
			SD.LeftReason,
			SD.AdmissionDate,
			SD.AdmissionStandard,
			SD.LeftStandard,
			SD.LCNumber,
			SD.LCDate,
			SD.StudentPhoto,
			SD.BloodGroup,
			SD.PresentAddress,
			SD.ContactNo,
			SD.Batch,
			SD.InactiveDate,
			OM.Title AS OrgName,
			SF.MotherName,
			SD.DivisionOrder,
			SD.Number AS StudentNumber,
			SF.FatherName,
			SD.Nationality,
			SD.MotherTongue,
			SD.BirthState,
			SD.BirthCountry,
			SD.SUId,
            SD.AdhaarNumber
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassID and BC.BatchId= @rBatchId
			
	WHERE 
			SD.OrgId=@rOrgId
		AND	SD.BatchId = @rBatchId 
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((MONTH(SD.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=0))
	    AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Altering [sStudent].[pRptStudentRegisterWithAddressGet]...';


GO


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

BEGIN 

	SELECT 
		 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SD.RollNo,
			SD.Code,
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,	
			SD.DateOfBirth,
			SD.Religion,
			SD.FamilyCast,
			CCM.Title AS FamilySubCast,
			SF.MotherName,
			SF.FatherName,
			SD.ParentContactNo AS ContactNo,
			SF.FatherOccupation,
			SD.PresentStreetOne + ' ' + SD.PresentStreetTwo +' ' +SD.PresentStreetThree AS Address,
			
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassDivision,
			  
			SD.ClassName,
			SD.DivisionName,
			 
			OM.Title AS OrgName,
			SD.DivisionOrder,
			SD.Number AS StudentNumber,
			SD.Batch                       
			
			
			
      
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			--INNER  JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SD.StudentId
			--INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SD.StudentId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SD.CastCategoryId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassId and BC.BatchId= @rBatchId 
			
	WHERE 
			SD.OrgId=@rOrgId
		AND	SD.BatchId = @rBatchId 
		AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((MONTH(SD.DateOfBirth)=@rDateOfBirth OR @rDateOfBirth=0))
	    AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Altering [sStudent].[pRptStudentStrengthDivisionStatusWiseGet]...';


GO


 
ALTER PROCEDURE [sStudent].[pRptStudentStrengthDivisionStatusWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rDepartmentId int,
	 
	 @rFromDate Date='',
	 @rToDate Date=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
  DECLARE @lCount Int
  Select
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		CM.Id AS ClassID,
		DM.Id as DivisionId,
		DM.OrderIndex AS DivisionOrder,
		Cm.OrderINdex AS ClassOrderIndex  ,
		--A.StudentId ,
		CM.DisplayTitle+' - '+DM.DisplayTitle AS ClassDivision,
		(
			Select COUNT(A.Id) 
			from 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id
			WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND (A.ClassId=CM.Id)
			AND (A.DivisionId=DM.Id) 
			AND SM.StatusId = 1
			AND ((SA.AdmissionDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SA.AdmissionDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		)AS ActiveStudent,
	     (
			Select COUNT(A.Id) 
			from 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id
			WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND (A.ClassId=CM.Id)
			AND (A.DivisionId=DM.Id) 
			AND SM.StatusId = 2
			AND ((SA.InactiveDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SA.InactiveDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		)AS InActiveStudent,
		(
			Select COUNT(A.Id) 
			from 
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SM.Id
			WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND (A.ClassId=CM.Id)
			AND (A.DivisionId=DM.Id) 
			AND SM.StatusId = 3
			AND ((SA.LeftDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SA.LeftDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		)AS LeftStudent
			FROM 
			 sSetup.tClassMaster CM  
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
			--LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
			--LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
			--LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			--LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=SM.AdmissionCategoryId
			  
    
	WHERE 
		 
		 ((CM.Id=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		 AND CM.OrgId =@rOrgId
		 AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	   END
GO
PRINT N'Altering [sStudent].[pRptStudentStrengthDivisionWiseGet]...';


GO


 
ALTER PROCEDURE [sStudent].[pRptStudentStrengthDivisionWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rDepartmentId int,
	 @rStudentCode varchar(20)='',
	 @rReportId int=0,
	 @rOrggroupBatchID int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

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


GO

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

BEGIN 

	
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,
			SA.Code,
			SA.RollNo AS RollNo,			
			SA.FirstName,			
			SA.LastName,
			SA.Name,		
			SA.ClassName,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber
      
	FROM  sStudent.vStudentLastAcademic SA
	INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassId and BC.BatchId= @rBatchId
			WHERE 
			SA.OrgId=@rOrgId
		AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		
		 EXCEPT
		SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,
			SA.Code,
			SA.RollNo AS RollNo,			
			SA.FirstName,			
			SA.LastName,
			SA.Name,		
			SA.ClassName,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber
			 FROM sHostel.tAssignRoom AR  INNER JOIN sStudent.vStudentLastAcademic SA ON  SA.StudentId=AR.SourceId  
			 INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
			 WHERE  AR.SourceTypeId = 2003 
			 AND AR.OrgGroupBatchId=@rOrgGroupBatchId  AND SA.OrgGroupBatchId=@rOrgGroupBatchId
			  
			EXCEPT
	  SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,
			SA.Code,
			SA.RollNo AS RollNo,			
			SA.FirstName,			
			SA.LastName,
			SA.Name,		
			SA.ClassName,
			SA.DivisionName,
			SA.StatusName,
			SA.DivisionOrder,
			SA.Number AS StudentNumber
			 FROM sTransport.tAssignRoute  TA 
			    INNER JOIN sTransport.tBusRouteDestinationMaster BRM ON BRM.Id=TA.PickupDestinationId
			    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BRM.BusRouteId 
			    INNER JOIN  sStudent.vStudentLastAcademic SA ON  SA.StudentId=TA.SourceId  
			    INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId 
			    WHERE  TA.SourceTypeId = 2003
			    AND SA.OrgGroupBatchId=@rOrgGroupBatchId   AND B.OrgGroupBatchId=@rOrgGroupBatchId
			  
			
END
GO
PRINT N'Altering [sStudent].[pRptTrancriptionCertificateGet]...';


GO

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

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.StudentId, 
			SA.ClassId,
			SA.DivisionId,			
			--SA.FirstName + ' ' +SA.MiddleName + ' ' +SA.LastName AS Name,
			
			SA.ClassName,
			
			SA.DivisionName,
			SA.DivisionOrder,
			SA.Name,
			SA.Number AS StudentNumber,
			SA.BatchName,
			SA.BatchId,
			SA.ClassOrderIndex,
			SO.DateOfBirth,
			SC.PermanentStreetOne,
			SC.PermanentStreetTwo,
			SC.PermanentStreetThree,
			SC.PermanentCountry,
			SC.PermanentState,
			SC.PermanentCity,
			SC.PermanentZipCode,
			ISNULL(SA.OrganizationName,'') AS OrganizationName,
			ISNULL(SA.Code,'') As Registrationno,
			'' As Board,
			SAD.AdmissionDate AS MonthofEnterance,
			'' As Courseduration,
			'' As Grade,
			'' As Medium,
			SM.Code,
			TA.SubjectId,
			TA.SubjectName as SubjectName,
			TA.LectureHoursPerWeek,
			TA.LabHoursPerWeek,
			TA.TotalMarks,
			TA.ObtainMarks,
			SA.DepartmentName,
			SA.StreetOne,
	        SA.StreetTwo,
	        SA.StreetThree,
	        SA.ZipCode 
	        
			
			
	FROM 
		 	sStudent.vStudentAcademic SA
		 	LEFT JOIN sStudent.tStudentOther SO
		 		ON SA.StudentId = SO.StudentId
		 	LEFT JOIN sStudent.tStudentCommunication SC
		 		ON SA.StudentId = SC.StudentId
		 	LEFT JOIN tTranscriptAssessment TA ON TA.AcademicId = SA.AcademicId 
		    LEFT JOIN sSetup.tSubjectMaster SM on TA.SubjectId=SM.Id
		    INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassId and BC.BatchId= @rBatchId
	WHERE 
			SA.OrgId=@rOrgId
		--AND	SA.BatchId = @rBatchId
		AND (ISNULL(SA.StudentId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrStudentId,',')) OR @rStrStudentId='') 
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
		--AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		--AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
		--AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Altering [sStudent].[pRptVerifyStudentDataListGet]...';


GO


ALTER PROCEDURE [sStudent].[pRptVerifyStudentDataListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAsOnDate date,
	 @rReportId int,
	 @rDepartmentId int,
	 @rStudentCode varchar(20)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SMast.Title AS StatusName,
			ISNULL(GM.Title,'') As Gender,
			SA.AdmissionDate,
			SA.LeftDate,
			A.ClassId,
			A.DivisionId,
			A.Id AS AcademicId,
			A.RollNo,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassDivision,
			SM.FirstName +' '+ SM.MiddleName +' '+ SM.LastName AS Name,
			SM.Code,
			DM.OrderIndex AS DivisionOrder
			
			FROM 
			
			sStudent.tAcademic A		
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId	
			INNER JOIN sStudent.tStudentOther SO ON A.StudentId=SO.StudentId
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sStudent.tStatusMaster SMast ON SMast.Id=SM.StatusId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
	WHERE 
		A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
END
GO
PRINT N'Altering [sStudent].[pStrengthStatusLEFTWiseGet]...';


GO
ALTER  PROCEDURE [sStudent].[pStrengthStatusLEFTWiseGet]
	  @rClassId int,
	  @rDivisionId int,
	  @rbatchId int,
	  @rOrgId int,
	  @rDepartmentId int=0,
	  @rBuilder1 nvarchar(max)='',
	  @rBuilder2 nvarchar(max)='',
	  @rStudentCode nvarchar(50)='',
	  @rReportId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		--declare @StudentId bigint=0
		-- Select 0 ClassId,0 MonthNumber,'' MonthTitle,0 YearNumber,'' ClassName,@StudentId As StudentId,'' builder1,0 ClassOrderIndex
		
		Create Table #table
		(
			ClassId int,
			MonthNumber int,
			MonthTitle nvarchar(10),
			YearNumber int,
			ClassName nvarchar(10),
			ClassOrderIndex int
		)
		Insert into #table
		(
			ClassId,
			MonthNumber,
			MonthTitle,
			YearNumber,
			ClassName,
			ClassOrderIndex
		)
		SELECT CM.Id AS ClassId, M.MonthNumber,M.MonthTitle,M.YearNumber,CM.Title As ClassName,Cm.OrderIndex As ClassOrderIndex
		FROM sSetup.tClassMaster CM CROSS APPLY sSetup.fMonthYearForBatchGet (@rbatchId) M
		INNER JOIN sSetup.tOrganizationMaster OM On OM.Id= CM.OrgId
		INNER JOIN   sSetup.tBatchMaster Bm on Bm.ORgId= OM.Id
		INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
		Where Bm.Id=@rbatchId
		 
		 
		Select 	t.ClassId,
			MonthNumber,
			MonthTitle,
			YearNumber,
			ClassName,A.StudentID,builder1 from #table t LEFT JOIN 
	 	(select  @rbuilder1 As builder1,A.Id As StudentId,LeftDate,A.ClassId As ClassId,Month(leftdate) AS LeftMonth
		from sStudent.tStudentAdmission SA 
		INNER JOIN sStudent.tAcademic A ON A.Studentid=Sa.StudentId
		  
		WHERE LeftDate >= (select fromdate from sSetup.tBatchMaster  where id=@rbatchId)
		 and LeftDate <= (Select Todate from sSetup.tBatchMaster where id = @rbatchId)
		 AND A.BatchId=@rBatchId and ((ClassId = @rClassId) OR (@rClassid=0))
		 )A ON A.ClassId = T.ClassId AND A.LeftMonth = t.MonthNumber
		 ORder by t.YearNumber,t.MonthNumber
		--Group by A.Id,Admissiondate,TItle 
END
GO
PRINT N'Altering [sStudent].[pStrengthStatusWiseGet]...';


GO
ALTER PROCEDURE [sStudent].[pStrengthStatusWiseGet]
	  @rClassId int,
	  @rDivisionId int,
	  @rbatchId int,
	  @rOrgId int,
	  @rDepartmentId int=0,
	  @rBuilder1 nvarchar(max)='',
	  @rBuilder2 nvarchar(max)='',
	  @rStudentCode nvarchar(50)='',
	  @rReportId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	--declare @StudentId bigint=0
	--	 Select 0 ClassId,0 MonthNumber,'' MonthTitle,0 YearNumber,'' ClassName,@StudentId As StudentId,'' builder1,0 ClassOrderIndex 
	   	Create Table #table
		(
			ClassId int,
			MonthNumber int,
			MonthTitle nvarchar(10),
			YearNumber int,
			ClassName nvarchar(10),
			ClassOrderIndex int
		)
		Insert into #table
		(
			ClassId,
			MonthNumber,
			MonthTitle,
			YearNumber,
			ClassName,
			ClassOrderIndex
		)
		SELECT CM.Id AS ClassId,  M.MonthNumber,M.MonthTitle,M.YearNumber,CM.Title As ClassName,Cm.OrderIndex As ClassOrderIndex
		FROM sSetup.tClassMaster CM CROSS APPLY sSetup.fMonthYearForBatchGet (@rbatchId) M
		INNER JOIN sSetup.tOrganizationMaster OM On OM.Id= CM.OrgId
		INNER JOIN   sSetup.tBatchMaster Bm on Bm.ORgId= OM.Id
		INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
		Where Bm.Id=@rbatchId
		
		Select 	t.ClassId,
			MonthNumber,
			MonthTitle,
			YearNumber,
			ClassName,A.StudentID,builder1,ClassOrderIndex from #table t LEFT JOIN 
	 	(select  @rbuilder1 As builder1,A.Id As StudentId,Admissiondate,A.ClassId As ClassId,Month(Admissiondate) AS AdmissionMonth
		from sStudent.tStudentAdmission SA 
		INNER JOIN sStudent.tAcademic A ON A.Studentid=Sa.StudentId
		   
		WHERE Admissiondate >= (select fromdate from sSetup.tBatchMaster  where id=@rbatchId)
		 and Admissiondate <= (Select Todate from sSetup.tBatchMaster where id = @rbatchId)
		 AND A.BatchId=@rBatchId and ((ClassId = @rClassId) OR (@rClassid=0))
		 )A ON A.ClassId = T.ClassId AND A.AdmissionMonth = t.MonthNumber
		 
		 Order by  t.YearNumber,t.MonthNumber
	 
		--Group by A.Id,Admissiondate,TItle
		
		
 
 
 
--;with months (date)
--AS
--(
--    SELECT (Select Fromdate from sSetup.tBatchMaster where Id=@rBatchid) 
--    UNION ALL
--    SELECT DATEADD(month,1,date)
--    from months
--    where DATEADD(month,1,date) < (Select Todate from sSetup.tBatchMaster  where Id=@rBatchId) 
    
--)
--select     [MonthName]    = DATENAME(mm ,Date)  
--            ,[MonthNumber]  = DATEPART(mm ,Date)  
            
--            ,[MonthYear]    = DATEPART(yy ,Date) 
--from months

 
END
GO
PRINT N'Altering [sStudent].[pStudentCustomSearchGet]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentCustomSearchGet]
(
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	--@rClassId nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9990-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9990-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9990-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount Smallint=0,
	@rStudentStatus Smallint=0,
	@rHostelId nvarchar(max) = '',
	@rFatherName nvarchar(50)='',
	@rMotherName nvarchar(50)='',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption  nvarchar(max) = ''
 )
AS
SET NOCOUNT ON

BEGIN
		DECLARE @Sql nvarchar(MAX)
		
		IF(@rDOBFromDate IS NULL)
			SET @rDOBFromDate='0001-01-01'
		IF(@rDOBToDate IS NULL)
			SET @rDOBToDate='9990-12-31'
		IF(@rDOAFromDate IS NULL)
			SET @rDOAFromDate='0001-01-01'
		IF(@rDOAToDate IS NULL)
			SET @rDOAToDate='9990-12-31'
		IF(@rDOLFromDate IS NULL)
			SET @rDOLFromDate='0001-01-01'
		IF(@rDOLToDate IS NULL)
			SET @rDOLToDate='9990-12-31'
		
		 
		SET @rDOBToDate = DATEADD(d,1,@rDOBToDate)		 
		SET @rDOAToDate = DATEADD(d,1,@rDOAToDate)		 
		SET @rDOLToDate = DATEADD(d,1,@rDOLToDate)	
		
		
	
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rCountry = sCommon.fSearchStringGet(@rCountry)
		SET @rState = sCommon.fSearchStringGet(@rState)
		 
		-- For Custom Tag
		IF (@rCustomTagId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId1
			INTO sStudent.tTempStudent2
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		END
		
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId1
			INTO sStudent.tTempStudent2
		END
			 
		-- For Custom Group
		IF (@rCustomGroupId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId2
			INTO sStudent.tTempStudent3
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId2
			INTO sStudent.tTempStudent3
		END
		
		-- For Club Group
		IF (@rClubId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId3
			INTO sStudent.tTempStudent4
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId3
			INTO sStudent.tTempStudent4
		END
		
		-- For Hostel
		IF (@rHostelId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId4
			INTO sStudent.tTempStudent8
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
			AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
			WHERE SM.OrgId = @rOrgId --AND A.BatchId = @BatchId 
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId4
			INTO sStudent.tTempStudent8
		END
		--Transport
		IF (@rBusRouteId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId5
			INTO sStudent.tTempStudent9
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
			AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE SM.OrgId = @rOrgId 
			AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId5
			INTO sStudent.tTempStudent9
		END
	
		IF (@rFeeExemption <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId6
			INTO sStudent.tTempStudent10
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sFee.tExemptionTypeMaster AT ON AT.Id = A.ExemptionTypeId
			 
			WHERE SM.OrgId = @rOrgId 
			AND (ISNULL(AT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId6
			INTO sStudent.tTempStudent10
		END
		
		SELECT 
				*,
				SCS.ClassName+'-'+SCS.DivisionName AS ClassName1
		INTO sStudent.tTempStudent1
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent2 T2 ON SCS.StudentId = T2.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent3 T3 ON SCS.StudentId = T3.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent4 T4 ON SCS.StudentId = T4.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent8 T8 ON SCS.StudentId = T8.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId5 OR @rBusRouteId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId6 OR @rFeeExemption = ''
		WHERE 
			SCS.OrgId = @rOrgId AND SCS.BatchId = @BatchId 
			AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%')OR(@rCountry = ''))
			AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))		 
			AND (( SCS.DateOfBirth  >= @rDOBFromDate) OR (ISNULL(SCS.DateOfBirth,'') = ''))
			AND (( SCS.DateOfBirth  < @rDOBToDate) OR (ISNULL(SCS.DateOfBirth,'') = ''))
			AND (( SCS.AdmissionDate >= @rDOAFromDate) OR (ISNULL(SCS.AdmissionDate,'') = ''))
			AND (( SCS.AdmissionDate < @rDOAToDate) OR (ISNULL(SCS.AdmissionDate,'') = ''))		 
			AND (( SCS.LeftDate  >= @rDOLFromDate) OR (ISNULL(SCS.LeftDate,'') = ''))
			AND (( SCS.LeftDate   < @rDOLToDate) OR (ISNULL(SCS.LeftDate,'') = ''))
			AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
			AND ((SCS.RepeatCount=@rRepeatCount)OR (@rRepeatCount=0))
			
             AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		    
		    
		    AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		    
		    AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')	
	        
	        AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
	        
	        AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
		    
		    AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
		            
		    AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		           
		    AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		           
		    AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		                   
		    AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		           
		    AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		     
		    AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')		
		    
		    AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		    
		    AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		    
		    AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		    
		    AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		    
		    AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		    
		    AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		    
		     -- AND (ISNULL(SCS.RepeatCount,1) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount=1)
		  
		    AND (ISNULL(SCS.StudentStatusId,'') IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatus,','))OR @rStudentStatus='')
		  
		  AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
			  
			AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		  
		    AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		    AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0)) 
		    AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		    AND ((SCS.Code >= @rFromCode) OR (@rFromCode=''))
			AND ((SCS.Code <= @rToCode) OR (@rToCode=''))
			AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND ((SCS.MiddleName Like @rFatherName  + '%') OR (@rFatherName = ''))	 
			AND ((SCS.MotherName Like @rMotherName  + '%') OR (@rMotherName = ''))	 
			AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')	
			AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')			
	if (@rOrderBy='ID No')
	BEGIN
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	END
	
	if (@rOrderBy='GR No')
	BEGIN
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	END
	 
		SET @sql=
		'SELECT 
				StudentId,
				Code AS Code,
				Name,
				ClassName1 AS ClassName,
				StatusName,
				ParentContactNo
		FROM sStudent.tTempStudent1 ORDER BY '+@rOrderBy

		exec(@Sql)
		 
		DROP Table sStudent.tTempStudent1
		DROP Table sStudent.tTempStudent2
		DROP Table sStudent.tTempStudent3
		DROP Table sStudent.tTempStudent4
		DROP Table sStudent.tTempStudent8
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
END
GO
PRINT N'Altering [sStudent].[pStudentFullProfileGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentFullProfileGet]
	 
	 @rBatchId int,
	 @rStudentId bigint,
	 @rReportId int=0,
	 @rOrgId int,
	 @rStrCode nvarchar(max)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rStatusId int=0,
	 @rDateOfBirth int=0,
	 @rDepartmentId int=0,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rOrgGroupBatchId int
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	SELECT 
			--Academic
			SA.StudentId AS Id,
			SA.FirstName + ' ' + ISNULL(SA.MiddleName,'') + ' ' + 	SA.LastName AS StudentName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,' - ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			SA.RollNo,
			ISNULL(SM.Title,'-') AS House,
			--Other
			CASE WHEN @rReportId=0 THEN ISNULL(SA.DateOfBirth,'0001/01/01')  
			WHEN @rReportId=1 THEN  SA.DateOfBirth END  AS DateOfBirth,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			ISNULL(SA.Religion,'') AS Religion,
			--Admission			
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,
			--ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.AdmissionDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.AdmissionDate END AS AdmissionDate,
	
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.LeftDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LeftDate END AS LeftDate,
						 
			ISNULL(SA.LeftStandard,'') AS LeftStandard,
			--ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SA.InactiveDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.InactiveDate END AS InactiveDate,		
			ISNULL(SA.LCNumber,'') AS LCNumber,
			--ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			 CASE WHEN @rReportId=0 THEN ISNULL(SA.LCDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SA.LCDate END AS LCDate,
			--Communication
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			--Parent Information
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			
			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			
			
			--Health Information
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			
			ISNULL(SH.IsPysicalDeformity,0) AS IsPysicalDeformity,
			ISNULL(SH.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			ISNULL(SH.IsMajorIllness,0) AS IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			ISNULL(SH.IsAllergy,0) AS IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			ISNULL(SH.IsPastHistory,0) As IsPastHistory ,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			--Hostel
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,
					
	   	    --ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentPhoto,
	   	   -- ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
	   	   -- ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
	   	    --ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
	   	   CASE WHEN @rReportId=0
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS StudentPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS MotherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), ''))
			END AS FatherPhoto,
			
			CASE WHEN @rReportId=0
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0))
			WHEN @rReportId=1
			THEN ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), ''))
			END AS RelativePhoto,
		   -- Transport Details
		    A.VehicleName AS VehicleName,
		    A.VehicleRegistrationNumber AS VehicleRegistrationNumber,
		    A.TypeOfVehicle AS TypeOfVehicle,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    A.DriverName,
		    A.DriverMobileNo,
		    A.ConductorName,
		    A.ConductorMobileNo,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,
		    
		    A.DropVehicleName AS DropVehicleName,
		    A.DropVehicleRegistrationNumber AS DropVehicleRegistrationNumber,
		    A.DropTypeOfVehicle AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    A.DropRouteDriverName AS DropRouteDriverName,
		    A.DropRouteDriverMobileNo AS DropRouteDriverMobileNo,
		    A.DropRouteConductorName AS DropRouteConductorName,
		    A.DropRouteConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		    
		    --ClassTeacher Details
		    ISNULL(EMT.Id,0) AS TeacherId,
		    EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName AS TeacherFullName,
		    EDM.Title AS TeacherDesignation,
		    EPD.Qualification AS TeacherQualification,
		    ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS TeacherPhoto,
		    ISNULL(DF.IsDisplayFamilyDetail,0) AS IsDisplayFamilyDetail,
		    ISNULL(DF.IsDisplaySiblingDetail,0) AS IsDisplaySiblingDetail,
		    ISNULL(DF.IsDisplayPassportDetail,0) AS IsDisplayPassportDetail,
		    ISNULL(DF.IsDisplayBankDetail,0) AS IsDisplayBankDetail,
		    ISNULL(DF.IsDisplayCBSEREGDetail,0) AS IsDisplayCBSEREGDetail,
		    ISNULL(DF.IsDisplayCollegeDetail,0) AS IsDisplayCollegeDetail,
		    ISNULL(DF.IsDisplayGOVREGNoDetail,0) AS IsDisplayGOVREGNoDetail,
		    ISNULL(DF.IsDisplayHealthDetail,0) AS IsDisplayHealthDetail,
		    ISNULL(DF.IsDisplayTransportDetail,0) AS IsDisplayTransportDetail,
		    ISNULL(DF.IsDisplayHostelDetail,0) AS IsDisplayHostelDetail,
		    ISNULL(DF.IsDisplayClubDetail,0) AS IsDisplayClubDetail,
		    
		    ISNULL(DF.IsDisplaySSCResultDDetail,0) AS IsDisplaySSCResultDDetail,
		    ISNULL(DF.IsDisplayHSCResultDetail,0) AS IsDisplayHSCResultDetail,
		    ISNULL(DF.IsDisplayJeeDetail,0) AS IsDisplayJeeDetail,
		    ISNULL(DF.IsDisplayDiplomaDetail,0) AS IsDisplayDiplomaDetail,
		    --Sibling Detail
		    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(SAD.BankAccountNumber,'')AS BankAccountNumber,
	        ISNULL(SAD.BankName,'')AS BankName,
	        ISNULL(SAD.BankBranch,'') AS BankBranch,
	        ISNULL(SAD.BankIFSCCode,'')AS BankIFSCCode,
	        ISNULL(SAD.Class9BoardRegistrationNumber,'') AS Class9BoardRegistrationNumber,
	        ISNULL(SAD.Class11BoardRegistrationNumber,'')AS Class11BoardRegistrationNumber,
	        ISNULL(SAD.PassportNumber,'')AS PassportNumber, 
	        ISNULL(SAD.PassportType,'') AS PassportType,
	       ISNULL( SAD.PassportCountryCode,'') AS PassportCountryCode,
	        CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportIssueDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportIssueDate END AS PassportIssueDate,
			CASE WHEN @rReportId=0 THEN ISNULL(SAD.PassportExpiryDate,'0001/01/01')
			WHEN @rReportId=1 THEN  SAD.PassportExpiryDate END AS PassportExpiryDate,
	        ISNULL(SA.UIDNumber,'')AS UIDNumber,
	        ISNULL(SA.AdhaarNumber,'') AS AdhaarNumber,
	       ISNull(SA.StatusId,0) AS StatusId,
	       ISNUll(SA.IsTransfer,0)AS IsTransfer,
	       ISNULL(SA.TransferFrom,'') AS TransferFrom,
	       ISNULL(SA.CertificateName,'') AS CertificateName,
	       ISNUll(SA.IsTFWS,0)AS IsTFWS,
	       ISNUll(SA.IsCertificateHolder,0)AS IsCertificateHolder,
	       ISNULL(CD.SSCBoard,'') AS SSCBoard,
	       ISNULL(CD.SSCSchool,'') AS SSCSchool,
	       ISNULL(CD.SSCPassingYear,'') AS SSCPassingYear,
	       ISNULL(CD.SSCObtainMarks,0) AS SSCObtainMarks,
	       ISNULL(CD.SSCOutOfMarks,0) AS SSCOutOfMarks,
	       ISNULL(CD.SSCPercentage,0) AS SSCPercentage,
	       ISNULL(CD.SSCMathMarks,0) AS SSCMathMarks,
	       ISNULL(CD.SSCMathOutOfMarks,0) AS SSCMathOutOfMarks,
	       ISNULL(CD.HSCBoard,'') AS HSCBoard,
	       ISNULL(CD.HSCSchool,'') AS HSCSchool,
	       ISNULL(CD.HSCPassingYear,0) AS HSCPassingYear,
	       ISNULL(CD.HSCObtainMarks,0) AS HSCObtainMarks,
	       ISNULL(CD.HSCOutOfMarks,0) AS HSCOutOfMarks,
	       ISNULL(CD.HSCPercentage,0) AS HSCPercentage,
	       ISNULL(CD.HSCPhysicsMarks,0) AS HSCPhysicsMarks,
	       ISNULL(CD.HSCPhysicsOutOfMarks,0) AS HSCPhysicsOutOfMarks,
	       ISNULL(CD.HSCChemistryMarks,0) AS HSCChemistryMarks,
	       ISNULL(CD.HSCChemistryOutOfMarks,0) AS HSCChemistryOutOfMarks,
	       ISNULL(CD.HSCMathMarks,0) AS HSCMathMarks,
	       ISNULL(CD.HSCMathOutOfMarks,0) AS HSCMathOutOfMarks,
	       ISNULL(CD.HSCBiologyMarks,0) AS HSCBiologyMarks,
	       ISNULL(CD.HSCBiologyOutOfMarks,0) AS HSCBiologyOutOfMarks,
	       ISNULL(CD.PCMMarks,0) AS PCMMarks,
	       ISNULL(CD.PCBMarks,0) AS PCBMarks,
	       ISNULL(CD.JEERollNo,'') AS JEERollNo,
	       ISNULL(CD.JEEMeritNo,'') AS JEEMeritNo,
	       ISNULL(CD.JEEMeritMarks,0) AS JEEMeritMarks,
	       ISNULL(CD.JEEOutOfMarks,0) AS JEEOutOfMarks,
	       ISNULL(CD.DiplomaBoard,'') AS DiplomaBoard,
	       ISNULL(CD.DiplomaCollege,'') AS DiplomaCollege,
	       ISNULL(CD.DiplomaPassingYear,'') AS DiplomaPassingYear,
	       ISNULL(CD.DiplomaObtainMarks,0) AS DiplomaObtainMarks,
	       ISNULL(CD.DiplomaOutOfMarks,0) AS DiplomaOutOfMarks,
	       ISNULL(CD.DiplomaPercentage,0) AS DiplomaPercentage,
	       ISNULL(CD.ApplicationNo,'') AS ApplicationNo,
	       ISNULL(CD.AdmissionRound,0) AS AdmissionRound,
	       ISNULL(CD.MaritalStatusId,0) AS MaritalStatusId,
	       ISNULL(MS.Title,'') AS MaritalStatus,
	       ISNULL(ACD.RepeatCount,1)AS RepeatCount,
	       ISNULL(SA.MotherTongue,'') As MotherTongue,
	       ISNULL(SA.FamilyCast,'') AS FamilyCast,
	      ISNULL(CM.Nationality,'') AS Nationality,
	       ISNULL(CT.Title,'') AS CasteCategory,
	       ISnull(SA.ClassName,'') AS ClassName ,
	       ISnull( SA.DivisionName,'') AS DivisionName,
	      ISNULL( SF.IsFatherExStudent,0) AS IsFatherExStudent,
	       ISnull(SF.FatherPassOutYear,'') AS FatherPassOutYear,
	       Isnull(SF.IsMotherExStudent,0) AS IsMotherExStudent,
	       Isnull(SF.MotherPassOutYear,'') AS MotherPassOutYear,
	       ISNULL(SF.IsRelativeExStudent,0) AS IsRelativeExStudent,
	       ISNULL(SF.RelativePassOutYear,'') AS RelativePassOutYear,
	       ISNULL(Sa.PresentDistanceFromSchool,0) AS PresentDistanceFromSchool,
	        SA.StudentId,
	        SA.ClassId,
	        SA.DivisionId,
	        SA.BirthState,
	        SA.BirthCountry,
	         ISNULL(SA.PreviousStandard,'')AS PreviousStandard 
	        
	       --[sHostel].[fHostelWardenGet](HM.Id) As WardenName
  FROM 
           sStudent.vStudentAllDetail SA
          -- LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId 
          -- LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId   
            LEFT JOIN
            (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 		   
		 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1       
           --LEFT JOIN sHostel.tHostelWarden HW ON HW.HostelId=HM.Id
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN 
           ( SElect AR1.SourceId,
           VM.Title AS VehicleName,
		    VM.RegistrationNumber AS VehicleRegistrationNumber,
		    TV.Title AS TypeOfVehicle,
		    ISNULL(BRM.Title,'') AS BusRoute,
		    BRM.DriverName,
		    BRM.DriverMobileNo,
		    BRM.ConductorName,
		    BRM.ConductorMobileNo,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    VM.Title AS DropVehicleName,
		    VM.RegistrationNumber AS DropVehicleRegistrationNumber,
		    TV1.Title AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		    BRM1.DriverName AS DropRouteDriverName,
		    BRM1.DriverMobileNo AS DropRouteDriverMobileNo,
		    BRM1.ConductorName AS DropRouteConductorName,
		    BRM1.ConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination
		      FROM
             sTransport.tAssignRoute AR1   
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId) A ON A.SourceId=SA.StudentId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
           INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
           
  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.BatchId=@rBatchId) OR(@rBatchId=0))
			AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='') 
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.StatusId=@rStatusId)OR(@rStatusId=0))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
			--AND(SA.OrgId=@rOrgId)
			
END
GO
PRINT N'Altering [sStudent].[pStudentGenerateReport]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentGenerateReport]
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9999-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9999-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount smallint=0,
	@rStudentStatusId smallint=0,
	@rHostelId nvarchar(max) = '',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption nvarchar(max)=''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate='0001-01-01'
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate='9999-12-31'
	IF(@rDOAFromDate IS NULL)
		SET @rDOAFromDate='0001-01-01'
	IF(@rDOAToDate IS NULL)
		SET @rDOAToDate='9999-12-31'
	IF(@rDOLFromDate IS NULL)
		SET @rDOLFromDate='0001-01-01'
	IF(@rDOLToDate IS NULL)
		SET @rDOLToDate='9999-12-31'
	IF(@rTitle != '' AND @rId = 0)
	BEGIN
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sStudent.tStudentCustomSearch
		(
			Id,
			Title,
			ColumnName,
			OrderBy,
			OrgId,
			Code,
			FirstName,	
			LastName,
			Country,
			State,
			City,
			Area,
			DivisionId,
			StatusId,
			TransportModeId,
			BusRouteDestinationId,
			BloodGroupId,
			GenderId,
			ReligionId,
			CastCategoryId,
			HouseId,
			MotherTongueId,
			NationalityId,
			Hobby,
			FatherQualification,
			MotherQualification,
			FatherOccupation,
			MotherOccupation,
			PreviousSchool,
			AdmissionCategoryId,
			DOBFromDate,
			DOBToDate,
			DOAFromDate,
			DOAToDate,
			DOLFromDate,
			DOLToDate,
			IsPysicalDeformity,
			IsMajorIllness,
			IsCommon,
			CreatedUserId,
			CreatedDateTime,
			IsBlackList,
			FromCode,
			ToCode,
			CustomTag,
			CustomGroup,
	        Club,
	        RepeatCount,
	        StudentStatusId,
	        Hostel,
	        StudentGroup,
	        StudentOtherGroup,
	       FeeExemption
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rColumnName,
			@rOrderBy,
			@rOrgId,
			@rCode,
			@rFirstName,	
			@rLastName,
			@rCountry,
			@rState,
			@rCity,
			@rArea,
			@rDivisionId,
			@rStatusId,
			@rTransportModeId,
			@rBusRouteDestinationId,
			@rBloodGroupId,
			@rGenderId,
			@rReligionId,
			@rCastCategoryId,
			@rHouseId,
			@rMotherTongueId,
			@rNationalityId,
			@rHobby,
			@rFatherQualification,
			@rMotherQualification,
			@rFatherOccupation,
			@rMotherOccupation,
			@rPreviousSchool,
			@rAdmissionCategoryId,
			@rDOBFromDate,
			@rDOBToDate,
			@rDOAFromDate,
			@rDOAToDate,
			@rDOLFromDate,
			@rDOLToDate,
			@rIsPysicalDeformity,
			@rIsMajorIllness,
			@rIsCommon,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rIsBlackList,
			@rFromCode,
			@rToCode,
			@rCustomTagId,
			@rCustomGroupId,
	        @rClubId,
			@rRepeatCount,
			@rStudentStatusId,
			@rHostelId,
			@rStudentGroupId,
	        @rStudentOtherGroupId,
			@rFeeExemption
			
		)
		--SELECT @lNextNumber AS Result
	END
	IF(@rId > 0)
	BEGIN
		Select
				@rColumnName=ColumnName,
				@rOrderBy=OrderBy,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rCountry=Country,
				@rState=State,
				@rCity=City,
				@rArea=Area,
				@rDivisionId=DivisionId,
				@rStatusId=StatusId,
				@rTransportModeId=TransportModeId,
				@rBusRouteDestinationId=BusRouteDestinationId,
				@rBloodGroupId=BloodGroupId,
				@rGenderId=GenderId,
				@rReligionId=ReligionId,
				@rCastCategoryId=CastCategoryId,
				@rHouseId=HouseId,
				@rMotherTongueId=MotherTongueId,
				@rNationalityId=NationalityId,
				@rHobby=Hobby,
				@rFatherQualification=FatherQualification,
				@rMotherQualification=MotherQualification,
				@rFatherOccupation=FatherOccupation,
				@rMotherOccupation=MotherOccupation,
				@rPreviousSchool=PreviousSchool,
				@rAdmissionCategoryId=AdmissionCategoryId,
				@rDOBFromDate=DOBFromDate,
				@rDOBToDate=DOBToDate,
				@rDOAFromDate=DOAFromDate,
				@rDOAToDate=DOAToDate,
				@rDOLFromDate=DOLFromDate,
				@rDOLToDate=DOLToDate,
				@rIsPysicalDeformity=IsPysicalDeformity,
				@rIsMajorIllness=IsMajorIllness,
				@rIsBlackList=IsBlackList,
				@rFromCode=FromCode,
				@rToCode=ToCode,
				@rCustomTagId=CustomTag,
				@rCustomGroupId = CustomGroup,
	            @rClubId = Club,
	            @rRepeatCount = RepeatCount,
	            @rStudentStatusId =StudentStatusId,
	            @rHostelId = Hostel,
	            @rStudentGroupId = StudentGroup,
	            @rStudentOtherGroupId = StudentOtherGroup,
	            
	           @rFeeExemption =FeeExemption
		FROM
			sStudent.tStudentCustomSearch
		WHERE
			Id=@rId
	END
	if(@rColumnName='ID No')
	BEGIN
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
	END
	if(@rOrderBy='ID No')
	BEGIN
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	END
	if(@rColumnName ='GR No')
	BEGIN
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
	END
	if(@rOrderBy ='GR No')
	BEGIN
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	END
	SET @rColumnName=Replace(@rColumnName,'PhysicalDeformityRemark','PysicalDeformityRemark')
	SET @rColumnName=Replace(@rColumnName,'IsPhysicalDeformity','IsPysicalDeformity')
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rCountry = sCommon.fSearchStringGet(@rCountry)
	SET @rState = sCommon.fSearchStringGet(@rState)
	--SET @rCity = sCommon.fSearchStringGet(@rCity)
	
		--IF (@rCustomTagId <> '')
		--BEGIN
		--	SELECT	
		--	DISTINCT SM.Id AS StudentId1
		--	INTO sStudent.tTempStudent3
		--	FROM sStudent.tStudentMaster SM
		--	INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
		--	INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		--	WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
		--	AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--END
		--ELSE
		--BEGIN
		--	SELECT 
		--	DISTINCT NULL AS StudentId1
		--	INTO sStudent.tTempStudent3
		--END
	
		-- For Custom Tag
		IF (@rCustomTagId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId1
			INTO sStudent.tTempStudent5
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId1
			INTO sStudent.tTempStudent5
		END
		
		-- For Custom Group
		IF (@rCustomGroupId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId2
			INTO sStudent.tTempStudent6
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId2
			INTO sStudent.tTempStudent6
		END
		
		-- For Club Group
		IF (@rClubId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId3
			INTO sStudent.tTempStudent7
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
			WHERE SM.OrgId = @rOrgId  AND A.BatchId = @BatchId 
			AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId3
			INTO sStudent.tTempStudent7
		END
		
		-- For Hostel
		IF (@rHostelId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId4
			INTO sStudent.tTempStudent9
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
			AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
			WHERE SM.OrgId = @rOrgId --AND A.BatchId = @BatchId 
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId4
			INTO sStudent.tTempStudent9
		END
	
	--Transport
		IF (@rBusRouteId <> '')
		BEGIN
			SELECT 
			DISTINCT SM.Id AS StudentId5
			INTO sStudent.tTempStudent10
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
			AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE SM.OrgId = @rOrgId 
			AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		END
		ELSE
		BEGIN
			SELECT 
			DISTINCT NULL AS StudentId5
			INTO sStudent.tTempStudent10
		END
		
		 
		SELECT 
			* into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
	    INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
	   --INNER JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6 OR @rFeeExemption = ''
		WHERE 
			SCS.OrgId = @rOrgId AND SCS.BatchId = @BatchId 
			AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
			AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
			AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
			AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%')OR(@rCountry = ''))
			AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
			--AND ((ISNULL(SCS.PermanentCity,'') Like @rCity + '%')OR(@rCity = ''))
			AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
			AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
			AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
			AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
			AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
			AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
				
			--AND (SCS.ClassId In( SELECT item FROM  sCommon.fnsplit(@rClassId,','))OR @rClassId=''))
		    
		    AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		    
		    AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		    
		    AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		         	          
			AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')	
	        
	        AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
	        
	        AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
		    
		    AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
		            
		    AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		           
		    AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		           
		    AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		                   
		    AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		           
		    AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		     
		    AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')		
		    
		    AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		    
		    AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		    
		    AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		    
		    AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
			
		    AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		    
			AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		
			AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
			
			AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
			
			 AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
			  
			AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		  
		  
			AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		    AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0)) 
		    AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		    AND ((SCS.Code >= @rFromCode) OR (@rFromCode=0))
		    AND ((SCS.Code <= @rToCode) OR (@rToCode=0))
			AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
			AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
			AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
			AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')		
			 AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')		
		if(@rColumnName='ID No')
		BEGIN
			SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [ID No]')
		END
		
		if(@rColumnName='GR No')
		BEGIN
			SET @rColumnName=Replace(@rColumnName,',Code',',Code AS [GR No]')
		END
		--SET @rColumnName=Replace(@rColumnName,',UIDNumber',','  +'&#39;+UIDNumber AS UIDNumber')
		--SET @rColumnName=Replace(@rColumnName,',UIDNumber',',' + '''''''''' +'+UIDNumber AS UIDNumber')
		 
			--select @rColumnName
		
		
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		exec(@Sql)
		
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10


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


GO
ALTER PROCEDURE [sSystem].[pIsAppUpgradeRequired]
	
	@rVersionNumber nvarchar(30)='',
	@rOSTypeId int = 0,
	@rOrgGroupId int = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	DECLARE @rOutput nvarchar(30)=''
	DECLARE @lVersionCode TABLE(Id int identity, VersionCode nvarchar(10))
	INSERT @lVersionCode SELECT * FROM sCommon.fnSplit(@rVersionNumber,'.')
	DECLARE @lCount int 
	SELECT @lCount = COUNT(VersionCode) FROM @lVersionCode
	DECLARE @LoopCounter INT = 1

	WHILE (@LoopCounter <= @lCount)
	BEGIN
		DECLARE @lVersionCodeSplited nvarchar(100)
		SELECT @lVersionCodeSplited = VersionCode FROM @lVersionCode WHERE Id = @LoopCounter
		
		IF(LEN(@lVersionCodeSplited)=2)
		BEGIN
			SET @rOutput = @rOutput + @lVersionCodeSplited
		END
		ELSE
		BEGIN
			SET @rOutput = @rOutput + '0' +@lVersionCodeSplited
		END
		SET @LoopCounter  = @LoopCounter  + 1
	END
	
	DECLARE @lInputVersionId int=0
	DECLARE @lVersionId int=0
	
	SET @lInputVersionId = CONVERT(int,@rOutput)
	
	SELECT TOP 1 @lVersionId = ISNULL(VersionId,0) FROM sSystem.tMobileAppStaticVersion WHERE OSTypeId = @rOSTypeId ORDER BY VersionId DESC 
	
	IF(@lVersionId <= @lInputVersionId)	
		SELECT 0 AS Result
	ELSE
		SELECT 1 AS Result
END
GO
PRINT N'Altering [sTally].[pReceiptPostingGet]...';


GO
ALTER PROCEDURE [sTally].[pReceiptPostingGet]

	 @rOrgGroupBatchId int,
	 @rReceiptBookId int,
	 @rReceiptDate Date,
	 @rToReceiptDate Date
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lTallyPostingType nVarchar(100)
	DECLARE @lOrgGroupId INT
	
	SELECT @lOrgGroupId = OrgGroupId from sSetup.tOrgGroupBatchMaster Where Id=@rOrgGroupBatchId
	
	SELECT @lTallyPostingType = CASE WHEN CS.ItemValue IS NULL THEN C.ItemValue ELSE CS.ItemValue END 
		FROM sConfig.tConfigurationMaster C
        INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
        LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id AND CS.SOURCEID= @lOrgGroupId
        WHERE  C.ItemKey = 'Tally.PostingType'
        
        IF @lTallyPostingType = 'FeeHeadWise' 
        BEGIN
			   SELECT	ReceiptDate,
						ISNULL(FHM.Title,'') AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						'' as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FHM.Id AS FeeId,
						0 AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					WHERE	FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
				group by ReceiptDate,FHM.Title,PM.Title,FHM.Id,FR.PayTypeId
				Order By ReceiptDate Desc
			END	
			
			IF @lTallyPostingType = 'ReceiptWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(SLM.LedgerName,'') AS FeeName,
						PM.Title AS PayType,						
						Sum(FRD.Amount) AS Amount,
						case When FR.PayTypeId = 1 then
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId <> 1 then 
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') + '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						AS Narration,					
						FR.PayTypeId AS PayTypeId,									
						A.StudentId AS FeeId,
						FRD.ReceiptId					 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId
					LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate					
				group by 
				ReceiptDate,PM.Title,
				SLM.LedgerName,FR.PayTypeId,A.StudentId,
				FRD.ReceiptId,Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),
				'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName				
				Order By ReceiptDate desc	
			END			
			
END
GO
PRINT N'Altering [sTally].[pStudentLedgerMappingGet]...';


GO
ALTER PROCEDURE [sTally].[pStudentLedgerMappingGet]

	 @rOrgId int,
	 @rReceiptBookId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
		SELECT 
		Distinct
			   ISNULL(SM.FirstName,'') + ' ' +  ISNULL(SM.MiddleName,'') + ' ' + ISNULL(SM.LastName,'') + '#' + CONVERT(NVARCHAR(10),ISNULL(SM.OrgId,0)) + '#' + CONVERT(NVARCHAR(20),ISNULL(SM.Code,0)) AS StudentName,
			   SM.Id AS StudentId,
			   ISNULL(SLM.LedgerName,'') AS LedgerName,
			   RCM.CompanyName
			FROM sStudent.tStudentMaster SM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId AND SM.OrgId = @rOrgId
			INNER JOIN sSetup.tOrgGroupBatchMaster OB ON OB.OrgGroupId = OM.OrgGRoupId
			INNER JOIN sTally.tReceiptBookCompanyMapping RCM ON RCM.OrgGroupBatchId = OB.Id AND RCM.ReceiptBookId=@rReceiptBookId
			LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId= SM.Id AND RCM.ReceiptBookId=SLM.ReceiptBookId	
		--WHERE SM.STATUSID= 1
END
GO
PRINT N'Altering [sTimetable].[pStudentTimeTableGet]...';


GO
ALTER PROCEDURE [sTimetable].[pStudentTimeTableGet]
	
	 @rStudentId bigint,
	 @rTimeTableSchemaId int,
	 @rDivisionId int
	 

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(Title) 
                    from sCommon.tDayMaster
                    group by Title,Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
     
 
set @query = 'SELECT LectureNumber , ' + @cols + ' from 
             (
            Select LectureNumber, ISNULL(EM.ShortName + '+ ''' - ''' +' + SM.Title,'''') AS EmployeeName ,DM.Title AS DayNames 
            from
            sTimetable.tTimeTable T 
            INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId AND TTS.IsPublish = 1
            INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=T.EmployeeId
	        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
	        INNER JOIN sStudent.tAcademic A ON A.DivisionId=T.DivisionId
	         WHERE    
	        ((A.StudentId=' + CAST(@rStudentId AS NVARCHAR(30))+'))
			AND  ((T.DivisionId=' + CAST(@rDivisionId AS NVARCHAR(30))+') OR ('+CAST(@rDivisionId AS NVARCHAR(30))+'= 0) )
	         AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') OR ('+CAST(@rTimeTableSchemaId AS NVARCHAR(30))+'= 0))
	       
            ) x
            pivot 
            (
                max(EmployeeName)
                for DayNames in (' + @cols + ')
            ) p '
            
print @query
execute(@query)
     
        
	
		
END
GO
PRINT N'Altering [sTimetable].[pTeacherTimeTableGet]...';


GO
 
 

ALTER PROCEDURE [sTimetable].[pTeacherTimeTableGet]
	
	 @rEmployeeId bigint,
	 @rBatchId int=0,
	 @rTimeTableSchemaId int
	

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(Title) 
                    from sCommon.tDayMaster
                    order by Id,Title 
                    
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
 
set @query = 'SELECT  LectureNumber,' + @cols + ' from 
             (
                Select LectureNumber, ISNULL(VBCD.ClassName + VBCD.DivisionName + ''  /  ''+ SM.Title,'''') AS DivisionTitle,DM.Title AS DayNames
            from
            sTimetable.tTimeTable T 
            INNER JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = T.TimeTableSchemaId AND TTS.IsPublish = 1
            INNER JOIN sCommon.tDayMaster DM ON DM.Id = T.DayId
            INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId
	        INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId
	         WHERE 
	        ((T.EmployeeId=' + CAST(@rEmployeeId AS NVARCHAR(30))+') OR ('+CAST(@rEmployeeId AS NVARCHAR(30))+'= 0))
	         
	         AND ((T.TimeTableSchemaId=' + CAST(@rTimeTableSchemaId AS NVARCHAR(30))+') )
            ) x
            pivot 
            (
                max(DivisionTitle)
                for DayNames in (' + @cols + ')
            ) p order by LectureNumber'
            
--print @query
 execute(@query)
     
    
     
     
     
     
     
     
      
        
	
		
END
GO
PRINT N'Altering [sTool].[pDeleteStaticData]...';


GO
 
ALTER PROCEDURE [sTool].[pDeleteStaticData]
 
	 
AS
SET NOCOUNT ON
BEGIN 
 

DELETE FROM sAlert.tEventMaster
DELETE FROM sCommon.tAutoCompleteMaster
DELETE FROM sCommon.tCommonMaster
DELETE FROM sCommon.tDepends
DELETE FROM sCommon.tModuleMaster
DELETE FROM sCommon.tPrefixFunctionality
DELETE FROM sCommon.tRefferedTableForObsoleteCheck
DELETE FROM sCommon.tRefferedTableWithoutForeignKey
DELETE FROM sCommon.tReport
DELETE FROM sCommon.tReportFormatGroupMaster
DELETE FROM sCommon.tReportGroupMaster
DELETE FROM sCommon.tSourceScreenMaster
DELETE FROM sCommon.tSourceTypeMaster
DELETE FROM sCommon.tStatusMaster
DELETE FROM sCommon.tStatusTypeMaster
DELETE FROM sCommon.tTableRowIdMaster
DELETE FROM sCommon.tUpdateFieldMaster
DELETE FROM sCommon.tValidationType
DELETE FROM sConfig.tColorLegendMaster
DELETE FROM sConfig.tConfigurationMaster
DELETE FROM sConfig.tConfigurationValue
DELETE FROM sSecurity.tMenu
DELETE FROM sSecurity.tResourceTypeMaster
DELETE FROM sSecurity.tScreen
DELETE FROM sSecurity.tScreenGroupMaster
DELETE FROM sSecurity.tScreenTypeMaster
DELETE FROM sSecurity.tTask
DELETE FROM sSystem.tTable
DELETE FROM sTool.tObjects
DELETE FROM sCommon.tReportTypeMaster


DELETE FROM sSetup.tAffiliationClassGroup
DELETE FROM sSetup.tAffiliationTypeMaster
DELETE FROM sSetup.tAffiliationMaster	
DELETE FROM sSetup.tStreamMaster

-- temp insert
DELETE FROM sAttendance.tAttendanceForMaster
DELETE FROM sEExam.tEntryModeMaster
DELETE FROM sSetup.tTermScopeMaster	 
 
DELETE FROM sConfig.tConfigurationLevelMaster

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

DELETE FROM sSecurity.tScreenGroupMapping
DELETE FROM sAssessment.tCCEExamMaster
DELETE FROM sSetup.tTermPatternMaster


DELETE FROM sAdmission.tAdmissionStatusMaster
DELETE FROM sAssessment.tCCERptGroup
DELETE FROM sHrm.tEmployeeICardTemplate
DELETE FROM sSecurity.tDashletMaster
DELETE FROM sStudent.tICardTemplate
DELETE FROM sSystem.tCustomQuery

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

DELETE FROM sOp.tPayTypeMaster
DELETE FROM sOp.tTransactionStatusMaster
--DELETE FROM sPayroll.tForm16B
DELETE FROM sStudent.tBatchStatusMaster
DELETE FROM [sFinanceCommon].[tPayTypeMaster]

DELETE FROM sAttendance.tAttendanceTagMaster
DELETE FROM sCommon.tLiveWithMaster
DELETE FROM sConfig.tDisplayFieldMaster

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

DELETE FROM sCommon.tCalculationTypeMaster
DELETE FROM sFee.tApplayAsMaster
DELETE FROM sSecurity.tScreenDependency
DELETE FROM sStudent.tSUIdFieldMaster

DELETE FROM [sAlert].[tAlertModeMaster]
DELETE FROM sCommon.tReportRemarkGroupMaster
DELETE FROM sStudent.tEnrollmentStatusMaster
DELETE FROM [sSetup].[tClassGroupMaster]

DELETE FROM sCommon.tTemplateSourceMaster
DELETE FROM sErp.tCustomerStatusMaster
DELETE FROM sErp.tInstallationTypeMaster
DELETE FROM sRecruitment.tRecruitmentStatusMaster

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

DELETE FROM sCommon.tImportFieldMaster
DELETE FROM sCRM.tHostingTypeMaster
DELETE FROM sHrm.tMainLeaveTypeMaster

DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sHrm.tTravelPeriodMaster
DELETE FROM sLoan.tInsterestTypeMaster

DELETE FROM sAppraisal.tBHRatingStatus
DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sAppraisal.tKPAMeasureMaster
DELETE FROM sAppraisal.tKPATypeMaster
DELETE FROM sAppraisal.tRatingStatus
DELETE FROM sCommon.tHeaderDisplayMaster
DELETE FROM sCommon.tModuleGroupMaster
DELETE FROM sHrm.tLeaveTransactionMaster
DELETE FROM sCommon.tCheckFrequencyMaster

DELETE FROM sErp.tLeadAffiliationMaster
DELETE FROM sErp.tLeadSourceMaster
DELETE FROM sErp.tLeadStatusMaster

DELETE FROM sSystem.tStaticVersion

DELETE FROM sCommunication.tFeedBackAnswerGroupMaster

DELETE FROM sCommon.tSubmitDocumentFunctionalityMaster
DELETE FROM sSetup.tMandatoryFeild
DELETE FROM sSetup.tMandatoryFeildFunctionalityMaster

DELETE FROM sSystem.tTimeZone
DELETE FROM sTool.tTestCaseTypeMaster

DELETE FROM sAlumni.tEmployeementType

DELETE FROM sErp.tCampusTypeMaster

END
GO
PRINT N'Altering [sTool].[pUpgradeVersion]...';


GO
 



ALTER PROCEDURE [sTool].[pUpgradeVersion]
	 
	@rVersionId int,
	@rVersion nvarchar(20),
	@rOrgGroupId int
	 
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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


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

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



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

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

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

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

-- update tablerowid master data from excel to table

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

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

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



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




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId


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

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


IF NOT EXISTS(SELECT 1 FROM sAdmission.tInquiryStatusMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sAdmission.tInquiryStatusMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,StatusId)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Title
						,Title
						,0
						,1
						,getdate()
						,NULL
						,NULL
						,@rOrgGroupId
						,Id						
						FROM sCommon.tStatusMaster
						where statustypeId = 104
						
	DECLARE @lMaxId int
	SET @lMaxId = sCommon.fGetIntIdForOrg(213,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sAdmission.tInquiryStatusMaster', @rCurrentNumber = @lMaxId
						
END




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

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

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

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


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

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

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


			
			
END


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

END


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

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

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

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

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

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

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

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

END
GO
PRINT N'Creating [sAdmission].[pRptAdmissionReceiptGet]...';


GO

CREATE PROCEDURE [sAdmission].[pRptAdmissionReceiptGet]
	 	 
	 	 @rBatchId int,
	 	 @rOrgId int ,
	 	 @rFormNo int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
			'' AS StudentName,
			'' AS FatherName,
			'' AS MotherName,
			'' AS StudentAddress,
			'' AS MobileNo,
			'' as FormNo,
			0 as ReceiptNumber,
			'' as ReceiptDate,
			'' AS ClassName,
			'' AS BatchName,
			0.0 as FormFeeAmount,
			'' AS FormFeeName 
	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
	WHERE
		 AF.BatchId = @rBatchId
		AND AF.OrgId = @rOrgId
		AND AF.FormNo =@rFormNo
END
GO
PRINT N'Creating [sAssessment].[pMarkEntryGenerate_New]...';


GO
CREATE PROCEDURE [sAssessment].[pMarkEntryGenerate_New]
	 	
	@rExamId int,
	@rClassId int,
	@rDivisionId int,
	@rExamList nvarchar(500),
	@rOrgId int,
	@rBatchId int 	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
BEGIN
	--BEGIN TRY
	 BEGIN	
	 DECLARE @lNextNumber BIGINT 
	 DECLARE @lResultId BIGINT
	 DECLARE @lCount INT
	 DECLARE @lMarkInDecimal bit
	 Declare @lExamId BigInt
	 DECLARE @Query nvarchar(max),@lIsMarksInDecimal bit,@lDecimalFormat nvarchar(10)
	 
		
	 select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId
	select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id= @rExamId

------- Result Master Entry	 
     IF NOT EXISTS (SELECT 1 FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId AND A.BatchId=@rBatchId
				AND R.ExamId=@rExamId AND A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0))		
	BEGIN
	
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResult', 0, 1, 1,@outNextNumber = @lNextNumber output	
		
		INSERT INTO sAssessment.tResult (Id,ExamId,AcademicId,TotalMarks,TotalObtain,ResultStatus,ResultGrade,ResultGradePoint,
		RankNumber,Percentage,Percentile,ResultRemark,OtherRemark1,UpdatedUserId,UpdatedDateTime) 
		
		SELECT @lNextNumber + ROW_NUMBER() OVER(ORDER BY A.AcademicId) AS Id,@rExamId,A.AcademicId,0,0,'','',0,0,0,0,'','',1,GETDATE() 
		From sStudent.vStudentAcademic A
		Where A.ClassId=@rClassId AND (A.DivisionId=@rDivisionId OR @rDivisionId=0) AND A.StatusId=1 AND A.BatchId=@rBatchId
		
		SELECT @lCount = COUNT(1) FROM sStudent.vStudentAcademic WHERE ClassId=@rClassId AND (DivisionId=@rDivisionId OR @rDivisionId =0) AND BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResult', @rCurrentNumber = @lNextNumber
			
	END
 --------- Result Detail Entry   
 
  IF NOT EXISTS (SELECT 1 FROM sAssessment.tResultDetail RD 
    INNER JOIN sAssessment.tResult R ON R.Id=RD.ResultId AND R.ExamId=@rExamId
    INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=R.AcademicId AND A.ClassId = @rClassId AND A.BatchId=@rBatchId
    AND (A.DivisionId=@rDivisionId OR @rDivisionId = 0)
    )
    BEGIN	
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tResultDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
				
				SET @Query = 'INSERT INTO sAssessment.tResultDetail (Id,ResultId,ExamDetailId,IsPresent,Obtain) 
						SELECT ' + CONVERT(NVARCHAR,@lNextNumber) + ' + ROW_NUMBER() OVER(ORDER BY ED1.ClassSubjectId) AS Id,
						R.Id,ED1.Id AS ExamDetailId,1 AS IsPresent,
						CASE WHEN  (SELECT Sum(ISNULL(Obtain,0))/SUM(Maximum)  AS Obtain FROM sAssessment.tResult RM 
						INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
						
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + ' AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
						AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
						INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId 
						WHERE RM.ExamId IN ' + @rExamList + ' AND RM.AcademicId = R.AcademicId AND ED.ClassSubjectId= ED1.ClassSubjectId
					    GROUP BY RM.AcademicId,ED.ClassSubjectId) * ED1.Maximum IS NULL THEN 0 ELSE 
						
						(SELECT Sum(ISNULL(Obtain,0))/SUM(Maximum)  AS Obtain FROM sAssessment.tResult RM 
						INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
						INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
						AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )
						INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
						INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = SA.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId 
						WHERE RM.ExamId IN ' + @rExamList + ' AND RM.AcademicId = R.AcademicId AND ED.ClassSubjectId= ED1.ClassSubjectId
					    GROUP BY RM.AcademicId,ED.ClassSubjectId) END  * ED1.Maximum  AS OBTAIN
					FROM 	sAssessment.tResult R 
							INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId = ' + CONVERT(NVARCHAR,@rClassId) + '
							INNER JOIN sAssessment.tExamDetail ED1 ON ED1.ExamId = R.ExamId
							AND (SA.DIVISIONID= ' + CONVERT(NVARCHAR,@rDivisionId) + ' OR ' + CONVERT(NVARCHAR,@rDivisionId) + ' = 0 )					
							and R.ExamId=' + CONVERT(NVARCHAR,@rExamId)
			
								
		--print(@Query)
		execute(@Query)
		
		SELECT @lCount = COUNT(RD.Id) FROM sAssessment.tResultDetail RD 
		INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id AND R.ExamId=@rExamId 
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.AcademicId AND SA.ClassId=@rClassId AND (SA.DivisionId=@rDivisionId OR @rDivisionId =0) AND SA.BatchId=@rBatchId
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tResultDetail', @rCurrentNumber = @lNextNumber 
		END
				  UPDATE RD SET RD.OBTAIN =  
(CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
Round((A.Obtain/Maxi)*ED.Maximum ,1)
WHEN ( @lIsMarksInDecimal = 1 AND @lDecimalFormat='0.00') 
THEN Round(Round((A.Obtain/Maxi)*ED.Maximum,2),2) 
ELSE	   
Round(ROUND((A.OBTAIN/Maxi)*ED.Maximum ,2),0) END)
											
								 FROM
						(SELECT 
							Sum(Obtain) AS Obtain,
							Sum(Maximum) AS Maxi,RM.AcademicId,ED.ClassSubjectId
						FROM sAssessment.tResult RM 
							INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
							INNER JOIN sAssessment.tExamMaster EM ON EM.Id = RM.ExamId
							INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = RM.AcademicId AND SA.BatchId = @rBatchId AND SA.ClassId = @rClassId
							AND (SA.DIVISIONID= @RDivisionId OR @RDivisionId = 0 )
							INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id AND ED.ExamId = EM.Id
							WHERE RM.ExamId IN (SELECT  cast(item as int) AS ExamID FROM  sCommon.fnsplit( REPLACE(REPLACE(@rExamList,'(',''),')','') ,','))
						GROUP BY RM.AcademicId,ED.ClassSubjectId )A
					INNER JOIN sAssessment.tResult R ON R.AcademicId =A.AcademicId
					INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND SA.ClassId = @rClassId
					AND (SA.DIVISIONID= @RDivisionId OR @RDivisionId = 0 )
					INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id  AND ED.ClassSubjectId=A.ClassSubjectId 
					AND RD.ExamDetailId=ED.Id AND ED.ExamId = @rExamId
		  
		SELECT 1 AS RESULT
   END
   --COMMIT TRANSACTION
	--END TRY

	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
PRINT N'Creating [sAssessment].[pTeacherEvaluationSubjectWiseGet]...';


GO
 

CREATE PROCEDURE [sAssessment].[pTeacherEvaluationSubjectWiseGet]
	 
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 --@rOrgId int=0,
	 @rGroupid int=0,
	 @rEmployeeId bigint=0,
	 @rSubjectId int=0
 	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	 select 
		@rBuilder1 AS Builder1,
		CM.ClassId  As ClassId,
		Dm.id As DivisionId,
		CS.Id AS ClassSubjectId,
		SM.Id AS SubjectId,
		SM.Code AS SubjectName,
		Cm.ClassName AS ClassName,
		DM.DisplayTitle AS DivisionName,
		Sm.OrderIndex As SubjectOrderIndex,
		case when @rGroupid=1 THEN Dm.Id
		when @rGroupid=2 THEN ClassName
		when @rGroupid=3 THEN CM.DepartmentId
	    when @rGroupid=4 THEN OM.Id
		ELSE 0  END  AS HeadId,
		case when @rGroupid=1 THEN ' Division : ' +CM.ClassName+ ' / '+Dm.DisplayTitle   
		when @rGroupid=2 THEN ' Class : ' + CM.ClassName
		when @rGroupid=3 THEN 'Department: ' + DP.Title 
		WHen @rGroupid=4 THen  'Organization : '+Om.Title END  AS HeadName,
		CASE WHEN @rGroupid=1 THEN DM.OrderIndex
				WHEN @rGroupid=2  THEN CM.OrderIndex
				WHEN @rGroupid=3  THEN DP.Id
				WHen @rGroupid=4 THen OM.OrderIndex  END AS OrderIndex,
		TS.EmployeeId,
		EMP.FirstName+' ' +EMP.MiddleName+' '+EMP.LastName AS EMPName,
	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
		INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId=CS.SubjectId AND TS.SubjectId=@rSubjectId
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId 
	  AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum AND TS.SubjectId=@rSubjectId) AS PassStudent,
  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	 INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	 INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
	 INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	 INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId=CS.SubjectId AND TS.SubjectId=@rSubjectId
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum AND TS.SubjectId=@rSubjectId) AS FailStudent 
	  
	 from
	 ssetup.tDivisionMaster DM
	 INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId 
	INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId 
	 INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DP.OrgId
INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId  AND TS.DivisionId=DM.ID
INNER JOIN sHrm.tEmployeeMaster EMP ON EMP.Id=TS.EmployeeId
		WHERE 
			--((DM.ID=@rDivisionId) or (@rDivisionId=0))
			--AND ((CM.Id=@rClassId) or (@rClassId=0))
			   CM.BatchId=@rBatchId
			AND EM.ExamSubGroupId = @rExamSubGroupId
			AND EM.BatchId = @rBatchId
			 AND TS.SubjectId=@rSubjectId
			
			
 -- UNION ALL
  
  
 -- 	 select 
	--	@rBuilder1 AS Builder1,
	--	DM.Classid As ClassId,
	--	Dm.id As DivisionId,
	--	--Cm.ClassName As Classname,
	--	--DM.DisplayTitle As DivisionName,
	--0 AS ClassSubjectId,
	--	0 AS SubjectId,
	--	'Over All' AS SubjectName,
	--	0 AS ClassOrderIndex,
	--	case when @rGroupByid=1 THEN Dm.Id
	--	when @rGroupByid=2 THEN CM.Classid
	--	when @rGroupByid=3 THEN CM.DepartmentId
	--    when @rGroupByid=4 THEN OM.Id
	--	ELSE 0    END  AS HeadId,
	--	case when @rGroupByid=1 THEN ' Division : ' +CM.ClassName+ ' / '+Dm.DisplayTitle  
	--	when @rGroupByid=2 THEN ' Class : ' + CM.ClassName  
	--	when @rGroupByid=3 THEN 'Department: ' + DP.Title 
	--	WHen @rGroupByid=4 THEN  'Organization : '+OM.Title
	--	END  AS HeadName,
	--	CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
	--			WHEN @rGroupByid=2  THEN CM.OrderIndex
	--			WHEN @rGroupByid=3  THEN DP.Id
	--			WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex,
	 

 --(select COUNT(R.AcademicId) from   sAssessment.tResult R  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	--  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND R.ResultStatus='PASS') AS PassStudent,
	  
	--  (select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	--  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL') AS FailStudent 
	  
	-- from
	-- ssetup.tDivisionMaster DM
	-- INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	-- INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId	
	--INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	-- INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	-- INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
 --   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DP.OrgId
 --   INNER JOIN sAcademic.tTeacherSubject TS ON TS.SubjectId=CS.SubjectId AND TS.EmployeeId=@rEmployeeId
	--	WHERE 
	--		((DM.ID=@rDivisionId) or (@rDivisionId=0))
	--		AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
	--		AND CM.BatchId=@rBatchId
	--		AND EM.ExamSubGroupId = @rExamSubGroupId
	--		AND EM.BatchId = @rBatchId
	--		AND TS.EmployeeId=@rEmployeeId
	END
GO
PRINT N'Creating [sCommunication].[pAllPhotoCategory_Get]...';


GO
 
CREATE PROCEDURE [sCommunication].[pAllPhotoCategory_Get]
	 
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 --@rOrgGroupId smallint,
	 
	 --@rOrgGroupBatchID int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

  declare @lOrgGroupId smallint,@lOrgGroupBatchID int,@lOrgId smallint
  
    
	Select @lOrgGroupId=OM.OrgGRoupId from sSetup.tOrganizationMaster OM
	INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id
	Where Bm.Id=@rBatchId
     
  SELECT   PCM.[Id]
  		  ,PCM.[Title]
          ,PCM.[IsObsolete],
          ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId
          
  FROM    [sCommunication].[tPhotoCategoryMaster]  PCM 
            
  WHERE   
      PCM.IsObsolete = 0
      AND ((PCM.Id = @rId) OR (@rId = 0))
      AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
      --AND PCM.ScopeSourceTypeId=@rScopeSourceId
      AND OrgGroupId=@lOrgGroupId
      ORDER BY PCM.CreatedDateTime DESC
    
END
GO
PRINT N'Creating [sCommunication].[pFeedbackQuestionDataGet]...';


GO
CREATE PROCEDURE [sCommunication].[pFeedbackQuestionDataGet]
	  
	 
	 @rOrgGroupBatchId int,
	 @rFeedbackId bigint ,
	 @rFeedbackForId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	  
	 SELECT	
			count(*) CountData,
			FQ.ID,
			FQ.QuestionNumber,
			FQ.Question,
			FQ.FeedbackTemplateId
					
		from sCommunication.tFeedback FB 
		INNER JOIN	sCommunication.tFeedbackTemplateQuestion FQ ON FQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FQR ON FQR.FeedbackID = FB.Id
		INNER JOIN sCommunication.tFeedbackQuestionResponse FA ON  FA.FeedBackResponseId = FQR.Id and FA.FeedbackTemplateQuestionId = FQ.Id 
						and ((ISNULL(FA.FeedbackAnswerDescription,'')!='') Or (FA.FeedbackAnswerTypeDetailId!=0))
	 
		WHERE FB.Id = @rFeedbackId ANd OrgGroupBatchId=@rOrgGroupBatchId  And FQR.FeedbackForId = @rFeedbackForId  
		Group by  FQ.Id,FQ.QuestionNumber,FQ.Question,FQ.FeedbackTemplateId 
		 
		 END
GO
PRINT N'Creating [sErp].[pDSRMasterAdd]...';


GO

Create PROCEDURE [sErp].[pDSRMasterAdd]

        @rId int,
        @rReportDate date,
        @rProjectId int,
        @rModule nvarchar(max),
        @rWorkTypeId int,
        @rWorkDescription nvarchar(max),
        @rHoursWorked decimal(5, 2),
        @rOrgId smallint,
        @rCreatedUserId bigint        
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 
	 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tDSR', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tDSR
		(
		    Id, 
		    ReportDate, 
		    ProjectId, 
		    Module, 
		    DSRWorkTypeId, 
		    WorkDescription, 
		    HoursWorked, 
		    OrgId,
		    CreatedUserId, 
		    CreatedDateTime, 
		    UpdatedDateTime ,
		    UpdatedUserId      
		)
	VALUES
		(
			@lNextNumber,
			@rReportDate,
			@rProjectId,
			@rModule,
			@rWorkTypeId,
			@rWorkDescription,
			@rHoursWorked,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			sCommon.fGetDate(),
			@rCreatedUserId
		)
		    SELECT 1 AS Result
	END	 
  ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tDSR
	    SET
			ReportDate = @rReportDate,
			ProjectId = @rProjectId,
			Module = @rModule,
			DSRWorkTypeId = @rWorkTypeId,
			WorkDescription = @rWorkDescription,
			HoursWorked = @rHoursWorked,
			OrgId = @rOrgId,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      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'Creating [sErp].[pDSRMasterGet]...';


GO


CREATE PROCEDURE [sErp].[pDSRMasterGet]

	 @rId int,
	 @rOrgId smallint,
	 @rModule nvarchar(100),
	 @rProjectId int ,
	 @rWorkTypeId int 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rModule = sCommon.fSearchStringGet(@rModule)
	END
	
	SELECT 
			PT.Id,
			PT.ReportDate,
			PT.ProjectId,
		    PT.Module,
		    PT.DSRWorkTypeId,
		    PT.WorkDescription,
		    PT.HoursWorked,
		    PT.CreatedUserId,
		    PT.CreatedDateTime,
		    PM.Title as Project,
		    Dwt.Title as DSRWorkType
		 
		
	FROM 
			sErp.tDSR  PT
			inner join sErp.tDSRWorkTypeMaster Dwt on Dwt.Id = PT.DSRWorkTypeId
			inner join sErp.tProjectMaster PM on PM.Id = PT.ProjectId
	WHERE 
		(PT.OrgId = @rOrgId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((PT.Module like @rModule) OR (ISNULL(@rModule,'') = ''))
		AND	((PT.ProjectId = @rProjectId) OR (@rProjectId = 0))
		AND	((PT.DSRWorkTypeId = @rWorkTypeId) OR (@rWorkTypeId = 0))
END
GO
PRINT N'Creating [sErp].[pDSRWorkTypeMasterAdd]...';


GO

Create PROCEDURE [sErp].[pDSRWorkTypeMasterAdd]

        @rId int,
        @rTitle nvarchar(100),
        @rCode nvarchar(100),
        @rInActive bit = 0,
        @rOrgId smallint,
        @rCreatedUserId bigint        
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		
		If Exists(select Id from sErp.tDSRWorkTypeMaster  where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		
		If Exists(select Id from sErp.tDSRWorkTypeMaster  where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		
		If  Exists(select Id from sErp.tDSRWorkTypeMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
			If  Exists(select Id from sErp.tDSRWorkTypeMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tDSRWorkTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tDSRWorkTypeMaster

		(
			Id,
			Code,
			Title,			
			OrgId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedDateTime,
			UpdatedUserId			
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rOrgId,
			@rInActive,
			@rCreatedUserId,
			sCommon.fGetDate(),
			sCommon.fGetDate(),
			@rCreatedUserId
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tDSRWorkTypeMaster
	    SET
			Code = @rCode,
			Title=@rTitle,
			IsObsolete=@rInActive,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      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'Creating [sErp].[pDSRWorkTypeMasterGet]...';


GO

Create PROCEDURE [sErp].[pDSRWorkTypeMasterGet]

	 @rId int,
	 @rOrgId smallint,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
			PT.Id,
			PT.Title,
			PT.Code,
		    PT.OrgId,
		    PT.CreatedUserId,
		    PT.CreatedDateTime,
		    PT.IsObsolete
		    
	FROM 
			sErp.tDSRWorkTypeMaster  PT
	WHERE 
		(PT.OrgId = @rOrgId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((PT.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((PT.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
END
GO
PRINT N'Creating [sErp].[pProjectAdd]...';


GO

CREATE PROCEDURE [sErp].[pProjectAdd]

        @rId int,
        @rTitle nvarchar(100),
        @rCode nvarchar(100),
        @rInActive bit = 0,
        @rOrgId smallint,
        @rCreatedUserId bigint        
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		
		If Exists(select Id from sErp.tProjectMaster  where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
		
		If Exists(select Id from sErp.tProjectMaster  where Code=@rCode AND OrgId=@rOrgId)
			BEGIN
			select -104 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		
		If  Exists(select Id from sErp.tProjectMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
			If  Exists(select Id from sErp.tProjectMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tProjectMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tProjectMaster
		(
			Id,
			Code,
			Title,			
			OrgId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedDateTime,
			UpdatedUserId			
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
			@rOrgId,
			@rInActive,
			@rCreatedUserId,
			sCommon.fGetDate(),
			sCommon.fGetDate(),
			@rCreatedUserId
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tProjectMaster
	    SET
			Code = @rCode,
			Title=@rTitle,
			IsObsolete=@rInActive,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
	      
	      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'Creating [sErp].[pProjectGet]...';


GO

CREATE PROCEDURE [sErp].[pProjectGet]

	 @rId int,
	 @rOrgId smallint,
	 @rTitle nvarchar(100),
	 @rCode nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
			PT.Id,
			PT.Title,
			PT.Code,
		    PT.OrgId,
		    PT.CreatedUserId,
		    PT.CreatedDateTime,
		    PT.IsObsolete
		    
	FROM 
			sErp.tProjectMaster PT
	WHERE 
		(PT.OrgId = @rOrgId)
		AND	((PT.Id = @rId) OR (@rId = 0))
		AND ((PT.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((PT.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
END
GO
PRINT N'Creating [sFee].[pFeePendingListGet]...';


GO
CREATE PROCEDURE [sFee].[pFeePendingListGet]
		
		@rOrgGroupBatchId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rCode nvarchar(20)='',
		@rFirstName nvarchar(100)='',
		@rLastName nvarchar(100) = '',
		@rReceiptBookId int=0,
		@rOrgId int=0,
		@rBatchId int=0,
		@rDepartmentId int=0,
		@rSUId nvarchar(20) = ''
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END		 
BEGIN 	
	
	DECLARE @p AS TempPendingFee
	
	INSERT INTO @p 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName
  FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId				
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			    ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				
			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
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			WHERE
		        ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				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 sSetup.tBatchMaster BM ON BM.Id=SA.BatchId	
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId)) 
         LEFT JOIN
		(
			SELECT 
				AT.SourceId,
				B.OrgGroupBatchId 
			FROM 
				sTransport.tAssignRoute AT 
				INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		) RT ON RT.SourceId = SA.StudentId 
		AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.Code=@rSUId) OR (@rSUId=''))
			AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
			AND ((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND SA.	StatusId = 1
			
			ORDER BY SA.RollNo
 
			SELECT
				OrgId,			 
				ReceiptBookId,
				AcademicId,
				DivisionId,
				ClassDivision,
				RollNo, 
				Name,
				Code,
				ReceiptBookTitle,
				OrgName,
				SUM(PendingAmount) AS PendingAmount, 
				[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
				ReceiptOrderIndex,
				BatchId,
				BatchName,
				'' AS SUId
			FROM @p 
				GROUP BY 
				OrgId,AcademicId,ReceiptBookId,DivisionId,BatchId,
				ClassDivision,RollNo, Name,Code,ReceiptBookTitle,
				OrgName,ReceiptOrderIndex,BatchName
				ORDER BY AcademicId
END
GO
PRINT N'Creating [sFee].[pGSTReceiptAdd]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

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

BEGIN
	BEGIN TRY

	  SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId
	
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
	END
	ELSE	
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId)

EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rIsCreated = @lIsCreated OUTPUT
 	IF(@lIsCreated = 1)
 		BEGIN
			SELECT -501 AS Result
			RETURN
		END
 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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


	INSERT INTO sFee.tReceipt
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptNumber,
		   ReceiptDate,
		   ReceiptAmount,
		   TotalReceiptAmount,
		   DiscountAmount,
		   PayTypeId,
		   ChequeNo,
		   BankName,
		   ReceiptBookId,
		   Remark,
		   IsObsolete,
		   BatchId,
		   CreatedUserId,
		   CreatedDateTime,
		   OrgGroupBatchId,
		   ChequeDate,
		   FeeInvoiceId,
		   CollectionGroupId,
		   AmountAfterDiscount,
		   CGSTPercentage,
		   SGSTPercentage,
		   CGSTAmount,
		   SGSTAmount
        )
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
		    @rReceiptNumber,
		    @rReceiptDate,
		    @rReceiptAmount,
		    @rTotalReceiptAmount,
		    @rDiscountAmount,
		    @rPayTypeId,
		    @rChequeNo,
		    @rBankName,
		    @rReceiptBookId,
		    @rRemark,
		    @rIsObsolete,
		    @rBatchId,
		    @rCreatedUserId,
		    sCommon.fGetDate(),
		    @rOrgGroupBatchId,
		    @rChequeDate,
		    @rFeeInvoiceId,
		    @rCollectionGroupId,
		    @lAmountAfterDiscount,
		    @lCGSTPercentage,
		    @lSGSTPercentage,
		    @lCGSTAmount,
		    @lSGSTAmount
		)
		
		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		
	FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
		IF (@rCharge > 0)
		BEGIN
		EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
		END
	
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) FROM sFee.tReceiptBookMaster where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
		EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
		END
 END 
	ELSE
	BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
	SELECT @rId AS RESULT
	END 
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sFee].[pRptStudentCountStatusGet]...';


GO
CREATE PROCEDURE [sFee].[pRptStudentCountStatusGet]  
    
		@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,  
		@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  
    
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN  
  
		DECLARE @rStudentCountStatus TABLE (  
			AcademicId bigint,  
			ReceiptBookId int, 
			OrgId int, 
			DepartmentId int, 
			ClassId int, 
			DivisionId int, 
			Amount decimal(12,0),  
			FAAmount decimal(12,0),  
			DiscountAmount decimal(12,0),  
			AdditionalAmount decimal(12,0),  
			NotApplicableAmount decimal(12,0),  
			PaidAmount decimal(12,0),  
			PendingAmount decimal(12,0)  
		)  
   
		INSERT INTO @rStudentCountStatus  
			SELECT   
			SA.AcademicId,  
			FS.ReceiptBookId,
			SA.OrgId,
			SA.DepartmentId,
			SA.ClassId,
			SA.DivisionId,  
			ISNULL(FS.Amount,0)AS Amount,  
			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  
		FROM   
		sStudent.vStudentAcademic SA  
		INNER JOIN   
		(  
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId  
		FROM sFee.tFeeSetup FS1  
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId  
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
		WHERE   
			((FS1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND (FS1.IsOptional=0)  
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			
		UNION ALL  

		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId  
			FROM sFee.tFeeSetup FS1  
			INNER JOIN sFee.tFeeOptional FO  
			ON FO.FeeSetupId=FS1.Id   
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId  
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId  
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))   
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
		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='')  
			) FS ON FS.AcademicId=SA.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId  
		LEFT JOIN  
		(  
		SELECT   
			ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId  
		FROM  
			sFee.tReceipt R   
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId   
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND (SA1.ClassId=@rClassId OR @rClassId=0)   
			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)  
		WHERE    
			(R.SourceTypeId = 2001)  
			AND (R.IsObsolete = 0)   
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)  
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND (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='')  
		GROUP BY FeeSetupId,R.SourceId  
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId  
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id  
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id  
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId   
		LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId  
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
		LEFT JOIN 
		(  
		SELECT   
			AT.SourceId   
		FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		) RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
		WHERE   
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))  
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))     
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))     
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
			AND ((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)))  
			)   
		ORDER BY SA.RollNo  
     
     
		DECLARE @rFinalResult TABLE (     
		DivisionId int,  
		ReceiptBookId int, 
		OrgId int, 
		DepartmentId int, 
		ClassId int, 
		FullyPaid decimal(12,2),  
		FullyUnPaid decimal(12,2),  
		PartiallyPaid decimal(12,2),  
		Additional decimal(12,2),  
		Exemption decimal(12,2),  
		NA decimal(12,2)  
		)  
  
 

		INSERT INTO @rFinalResult  

		SELECT DivisionId,ReceiptBookId,OrgId,DepartmentId,ClassId,
		ISNULL((SELECT COUNT(Academicid) FROM  
		(SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)=SUM(PaidAmount)) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS FullyPaid, 

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		GROUP BY DivisionId,AcademicId   
		HAVING SUM(PaidAmount)=0  ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0)  AS FullyUnPaid,  

		ISNULL((SELECT COUNT(Academicid) FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(Amount)+SUM(FAAmount)<> SUM(PaidAmount)  AND SUM(PaidAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS PartiallyPaid,  

		ISNULL((SELECT COUNT(Academicid)  FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(AdditionalAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0)AS Additional,  

		ISNULL((SELECT COUNT(Academicid)  FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(DiscountAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS Exemption,  

		ISNULL((SELECT COUNT(Academicid)  FROM  (  
		SELECT Academicid,DivisionId FROM @rStudentCountStatus  
		GROUP BY DivisionId,AcademicId   
		HAVING  SUM(NotApplicableAmount) > 0 ) AS A  
		GROUP BY A.DivisionId Having A.DivisionId=SCS.DivisionId),0) AS NA  
		FROM @rStudentCountStatus SCS Group By DivisionId,ReceiptBookId, OrgId,  DepartmentId, ClassId
  
		SELECT  
			@rBuilder1 AS Builder1,  
			@rBuilder2 AS Builder2,  
			@rIsDetail AS IsDetail,  
			@rIsFilter As IsFilter,  
			@rIsHeader As IsHeader,   
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
			RBM.Id AS ReceiptBookId,  
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
			OM.Id AS OrgId,  
			OM.DisplayTitle AS OrgName,  
			OM.OrderIndex AS OrgOrderIndex,  
			DM.Id AS DepartmentId,  
			DM.Title AS DepartmentName,  
			CM.Id AS ClassId,  
			CM.Title AS ClassName,  
			CM.OrderIndex AS ClassOrderIndex,  
			DivM.Id AS DivisionId,  
			DivM.Title AS DivisionName,  
			DivM.OrderIndex AS DivisionOrderIndex,  
			CM.Title+' - '+DivM.Title AS ClassDivision,  
			FR.FullyPaid,  
			FR.FullyUnPaid,  
			FR.PartiallyPaid,  
			FR.Additional,  
			FR.Exemption,  
			FR.NA  
		FROM 
			@rFinalResult FR  
			INNER JOIN sSetup.tDivisionMaster DivM ON  FR.DivisionId = DivM.Id  
			INNER JOIN sSetup.tClassMaster CM ON  CM.Id = FR.ClassId  
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = FR.DepartmentId  
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = FR.OrgId 
			INNER JOIN sFee.tReceiptBookMaster RBM ON  RBM.Id = FR.ReceiptBookId
END
GO
PRINT N'Creating [sLibrary].[pRptMagazineMonthlyList]...';


GO


CREATE PROCEDURE [sLibrary].[pRptMagazineMonthlyList]

	 
	@rLibraryId int=0 ,
 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rMagazineTypeId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		--Select 
		--	'' V1,'' V2,'' V3,'' V4,'' V5,'' V6,'' V7,'' V8,'' V9,'' V10,'' V11,'' V12,0 Id,
		--	'' Title,'' I1,'' I2,'' I3,'' I4,'' I5,'' I6,'' I7,'' I8,'' I9,'' I10,'' I11,'' I12 ,
		--	 0 P1,0 P2,0 P3,0 P4,0 P5,0 P6,0 P7,0 P8,0 P9,0 P10,0 P11,0 P12,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2,
		--    '' ReportOrgTitle,'' SmallAddress1,'' SmallAddress2
	Declare @lCount int
	Declare @MagazineId bigint
	Create Table #temp
	(
			Id int identity,MagazineId nvarchar(20),V1 nvarchar(max),V2 nvarchar(max),V3 nvarchar(max),V4 nvarchar(max),V5 nvarchar(max),V6 nvarchar(max),
			V7 nvarchar(max),V8 nvarchar(max),V9 nvarchar(max),V10 nvarchar(max),V11 nvarchar(max),V12 nvarchar(max),
			I1 nvarchar(max),I2 nvarchar(max),I3 nvarchar(max),I4 nvarchar(max),I5 nvarchar(max),I6 nvarchar(max),
			I7 nvarchar(max),I8 nvarchar(max),I9 nvarchar(max),I10 nvarchar(max),I11 nvarchar(max),I12 nvarchar(max),
			P1 decimal(8,2),P2 decimal(8,2),P3 decimal(8,2),P4 decimal(8,2),P5 decimal(8,2),P6 decimal(8,2),
			P7 decimal(8,2),P8 decimal(8,2),P9 decimal(8,2),P10 decimal(8,2),P11 decimal(8,2),P12 decimal(8,2),
	)
	Insert Into #temp
	(
			MagazineId--V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12
			
	)
    Select  Id from sLibrary.tMagazineMaster
    Where  LibraryId=@rLibraryId
    AND ((MagazineTypeId=@rMagazineTypeId) OR (@rMagazineTypeId=0))
    	
    select  @lCount=COUNT(*) from #temp
    while(@lCount>0)
    BEGIN
		select @MagazineId = MagazineId from #temp Where Id= @lCount
		 
		Update #temp Set V1 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
						AND Month(ReceiveDate)=1 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I1 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=1
					  AND tm.MagazineId=@MagazineId 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 P1 = (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=1)
					 Where MagazineId=@MagazineId 
					 
		  Update #temp Set V2 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=2 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					I2 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=2
					  AND tm.MagazineId=@MagazineId

					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					  P2 = (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=2)
					Where MagazineId=@MagazineId 
					 
		  Update #temp Set V3 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=3 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I3 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=3
					AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 P3 = (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=3)
					 Where MagazineId=@MagazineId 
					 
		  Update #temp Set V4 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=4 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I4 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=4
						AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 P4 = (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=4)
					 Where MagazineId=@MagazineId 
	                 
		     Update #temp Set V5 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=5 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I5 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=5
								AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					  P5 = (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=5)
					  Where MagazineId=@MagazineId
		
		  Update #temp Set V6 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=6 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I6 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=6
						AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') ,
					  P6 = (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=6)
					 Where MagazineId=@MagazineId
					 
	  Update #temp Set V7 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=7
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I7 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=7
							AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					  P7= (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=7)
					 Where MagazineId=@MagazineId
					 
		  Update #temp Set V8= STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=8
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I8 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=8
						AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') ,
					  P8= (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=8)
					 Where MagazineId=@MagazineId
					 
		  Update #temp Set V9 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=9
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I9 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=9
							AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 P9= (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=9)
					 Where MagazineId=@MagazineId
					 
		  Update #temp Set V10 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'') 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=10
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 I10 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=10
								AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') ,
					  P10= (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=10)
					 Where MagazineId=@MagazineId
					 
		  Update #temp Set V11 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'')
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=11
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') ,
			 	    I11 = STUFF((SELECT     ',' +ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=11 
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					 P11= (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=11)
					 Where MagazineId=@MagazineId
					 
		  Update #temp Set V12 = STUFF((SELECT     ',' + ISNULL(MR.VolumeNumber,'')
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = tm.MagazineId Where TM.MagazineId=@MagazineId
					AND Month(ReceiveDate)=12
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') ,
					 I12 =  STUFF((SELECT ',' + ISNULL(Convert(nvarchar(max),MR.IssueNumber),0) 
					  From #temp tm INNER JOIN sLibrary.tMagazineReceive MR ON MR.MagazineId = Tm.MagazineId Where Month(ReceiveDate)=12
					AND tm.MagazineId=@MagazineId
					 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
					        P12= (Select SUM(MagazineAmount) from sLibrary.tMagazineReceive Where MagazineId=@MagazineId AND Month(ReceiveDate)=12)
					 Where MagazineId=@MagazineId
		 
	 
					  
					 
		Set @lCount=@lCount-1
    END

       
    
	Select Tm.V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12,M.Id,
			M.Title,I1,I2,I3,I4,I5,I6,I7,I8,I9,I10,I11,I12 
			,P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2,
			LM.ReportOrgTitle,LM.SmallAddress1,LM.SmallAddress2
     from #temp Tm
     INNER JOIN sLibrary.tMagazineMaster M ON M.Id=Tm.MagazineId
     AND ((MagazineTypeId=@rMagazineTypeId) OR (@rMagazineTypeId=0))
     LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=M.LibraryId
    --  Where  LibraryId=110100001
    --AND ((MagazineTypeId=0) OR (0=0))
    
     
END
GO
PRINT N'Creating [sSetup].[pBatchMasterStudentStrengthGet]...';


GO
CREATE PROCEDURE [sSetup].[pBatchMasterStudentStrengthGet]
	 @rId int = 0,
	 @rCode nvarchar(20),
	 @rTitle nvarchar(100),
	 @rOrgId int,
	 @rIsSearch bit=0,
	 @rOrgGroupBatchId int=0,
	 @rOrgGroupId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 DECLARE @lPickGrid VARCHAR(max)=''
	 Select @lPickGrid=@lPickGrid+'<tr>
	 <td>'+OM.DisplayTitle+'</td>
	  <td>'+OGBM.Title+'</td>
	   <td>'+BM.Title+'</td>
	    <td>'+convert(nvarchar,BM.FromDate)+'</td>
	     <td>'+convert(nvarchar,BM.ToDate)+'</td>
	      <td>'+CASE WHEN (BM.IsActive=0)
	      THEN	
			'False'
	       Else 'True' 
	       END+'</td>
	       <td>'+ CASE WHEN (BM.IsInContext=0)
	       THEN 'False'  Else 'True' 
	       END+'</td>
	       <td>'+CASE WHEN (BM.IsHistory=0)
	       THEN 'False' ELSE 'True'
	         END+'</td>
	      </tr>' 
  FROM 
            sSetup.tBatchMaster BM
            INNER JOIN sSetup.tOrgGroupBatchMaster OGBM
				ON OGBM.Id = BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrganizationMaster OM
				ON OM.Id = BM.OrgId
			LEFT join sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.batchGroupId  
  WHERE 
  
    ((BM.Id = @rId) OR (@rId = 0))
    AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
	AND ((BM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
	AND ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))  
	AND ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))  
	--AND BM.IsActive=1
	--AND(BM.OrgId=@rOrgId)

ORDER BY OM.Id, BM.OrderIndex ASC

select isnull(@lPickGrid,'') as PickGrid
END
GO
PRINT N'Creating [sStudent].[pRptCastCategoryStudentStrengthGet]...';


GO


CREATE PROCEDURE [sStudent].[pRptCastCategoryStudentStrengthGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	  
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromDate date='',
	 @rToDate date='',
	  
	 @rDepartmentId int ,
	 @rCasteCategoryIds nvarchar(max) = '' ,
	 @rClassGroup bit=0,
	 @rDivisionGroup bit=0,
	 @rDepartmentGroup bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
 
	SELECT 
			
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.AdmissionDate >= @rFromDate AND SA.AdmissionDate <= @rToDate 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=2
			AND CCT.Id=SO.CastCategoryId
			AND A.BatchId = @rBatchId  
			 
			) AS NewGirls,
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.AdmissionDate >= @rFromDate AND SA.AdmissionDate <= @rToDate
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=1
			AND CCT.Id=SO.CastCategoryId
			AND A.BatchId = @rBatchId  
			 
			) AS NewBoys,
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.LeftDate >= @rFromDate AND SA.LeftDate <= @rToDate
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=2
			AND CCT.Id=SO.CastCategoryId
			AND A.BatchId = @rBatchId  
			 
			) AS LeftGirls,
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.LeftDate >= @rFromDate AND SA.LeftDate <= @rToDate
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=1
			AND CCT.Id=SO.CastCategoryId
			AND A.BatchId = @rBatchId  
			 
			) AS Leftboys,
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.AdmissionDate < @rFromDate 
			AND (SA.LeftDate > @rFromDate OR ISNULL(SA.LeftDate,'')= '')
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=2
			AND CCT.Id=SO.CastCategoryId
			AND A.BatchId = @rBatchId  
			 
			) AS TotalGirls,
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.AdmissionDate < @rFromDate 
			AND (SA.LeftDate > @rFromDate OR ISNULL(SA.LeftDate,'')= '')
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=1
			AND CCT.Id=SO.CastCategoryId
			AND A.BatchId = @rBatchId  
			 
			) AS TotalBoys,
			
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.AdmissionDate > @rFromDate 
			AND (SA.LeftDate > @rFromDate OR ISNULL(SA.LeftDate,'')= '')
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=2
			AND CCT.Id=SO.CastCategoryId
			AND A.BatchId = @rBatchId  
			 
			) AS AfterGirls,
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.AdmissionDate > @rFromDate 
			AND (SA.LeftDate > @rFromDate OR ISNULL(SA.LeftDate,'')= '')
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=1
			AND CCT.Id=SO.CastCategoryId
			AND A.BatchId = @rBatchId  
			 
			) AS AfterBoys,
			
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SO.GenderId,
			CCT.Title AS CastCategory,
			GM.Title As Gender,
			CM.Title As Class,
			DM.Title As Division,
			CM.Title+'-'+DM.Title As ClassDivision,
			Depart.Title As DepartmentTitle,
			CM.Id AS ClassID,
			DM.Id As DivisionId,
			@rDepartmentGroup As DepartmentGroup ,
			@rClassGroup As ClassGroup,
			@rDivisionGroup AS DivisionGroup
			
	FROM sStudent.tAcademic A1 			 
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A1.StudentId
			INNER JOIN sCommon.tCastCategoryMaster CCT ON CCT.Id=SO.CastCategoryId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A1.ClassId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A1.DivisionId
			INNER JOIN sSetup.tDepartmentMaster Depart ON Depart.Id=CM.DepartmentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
	WHERE	  ((A1.ClassId =@rClassId) OR (@rClassId=0)) 
			AND ((A1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
			AND  A1.BatchId = @rBatchId 
			 AND (ISNULL(CCT.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rCasteCategoryIds,','))OR @rCasteCategoryIds='')
	Group By  SO.GenderId,GM.Title,CCT.Title,CM.Id,DM.Id,CM.DepartmentId,CM.Title,DM.Title ,CCT.Id,Gm.Id ,Depart.Title
	
	 
END


 

--select AD.* from sStudent.tStudentMaster SM INNER JOIN sStudent.tAcademic A
--ON A.StudentId = SM.Id 
--INNER JOIN sStudent.tStudentAdmission AD ON SM.Id = Ad.StudentId 
--WHERE A.divisionId = 100100028
GO
PRINT N'Creating [sStudent].[pRptRelegionStudentStrengthGet]...';


GO


CREATE PROCEDURE [sStudent].[pRptRelegionStudentStrengthGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	  
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromDate date='',
	 @rToDate date='',
	  
	 @rDepartmentId int ,
	  @rReligionIds nvarchar(max) = '' ,
	   @rDepartmentGroup bit=0,
	   @rClassGroup bit=0,
	   @rDivisionGroup bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
 
	SELECT 
			
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.AdmissionDate >= @rFromDate AND SA.AdmissionDate <= @rToDate 
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=2
			AND RE.Id=SO.ReligionId
			AND A.BatchId = @rBatchId  
			 
			) AS NewGirls,
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.AdmissionDate >= @rFromDate AND SA.AdmissionDate <= @rToDate
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=1
			AND RE.Id=SO.ReligionId
			AND A.BatchId = @rBatchId  
			 
			) AS NewBoys,
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.LeftDate >= @rFromDate AND SA.LeftDate <= @rToDate
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=2
			AND RE.Id=SO.ReligionId
			AND A.BatchId = @rBatchId  
			 
			) AS LeftGirls,
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.LeftDate >= @rFromDate AND SA.LeftDate <= @rToDate
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=1
			AND RE.Id=SO.ReligionId
			AND A.BatchId = @rBatchId  
			 
			) AS Leftboys,
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.AdmissionDate < @rFromDate 
			AND (SA.LeftDate > @rFromDate OR ISNULL(SA.LeftDate,'')= '')
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=2
			AND RE.Id=SO.ReligionId
			AND A.BatchId = @rBatchId  
			 
			) AS TotalGirls,
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.AdmissionDate < @rFromDate 
			AND (SA.LeftDate > @rFromDate OR ISNULL(SA.LeftDate,'')= '')
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=1
			AND RE.Id=SO.ReligionId
			AND A.BatchId = @rBatchId  
			 
			) AS TotalBoys,
			
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.AdmissionDate > @rFromDate 
			AND (SA.LeftDate > @rFromDate OR ISNULL(SA.LeftDate,'')= '')
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=2
			AND RE.Id=SO.ReligionId
			AND A.BatchId = @rBatchId  
			 
			) AS AfterGirls,
			(
			
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId 		 
			WHERE SA.AdmissionDate > @rFromDate 
			AND (SA.LeftDate > @rFromDate OR ISNULL(SA.LeftDate,'')= '')
			AND A.ClassId =CM.Id AND A.DivisionId=DM.Id AND SO.GenderId=Gm.Id  AND So.GenderId=1
			AND RE.Id=SO.ReligionId
			AND A.BatchId = @rBatchId  
			 
			) AS AfterBoys,
			
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SO.GenderId,
			RE.Title AS Religion,
			GM.Title As Gender,
			CM.Title As Class,
			DM.Title As Division,
			CM.Title+'-'+DM.Title As ClassDivision,
			Depart.Title As DepartmentTitle,
			CM.Id AS ClassID,
			DM.Id As DivisionId,
			@rDepartmentGroup As DepartmentGroup ,
			@rClassGroup As ClassGroup,
			@rDivisionGroup AS DivisionGroup
			
	FROM sStudent.tAcademic A1 			 
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A1.StudentId
			INNER JOIN sCommon.tReligionMaster RE ON RE.Id=SO.ReligionId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A1.ClassId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A1.DivisionId
			INNER JOIN sSetup.tDepartmentMaster Depart ON Depart.Id=CM.DepartmentId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  CM.Id and BC.BatchId= @rBatchId
	WHERE	  ((A1.ClassId =@rClassId) OR (@rClassId=0)) 
			AND ((A1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
			AND  A1.BatchId = @rBatchId 
			 AND (ISNULL(RE.Id,0) IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionIds,','))OR @rReligionIds='')
	Group By  SO.GenderId,GM.Title,RE.Title,CM.Id,DM.Id,CM.DepartmentId,CM.Title,DM.Title ,RE.Id,Gm.Id ,Depart.Title
	
	 
END


 

--select AD.* from sStudent.tStudentMaster SM INNER JOIN sStudent.tAcademic A
--ON A.StudentId = SM.Id 
--INNER JOIN sStudent.tStudentAdmission AD ON SM.Id = Ad.StudentId 
--WHERE A.divisionId = 100100028
GO
PRINT N'Creating [sStudent].[pStudentCountClassWiseGet]...';


GO




 CREATE  PROCEDURE [sStudent].[pStudentCountClassWiseGet]
	 
	 
	 @rDepartmentId int,
	 @rOrgGroupBatchId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	Select
		COUNT(SM.Id) As StudentCount,
		DeptM.Title AS DepartName, 
		CM.Title +'-'+Dm.Title As ClassDivision,
		(Select count(SM1.ID) from sStudent.tStudentMaster  SM1
		INNER JOIN sStudent.tAcademic A1 ON A1.StudentId= SM1.ID
		INNER JOIN sSetup.tClassMaster CM1 ON CM1.Id=A1.ClassId  
		INNER JOIN sSetup.tDivisionMaster DM1 ON DM1.Id=A1.DivisionId
		INNER JOIN sSetup.tBatchMaster BM1 ON BM1.Id = A1.BatchId
		Where CM1.Id = CM.Id AND DM1.Id=DM.Id And BM1.OrgGroupBatchId = Bm.OrgGroupBatchId 
		and BM.IsInContext=BM1.IsInContext  ) As TotalCount 
		 
		
	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.tDepartmentMaster DeptM on DeptM.Id=Cm.DepartmentId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		Where
		CM.DepartmentId= @rDepartmentId And SM.StatusId=1 And BM.OrgGroupBatchId=@rOrgGroupBatchId and BM.IsInContext=1
	Group BY  DeptM.Title,CM.Title,Dm.Title,CM.OrderIndex,DM.OrderIndex,CM.Id,DM.Id, Bm.OrgGroupBatchId  , BM.IsInContext 
	Order By CM.OrderIndex,DM.OrderIndex
		
	
END
GO
PRINT N'Creating [sStudent].[pStudentCountDepartWiseGet]...';


GO




 CREATE PROCEDURE [sStudent].[pStudentCountDepartWiseGet]
	 
	 
	 @rOrgId int,
	 @rOrgGroupBatchId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	Select
		COUNT(SM.Id) As StudentCount,
		DeptM.ID,
		DeptM.Title AS DepartName, 
		(Select count(SM1.ID) from sStudent.tStudentMaster  SM1
		INNER JOIN sStudent.tAcademic A1 ON A1.StudentId= SM1.ID
		INNER JOIN sSetup.tClassMaster CM1 ON CM1.Id=A1.ClassId
		INNER JOIN sSetup.tDepartmentMaster DeptM1 on DeptM1.Id=Cm1.DepartmentId 
		INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id=DeptM1.OrgId
		INNER JOIN sSetup.tBatchMaster BM1 ON BM1.Id = A1.BatchId
		Where DeptM1.Id =DeptM.Id And BM1.OrgGroupBatchId =BM.OrgGroupBatchId 
		and BM.IsInContext=BM1.IsInContext ) As TotalCount,
		OM.DisplayTitle
		
	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 DeptM on DeptM.Id=Cm.DepartmentId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DeptM.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		Where
		DeptM.OrgId= @rOrgId And SM.StatusId=1  And BM.OrgGroupBatchId=@rOrgGroupBatchId and BM.IsInContext=1
	Group BY DeptM.ID,DeptM.Title,DeptM.Orgid,OM.DisplayTitle,BM.OrgGroupBatchId,OM.Id , BM.IsInContext
		
	
END
GO
PRINT N'Creating [sStudent].[pStudentCountOrgWiseGet]...';


GO




 CREATE PROCEDURE [sStudent].[pStudentCountOrgWiseGet]
	 
	 
	 @rOrgGroupId int,
	 @rOrgGroupBatchId int
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	Select
		COUNT(SM.Id) As StudentCount,
		OM.ID AS OrgId,
		OM.DisplayTitle AS OrgName,
		OM.Code ,
		(Select count(SM1.ID) from sStudent.tStudentMaster SM1
		INNER JOIN  sSetup.tOrganizationMaster OM1 ON SM1.OrgId=OM1.Id
		INNER JOIN sStudent.tAcademic A1 ON A1.StudentId= SM1.ID 
		INNER JOIN sSetup.tBatchMaster BM1 ON BM1.Id = A1.BatchId
		Where SM1.Orgid =OM.Id And BM1.OrgGroupBatchId = Bm.OrgGroupBatchId And OM1.OrgGroupId =Om.OrgGroupId 
		and BM.IsInContext=BM1.IsInContext 
		) As TotalCount
		
	From
		sStudent.tStudentMaster SM 
		INNER JOIN  sSetup.tOrganizationMaster OM ON SM.OrgId=OM.Id
		INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		Where
		Om.OrgGroupId = @rOrgGroupId And SM.StatusId=1 And BM.OrgGroupBatchId = @rOrgGroupBatchId and BM.IsInContext=1
	Group BY OM.ID,OM.DisplayTitle,OM.Code ,Om.OrgGroupId , Bm.OrgGroupBatchId, BM.IsInContext--,SM.StatusId
		
	
END
GO
  
 
  
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('18.01.11',180111,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO