GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('18.07.14',180714,'BEGIN','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO
GO
PRINT N'Dropping PK_CBSESchool...';


GO
ALTER TABLE [dbo].[CBSESchoolRow] DROP CONSTRAINT [PK_CBSESchool];


GO
PRINT N'Altering [dbo].[CBSESchoolFinal]...';


GO
ALTER TABLE [dbo].[CBSESchoolFinal]
    ADD [District] NVARCHAR (100) NULL;


GO
PRINT N'Altering [dbo].[CBSESchoolRow]...';


GO
ALTER TABLE [dbo].[CBSESchoolRow] DROP COLUMN [AutoId];


GO
ALTER TABLE [dbo].[CBSESchoolRow] ALTER COLUMN [No] NVARCHAR (50) NULL;


GO
PRINT N'Altering [sAlert].[tEmailConfiguration]...';


GO
ALTER TABLE [sAlert].[tEmailConfiguration]
    ADD [IsAuthenticateUsername] BIT            NULL,
        [DisplayName]            NVARCHAR (200) NULL;


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


GO
ALTER TABLE [sErp].[tDSR]
    ADD [WorkCount] DECIMAL (10, 2) NULL;


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


GO
ALTER TABLE [sFee].[tChargeAccountPosting]
    ADD [SourceTypeId] INT NULL;


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


GO
ALTER TABLE [sFee].[tFeeSetup]
    ADD [FeeDuration] NVARCHAR (100) NULL;


GO
PRINT N'Altering [sHrm].[tEmployeeStatutoryAndOther]...';


GO
ALTER TABLE [sHrm].[tEmployeeStatutoryAndOther]
    ADD [UAN] NVARCHAR (20) NULL;


GO
PRINT N'Altering [sProcurement].[tStockIssue]...';


GO
ALTER TABLE [sProcurement].[tStockIssue]
    ADD [OtherLocationSourceTypeId] SMALLINT NULL,
        [OtherLocationSourceId]     INT      NULL;


GO
PRINT N'Altering [sProcurement].[tStockIssueRequest]...';


GO
ALTER TABLE [sProcurement].[tStockIssueRequest]
    ADD [RequestOrgId] SMALLINT NULL;


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


GO
ALTER TABLE [sSecurity].[tOrgGroupMobileApp]
    ADD [VTSAccountId] NVARCHAR (100) NULL;


GO
PRINT N'Altering [sSecurity].[tResourceTypeMaster]...';


GO
ALTER TABLE [sSecurity].[tResourceTypeMaster]
    ADD [OrderIndex] INT NULL;


GO
PRINT N'Altering [sStudent].[tCollegeDetail]...';


GO
ALTER TABLE [sStudent].[tCollegeDetail]
    ADD [SSCPercentile] DECIMAL (10, 2) NULL,
        [SSCGrade]      NVARCHAR (20)   NULL;


GO
PRINT N'Altering [sSystem].[tSettingInfo]...';


GO
ALTER TABLE [sSystem].[tSettingInfo] ALTER COLUMN [Id] SMALLINT NOT NULL;


GO
PRINT N'Creating PK_tSettingInfo...';


GO
ALTER TABLE [sSystem].[tSettingInfo]
    ADD CONSTRAINT [PK_tSettingInfo] 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 [sAssessment].[tTempGeneralExam1]...';


GO
CREATE TABLE [sAssessment].[tTempGeneralExam1] (
    [AcademicId]         BIGINT          NOT NULL,
    [ClassId]            INT             NOT NULL,
    [DivisionId]         INT             NOT NULL,
    [RollNo]             INT             NULL,
    [OrgId]              SMALLINT        NOT NULL,
    [BatchId]            INT             NOT NULL,
    [Organization]       NVARCHAR (100)  NOT NULL,
    [Batch]              NVARCHAR (100)  NOT NULL,
    [StudentId]          BIGINT          NOT NULL,
    [Code]               NVARCHAR (20)   NOT NULL,
    [Number]             BIGINT          NOT NULL,
    [FirstName]          NVARCHAR (100)  NOT NULL,
    [LastName]           NVARCHAR (100)  NOT NULL,
    [Name]               NVARCHAR (300)  NULL,
    [StatusId]           SMALLINT        NOT NULL,
    [ClassName]          NVARCHAR (100)  NOT NULL,
    [DivisionName]       NVARCHAR (100)  NOT NULL,
    [StatusName]         NVARCHAR (50)   NOT NULL,
    [ResultId]           BIGINT          NOT NULL,
    [ExamId]             INT             NOT NULL,
    [TotalMarks]         DECIMAL (8, 2)  NOT NULL,
    [TotalObtain]        DECIMAL (8, 2)  NOT NULL,
    [ResultStatus]       NVARCHAR (50)   NOT NULL,
    [ResultGrade]        NVARCHAR (10)   NOT NULL,
    [ResultGradePoint]   DECIMAL (6, 2)  NOT NULL,
    [RankNumber]         INT             NOT NULL,
    [Percentage]         DECIMAL (5, 2)  NOT NULL,
    [Percentile]         DECIMAL (5, 2)  NOT NULL,
    [ResultRemark]       NVARCHAR (200)  NOT NULL,
    [OtherRemark1]       NVARCHAR (200)  NOT NULL,
    [ExamCode]           NVARCHAR (20)   NOT NULL,
    [ExamName]           NVARCHAR (100)  NOT NULL,
    [CreatedUserId]      BIGINT          NULL,
    [CreatedUserName]    NVARCHAR (100)  NULL,
    [ExamSubGroupId]     INT             NULL,
    [ExamSeatNo]         NVARCHAR (20)   NULL,
    [TotalDays]          SMALLINT        NULL,
    [PresentDays]        SMALLINT        NULL,
    [StudentHeight]      DECIMAL (6, 2)  NULL,
    [StudentWeight]      DECIMAL (6, 2)  NULL,
    [ResultRemark1]      NVARCHAR (200)  NULL,
    [ResultRemark2]      NVARCHAR (200)  NULL,
    [MyGoal]             NVARCHAR (200)  NULL,
    [MyInterestHobby]    NVARCHAR (200)  NULL,
    [MyStrength]         NVARCHAR (200)  NULL,
    [Achievements]       NVARCHAR (200)  NULL,
    [AreaOfInterest]     NVARCHAR (200)  NULL,
    [Responsibility]     NVARCHAR (200)  NULL,
    [DentalHygiene]      NVARCHAR (50)   NULL,
    [VisionLeft]         NVARCHAR (50)   NULL,
    [VisionRight]        NVARCHAR (50)   NULL,
    [DepartmentId]       INT             NULL,
    [MyActivity]         NVARCHAR (200)  NULL,
    [ClassTeacherRemark] NVARCHAR (1000) NULL,
    [HouseRemark]        NVARCHAR (1000) NULL,
    [ResultRemark3]      NVARCHAR (200)  NULL,
    [GeneralRemark]      NVARCHAR (200)  NULL
);


GO
PRINT N'Creating [sCommunication].[tNoticeBoard]...';


GO
CREATE TABLE [sCommunication].[tNoticeBoard] (
    [AutoId]       BIGINT   IDENTITY (1, 1) NOT NULL,
    [SourceTypeId] SMALLINT NOT NULL,
    [SourceId]     BIGINT   NOT NULL,
    [IsUpdate]     BIT      NOT NULL
);


GO
PRINT N'Creating PK_tNoticeBoard...';


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


GO
PRINT N'Creating [sProcurement].[tOtherLocationSourceTypeMaster]...';


GO
CREATE TABLE [sProcurement].[tOtherLocationSourceTypeMaster] (
    [Id]         INT            NOT NULL,
    [Code]       NVARCHAR (100) NOT NULL,
    [Title]      NVARCHAR (100) NOT NULL,
    [IsObsolete] BIT            NOT NULL
);


GO
PRINT N'Creating [sProcurement].[tOtherStockBatch]...';


GO
CREATE TABLE [sProcurement].[tOtherStockBatch] (
    [Id]                        BIGINT          NOT NULL,
    [OtherLocationSourceTypeId] SMALLINT        NULL,
    [OtherLocationSourceId]     INT             NULL,
    [StockBatchId]              INT             NULL,
    [AvailableQuantity]         DECIMAL (12, 2) NOT NULL
);


GO
PRINT N'Creating [sProcurement].[tOtherStockIssue]...';


GO
CREATE TABLE [sProcurement].[tOtherStockIssue] (
    [Id]                            BIGINT         NOT NULL,
    [Number]                        NVARCHAR (20)  NOT NULL,
    [IssuedByName]                  NVARCHAR (100) NOT NULL,
    [FromOtherLocationSourceTypeId] SMALLINT       NULL,
    [FromOtherLocationSourceId]     INT            NULL,
    [IssueToSourceTypeId]           INT            NULL,
    [IssueToSourceId]               BIGINT         NULL,
    [IssueToName]                   NVARCHAR (200) NULL,
    [Remark]                        NVARCHAR (300) NULL,
    [IssueDate]                     DATE           NULL,
    [CreatedUserId]                 BIGINT         NOT NULL,
    [CreatedDateTime]               DATETIME       NOT NULL,
    [StoreLocationId]               INT            NOT NULL
);


GO
PRINT N'Creating [sProcurement].[tOtherStockIssueBatch]...';


GO
CREATE TABLE [sProcurement].[tOtherStockIssueBatch] (
    [Id]                BIGINT          NOT NULL,
    [OtherStockIssueId] BIGINT          NOT NULL,
    [OtherStockBatchId] BIGINT          NULL,
    [Quantity]          DECIMAL (12, 2) NOT NULL
);


GO
PRINT N'Creating [sProcurement].[tOtherStockLocationMaster]...';


GO
CREATE TABLE [sProcurement].[tOtherStockLocationMaster] (
    [OrgGroupId]      SMALLINT       NULL,
    [Id]              INT            NOT NULL,
    [Code]            NVARCHAR (100) NULL,
    [Title]           NVARCHAR (100) NOT NULL,
    [IsObsolete]      BIT            NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NOT NULL,
    [UpdatedDateTime] DATETIME       NOT NULL,
    [StoreLocationId] INT            NULL
);


GO
PRINT N'Creating PK_tScreenHelp...';


GO
ALTER TABLE [sSecurity].[tScreenHelp]
    ADD CONSTRAINT [PK_tScreenHelp] PRIMARY KEY CLUSTERED ([ScreenId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO
PRINT N'Altering [sAttendance].[fWeekHOffGet]...';


GO

ALTER FUNCTION [sAttendance].[fWeekHOffGet](@rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rClassId bigint,@rStatus nvarchar(10),@rOrgId smallint)
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN
if isnull(@rStatus,'') = ''
BEGIN
	 
	DECLARE @lWeekOff nvarchar(20)
	Declare @WeekNumber int,@StudentSecondWeekOffRule int,@StudentFirstWeekOffRule int
	DECLARE @lDate datetime,@lWeekDay1 nvarchar(20),@lWeekDay2  nvarchar(20)
	SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @rDay)
	 
	  
	if exists(Select 1 from sActivity.tWeekOffSetting WHEre SourceId = @rClassId AND SourceTypeId=2001)
    BEGIN
		 
	     Select @lWeekDay1 = FirstWeekOffDayId From sActivity.tWeekOffSetting  Where SourceId = @rClassId AND SourceTypeId=2001
	     Select @lWeekDay2 = SecondWeekOff From sActivity.tWeekOffSetting  Where SourceId = @rClassId AND SourceTypeId=2001  
    END 
    Else
    BEGIN
	     Select @lWeekDay1 = StudentFirstWeekOffDayId From sSetup.tOrganizationMaster  Where Id = @rOrgId 
	     Select @lWeekDay2 = StudentSecondWeekOffDayId From sSetup.tOrganizationMaster  Where Id = @rOrgId 
	     
	END
	   
	SET @lWeekOff = [sAssessment].[fGetdayNumber](@lDate)
	Set @WeekNumber = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @lDate), 0)), 0), @lDate - 1) + 1
	  
	if exists(Select 1 from sActivity.tWeekOffSetting WHEre SourceId = @rClassId AND SourceTypeId=2001)
	BEGIN 
	     Select @StudentFirstWeekOffRule = FristWeekOffRuleId From sActivity.tWeekOffSetting WHEre SourceId = @rClassId AND SourceTypeId=2001
	     Select @StudentSecondWeekOffRule = SEcondWeekOffRuleId From sActivity.tWeekOffSetting WHEre SourceId = @rClassId AND SourceTypeId=2001
	       
	END
	Else
	BEGIN
	     Select @StudentFirstWeekOffRule = StudentFirstWeekOffRuleId From sSetup.tOrganizationMaster WHEre Id = @rOrgId 
	     Select @StudentSecondWeekOffRule = StudentSecondWeekOffRuleId From sSetup.tOrganizationMaster WHEre Id = @rOrgId 
	    
	END
     
	--IF(@lDate > GETDATE())
 --   BEGIN
 --   	SET @rStatus = ''
    	 
	--    RETURN @rStatus	
	--END	
	if @StudentFirstWeekOffRule = 1 
	BEGIN	 
		if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
			END
		 
		IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rClassId) OR (@rClassId=0)) 
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		        BEGIN
			         SET @rStatus = 'H'	
			   END
		 
	END
	Else if @StudentFirstWeekOffRule = 2 
	BEGIN
				     
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			 
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rClassId) OR (@rClassId=0)) 
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		        BEGIN
			         SET @rStatus = 'H'	
			   END
				 
			END
			--Else
			--BEGIN
			--	Set @rStatus =''
			--END
		END
		--Else
		--BEGIN
		--	Set @rStatus = ''
		--	RETURN @rStatus	
		--END
	END
	
	else if @StudentFirstWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rClassId) OR (@rClassId=0)) 
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
				END
				 
			END
			--Else
			--BEGIN
			--	Set @rStatus = ''
			--END
			 
		END
		--else
		--BEGIN
		--	Set @rStatus = ''
		--	RETURN @rStatus	
		--END
	END
	else if @StudentFirstWeekOffRule = 4
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rClassId) OR (@rClassId=0)) 
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
				END
				 
			END
			--else
			--BEGIN
			--	Set @rStatus = ''
			--END
			 
		END
		--else
		--BEGIN
		--	Set @rStatus = ''
		--	RETURN @rStatus	
		--END
	END
	   
	if @StudentSecondWeekOffRule = 1 
	BEGIN	 
		if(@lWeekOff = @lWeekDay2)
			BEGIN
			
			Set @rStatus = 'W'
			END
		 
		IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rClassId) OR (@rClassId=0)) 
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
				END
		RETURN @rStatus	
	END
	Else if @StudentSecondWeekOffRule = 2 
	BEGIN
	     
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
			 
				Set @rStatus = 'W'
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rClassId) OR (@rClassId=0)) 
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
				END
				RETURN @rStatus	
			END
			--else
			--BEGIN
			--	Set @rStatus= ''
			--END
			 
		END
		--else
		--BEGIN
		--	Set @rStatus = ''
		--	RETURN @rStatus	
		--END
		
	END
	
	else if @StudentSecondWeekOffRule = 3
	BEGIN
	
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rClassId) OR (@rClassId=0)) 
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
				END
				RETURN @rStatus	
			END
			--else
			--BEGIN
			--	Set @rStatus=''
			--END
			 
		END
		--else
		--BEGIN
		--	Set @rStatus = ''
		--	RETURN @rStatus	
		--END
	END
	else if @StudentSecondWeekOffRule = 4
	BEGIN
		 
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rClassId) OR (@rClassId=0)) 
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @rStatus = 'H'	
				END
				RETURN @rStatus	
			END
			--else
			--BEGIN
			--	Set @rStatus = ''
			--END
			 
		END
		--else
		--BEGIN
		--	Set @rStatus = '-'
		--	RETURN @rStatus	
		--END
	END
	END
	RETURN @rStatus	
	
END
GO
PRINT N'Altering [sHrm].[fWeekHOffGet]...';


GO
ALTER FUNCTION [sHrm].[fWeekHOffGet](@rEmployeeId bigint, @rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDepartmentId int,@rOrgId smallint)
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lStatus nvarchar(200)='-' 
DECLARE @lWeekOff nvarchar(20)
Declare @WeekNumber int,@EmpSecondWeekOffRule int,@EmpFirstWeekOffRule int
DECLARE @lDate datetime,@lWeekDay1 nvarchar(20),@lWeekDay2  nvarchar(20)
SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @rDay)

if exists(Select 1 from sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95)
BEGIN
	Select @lWeekDay1 = FirstWeekOffDayId From sActivity.tWeekOffSetting  Where SourceId = @rEmployeeId AND SourceTypeId=95
	Select @lWeekDay2 = SecondWeekOff From sActivity.tWeekOffSetting  Where SourceId = @rEmployeeId AND SourceTypeId=95  
 END 
 Else
 BEGIN
	Select @lWeekDay1 = EmployeeFirstWeekOffDayId From sSetup.tOrganizationMaster  Where Id = @rOrgId 
	Select @lWeekDay2 = EmployeeSEcondWeekOffDayId From sSetup.tOrganizationMaster  Where Id = @rOrgId 
 END
 
  SET @lWeekOff = [sAssessment].[fGetdayNumber](@lDate)
 --Select  @lStatus =  Case When @lWeekOff = @lWeekDay1 Then 'W' Else '-' End 
Set @WeekNumber = datediff(week, dateadd(week, datediff(week, 0, dateadd(month, datediff(month, 0, @lDate), 0)), 0), @lDate - 1) + 1
 
if exists(Select 1 from sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95)
BEGIN
	 
	Select @EmpFirstWeekOffRule = FristWeekOffRuleId From sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95
	Select @EmpSecondWeekOffRule = SEcondWeekOffRuleId From sActivity.tWeekOffSetting WHEre SourceId = @rEmployeeId AND SourceTypeId=95
	 
 END
 Else
 BEGIN
   
	Select @EmpFirstWeekOffRule = EmployeeFirstWeekOffRuleId From sSetup.tOrganizationMaster WHEre Id = @rOrgId 
	Select @EmpSecondWeekOffRule = EmployeeSecondWeekOffRuleId From sSetup.tOrganizationMaster WHEre Id = @rOrgId 
	 
 END
--IF(@lDate > GETDATE())
--BEGIN
--	SET @lStatus = ''
--	RETURN @lStatus	
--END	 
	 
--if @lStatus = 'W'
--BEGIN
	
	if @EmpFirstWeekOffRule = 1 
	BEGIN
		if(@lWeekOff = @lWeekDay1)
			BEGIN	
				Set @lStatus = 'W'
				RETURN @lStatus	
			 END 			 
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId 
						WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId = 3
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		        BEGIN
			         SET @lStatus = 'H'	
			   RETURN @lStatus		
		        END
			
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
			  if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
				RETURN @lStatus	
	END
	Else if @EmpFirstWeekOffRule = 2 
	BEGIN
		   
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId = 3
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
		        BEGIN
			         SET @lStatus = 'H'	
			   RETURN @lStatus		
		        END
			
				SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
				FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
				WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
			
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
				RETURN @lStatus	
			END
			Else
			BEGIN
				Set @lStatus ='-'
			END
			 
		END
		Else
		BEGIN
			Set @lStatus = '-'
			RETURN @lStatus	
		END
	END
	else if @EmpFirstWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId = 3
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
			
			SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
			FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
			WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
			
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
				RETURN @lStatus	
			END
			Else
			BEGIN
				Set @lStatus = '-'
			END
			 
		END
		else
		BEGIN
			Set @lStatus = '-'
			RETURN @lStatus	
		END
	END
	else if @EmpFirstWeekOffRule = 4
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId = 3
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
				
			SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
			FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
			WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
			
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
				RETURN @lStatus	
			END
			else
			BEGIN
				Set @lStatus = '-'
			END
			 
		END
		else
		BEGIN
			Set @lStatus = '-'
			RETURN @lStatus	
		END
	END
--END
	
--Else
--BEGIN
	   
      if @EmpSecondWeekOffRule = 1 
	BEGIN	 
		 if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
			END
		 
	END
	Else if @EmpSecondWeekOffRule = 2 
	BEGIN
	 
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId = 3
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
			
			SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
			FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
			WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
			
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
				RETURN @lStatus	
			END
			else
			BEGIN
				Set @lStatus= '-'
			END
			 
		END
		else
		BEGIN
			Set @lStatus = '-'
			RETURN @lStatus	
		END
	END
	else if @EmpSecondWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId = 3
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
			
			SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
			FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
			WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
			
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
				RETURN @lStatus	
			END
			else
			BEGIN
				Set @lStatus='-'
			END
			 
		END
		else
		BEGIN
			Set @lStatus = '-'
			RETURN @lStatus	
		END
	END
	else if @EmpSecondWeekOffRule = 4
	BEGIN
		 
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
				IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND SourceTypeId = 3
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
				BEGIN
					SET @lStatus = 'H'	
					RETURN @lStatus	
				END
					
			SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
			FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
			WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
			
				 if Exists(Select 1 from  sHrm.tEmployeeAttendanceRegister Where EmployeeId=@rEmployeeId AND AttendanceDate = @lDate AND BatchId=@rBatchId AND IsPresent=1)
					BEGIN 
						SET @lStatus = 'P'
					END
				RETURN @lStatus	
			END
			else
			BEGIN
				Set @lStatus = '-'
			END
			 
		END
		else
		BEGIN
			Set @lStatus = '-'
			RETURN @lStatus	
		END
	END
--END
 
 
  
			
	RETURN @lStatus	
END
GO
PRINT N'Altering [sHrm].[fWeekHOffHolidayGet]...';


GO
ALTER FUNCTION [sHrm].[fWeekHOffHolidayGet](@rEmployeeId bigint, @rForYear smallint,@rForMonth smallint,@rDay smallint,@rBatchId int,@rDepartmentId int,@rOrgId smallint)
RETURNS nvarchar(20) WITH EXECUTE AS CALLER
AS 
BEGIN
DECLARE @lStatus nvarchar(200)='-' 
	BEGIN
		
		DECLARE @lDate nvarchar(20)  
		DECLARE @lWeekOff nvarchar(100)
	 
		SET @lDate = CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + CONVERT(nvarchar(10), @rDay)
		
		IF ISDATE (@lDate)=1
		BEGIN
			DECLARE @tbl TABLE(tid int identity(1,1),id int)
			INSERT INTO @tbl
			SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS dgid FROM
			(
				SELECT CAST('<XMLRoot><RowData>' + REPLACE(weekoffs,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
				FROM sSetup.tOrganizationMaster where Id = @rOrgid
			) t CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)
			 
			SET @lWeekOff = [sAssessment].[fGetWeekdayNumber](@lDate)
			
			IF  EXISTS(SELECT 1 from @tbl where @lWeekOff in (id)) 
			BEGIN
				SET @lStatus = 'W'
				RETURN @lStatus	
			END	 
			
			IF(@lDate > GETDATE())
			BEGIN
				SET @lStatus = ''
				RETURN @lStatus	
			END	 
			
			IF   EXISTS(SELECT 1 FROM sActivity.tEventSchedule ES INNER JOIN  sActivity.tEventAssign EA ON EA.EventScheduleId=ES.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EA.SourceId WHERE ES.BatchId = @rBatchId AND ((SourceId=@rDepartmentId) OR (@rDepartmentId=0)) 
						AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
			BEGIN
				SET @lStatus = 'H'	
				--RETURN @lStatus		
			END
			
			SELECT @lStatus=LTM.Code + ' / ' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
			FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
			WHERE L.StatusId = 550 AND L.EmployeeId = @rEmployeeId AND @lDate BETWEEN L.FromDate AND L.ToDate
		 END
	END	
	RETURN @lStatus	
END
GO
PRINT N'Altering [sStudent].[vStudentAllDetail]...';


GO

/******************************************************************************  
 Purpose          : To get Doctor details  
 Created date     : 18 Jan 2012  
 Author           : Rajendra Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 Last Change Desc : Moved EmployeeMaster from sCommon to sHrm.
*******************************************************************************/  
ALTER VIEW [sStudent].[vStudentAllDetail]  
  
AS  
  
SELECT 
	  A.Id AS AcademicId,	  
	  A.ClassId,
	  A.DivisionId,
	  A.RollNo,
	  A.OrgId,
	  A.BatchId,
	  SM.Id AS StudentId,
	  SM.Code,
	  SM.Number,
	  SM.FirstName,
	  SM.MiddleName,
	  SM.LastName,
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	  CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,
	  SA.LCProgress,
	  SA.LCConduct,
	  SA.LeftDate,
	  SA.PreviousSchool,
	  SA.LeftReason,
	  SA.InactiveDate,
	  SA.AdmissionDate,
	  AdmissionStandard=(SELECT Title FROM SSetup.tClassMaster WHERE Id=SA.AdmissionStandardId),
	  LeftStandard=(SELECT Title FROM SSetup.tClassMaster WHERE Id=SA.LeftStandardId),
	  SA.LCNumber,
	  SA.LCDate,
	  RM.Title AS Religion,
	  SO.FamilyCast,
	  SO.FamilySubCast,
	  SO.BirthPlace,
	  SO.BirthTaluka,
	  SO.BirthDistrict,
	  ISNULL(SO.DateOfBirth,'0001/01/01') AS DateOfBirth,
	  SO.BirthDateInWord,
	  (SI.StudentPhoto) AS StudentPhoto,
	  (SI.FatherPhoto) AS FatherPhoto,
	  (SI.MotherPhoto) AS MotherPhoto,
	  (SI.RelativePhoto) AS RelativePhoto,
	  BGM.Title AS BloodGroup,
	  ISNULL(SC.PermanentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS PresentAddress,
	  ISNULL(GM.Title,'') AS Gender,
	  ISNULL(SC.StudentContactNo,'') AS ContactNo,
	  BM.Title AS Batch,
	  ISNULL(ACM.Title,'') AS AdmissionCategory,
	  SO.HouseId,
	  ISNULL(SC.PresentStreetone,'') AS PresentStreetone,
	  ISNULL(SC.PresentStreetTwo,'') AS PresentStreetTwo,
	  ISNULL(SC.PresentStreetThree,'') AS PresentStreetThree,
	  ISNULL(SC.PresentCity,'-') AS PresentCity,
	  ISNULL(SC.PresentState,'-') As PresentState,
	  ISNULL(SC.PresentZipCode,'-') as PresentZipCode,
	  ISNULL(SC.PresentCountry,'-') AS PresentCountry,
	  ISNULL(SC.PresentContactNo,'-') as PresentContactNo,
	  ISNULL(SC.ParentEmail,'-') AS ParentEmail,
	  ISNULL(SC.ParentContactNo,'-') AS ParentContactNo,
	  ISNULL(SC.StudentContactNo,'-') AS StudentContactNo,
	  DM.OrderIndex AS DivisionOrder,
	  SM.RegistrationNumber,
	  BM.IsActive AS IsActiveBatch,
	  CM.DepartmentId,
	  BM.OrgGroupBatchId ,
	  ISNULL(SO.UIDNumber,'' ) AS UIDNumber,
	  ISNULL(SO.AdhaarNumber,'') AS AdhaarNumber,
	  ISNULL(SM.SUId,'') AS SUId,
	  ISNUll(SA.IsTransfer,0)AS IsTransfer,
	  ISNULL(SA.TransferFrom,'') AS TransferFrom,
	  ISNULL(SA.CertificateName,'') AS CertificateName,
	  ISNUll(SA.IsTFWS,0)AS IsTFWS,
	  ISNUll(SA.IsCertificateHolder,0)AS IsCertificateHolder,
	  ISNULL(SC.EmergencyStreetOne,'') AS EmergencyStreetOne,
	  ISNULL(SC.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
	  ISNULL(SC.EmergencyStreetThree,'') AS EmergencyStreetThree,
	  ISNULL(SC.EmergencyCountry,'') AS EmergencyCountry,
	  ISNULL(SC.EmergencyState,'') As EmergencyState,
	  ISNULL(SC.EmergencyCity,'') AS EmergencyCity,
	  ISNULL(SC.EmergencyZipCode,'') as EmergencyZipCode,
	  ISNULL(SC.EmergencyContactNo,'') AS EmergencyContactNo,
	  ISNULL(CM.StreamId,0) AS StreamId,
	  Isnull(SO.CastCategoryId,0) AS CastCategoryId,
	  Isnull(SO.NationalityId,0) AS NationalityId,
	  ISNULL(SO.MotherTongue,'') As MotherTongue,
	  Isnull(SO.BirthState,'') AS BirthState,
	  ISNULL(SO.BirthCountry,'') As BirthCountry,
	  ISNULL(SC.PermanentStreetOne,'') AS  PermanentStreetOne ,
	  ISNULL(SC.PermanentStreetTwo,'')  AS  PermanentStreetTwo,
	  ISNULL(SC.PermanentStreetThree,'') AS PermanentStreetThree,
	  ISNULL(SC.PermanentCity,'') AS PermanentCity,
	  ISNULL(SC.PermanentState,'') AS PermanentState,
	  ISNULL(SC.PermanentCountry,'') AS PermanentCountry,
	  ISNULL(SC.PermanentZipCode,'') AS PermanentZipCode,
	  ISNULL(SC.PermanentContactNo,'') AS PermanentContactNo,
	  ISNULL(Sc.StudentEmail,'') AS StudentEmail,
	  ISNULL(SC.PresentDistanceFromSchool,0) AS PresentDistanceFromSchool,
	  ISNULL(NM.Nationality,'') AS Nationality,
	  ISNULL(SA.PreviousStandard,'')AS PreviousStandard  
	 
  FROM 
  
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId
	LEFT JOIN sStudent.tStudentCommunication SC 
		ON SC.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentOther SO
		ON SO.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentAdmission SA
		ON SA.StudentId=A.StudentId
	LEFT JOIN sCommon.tReligionMaster RM
		ON RM.Id=SO.ReligionId
	LEFT JOIN sStudent.tStudentImages SI
		ON SI.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM
		ON BGM.Id=SO.BloodGroupId
	INNER JOIN sSetup.tBatchMaster BM
		ON BM.Id=A.BatchId
	LEFT JOIN sCommon.tGenderMaster GM 
		ON GM.Id=SO.GenderId
	LEFT JOIN sStudent.tAdmissionCategoryMaster ACM 
		ON ACM.Id=SM.AdmissionCategoryId
	INNER JOIN sSetup.tOrganizationMaster OM
	    ON SM.OrgId = OM.Id
	LEFT JOIN sCommon.tCountryMaster NM ON Nm.Id=SO.NationalityId
GO
PRINT N'Altering [sStudent].[vStudentCommunication]...';


GO





/******************************************************************************  
 Purpose          : To get Doctor details  
 Created date     : 18 Jan 2012  
 Author           : Rajendra Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 Last Change Desc : Moved EmployeeMaster from sCommon to sHrm.
*******************************************************************************/  
ALTER VIEW [sStudent].[vStudentCommunication]  
  
AS  
  
SELECT 
	  A.Id AS AcademicId,	  
	  A.ClassId,
	  A.DivisionId,
	  A.RollNo,
	  A.OrgId,
	  A.BatchId,
	  SM.Id AS StudentId,
	  SM.Code,
	  SM.Number,
	  SM.FirstName,
	  SM.LastName,
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	  CM.DepartmentId,
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,
	  ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
	  ISNULL(SC.ParentEmail,'') AS ParentEmail,
	  ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
	  ISNULL(SC.StudentEmail,'') AS StudentEmail,
	  SO.DateOfBirth,
	  CM.OrderIndex AS ClassOrderIndex,
	  DM.OrderIndex AS DivisionOrderIndex,
	  ISNULL(BM.IsActive,0) AS IsActiveBatch,
	  BM.OrgGroupBatchId,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.MotherContactNo,
	  SF.MotherMail,
	  OM.OrgGroupId,
	  ISNULL(SM.SUId,'') AS SUId,
	  SM.AdmissionCategoryId
  FROM 
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId	 
	LEFT JOIN sStudent.tStudentCommunication SC
		ON SC.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentFamily SF
		ON SF.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentOther SO
		ON SO.StudentId=A.StudentId
	INNER JOIN sSetup.tOrganizationMaster OM
	    ON SM.OrgId = OM.Id	
	INNER JOIN sSetup.tBatchMaster BM 
		ON BM.Id = A.BatchId
GO

GO
PRINT N'Altering [sAcademic].[pXMLTopicMasterAdd]...';


GO
ALTER PROCEDURE [sAcademic].[pXMLTopicMasterAdd]
	(
		@rXml  nvarchar(MAX),
		@rOrgId int,
		@rClassId int,
		@rSubjectId int,
		@rCreatedUserId bigint 
		
	)
AS

SET NOCOUNT ON

BEGIN

 

DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT			
 
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXml
	
	 
	
	 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tTopicMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sAcademic.tTopicMaster
	(		Id,
			Number,
			Title,
			SubjectId,
			ClassID,
			OrgId,
			CreatedUserId,
			CreatedDateTime 
			
	)
	SELECT	
			@lNextNumber+ ROW_NUMBER() OVER(ORDER BY Number),
			A.Number,
			A.Title,
			@rSubjectId,
			@rClassID,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate() 
			 
			
	FROM OPENXML (@intDoc, '/Table/TopicMaster', 1)
	WITH
	(
			 
			Number nvarchar(100) '@Number',
			Title nvarchar(100) '@Title' 
			 
	)A  
	

	EXEC sp_xml_removedocument @intDoc
	
	SELECT @lNextNumber = MAX(ID) FROM sAcademic.tTopicMaster Where OrgId=@rOrgId
    EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAcademic.tTopicMaster', @rCurrentNumber = @lNextNumber 

	SELECT 1 as Result
	 
END
GO
PRINT N'Altering [sAccounting].[pBalanceSheet]...';


GO
ALTER PROCEDURE [sAccounting].[pBalanceSheet]

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

BEGIN

  --SELECT   '' AS OrgTitle,
--	   '' AS SmallAddress1,
--       '' As SmallAddress2,
  --'' AS Builder1,
	 --    '' AS Builder2,
  --       '' AS IncomeGroup,
	 --    '' AS IncomeLedger,
	 --    '' AS Income,
	 --    '' AS ClosingBalance,
	 --    '' AS ExpenseGroup,
	 --    '' AS ExpenseLedger,
	 --    '' AS Expense,
	 --    '' AS OpeningBalance

Declare @lLedgerId int 
Declare @lOpeningBalance Decimal (12,2)
Declare @ltIncome Decimal (12,2)
Declare @ltExpense Decimal (12,2)
Declare @lInIncome Decimal(12,2)
Declare @lInClosing Decimal(12,2)
Declare @lExOpening Decimal(12,2)
Declare @lExExpense Decimal(12,2)
Declare @lGrossProfit Decimal(12,2)
Declare @lGrossLoss Decimal(12,2)
Declare @lCount int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150)
DECLARE @1ExpenceCount int
DECLARE @1IncomeCount int
DECLARE @lProfitLostAmount Decimal(12,2)
DECLARE @lOpenigCrAmount Decimal(12,2)
DECLARE @lOpeningDrAmount Decimal(12,2)
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)
 		)
 		  	
 		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,'',''
				
		
		---- Start Profilt Loss
			CREATE TABLE #TempExpenseGroup1
		(
		   Id INT IDENTITY(1,1),
		   ExpenseGroupId int,
		   ExpenseGroup nvarchar(200),
		   ExpenseLedger nvarchar(200),
		   Expense decimal(22,2) default 0.0,
		   OpeningBalance decimal(22,2)		 
		)
		
		CREATE TABLE #TempIncomeGroup1
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroupId int,
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(22,2) default 0.0,
		   ClosingBalance decimal		 
		)
		
		INSERT INTO #TempExpenseGroup1
		SELECT 
		ISNULL(LG.Id,0)AS ExpenseGroupId,
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance
 
	    FROM sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID  = 4 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) > 0
		Order By LMG.Id	
		
		
		INSERT INTO #TempIncomeGroup1
        SELECT  		
        ISNULL(LG.Id,0)AS IncomeGroupId,
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
		FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID = 3 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) >  0
		Order By LMG.Id			
		

		SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup1
	    SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup1
		
		
	   If(@1InComeCount > @1ExpenceCount)
	     BEGIN	          
			if @1ExpenceCount =  0 
			begin
				SELECT @lProfitLostAmount  = isnull(SUM(Income),0) 
				FROM #TempIncomeGroup1 IG 
			end
			else
			begin			
				SELECT @lProfitLostAmount  = isnull(SUM(Income),0) - isnull(SUM(Expense),0)
				FROM #TempIncomeGroup1 IG LEFT JOIN #TempExpenseGroup1 EG ON isnull(EG.Id,0) = isnull(IG.Id,0)
			end
	     END
	     ELSE
	     BEGIN
		 if @1ExpenceCount =  0 
			begin
				SELECT @lProfitLostAmount  = isnull(SUM(Income),0) 
				FROM #TempIncomeGroup1 IG 
			end
			else
			begin		
	           SELECT @lProfitLostAmount=isnull((isnull(SUM(Income),0)-isnull(SUM(Expense),0)),0)
	           FROM  #TempExpenseGroup1 EG   LEFT JOIN #TempIncomeGroup1 IG ON isnull(EG.Id,0) = isnull(IG.Id,0)
			end
	     END	
		
		SELECT @lOpenigCrAmount= SUM(OpeningBalance) from sAccounting.tLedgerMaster L 
		WHERE LedgerTypeId = 1 AND L.AccountingYearId = @rAccountingYearId

		SELECT @lOpeningDrAmount= SUM(OpeningBalance) from sAccounting.tLedgerMaster L 
		WHERE LedgerTypeId = 2 AND L.AccountingYearId = @rAccountingYearId
		
	
		---- End Profit Loass
		
		CREATE TABLE #TempExpenseGroup
		(
		   Id INT IDENTITY(1,1),
		   ExpenseGroupId int,
		   ExpenseGroup nvarchar(200),
		   ExpenseLedger nvarchar(200),
		   Expense decimal(22,2),
		   OpeningBalance decimal(22,2)		 
		)
		
		CREATE TABLE #TempIncomeGroup
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroupId int,
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(22,2),
		   ClosingBalance decimal		 
		)
		
		
		
		
		
		
		INSERT INTO #TempIncomeGroup
		SELECT 
		ISNULL(LG.Id,0)AS ExpenseGroupId,
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance
	    
	    FROM sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID  = 2 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) > 0 
		Order By LG.Title,LMG.Id	
		
		
		INSERT INTO #TempExpenseGroup
        SELECT  	
        ISNULL(LG.Id,0)AS IncomeGroupId,	
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
		FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID = 1 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) >  0
		Order By LG.Title,LMG.Id	
		
		

	   SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup
	   SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup
		--- profit loss   
		IF  @lProfitLostAmount  is null 
		BEGIN
			SET @lProfitLostAmount  = 0
		END
	   IF @lProfitLostAmount > 0
	   BEGIN
			UPDATE TG SET Income = OpeningBalance 
			FROM #TempIncomeGroup TG INNER JOIN sAccounting.tLedgerMaster LM
			ON TG.IncomeLedger = LM.Title COLLATE DATABASE_DEFAULT  AND LM.Code = '4' AND LM.AccountingYearId = @rAccountingYearId
			INSERT INTO #TempIncomeGroup (IncomeGroup,IncomeLedger,Income,ClosingBalance) VALUES ('','Net Proft',@lProfitLostAmount,@lProfitLostAmount)
			--WHERE IncomeLedger = (SELECT TITLE FROM sAccounting.tLedgerMaster WHERE Code='4' AND
			--AccountingYearId=@rAccountingYearId)
	   END
	   ELSE
	   BEGIN
	  
	   	    UPDATE TG SET Expense = Isnull(lm.OpeningBalance,0) 			 
			FROM #TempExpenseGroup TG INNER JOIN sAccounting.tLedgerMaster LM
			ON  LM.Code = '4' AND LM.AccountingYearId = @rAccountingYearId	AND   TG.ExpenseLedger = LM.Title  	COLLATE DATABASE_DEFAULT 	
			INSERT INTO #TempExpenseGroup (ExpenseGroup,ExpenseLedger,Expense,OpeningBalance) VALUES ('','Net Loss',@lProfitLostAmount,@lProfitLostAmount)

			--UPDATE #TempExpenseGroup SET Expense =@lProfitLostAmount 
			--WHERE ExpenseLedger = (SELECT TITLE FROM sAccounting.tLedgerMaster WHERE Code='4' AND
			--AccountingYearId=@rAccountingYearId)
	   END
	   
	   -- Close Profit loss
		-- Opening Difference
  		IF (@lOpenigCrAmount > @lOpeningDrAmount )
		BEGIN
			INSERT INTO #TempExpenseGroup (ExpenseGroupId,ExpenseGroup,ExpenseLedger,Expense,OpeningBalance) VALUES (0,'','Diff In Opening Balance',@lOpenigCrAmount - @lOpeningDrAmount,0)
		END
		ELSE
		BEGIN
			INSERT INTO #TempIncomeGroup (IncomeGroupId,IncomeGroup,IncomeLedger,Income,ClosingBalance) VALUES (0,'','Diff In Opening Balance',@lOpeningDrAmount-@lOpenigCrAmount,0)
		END
		--end Opening Deifference
	   
	   
	   If(@1InComeCount > @1ExpenceCount)
	     BEGIN	   	       
	           SELECT @ReportOrgTitle  AS OrgTitle,
	             @SmallAddress1 AS SmallAddress1,
				 @SmallAddress2 AS SmallAddress2, 
	             @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2, 
				   ISNULL(IncomeGroupId,0) AS IncomeGroupId,
	               ISNULL(IncomeGroup,'') AS IncomeGroup, 
	               ISNULL(IncomeLedger,'') AS IncomeLedger,
	               ISNULL(ClosingBalance,0) AS ClosingBalance,
	               isnull(Income,0) AS Income,	   
				   ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,           
	               ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	               ISNULL(ExpenseLedger,'') AS ExpenseLedger,
				   ISNULL(OpeningBalance,0) AS OpeningBalance,	          
				   ISNULL(Expense,0.00) AS Expense
	           FROM #TempIncomeGroup IG LEFT JOIN #TempExpenseGroup EG ON EG.Id = IG.Id	  
	             
	     END
	     ELSE
	     BEGIN
	         SELECT Isnull(@ReportOrgTitle,'')  AS OrgTitle,
	             isnull(@SmallAddress1,'') AS SmallAddress1,
				 isnull(@SmallAddress2,'') AS SmallAddress2, 
					 @rBuilder1 AS Builder1
					,@rBuilder2 AS Builder2, 
				   ISNULL(IncomeGroupId,0) AS IncomeGroupId,           
	               ISNULL(IncomeGroup,'') AS IncomeGroup, 
	               ISNULL(IncomeLedger,'') AS IncomeLedger,
	               ISNULL(ClosingBalance,0) AS ClosingBalance,
	               ISNULL(Income,0) AS Income,
	               ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,           
	               ExpenseGroup AS ExpenseGroup,
	               ExpenseLedger,
				   ISNULL(OpeningBalance,0) AS OpeningBalance,
				   ISNULL(Expense,0) AS Expense        
	           FROM  #TempExpenseGroup EG   LEFT JOIN #TempIncomeGroup IG ON EG.Id = IG.Id		        
	          
	     END	
	     
	     DROP TABLE #TempExpenseGroup
	     DROP TABLE #TempIncomeGroup
		
		
		
--SELECT  
		
--		ISNULL(CASE WHEN LMG.ID=2 THEN LG.Title END,'') AS IncomeGroup,
--		ISNULL(CASE WHEN LMG.ID=2 THEN L.Title END,'') AS IncomeLedger,
--		ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance,
--		ISNULL(CASE WHEN LMG.ID=2 THEN SUM(UC.Closing_Balance) END,0) AS Income,
--		ISNULL(CASE WHEN LMG.ID=1  THEN LG.Title END,'') AS ExpenseGroup,
--		ISNULL(CASE WHEN LMG.ID=1  THEN L.Title END,'') AS ExpenseLedger,
--		ISNULL(CASE WHEN LMG.ID=1 THEN SUM(UC.Closing_Balance) END,0) AS Expense,
--		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
--		FROM sAccounting.tLedgerMaster L 
--		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
--		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id 
--		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id AND LMG.Id in (1,2)		
--		GROUP BY LG.Title,LMG.ID
--		,L.Title	
--		Order By LMG.Id	
END
GO
PRINT N'Altering [sAccounting].[pDayBook]...';


GO
ALTER PROCEDURE [sAccounting].[pDayBook]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rStartDate Date,
	@rEndDate Date,
	@rOrgGroupId int = 0,
	@rAccountingYearId [int],
	@rLedgerId [int],
	  @rAccountId int=0
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
   
    DECLARE @1OpeningBalance DECIMAL(22,2)
    DECLARE @1ClosingBalance DECIMAl(22,2)
   
   IF(@rLedgerId > 0)
    BEGIN   
    
    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
    
    END
    	

	SELECT 
	@rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,
	T.Id AS TransactionId,
	T.TransactionDate,
	T.VoucherNumber,
	L.TITLE,
	VTM.Title As VoucherType,
	T.Narration,
	ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * ISNULL(SUM(TD.AMOUNT),0) END,0) AS CREDIT,
	ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN ISNULL(SUM(TD.AMOUNT),0) END,0) AS DEBIT,
	CASE WHEN TD.TransactionTypeId = 1 THEN 'CREDIT' ELSE 'DEBIT' END AS TOBY,
	ISNULL(@1OpeningBalance,0) AS OpeningBalance,
	ISNULL(@1ClosingBalance,0) AS ClosingBalance,
	AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2
	
	from sAccounting.tTransaction T 
	INNER JOIN sAccounting.tTransactionDetail TD ON TD.TransactionId=T.Id 
	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
	LEFT 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	
	(TD.LedgerId =  @rLedgerId  OR @rLedgerId  =0) AND
	T.AccountingYearID=@rAccountingYearId AND
	 L.AccountingYearId = @rAccountingYearId
	 AND ((L.CODE <> '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE <> '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE <> '2' AND VTM.Title ='Journal Voucher' And TransactionTypeId <> 2)	 
	 or (L.CODE = '2' AND VTM.Title ='Contra Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Payment Voucher' And TransactionTypeId <> 1)
	 Or (L.CODE = '2' AND VTM.Title ='Receipt Voucher' And TransactionTypeId <> 2)
	 Or (L.CODE = '2' AND VTM.Title ='Journal Voucher' And TransactionTypeId <> 2)
	 )

	AND (T.AccountId=@rAccountId OR @rAccountId=0 )  
	 
	GROUP BY 	T.TransactionDate,TD.TransactionTypeId,T.VoucherNumber,T.Id,
				L.Title,VTM.Title,T.Narration,AM.ReportOrgTitle,AM.SmallAddress1,AM.SmallAddress2
END
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.TransactionDate,T.VoucherNumber
END
GO
PRINT N'Altering [sAccounting].[pProfitAndLoss]...';


GO

ALTER PROCEDURE [sAccounting].[pProfitAndLoss]

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

BEGIN
--SELECT '' AS OrgTitle,
--	   '' AS SmallAddress1,
--       '' As SmallAddress2,
--'' AS Builder1,
--	   '' AS Builder2,
--         '' AS IncomeGroup,
--	     '' AS IncomeLedger,
--	     '' AS Income,
--	     '' AS ClosingBalance,
--	     '' AS ExpenseGroup,
--	     '' AS ExpenseLedger,
--	     '' AS Expense,
--	     '' AS OpeningBalance
	    

Declare @lLedgerId int 
Declare @lOpeningBalance Decimal (12,2)
Declare @ltIncome Decimal (12,2)
Declare @ltExpense Decimal (12,2)
Declare @lInIncome Decimal(12,2)
Declare @lInClosing Decimal(12,2)
Declare @lExOpening Decimal(12,2)
Declare @lExExpense Decimal(12,2)
Declare @lGrossProfit Decimal(12,2)
Declare @lGrossLoss Decimal(12,2)
Declare @lCount int
Declare @lLedgerName Nvarchar(150)
Declare @lLedgerGroupName Nvarchar(150)
Declare @lLedgerMainGroupName Nvarchar(150) 
DECLARE @1ExpenceCount int
DECLARE @1IncomeCount int
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)
 		)  	
 		INSERT INTO #tempUpdateClosingBalance (LedgerId,Temp_Op_Balance,Closing_Balance,Transaction_Balance)
		EXEC [sAccounting].[pUpdateClosingBalance] @rStartDate,@rEndDate,@rOrgGroupId,@rAccountingYearId,'',''
		
		
		CREATE TABLE #TempExpenseGroup
		(
		   Id INT IDENTITY(1,1),
		   ExpenseGroupId int,
		   ExpenseGroup nvarchar(200),
		   ExpenseLedger nvarchar(200),
		   Expense decimal(22,2),
		   OpeningBalance decimal(22,2)		 
		)
		
		CREATE TABLE #TempIncomeGroup
		(
		   Id INT IDENTITY(1,1),
		   IncomeGroupId int,
		   IncomeGroup nvarchar(200),
		   IncomeLedger nvarchar(200),
		   Income decimal(22,2),
		   ClosingBalance decimal		 
		)
		
		INSERT INTO #TempExpenseGroup
		SELECT 
        Isnull(Lg.Id,0) as ExpenseGroupId,		
		ISNULL(LG.Title,'') AS ExpenseGroup,
		ISNULL(L.Title,'') AS ExpenseLedger,	
		ISNULL(SUM(UC.Closing_Balance),0) AS Expense,
	    ISNULL(SUM(L.OpeningBalance),0) AS OpeningBalance
 
	    FROM sAccounting.tLedgerMaster L
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID  = 4 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id	having ISNULL(SUM(UC.Closing_Balance),0) > 0
		Order By LMG.Id	
		
		
		INSERT INTO #TempIncomeGroup
        SELECT  
        Isnull(Lg.Id,0) as IncomeGroupId,		
		ISNULL(LG.Title,'') AS IncomeGroup,
		ISNULL(L.Title,'') AS IncomeLedger,
		ISNULL(SUM(UC.Closing_Balance),0) AS Income,
		ISNULL(SUM(UC.Closing_Balance),0) AS ClosingBalance
		FROM sAccounting.tLedgerMaster L 
		INNER JOIN sAccounting.tLedgerGroupMaster LG ON L.LedgerGroupId = LG.Id
		INNER JOIN sAccounting.tLedgerMainGroupMaster LMG ON LG.LedgerMainGroupId = LMG.Id
		INNER JOIN #tempUpdateClosingBalance UC ON L.Id=UC.LedgerId
		WHERE LMG.ID = 3 AND L.AccountingYearId = @rAccountingYearId AND LG.AccountingYearId = @rAccountingYearId
		GROUP BY LG.Title,LMG.ID,L.Title,LG.Id having ISNULL(SUM(UC.Closing_Balance),0) > 0	
		Order By LMG.Id			
	      
	     
	   SELECT @1ExpenceCount = count(Id) From #TempExpenseGroup
	   SELECT @1IncomeCount = Count(Id) From #TempIncomeGroup
	   If(@1InComeCount >= @1ExpenceCount)
	     BEGIN		    
	           SELECT @ReportOrgTitle  AS OrgTitle,
				@SmallAddress1 AS SmallAddress1,
				@SmallAddress2 AS SmallAddress2, 
	             @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2,
	               Isnull(IncomeGroupId,0) AS IncomeGroupId,
	               IncomeGroup, 
	               IncomeLedger,
	               ClosingBalance,
	               Income,
	               ISNULL(ExpenseGroupId,0) AS ExpenseGroupId,
	               ISNULL(ExpenseGroup,'') AS ExpenseGroup,
	               ISNULL(ExpenseLedger,'') AS ExpenseLedger,
				   ISNULL(OpeningBalance,0) AS OpeningBalance,	          
				   ISNULL(Expense,0.00) AS Expense
	           FROM #TempIncomeGroup IG 
	           LEFT JOIN #TempExpenseGroup EG ON EG.Id = IG.Id	  
	          
	     END
	     ELSE
	     BEGIN
	    
	     
	         SELECT @ReportOrgTitle  AS OrgTitle,
	             @SmallAddress1 AS SmallAddress1,
				 @SmallAddress2 AS SmallAddress2, 
				 @rBuilder1 AS Builder1
				,@rBuilder2 AS Builder2, 
				   Isnull(IncomeGroupId,0) AS IncomeGroupId,
	               ISNULL(IncomeGroup,'') AS IncomeGroup, 
	               ISNULL(IncomeLedger,'') AS IncomeLedger,
	               ISNULL(ClosingBalance,0) AS ClosingBalance,
	               ISNULL(Income,0) AS Income,
	               Isnull(ExpenseGroupId,0) AS ExpenseGroupId,
	               ExpenseGroup AS ExpenseGroup,
	               ExpenseLedger,
				   OpeningBalance,
				   Expense       
	           FROM  #TempExpenseGroup EG  LEFT JOIN #TempIncomeGroup IG ON EG.Id = IG.Id	
	                  
	     END	
	     
	     DROP TABLE #TempExpenseGroup
	     DROP TABLE #TempIncomeGroup
		
END
GO
PRINT N'Altering [sAccounting].[pVoucherListGet]...';


GO

ALTER PROCEDURE [sAccounting].[pVoucherListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rVoucherTypeId int = 0,
	 @rTransactionDate Date,
	 @rTransactionDateTo Date,
	 @rVoucherNumber int,
	 @rVoucherNumberTo int,
	 @rLedgerId int,
	 @rNarration nvarchar(100),
	 @rAmount int,
	 @rAccountingYearId int = 0,
	 @rIsApproved bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

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


GO
ALTER PROCEDURE [sAlert].[pEmailConfigurationAdd]
	
	@rOrgId smallint,
	@rMailTypeId tinyint,
	@rSMTPServer nvarchar(500),
	@rSMTPPort int,
	@rEnableSSL bit,
	@rSendUserName nvarchar(200),
	@rSendPassword nvarchar(200),
	@rFromMail nvarchar(200),
	@rOrgGroupId smallint,
	@rIsAllOrg bit,
	@rAPIKey nvarchar(200)='',
	@rSecretKey nvarchar(200)='',
	@rIsAuthenticateUsername bit = 0,
	@rDisplayName nvarchar(200) = ''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY
	 BEGIN TRANSACTION	
	 
	 IF(@rIsAllOrg=1)
	 BEGIN
		DECLARE @lCount INT
		
		CREATE TABLE #tTable  
		(
			Id bigint identity,
			OrgId smallint
		)
		INSERT INTO #tTable
		(
			OrgId
		)
		SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId
		
		SELECT @lCount =  COUNT(Id) FROM #tTable
		WHILE @lCount > 0 
		BEGIN
			SELECT @rOrgId=OrgId FROM #tTable WHERE Id = @lCount
		
			IF NOT EXISTS(SELECT OrgId FROM sAlert.tEmailConfiguration WHERE OrgId=@rOrgId AND MailTypeId = @rMailTypeId)
			BEGIN
				INSERT INTO sAlert.tEmailConfiguration
				(
					OrgId,
					MailTypeId,
					SMTPServer,
					SMTPPort,
					EnableSSL,
					SendUserName,
					SendPassword,
					FromMail,
					APIKey,
					SecretKey,
					IsAuthenticateUsername,
					DisplayName
				)
				VALUES
				(
					@rOrgId,
					@rMailTypeId,
					@rSMTPServer,
					@rSMTPPort,
					@rEnableSSL,
					@rSendUserName,
					@rSendPassword,
					@rFromMail,
					@rAPIKey,
					@rSecretKey,
					@rIsAuthenticateUsername,
					@rDisplayName
				)
			END	 
			ELSE
			BEGIN
				UPDATE  sAlert.tEmailConfiguration
				SET
					MailTypeId=@rMailTypeId,
					SMTPServer=@rSMTPServer,
					SMTPPort=@rSMTPPort,
					EnableSSL=@rEnableSSL,
					SendUserName=@rSendUserName,
					SendPassword=@rSendPassword,
					FromMail=@rFromMail,
					APIKey=@rAPIKey,
					SecretKey=@rSecretKey,
					IsAuthenticateUsername = @rIsAuthenticateUsername,
					DisplayName=@rDisplayName
				WHERE OrgId = @rOrgId AND MailTypeId = @rMailTypeId	   
			END  
			SELECT @rOrgId AS Result
			SET @lCount = @lCount - 1
		END
	 END
	 ELSE
	 BEGIN
	IF NOT EXISTS(SELECT OrgId FROM sAlert.tEmailConfiguration WHERE OrgId=@rOrgId AND MailTypeId = @rMailTypeId)
	BEGIN
		INSERT INTO sAlert.tEmailConfiguration
			(
				OrgId,
				MailTypeId,
				SMTPServer,
				SMTPPort,
				EnableSSL,
				SendUserName,
				SendPassword,
				FromMail,
				APIKey,
				SecretKey,
				IsAuthenticateUsername,
				DisplayName
			)
		VALUES
			(
				@rOrgId,
				@rMailTypeId,
				@rSMTPServer,
				@rSMTPPort,
				@rEnableSSL,
				@rSendUserName,
				@rSendPassword,
				@rFromMail,
				@rAPIKey,
				@rSecretKey,
				@rIsAuthenticateUsername,
				@rDisplayName
			)
		END	 
	 ELSE
		 BEGIN
			UPDATE  sAlert.tEmailConfiguration
			SET
				MailTypeId=@rMailTypeId,
				SMTPServer=@rSMTPServer,
				SMTPPort=@rSMTPPort,
				EnableSSL=@rEnableSSL,
				SendUserName=@rSendUserName,
				SendPassword=@rSendPassword,
				FromMail=@rFromMail,
				APIKey=@rAPIKey,
				SecretKey=@rSecretKey,
				IsAuthenticateUsername = @rIsAuthenticateUsername,
				DisplayName = @rDisplayName
		      
			  WHERE OrgId = @rOrgId AND MailTypeId = @rMailTypeId	   
		 END  
		SELECT @rOrgId AS Result
	END
		
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sAlert].[pEmailConfigurationGet]...';


GO
ALTER PROCEDURE [sAlert].[pEmailConfigurationGet]
	 
	 @rOrgId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 

	SELECT
			EC.MailTypeId,
			EC.SMTPServer,
			EC.SMTPPort,
			EC.EnableSSL,
			EC.SendUserName,
			EC.SendPassword,
			EC.FromMail,
			@rOrgId AS OrgId,
			ISNULL(EC.APIKey,'') AS APIKey,
			ISNULl(EC.SecretKey,'') AS SecretKey,
			ISNULL(EC.IsAuthenticateUsername,0) AS IsAuthenticateUsername,
			ISNULl(EC.DisplayName,'') AS DisplayName
	FROM
			sAlert.tEmailConfiguration EC
	WHERE 
			EC.OrgId=@rOrgId
END
GO
PRINT N'Altering [sAlert].[pFeeDueGet]...';


GO
ALTER PROCEDURE [sAlert].[pFeeDueGet]
		
		 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rToDate date,
	 	 @rMailSubject nvarchar(500)='',
	 	 @rAdmissionCategoryId int=0
	 	 
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
 
SELECT 
            D.AcademicId,
			D.RollNo,
			D.Name,
			D.Code,
			D.MobileNo,	
			D.EmailId,
			D.StudentContactNo,
			D.StudentEmail,
			D.FatherContactNo,
			D.FatherMail,
			D.MotherContactNo,
			D.MotherMail,
			SUM(D.PendingAmount) As PendingAmount,
			replace (
			replace(replace(replace(@rTemplate,'[Name]',D.Name),
			'[Class]',D.ClassName),
			'[Division]',D.DivisionName),
			'[PendingAmount]',convert(int,(SUM(D.PendingAmount))))
			 AS Template,
			@rMailSubject AS Subject
			
			FROM
			(
	
 			SELECT
			 			 
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.ClassName,
			SA.DivisionName,
			SA.Code,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			--replace (
			--replace(@rTemplate,'[Name]',SA.Name),
			--'[PendingAmount]',(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(R.PaidAmount,0.00)))
			-- AS Template,
		 
			--replace(@rTemplate,'[Name]',SA.Name) 
			-- AS Template,
			 SA.DivisionOrder,
			(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(R.PaidAmount,0.00))  AS PendingAmount
			 	 
  FROM 
  
		sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			    AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.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 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				--AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId 
			 AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=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 ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				
		) 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 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 (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				--AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				--AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				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.vStudentCommunication SC ON
		 SC.AcademicId = SA.AcademicId
		 
	
	WHERE	
	         SA.StatusId = 1 AND
			((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			--AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
			--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 (SA.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId=0)
 ) D
 GROUP BY 
			D.AcademicId,
			D.RollNo,
			D.Name,
			D.ClassName,
			D.DivisionName,
			D.Code,
			D.MobileNo,	
			D.EmailId,
			D.StudentContactNo,
			D.StudentEmail,
			D.FatherContactNo,
			D.FatherMail,
			D.MotherContactNo,
			D.MotherMail,
			D.DivisionOrder 
 Order by D.DivisionOrder,D.Rollno	
				
END
GO
PRINT N'Altering [sAlert].[pFeeReceiptEntryGet]...';


GO
ALTER PROCEDURE [sAlert].[pFeeReceiptEntryGet]
	 	 
	 	 @rReceiptId bigint,
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rAdmissionCategoryId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			@rSubject AS Subject,
			replace (
			replace (
			replace (
			replace (
			replace (
			replace(@rTemplate,'[Name]',SC.Name),
			'[Class]',SC.ClassName),
			'[Division]',SC.DivisionName),
			'[ReceiptNumber]',R.ReceiptNumber),
			'[ReceiptDate]',R.ReceiptDate),
			'[PaidAmount]',convert(int,R.ReceiptAmount))
			 AS MsgText
		
		
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sFee.tReceipt R ON R.SourceId=SC.AcademicId AND R.SourceTypeId=2001 AND R.IsObsolete=0
			AND ((R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((R.Id=@rReceiptId) OR (@rReceiptId=0))
		
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (SC.StatusId=1)
		AND (SC.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		ORDER BY R.ReceiptNumber
END
GO
PRINT N'Altering [sAssessment].[pExamScheduleGet]...';


GO
ALTER PROCEDURE [sAssessment].[pExamScheduleGet]
 
	@rExamId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT
		SM.Title AS 'Subject',
		ED.ExamDate AS ExamDate,
		ED.ExamTime AS ExamTime,
		ISNULL(ED.ExamTopic,'') AS ExamTopic
	FROM 
		sAssessment.tExamMaster E 
		INNER JOIN sAssessment.tExamDetail ED ON E.Id = ED.ExamId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
	WHERE 
		ED.ExamId = @rExamId  AND ISNULL(E.IsPublishExamSchedule,0) = 1
	ORDER BY 
		ED.ExamDate	
END
GO
PRINT N'Altering [sAttendance].[pAttenanceRegisterGetNew]...';


GO

 -- exec [sAttendance].[pAttenanceRegisterGetNew] '','',1,1001,7,2016,100100001,100100001,100100114,0,0,1
ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGetNew]
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0
	WITH EXECUTE AS CALLER
AS	
SET NOCOUNT ON
	DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	Declare @Days int 
	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
	
BEGIN 
CREATE Table #AttendanceRegistertempTable
(
	 
	ClassDivisionTitle Nvarchar(50),
	Code nvarchar(50),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(50),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(50),
	DivisionName nvarchar(50),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int,
	AdmissionDate date 
	 
 
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId ,
	AdmissionDate 
	 
  
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	 OM.FooterSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 A.AdmissionDate 
	 
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
			 
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))

				
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=@Days 
BEGIN

INSERT INTO #TempDaysTempTable
(
	DayPart,
    Value
)
SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffGet](@rForYear,@rForMonth,@li,@rBatchId,@rDivisionId,'',@rOrgId) 
 
 
SET @li = @li + 1

END
 
 
--DECLARE @TotalRecords int,@lpaging varchar(max)='',@PageSize int =100
--SELECT @TotalRecords = count(*)	 from #AttendanceRegistertempTable
--SELECT @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@PageIndex,@TotalRecords,@PageSize)

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			 
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			 ISNULL(TC.TCount,0) AS AttendanceCount,
				
		      ISNULL(AC.ACount,0) As  AbsentCount,
		       ISNULL(PC.PCount,0) As  PresentUpto,
		       ISNULL(AAC.AACount,0) As  AbsentUpto,
		       
		       ClassOrderIndex,
		       DivisionOrderIndex,
		       FooterSignature,				 
			0 AS TotalPresent ,
	 			   sAttendance.fAttendanceAdmissionDateGet(AdmissionDate,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),LeftDate,[1]) AS P1,
	 	 
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02'),LeftDate,[2]) AS P2,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03'),LeftDate,[3]) AS P3,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04'),LeftDate,[4]) AS P4,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05'),LeftDate,[5]) AS P5,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06'),LeftDate,[6]) AS P6,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07'),LeftDate,[7]) AS P7,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08'),LeftDate,[8]) AS P8,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09'),LeftDate,[9]) AS P9,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10'),LeftDate,[10]) AS P10,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11'),LeftDate,[11]) AS P11,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12'),LeftDate,[12]) AS P12,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13'),LeftDate,[13]) AS P13,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14'),LeftDate,[14]) AS P14,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15'),LeftDate,[15]) AS P15,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16'),LeftDate,[16]) AS P16,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17'),LeftDate,[17]) AS P17,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18'),LeftDate,[18]) AS P18,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19'),LeftDate,[19]) AS P19,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20'),LeftDate,[20]) AS P20,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21'),LeftDate,[21]) AS P21,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22'),LeftDate,[22]) AS P22,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23'),LeftDate,[23]) AS P23,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24'),LeftDate,[24]) AS P24,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25'),LeftDate,[25]) AS P25,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26'),LeftDate,[26]) AS P26,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27'),LeftDate,[27]) AS P27,
			sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28'),LeftDate,[28]) AS P28,
			CASE WHEN @Days>=29 THEN  sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29'),LeftDate,[29])end AS P29,
			CASE WHEN @Days>=30 THEN sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30'),LeftDate,[30]) end AS P30,
		    CASE WHEN @Days>=31 THEN sAttendance.fAttendanceAdmissionDateGet(AdmissionDate, (CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31'),LeftDate,[31]) end AS P31,
		 
 
sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth
,0 Ispresent,
0 AS AttendanceTagId 
  
--,AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE 
			 WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LA' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'ED' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,
		AdmissionDate 
 
		 -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
		
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount
		--,IsPresent,AttendanceTagId 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
			--,IsPresent,AttendanceTagId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
             --AND ( StatusId = 1)
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(
		SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			 AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
    LEFT JOIN
	(
		SELECT A.Id AS AcademicId, COUNT(1) AS AACount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
 
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			 AND SR.IsPresent = 0    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
			GROUP BY A.Id 
    ) AAC ON AAC.AcademicId = PivotTable.AcademicId
    
    ORDER BY RollNo;
    
select * from #TempDaysTempTable
--select '' as paging

drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
END
GO
PRINT N'Altering [sAudit].[pActivityLogGet]...';


GO
ALTER PROCEDURE [sAudit].[pActivityLogGet]
	
	@rOrgGroupId int,
	@rOrgId int,
	@rUserName nvarchar(100),
	@rScreenName nvarchar(100),
	@rActivity nvarchar(100),
	@rFromDate date,
	@rToDate date
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rScreenName = sCommon.fSearchStringGet(@rScreenName)
SET @rActivity = sCommon.fSearchStringGet(@rActivity)
SET @rToDate = DATEADD(day,1,@rToDate)
       SELECT 
       
            AL.OrgGroupId,
            AL.OrgId,
            OM.Title AS OrganizationName,
            AL.UserId,
			U.DisplayTitle AS UserName,
			U.LoginTitle,
			U.SessionId,
			S.Title AS ScreenName,
			AL.AuditDate,
			substring(AL.Activity, CHARINDEX(' ', AL.Activity)+1, len(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1)) AS  Activity,
			--replace(AL.Activity,' ','') AS  Activity,
			ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
			ISNULL(AL.RecordDetail,'') AS RecordDetail
			
       FROM 
       
       sAudit.tActivityLog AL
       INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
	   INNER JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId
          
       WHERE 
       
       AL.OrgGroupId = @rOrgGroupId
       AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
       AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
       AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
       AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))
       AND (AL.AuditDate >= @rFromDate)
	   AND (AL.AuditDate <= @rToDate)
       ORDER BY AL.AuditDate DESC
		
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,'') = '') and (isnull(EJD.dateofleaving,'') ='' or EJD.dateofleaving  > @lAttendanceDate)
	ORDER BY EM.Code

	TRUNCATE TABLE #TempMonthTrans
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,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			SM.LastName as Surname,
			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,
			CM.DisplayTitle  AS ClassName,
			@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 ,
			 SO.DateOfBirth,
			 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 [sCommon].[pOrganizationSetupRemove]...';


GO
 

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

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


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

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

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

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

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

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

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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


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

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

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

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

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

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

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

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


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

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

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

	SELECT 1 AS Result
 
-- COMMIT TRANSACTION
		
--	END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
		
--	END CATCH
END
GO
PRINT N'Altering [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
DELETE FROM sSecurity.tOrgGroupMobileAppDetail WHERE OrgGroupId = @rOrgGroupId

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


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

	-- special case will come orgwise and orggroupwise

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


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


DELETE FROM sProcurement.tOtherStockBatch WHERE CAST(LEFT(StockBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockIssue WHERE CAST(LEFT(StoreLocationId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockIssueBatch WHERE CAST(LEFT(OtherStockBatchId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sVts.tvtsOrgGroupMaster WHERE OrgGroupId = @rOrgGroupId
	
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].[pScreenGroupDataListGet]...';


GO
ALTER PROCEDURE [sCommon].[pScreenGroupDataListGet]
          
           @rScreenGroupId int,
           @rUserId bigint   
AS
SET NOCOUNT ON

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


GO
ALTER 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
		  ,ISNULL(PCM.Remark,'') AS Remark
          
  FROM    [sCommunication].[tPhotoCategoryMaster]  PCM 
            
  WHERE   
       ((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'Altering [sCommunication].[pAssignmentListGet]...';


GO
ALTER PROCEDURE [sCommunication].[pAssignmentListGet]
	 @rBatchId int,
	 @rUserId bigint,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int,
	 @rSyncedAssignmentId bigint = 0,
	 @rName nvarchar(100)='',
	 @rFromDate date='',
	 @rToDate date=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END
	
	if @rUserSourceTypeId   = 2003 -- For Student Login
	
	BEGIN
	
	
 	SELECT 	
			A1.Id as AssignmentId,
			A1.SubjectId,
			SM.Title as SubjectName,
			A1.Title,
			A1.Remark,
			A1.StartDate,
			A1.EndDate,
			ISNULL(AV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			SM.OrgId
	 FROM 
            sCommunication.tAssignment A1       
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A1.SubjectId 
            LEFT JOIN sCommunication.tAssignmentView AV ON AV.AssignmentId=A1.Id AND UserId=@rUserId     
            INNER JOIN sCommunication.tAssignmentScope AS1 ON AS1.AssignmentId=A1.Id 
            INNER JOIN ( SELECT A.DivisionId FROM sStudent.tAcademic A 
            WHERE A.StudentId = @rUserSourceId  AND A.BatchId = @rBatchId) D
            ON D.DivisionId =  AS1.SourceId AND AS1.SourceTypeId = 2005
            INNER JOIN sSecurity.tUser U ON U.Id=A1.CreatedUserId   
             WHERE 	 A1.BatchId=@rBatchId 
             AND ( A1.Id > @rSyncedAssignmentId OR @rSyncedAssignmentId = 0)
            AND (Convert(date,A1.CreatedDateTime)>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
			AND (Convert(date,A1.CreatedDateTime)<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
			AND (A1.Title like @rName OR ISNULL(@rName,'')='')
             Order by A1.CreatedDateTime DESC 
					

	
 END
 ELSE 
 BEGIN
 --IF @rUserSourceTypeId   = 2003 -- For Student Login
 	SELECT 	
			A1.Id as AssignmentId,
			A1.SubjectId,
			SM.Title as SubjectName,
			A1.Title,
			A1.Remark,
			A1.StartDate,
			A1.EndDate,
			ISNULL(AV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			SM.OrgId
	 FROM 
            sCommunication.tAssignment A1 
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A1.SubjectId 
            LEFT JOIN sCommunication.tAssignmentView AV ON AV.AssignmentId=A1.Id AND UserId=@rUserId           
            INNER JOIN sCommunication.tAssignmentScope AS1 ON AS1.AssignmentId=A1.Id 
            INNER JOIN ( SELECT EJD.OrganizationDepartmentId FROM sHrm.tEmployeeMaster EM
            INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
             WHERE EM.Id = @rUserSourceId) D
            ON D.OrganizationDepartmentId =  AS1.SourceId AND AS1.SourceTypeId = 2017
             INNER JOIN sSecurity.tUser U ON U.Id=A1.CreatedUserId   
             WHERE 	 A1.BatchId=@rBatchId 
               AND ( A1.Id > @rSyncedAssignmentId OR @rSyncedAssignmentId = 0)
                AND (Convert(date,A1.CreatedDateTime)>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
			AND (Convert(date,A1.CreatedDateTime)<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
			AND (A1.Title like @rName OR ISNULL(@rName,'')='')
					Order by A1.CreatedDateTime DESC
             
 END
 END
GO
PRINT N'Altering [sCommunication].[pBlogGet]...';


GO
ALTER PROCEDURE [sCommunication].[pBlogGet]
	 
	 @rId bigint,
	 @rOrgGroupBatchId int,
	 @rTitle nvarchar(200),
	 @rCreatedUserId bigint,
	 @rIsSearch bit = 1,
	 @rOrgId smallint,
	 @rSyncedBlogId bigint=0,
	 @rCreatedDateTime Date='',
	 @rFromDate date='',
	 @rToDate date=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
			Distinct(B.Id),
			B.OrgGroupBatchId,
		    OGBM.Title AS OrgGroupBatch,
		    B.Title,
		    B.Remark,
		    B.IsPublish,
		    U.DisplayTitle AS BlogCreatedUserName,
		    B.CreatedDateTime AS BlogCreatedDateTime,		 
		    (SELECT  ISNULL(Count(1),0) FROM sCommunication.tBlogFavorite BF WHERE BF.BlogId = B.Id) AS TotalBlogFavorite,
		    (SELECT ISNULL( Count(1),0) FROM sCommunication.tBlogComment BC WHERE BC.BlogId = B.Id) AS TotalBlogComment
		    
  FROM 
            sCommunication.tBlog B
            INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=B.OrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=B.CreatedUserId
			INNER JOIN sCommunication.tBlogScope BS ON BS.BlogId=B.Id AND ((BS.SourceId=@rOrgId)OR (@rOrgId=0))
  WHERE 
  
		((B.Id = @rId) OR (@rId = 0))
	AND ((B.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((B.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	AND ((B.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ( B.Id > @rSyncedBlogId OR @rSyncedBlogId = 0)
	AND ((convert(date,B.CreatedDateTime) = convert(date,@rCreatedDateTime)) OR (ISNULL(@rCreatedDateTime,'') = ''))
	AND (CONVERT(date,B.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
	AND (CONVERT(date,B.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='')
END
GO
PRINT N'Altering [sCommunication].[pCircularListGet]...';


GO
ALTER PROCEDURE [sCommunication].[pCircularListGet]
	 
	 @rOrgGroupBatchId int,
	 @rUserId bigint,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int,
	 @rSyncedCircularId bigint = 0,
	 @rStartDate date='',
	 @rName nvarchar(200)='',
	 @rFromDate date='',
	 @rToDate date=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	
	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END
	
	 DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint

	
	if @rUserSourceTypeId   = 95 -- For Employee Login
	
	BEGIN
	
		--DECLARE @lDepartmentId int,@lOrgId int,@lDepartmentId int
		
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId
		
	SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
			  
	 FROM 
            sCommunication.tCircular C 
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId           
            INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
             WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId) OR
            (CS.SourceTypeId = 95 AND CS.SourceId =@lEmployeeId))
              AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D
				ON D.CircularId= C.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            AND C.AssigneeId IN (1,3) 
            AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
            AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
			AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
			AND (C.Title like @rName OR ISNULL(@rName,'')='')
           	ORDER BY C.StartDate DESC
			
	
 END
 ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
 BEGIN
 
 
 SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId
  FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM
	ON A.BatchId = BM.Id 
	AND BM.IsActive = 1 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
  
 	SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
	 FROM 
            sCommunication.tCircular C 
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId      
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId
            INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
            WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId) OR
            (CS.SourceTypeId = 2016 AND CS.SourceId =@lClassId) OR
            (CS.SourceTypeId = 2005 AND CS.SourceId =@lDivisionId) OR
            (CS.SourceTypeId = 2003 AND CS.SourceId =@lStudentId) OR
            (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId) )
            AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D
				ON D.CircularId= C.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            AND C.AssigneeId IN (1,2) 
             AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
             AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
			 AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
			 AND (C.Title like @rName OR ISNULL(@rName,'')='')
            ORDER BY C.StartDate DESC

 END
 ELSE
  --For Other Users
 BEGIN
 
 SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
	 FROM 
            sCommunication.tCircular C     
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId  
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( C.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
             AND C.AssigneeId IN (1,2,3)
             AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
             AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
		     AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
		     AND (C.Title like @rName OR ISNULL(@rName,'')='')
            ORDER BY C.StartDate DESC

 
 	--SELECT 	
		--	C.Id as CircularId,
		--	C.Title,
		--	C.Remark,
		--	C.StartDate,
		--	CV.UserId,
		--	U.DisplayTitle as CreatedUserName	    
	 --FROM 
  --          sCommunication.tCircular C       
  --          LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
  --          INNER JOIN sCommunication.tCircularScope CS ON CS.CircularId=C.Id 
  --          INNER JOIN ( SELECT A.DivisionId FROM sStudent.tAcademic A            
  --           WHERE A.StudentId = @rUserSourceId ) D
  --          ON D.DivisionId =  CS.SourceId AND CS.SourceTypeId = 2005
  --          INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
  --          INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
  --          WHERE ( C.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
  --          Order by C.CreatedDateTime DESC


 END
 END
GO
PRINT N'Altering [sCommunication].[pMyUpdateGet]...';


GO
ALTER PROCEDURE [sCommunication].[pMyUpdateGet]
	 
@rOrgId int,	 
@rBatchId int,
@rOrgGroupBatchId int,
@rUserId bigint,
@rUserSourceId bigint,
@rUserSourceTypeId int,
@rSyncedAssignmentId bigint,
@rSyncedCircularId bigint,
@rSyncedPollId bigint,
@rSyncedQueryCommentId bigint,
@rSyncedNewsId bigint,
@rSyncedBlogId bigint,
@rSyncedBehaviourId bigint,
@rSyncedActivityId bigint,
@rSyncedResultId bigint,
@rSyncedAssignTaskId bigint,
@rSyncedPhotoCategoryId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	DECLARE @lAcademicId bigint,
	 @lScopeSourceId int,
	 @lScopeSourceTypeId int,
	 @lStudentId bigint,
	 @lClassId int,
	 @lDivisionId int,
	 @lOrgId int,
	 @lDepartmentId int,
	 @lAssignmentStatus bit=0,
	 @lCircularStatus bit=0,
	 @lPollStatus bit=0,
	 @lQueryStatus bit=0,
	 @lBlogStatus bit=0,
	 @lNewsStatus bit=0,
	 @lBehaviourStatus bit=0,
	 @lActivityStatus bit=0,
	 @lResultStatus bit=0,
	 @lAssignTaskStatus bit=0,
	 @lPhotoCategoryStatus bit=0,
	 @lIsActive bit=0,
	 @lIsOptimizeAppImageUpload bit=0

IF(	@rUserSourceTypeId = 2003)	
BEGIN
  SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId
  FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM
	ON A.BatchId = BM.Id AND BM.IsActive = 1 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
--SELECT @lAcademicId = Id, @lScopeSourceId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rUserSourceId AND BatchId = @rBatchId
SET @lScopeSourceId = @lDivisionId
SET @lScopeSourceTypeId = 2005
END
ELSE
BEGIN
	SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId  FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId
--SELECT @lScopeSourceId = OrganizationDepartmentId FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId
SET @lScopeSourceId = @lDepartmentId
SET @lScopeSourceTypeId = 2004
END

 
IF EXISTS(SELECT 1 FROM sCommunication.tAssignmentScope ASO INNER JOIN  sCommunication.tAssignment A
	ON A.Id = ASO.AssignmentId
WHERE ASO.AssignmentId > @rSyncedAssignmentId AND ASO.SourceTypeId = @lScopeSourceTypeId AND ASO.SourceId = @lScopeSourceId AND A.BatchId=@rBatchId)
SET @lAssignmentStatus = 1


IF(	@rUserSourceTypeId = 2003)	
BEGIN

    IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS WHERE
      ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) 
      OR (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId)
      OR (CS.SourceTypeId = 2016 AND CS.SourceId =@lClassId)
      OR (CS.SourceTypeId = 2005 AND CS.SourceId =@lDivisionId)
       OR (CS.SourceTypeId = 2003 AND CS.SourceId =@lStudentId)
        OR (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId)
        
      )
       AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D ON D.CircularId= C.Id
     	--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
        WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
        AND C.AssigneeId IN (1,2) AND C.OrgGroupBatchId=@rOrgGroupBatchId) 
      SET @lCircularStatus = 1

END 
ELSE
BEGIN
	IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
       WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId))
       AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D ON D.CircularId= C.Id
       --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
       WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
       AND C.AssigneeId IN (1,3) AND C.OrgGroupBatchId=@rOrgGroupBatchId) 
     SET @lCircularStatus = 1      	

END
--IF EXISTS(SELECT 1 FROM sCommunication.tCircularScope WHERE  CircularId > @rSyncedCircularId AND SourceTypeId = @lScopeSourceTypeId AND SourceId = @lScopeSourceId)
--SET @lCircularStatus = 1

IF EXISTS(SELECT 1 FROM sCommunication.tPoll P INNER JOIN sCommunication.tPollMember PM ON P.Id=PM.PollId
	WHERE PM.PollId > @rSyncedPollId AND PM.SourceTypeId = @lScopeSourceTypeId AND PM.SourceId = @lScopeSourceId AND P.OrgGroupBatchId=@rOrgGroupBatchId)
SET @lPollStatus = 1

IF EXISTS(SELECT 1 FROM sCommunication.tBlogScope BS INNER JOIN sCommunication.tBlog B
ON B.Id = BS.BlogId
WHERE B.IsPublish = 1 AND BS.BlogId > @rSyncedBlogId AND BS.SourceTypeId = 2021 AND BS.SourceId = @rOrgId AND B.OrgGroupBatchId = @rOrgGroupBatchId)
SET @lBlogStatus = 1

IF EXISTS(SELECT 1 FROM  sCommunication.tNews N INNER JOIN sCommunication.tNewsScope NS ON N.Id=NS.NewsId 
	  WHERE NS.NewsId > @rSyncedNewsId AND NS.SourceTypeId = 2021 AND NS.SourceId = @rOrgId AND N.OrgGroupBatchId = @rOrgGroupBatchId)
SET @lNewsStatus = 1

--IF EXISTS(SELECT 1 FROM sCommunication.tNewsScope WHERE NewsId > @rSyncedNewsId AND SourceTypeId = @rOrgId AND SourceId = 1016)
--SET @lNewsStatus = 1

IF EXISTS(SELECT 1 FROM sCommunication.tUploadResult WHERE Id > @rSyncedResultId AND DivisionId = @lScopeSourceId AND BatchId=@rBatchId AND IsObsolete=0 )
SET @lResultStatus = 1

IF EXISTS(SELECT 1 FROM  
sCommunication.tPhotoCategoryMaster PCM
INNER JOIN sCommunication.tPhotoCategoryOrg PCO 
ON PCM.Id=PCO.PhotoCategoryId WHERE PCM.Id > @rSyncedPhotoCategoryId AND PCO.OrgId = @rOrgId  AND PCM.IsObsolete=0 )
SET @lPhotoCategoryStatus = 1


IF EXISTS(SELECT 1 FROM sCommunication.tAssignTask WHERE  Id > @rSyncedAssignTaskId AND AssignedToSourceTypeId = @rUserSourceTypeId 
AND AssignedToSourceId = @rUserSourceId AND IsCompleted=0 AND IsClosed=0 AND OrgId=@rOrgId)
SET @lAssignTaskStatus = 1


IF EXISTS(SELECT 1 FROM  sActivity.tActivity A INNER JOIN sActivity.tActivityParticipant AP ON A.Id=AP.ActivityId
	WHERE AP.ActivityId > @rSyncedActivityId AND AP.SourceTypeId = @rUserSourceTypeId AND AP.SourceId = @rUserSourceId AND A.BatchId=@rBatchId)
SET @lActivityStatus = 1



IF EXISTS(SELECT 1 FROM sCommunication.tBehaviour WHERE Id > @rSyncedBehaviourId AND AcademicId = @lAcademicId )
SET @lBehaviourStatus = 1

IF EXISTS(SELECT 1 FROM sCommunication.tQuery Q INNER JOIN sCommunication.tQueryComment QC ON Q.Id=QC.QueryId
WHERE Q.CreatedUserId=@rUserId AND Q.IsUserView=0 AND QC.Id>@rSyncedQueryCommentId AND QC.CreatedUserId <> @rUserSourceId AND Q.OrgGroupBatchId=@rOrgGroupBatchId)
SET @lQueryStatus = 1
 
IF(@rUserSourceTypeId = 2003)
BEGIN 
	DECLARE @lStatusId1 smallint=0
 	SELECT @lStatusId1 = StatusId FROM sStudent.tStudentMaster SM WHERE Id = @rUserSourceId
	IF(@lStatusId1=1)
	BEGIN 
		SET @lIsActive = 1
	END	ELSE
	BEGIN
		SET @lIsActive = 0
	END
END
ELSE IF(@rUserSourceTypeId = 95)
BEGIN 
	DECLARE @lStatusId2 smallint=0
	SELECT @lStatusId2 = StatusId FROM sHrm.tEmployeeMaster EM WHERE Id = @rUserSourceId
	
	IF(@lStatusId2=7)
	BEGIN 
		SET @lIsActive = 1
	END	ELSE
	BEGIN
		SET @lIsActive = 0
	END
END

DECLARE @lOrgGroupId int=0
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id =@rOrgId
DECLARE @lOptimizeAppImageUpload nvarchar(50)
SELECT @lOptimizeAppImageUpload = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 247 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
IF (@lOptimizeAppImageUpload IS NULL) OR (@lOptimizeAppImageUpload = 'False')
	SET @lIsOptimizeAppImageUpload = 0
ELSE
	SET @lIsOptimizeAppImageUpload = 1	
 
CREATE TABLE #Module (
Id int,
Title nvarchar(50),
IsNew bit )
INSERT INTO #Module VALUES (1,'IsActiveCheck',@lIsActive)
INSERT INTO #Module VALUES (2,'IsOptimizeAppImageUpload',@lIsOptimizeAppImageUpload)
INSERT INTO #Module VALUES (20085,'Circular',@lCircularStatus)
INSERT INTO #Module VALUES (20088,'Query',@lQueryStatus)
INSERT INTO #Module VALUES (20099,'Blog',@lBlogStatus)
INSERT INTO #Module VALUES (20104,'News',@lNewsStatus)
INSERT INTO #Module VALUES (20172,'AssignTask',@lAssignTaskStatus)
INSERT INTO #Module VALUES (20183,'Gallery',@lPhotoCategoryStatus)
INSERT INTO #Module VALUES (20204,'Poll',@lPollStatus)
INSERT INTO #Module VALUES (20093,'Assignment',@lAssignmentStatus)
INSERT INTO #Module VALUES (20209,'Activity',@lActivityStatus)
INSERT INTO #Module VALUES (20130,'Behaviour',@lBehaviourStatus)
INSERT INTO #Module VALUES (20180,'Result',@lResultStatus)
	
SELECT * FROM #Module
 
--SELECT @lAssignmentStatus AS Assignment,@lCircularStatus AS Circular,@lPollStatus AS Poll,@lQueryStatus AS Query,
--@lBlogStatus AS Blog,@lNewsStatus AS News,@lBehaviourStatus AS Behaviour,
--@lActivityStatus AS Activity,@lResultStatus AS Result,@lAssignTaskStatus AS AssignTask,@lPhotoCategoryStatus AS Gallery

END
GO
PRINT N'Altering [sCommunication].[pNewsGet]...';


GO
ALTER PROCEDURE [sCommunication].[pNewsGet]
	 
	 @rId bigint=0,
	 @rOrgGroupBatchId int,
	 @rTitle nvarchar(200),
	 @rIsSearch bit = 1,
	 @rOrgId smallint,
	 @rSyncedNewsId bigint = 0,
	 @rFromDate date='',
	 @rToDate date=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF @rIsSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			DISTINCT(N.Id),
			N.OrgGroupBatchId,
		    OGBM.Title AS OrgGroupBatch,
		    N.Title,
		    N.Remark,
		    U.DisplayTitle AS NewsCreatedUserName,
		    N.CreatedDateTime AS NewsCreatedDateTime,
		    (SELECT ISNULL( Count(1),0) FROM sCommunication.tNewsComment NC WHERE NC.NewsId = N.Id) AS TotalNewsComment
		    
	FROM 
			sCommunication.tNews N
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=N.OrgGroupBatchId
			INNER JOIN sSecurity.tUser U ON U.Id=N.CreatedUserId
			INNER JOIN sCommunication.tNewsScope NS ON NS.NewsId=N.Id AND ((NS.SourceId=@rOrgId)OR (@rOrgId=0))
	WHERE 
	  
			((N.Id = @rId) OR (@rId = 0))
		AND ((N.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((N.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND ( N.Id > @rSyncedNewsId OR @rSyncedNewsId = 0)
		AND (CONVERT(date,N.CreatedDateTime)>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (CONVERT(date,N.CreatedDateTime)<=@rToDate OR ISNULL(@rToDate,'')='')
		
		order by N.CreatedDateTime DESC
END
GO
PRINT N'Altering [sCommunication].[pViewPhotoCategoryMaster_Get]...';


GO
ALTER PROCEDURE [sCommunication].[pViewPhotoCategoryMaster_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 ClassId = 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) OR (@rId=0))  AND PCM.IsObsolete=0
	 
      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) OR (@rId=0))  AND PCM.IsObsolete=0
        
  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 [sErp].[pDSRMasterGet]...';


GO
ALTER PROCEDURE [sErp].[pDSRMasterGet]

	 @rId int,
	 @rUserId bigint,
	 @rFromDate Date,
	 @rTillDate Date,
	 @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,
		    convert(int,PT.HoursWorked) As HoursWorked,
		    PT.CreatedUserId,
		    PT.CreatedDateTime,
		    PM.Title as Project,
		    Dwt.Title as DSRWorkType,
			CASE WHEN PT.MinuteWorked IS NULL THEN 	PARSENAME(PT.HoursWorked,1)  ELSE ISNUll(PT.MinuteWorked,0) END  AS  MinuteWorked,
			CONVERT(nvarchar(10),CONVERT(int,PT.HoursWorked)) +':'+ CONVERT(nvarchar(10),ISNUll(PT.MinuteWorked,0)) AS HoursWork
		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))
		AND ((PT.CreatedUserId = @rUserId) OR (@rUserId = 0))
		AND ((PT.ReportDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	    AND ((PT.ReportDate <= @rTillDate) OR (ISNULL(@rTillDate,'') = ''))
	    
	    order by ReportDate desc
END
GO
PRINT N'Altering [sErp].[pDSRMasterSearchGet]...';


GO

ALTER PROCEDURE [sErp].[pDSRMasterSearchGet]

	 @rId int,
	 @rUserId bigint,
	 @rFromDate Date,
	 @rTillDate Date,
	 @rOrgId smallint,
	 @rModule nvarchar(100),
	 @rProjectId int ,
	 @rWorkTypeId int ,
	 @rActive bit = 0
	 	 
	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,
		    u.DisplayTitle,
		    CONVERT(nvarchar(10),CONVERT(int,PT.HoursWorked)) +':'+ CONVERT(nvarchar(10),ISNUll(PT.MinuteWorked,0)) AS HoursWork
		 
		
	FROM 
			sErp.tDSR  PT
			inner join sErp.tDSRWorkTypeMaster Dwt on Dwt.Id = PT.DSRWorkTypeId
			inner join sErp.tProjectMaster PM on PM.Id = PT.ProjectId
			inner join sSecurity.tUser u on u.Id = PT.CreatedUserId
	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))
		AND ((u.id = @rUserId) OR (@rUserId = 0))
		AND ((PT.ReportDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	    AND ((PT.ReportDate <= @rTillDate) OR (ISNULL(@rTillDate,'') = ''))
	    and PM.IsActive =@rActive
	    
	    order by ReportDate desc
	    
	
		
		
		
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,
			@rSourceTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION
		
		
	DECLARE @lNextNumber BIGINT
	DECLARE @lNextNumberPosting INT
	DECLARE @1AccountId int 
	DECLARE @1AccountYearId int 
	DECLARE @lVoucherNumber bigint
	
    SELECT @1AccountId = AYM.AccountId, @1AccountYearId = AYM.Id FROM sAccounting.tAccountingYearMaster AYM 
    INNER JOIN sAccounting.tAccountMaster AM ON AM.Id = AYM.AccountId 
    WHERE AM.Title= sSetup.fPortalXMLTagsReplaceReverse(@rAccount) AND AYM.Title = @rAccountingYear
    
    SELECT @lVoucherNumber = ISNULL(Max(T.VoucherNumber),0) + 1 FROM sAccounting.tTransaction T
	WHERE VoucherTypeId=@rVoucherTypeId AND AccountingYearId = @1AccountYearId
    
    IF NOT EXISTS (SELECT 1 FROM sFee.tChargeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId 
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId AND SourceTypeId=@rSourceTypeId)
    BEGIN
		 
		SELECT @lNextNumberPosting = ISNULL(MAX(Id),0) + 1 FROM sFee.tChargeAccountPosting
		INSERT INTO sFee.tChargeAccountPosting
		(
			Id,
			AccountYearId,
			AccountId,
			TransactionDate,
			VoucherTypeId,
			CreditLedger,
			DebitLedger,
			ReceiptBookId,
			SourceTypeId
		)
		VALUES
		(
			@lNextNumberPosting,
			@1AccountYearId,
			@1AccountId,
			@rTransactionDate,
			@rVoucherTypeId,
			@rCreditLedgerId,
			@rDebitLedgerId,
			@rReceiptBookId,
			@rSourceTypeId
		)
    END
	
	SELECT @lNextNumberPosting = Id FROM sFee.tChargeAccountPosting WHERE AccountYearId=@1AccountYearId AND AccountId=@1AccountId 
    AND TransactionDate=@rTransactionDate AND VoucherTypeId=@rVoucherTypeId AND CreditLedger=@rCreditLedgerId
    AND DebitLedger = @rDebitLedgerId AND ReceiptBookId=@rReceiptBookId AND SourceTypeId=@rSourceTypeId
  
 
	IF EXISTS (SELECT 1 FROM [sAccounting].[tTransaction] WHERE SOURCEID=@lNextNumberPosting and Narration like '%Charge Receipt%')
	BEGIN
		delete from [sAccounting].[tTransactionDetail] Where TransactionId in (Select Id From sAccounting.tTransaction Where SourceId =@lNextNumberPosting AND SourceTypeId=2 )
		Select Id as result From sAccounting.tTransaction Where SourceId =@lNextNumberPosting AND SourceTypeId=2
		COMMIT TRANSACTION				
		RETURN 
		--SELECT 101 AS Result
		--COMMIT TRANSACTION				
		--RETURN 
	END
    
    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sAccounting.tTransaction', 0, 1, 1,@outNextNumber = @lNextNumber output		
	INSERT INTO [sAccounting].[tTransaction]
			   (
			    [Id],
			    [OrgGroupId],
			    [AccountingYearId],
			    [TransactionDate],
			    [Narration],
			    [VoucherNumber],
			    [VoucherTypeId],
			    [IsProfitAndLoss],
			    [RepeatLedger],
			    [CreatedUserId],
			    [CreatedDateTime],
			    [AccountId],
			    [SourceTypeId],
			    [SourceId],
			    [ChequeNo],
			    [BankName],
			    [ChequeDate],
			    [ChequeClearDate],
			    [PayTypeId]
			   )
		 VALUES
			   (
				@lNextNumber,
			    @rOrgGroupId,
			    @1AccountYearId,
			    @rTransactionDate,
			    @rNarration,
			    @lVoucherNumber,
			    @rVoucherTypeId,
			    @rIsProfitAndLoss,
			    @rRepeatLedger,
			    @rCreatedUserId,
			    sCommon.fGetDate(),
			    @1AccountId,
			    2,
			    @lNextNumberPosting,
			    @rChequeNo,
			    @rBankName,
			    @rChequeDate,
			    '',
			    @rPayTypeId
			   )
		    SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [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,
		   @rSourceTypeId int
           
	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	,R.SourceTypeId,	
					--ISNULL(CASE WHEN R.SourceTypeId = 2001 Then 'Student' END,0) AS SourceName,
					--ISNULL(CASE WHEN R.SourceTypeId = 95 Then 'Employee' END,0) AS SourceName,
					CASE WHEN R.SourceTypeId = 2001 Then 'Student' WHEN R.SourceTypeId = 3 then 'Other'
					ELSE 'Employee' END AS Name
					 		
			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					
					LEFT JOIN sStudent.tAcademic A On A.Id=R.SourceId  AND (R.SourceTypeId = 2001  OR @rSourceTypeId=0)
					LEFT JOIN sHrm.tEmployeeMaster EM On EM.Id=R.SourceId AND (R.SourceTypeId = 95  OR @rSourceTypeId=0)
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.BatchId  
				WHERE 	(R.SourceTypeId =@rSourceTypeId OR @rSourceTypeId=0) 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.SourceTypeId
	 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	,R.SourceTypeId,
			CASE WHEN R.SourceTypeId = 2001 Then 'Student' WHEN R.SourceTypeId = 3 then 'Other'
					ELSE 'Employee' END AS Name			
		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
             LEFT JOIN sStudent.tAcademic A On A.Id=R.SourceId AND (R.SourceTypeId = 2001  OR @rSourceTypeId=0)
             LEFT JOIN sHrm.tEmployeeMaster EM On EM.Id=R.SourceId AND (R.SourceTypeId = 95  OR @rSourceTypeId=0)
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.BatchId  
		WHERE (R.SourceTypeId =@rSourceTypeId OR @rSourceTypeId=0) AND
			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,R.SourceTypeId
			
		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,
			R.SourceTypeId,
			CASE WHEN R.SourceTypeId = 2001 Then 'Student' WHEN R.SourceTypeId = 3 then 'Other'
					ELSE 'Employee' END AS Name
				
						
		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
            LEFT JOIN sStudent.tAcademic A On A.Id=R.SourceId AND (R.SourceTypeId = 2001  OR @rSourceTypeId=0)
			LEFT JOIN sHrm.tEmployeeMaster EM On EM.Id=R.SourceId AND (R.SourceTypeId = 95  OR @rSourceTypeId=0)
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.BatchId  
		WHERE (R.SourceTypeId =@rSourceTypeId OR @rSourceTypeId=0) AND 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,R.SourceTypeId 
		END
END
GO
PRINT N'Altering [sFee].[pFeeAllocationGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeAllocationGet]
	 
		
		@rSourceId bigint ,
		@rSourceTypeId int,
		@rBatchId int,
		@rStudentId bigint =0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 	
	if (@rStudentId <> 0)
	SELECT @rSourceId = Id, @rSourceTypeId = 2001 FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId
		DECLARE @lClassId int
		DECLARE @lAdmissionCategoryId int
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId

SELECT 
			FM.Title AS FeeName,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			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.NotApplicableAmount,0.00) AS NotApplicableAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FM.OrderIndex,
			0 AS ReceiptNumber,
			'1900-01-01'AS ReceiptDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			FS.CollectionGroupId,
			FM.FeeHeadId,
			FS.FeeDuration
			
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				ISNULL(FS1.FeeDuration,'')  AS FeeDuration
			FROM sFee.tFeeSetup FS1
			   
				WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = @rBatchId
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,
				ISNULL(FS1.FeeDuration,'') AS FeeDuration
				 
			FROM sFee.tFeeSetup FS1
			 
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND(FO.SourceTypeId=@rSourceTypeId)
			WHERE
			 FS1.BatchId = @rBatchId
			AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
		) FS ON FS.FeeId=FM.Id
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)
		LEFT JOIN
		(
		    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
		    FROM
		    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
			WHERE						
			 R.SourceId= @rSourceId
			AND ((R.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))
			AND R.IsObsolete = 0 
			AND R.BatchId = @rBatchId
			 GROUP BY FeeSetupId
		) R ON R.FeeSetupId = FS.Id	
WHERE 
	FS.BatchId=@rBatchId
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC

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


GO
ALTER 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) = '',
		@rUptoDate date=''
		
	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
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			
			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'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,
		CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		--R.ChequeNo,
		R.BankName,
		R.ReceiptBookId,
		RBM.Title AS ReceiptBook,
		R.IsObsolete,
		A.OrgId,
		OM.DisplayTitle AS Organization,
		R.BatchId,
		BM.Title AS Batch,
		R.Remark,
		ISNULL(R.IsChequeCleared,0) AS IsChequeCleared,
		ISNULL(R.ChequeClearDate,'') AS ChequeClearDate,
		ISNULL(R.ChequeDate,'') AS ChequeDate,
		ISNULL(R.CollectionGroupId,0) AS CollectionGroupId,
		Cm.title,
		CM.Id,
		ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
		CM.Title +' - '+ DM.Title AS Class,
		A.SUId,
		ISNULL(R.AmountAfterDiscount,0)AS AmountAfterDiscount,
		ISNULL(R.CGSTPercentage,0)AS CGSTPercentage,
		ISNULL(R.SGSTPercentage,0)AS SGSTPercentage,
		ISNULL(R.CGSTAmount,0)AS CGSTAmount,
		ISNULL(R.SGSTAmount,0)AS SGSTAmount,
		ISNULL(R.DepositedLedgerId,0) AS DepositedLedgerId
  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].[pFeeSetupAdd]...';


GO
ALTER PROCEDURE [sFee].[pFeeSetupAdd]
	 
		   @rId int,
           @rClassId int,
           @rAdmissionCategoryId int,
           @rBatchId int,
           @rFeeId int,
           @rIsOptional bit,
           @rIsVariable bit,
           @rAmount decimal(12,2),
           @rStartDate date,
           @rEndDate date,
           @rReceiptBookId int,
           @rCreatedUserId bigint,
		   @rUpdatedUserId bigint,
		   @rOrgId int,
		   @rCheck bit,
		   @rIsServiceTax bit,
		   @rCollectionGroupId int = 0,
		   @rOrgGroupId int=0,
		   @rFeeDuration nvarchar(100) =''
		   

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lFeeSetupId int=0
	
	 IF(@rCheck=1 AND @rId>0)
	 BEGIN
	 
	 IF(@rIsOptional = 1 AND @rIsVariable = 1)
	 BEGIN
		  SELECT 0 as Result
		  RETURN
	 END
	 ELSE
	 BEGIN
			IF EXists( SELECT * FROM (
			SELECT AcademicId,	   
					(SELECT ISNULL(SUM(RD.Amount),0)  
					FROM sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD
					ON	RD.ReceiptId = R.Id
					AND RD.FeeSetupId = @rId
					WHERE R.SourceId = VA.AcademicId AND R.IsObsolete = 0) PaidAmount,		      
					(SELECT ISNULL(VariableAmount,0)-ISNULL(DiscountAmount,0) +
					IsNULL(AdditionalAmount,0) - ISNULL(NotApplicableAmount,0)  
					FROM  sFee.tFeeAllocation A		  
					WHERE A.SourceId = VA.AcademicId AND A.FeeSetupId = @rId  ) AllocationAmount
					--,
					--(SELECT Amount FROM sFee.tFeeSetup S WHERE S.Id = @rId 
					----S.ClassId = VA.AcademicId
					----AND S.AdmissionCategoryId = VA.AdmissionCategoryId
					--) AS FeeSetupAmount	   
			FROM sStudent.vStudentAcademic VA	   
			WHERE ClassId = @rClassId AND AdmissionCategoryId = @rAdmissionCategoryId AND VA.BatchId = @rBatchId
			   ) ST WHERE (@rAmount + ISNULL(ST.AllocationAmount,0) - ISNULL(ST.PaidAmount,0) < 0))
			   
			   select @rId as Result
			   ELSE
			   SELECT 0 as Result
			   RETURN
	 END
	 
		   
		   
		  --WHERE ST.Amount + AllocationAmount - PaidAmount > 0
		  
	 
	 
		    
		  
	 
		      
	 -- SELECT @lFeeSetupId=R.FeeSetupId FROM
	 -- sFee.tFeeSetup FS
		--LEFT JOIN
		--(
		--    SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		--    RD.FeeSetupId,FA.VariableAmount,FA.AdditionalAmount,FA.DiscountAmount,FA.NotApplicableAmount 
		--    FROM
		--    sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id
		--     LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=RD.FeeSetupId AND FA.SourceId=R.SourceId 
		--     AND FA.SourceTypeId=R.SourceTypeId	
		--	WHERE						
		--	 R.IsObsolete = 0 
		--	 GROUP BY RD.FeeSetupId,R.SourceId,R.SourceTypeId,FA.VariableAmount,FA.AdditionalAmount,
		--	 FA.DiscountAmount,FA.NotApplicableAmount
		
		--) R ON R.FeeSetupId = FS.Id 
		--where ISNULL(R.FeeSetupId,0)=@rId 
		--AND (@rAmount +  ISNULL(R.VariableAmount,0) + ISNULL(R.AdditionalAmount,0.00) -  ISNULL(R.DiscountAmount,0)-ISNULL(R.NotApplicableAmount,0) -ISNULL(R.PaidAmount,0))<0
		--BEGIN
		--	select @lFeeSetupId as Result
		--	RETURN
		--END
		
	END
	 
 IF(@rId = 0)	
BEGIN

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

	INSERT INTO sFee.tFeeSetup
		(
		   Id,
           ClassId,
           AdmissionCategoryId,
           BatchId,
           FeeId,
           IsOptional,
           IsVariable,
           Amount,
           StartDate,
           EndDate,
           ReceiptBookId,
           CreatedUserId,
           CreatedDateTime,
           IsServiceTax,
           CollectionGroupId,
           FeeDuration
        )
	VALUES
		(
			@lNextNumber,
			@rClassId,
			@rAdmissionCategoryId,
            @rBatchId,
            @rFeeId,
            @rIsOptional,
            @rIsVariable,
            @rAmount,
            @rStartDate,
            @rEndDate,
            @rReceiptBookId,
            @rCreatedUserId,
			sCommon.fGetDate(),
			@rIsServiceTax,
			@rCollectionGroupId,
			@rFeeDuration
		)
		SELECT 1 AS Result
		             
	END	 
	 ELSE
	 BEGIN
	 
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tFeeSetup
	    SET
			 --ClassId=@rClassId,
			 --AdmissionCategoryId=@rAdmissionCategoryId,
    --         BatchId=@rBatchId,
             IsOptional=@rIsOptional,
             IsVariable=@rIsVariable,
             Amount=@rAmount,
             StartDate=@rStartDate,
             EndDate=@rEndDate,
             ReceiptBookId=@rReceiptBookId,
             UpdatedUserId=@rUpdatedUserId,
			 UpdatedDateTime=sCommon.fGetDate(),
			 IsServiceTax=@rIsServiceTax,
			 CollectionGroupId=@rCollectionGroupId,
			 FeeDuration=@rFeeDuration
	      WHERE (Id = @rId)
	       --AND (FeeId=@rFeeId) 
	      SELECT 11 AS Result   
	 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
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sFee].[pFeeSetupFeeWiseGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeSetupFeeWiseGet]
				
		   
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rFeeId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
		ISNULL(FS.Id,0)AS Id,
		ISNULL(CM.Id,0)AS ClassId,
		ISNULL(CM.Title,'') AS ClassName,
		ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
		ISNULL(FS.BatchId,0)AS BatchId,
		ISNULL(FS.IsOptional,0)AS IsOptional,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'0001-01-01 00:00:00.00')AS StartDate,
		ISNULL(FS.EndDate,'0001-01-01 00:00:00.00')AS EndDate,
		ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
		CASE WHEN (SELECT COUNT(*) FROM sFee.tReceiptDetail WHERE FeeSetupId=FS.Id) <= 0 THEN 'True' ELSE 'False' END AS IsReceiptBookChange,
		ISNULL(FS.IsServiceTax,0)AS IsServiceTax,
		ISNULL(FS.CollectionGroupId,0) AS CollectionGroupId,
		ISNULL(FS.FeeDuration,'')  AS FeeDuration
  FROM 
		sSetup.tClassMaster CM
		INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id AND BC.BatchId = @rBatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		LEFT JOIN sFee.tFeeSetup FS ON CM.Id=FS.ClassId 
		AND (FS.FeeId=@rFeeId OR @rFeeId= 0) 
		AND (FS.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId= 0) 
		AND (FS.BatchId=@rBatchId)
		LEFT JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
WHERE 
		OM.OrgGroupId=@rOrgGroupId
		ORDER BY FS.StartDate,CM.OrderIndex
END
GO
PRINT N'Altering [sFee].[pFeeSetupGet]...';


GO
 
ALTER PROCEDURE [sFee].[pFeeSetupGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		   @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(FS.Id,0)AS Id,
			ISNULL(CM.Id,0)AS ClassId,
			ISNULL(CM.Title,'') AS ClassName,
			ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
			FM.Title AS FeeTitle,
			ISNULL(FS.BatchId,0)AS BatchId,
			ISNULL(FM.Id,0)AS FeeId,
			ISNULL(FS.IsOptional,0)AS IsOptional,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'0001-01-01 00:00:00.00')AS StartDate,
			ISNULL(FS.EndDate,'0001-01-01 00:00:00.00')AS EndDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(FHM.Id,0) AS FeeHeadId,
			ISNULL(FHM.Title,'') AS FeeHeadName,
			CASE WHEN (SELECT COUNT(*) FROM sFee.tReceiptDetail WHERE FeeSetupId=FS.Id) <= 0 THEN 'True' ELSE 'False' END AS IsReceiptBookChange,
			ISNULL(FS.IsServiceTax,0)AS IsServiceTax,
			ISNULL(FS.CollectionGroupId,0) AS CollectionGroupId,
			ISNULL(FS.FeeDuration,'')  AS FeeDuration
  FROM 
			sFee.tFeeMaster FM
		LEFT JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId 
		AND (FS.ClassId=@rClassId OR @rClassId= 0) 
		AND (FS.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId= 0) 
		AND (FS.BatchId=@rBatchId)
		LEFT JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId
		LEFT JOIN sSetup.tClassMaster CM ON CM.Id=FS.ClassId
WHERE 
		FM.OrgGroupId=@rOrgGroupId
		ORDER BY FS.StartDate,FHM.OrderIndex,FM.OrderIndex
END
GO
PRINT N'Altering [sFee].[pRptFeePendingWithFeeNameGet]...';


GO


ALTER PROCEDURE [sFee].[pRptFeePendingWithFeeNameGet]
		@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 	


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

 
	--CREATE TYPE  TempPendingFee AS TABLE
	--(
	--AcademicId bigint
	--,
	--RollNo int,
	--Name nvarchar(200),
	--Code nvarchar(20),
	--ClassId int,
	--DivisionId int,
	--ClassName nvarchar(100),
	--DivisionName nvarchar(100),
	--ClassDivision nvarchar(100),
	--FeeSetupId int,
	--IsVariable int,
	--Amount Decimal(12,2),
	--StartDate date,
	--EndDate date,
	--FAAmount Decimal(12,2),
	--DiscountAmount Decimal(12,2),
	--AdditionalAmount Decimal(12,2),
	--PaidAmount Decimal(12,2),
	--PendingAmount Decimal(12,2),
	--Remark nvarchar(200),
	--ReceiptBookId int,
	--FeeName nvarchar(100),
	--FeeCode nvarchar(100),
	--OrgId int,
	--OrgName nvarchar(200),
	--OrgOrderIndex int,
	--ReceiptBookTitle nvarchar(200),
	--ReceiptOrderIndex int	
	--)
	
	DECLARE @p as TempPendingFee
	
	INSERT INTO  @p 
	 
	SELECT 
		--@rBuilder1 AS Builder1,
		--@rBuilder2 AS Builder2,
		--@rIsDetail AS IsDetail,
		--@rIsFilter As IsFilter,
		--@rIsHeader As IsHeader,
		SA.AcademicId
		,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		0 AS BatchId,
		'' AS BatchName,
		'',
		'',
		''	
  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)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (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.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)
				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='')
		) 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)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @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 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

			SELECT
			@rBuilder1 as Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookId
			 END) AS ReceiptBookId,	
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookTitle
			 END) AS ReceiptBookTitle,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptOrderIndex
			 END) AS ReceiptOrderIndex,	 
			
			OrgId,			 
			--ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,RollNo, Name,Code,
			--ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName
			--ReceiptOrderIndex
			FROM @p 
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,
			ClassDivision,RollNo, Name,Code,
			ReceiptBookTitle,OrgName,ReceiptOrderIndex	
			ORDER BY AcademicId
 
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 = @rOrgGroupId
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @rReceiptId

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

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,
			--SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) END AS ChequeNo,
			--ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,			
			
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN @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 ,
	        SF.FatherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark
	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 AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM 
				ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U
				ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM
				ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM
				ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM
				ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId
			LEFT JOIN sFee.tCollectionGroupMaster CGM
				ON CGM.Id=FR.CollectionGroupId
			LEFT JOIN sFee.tFeeInvoice FI
				ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
	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 [sHrm].[pEmployeeStatutoryDetailAdd]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeStatutoryDetailAdd]

	       @rEmployeeId bigint,
	       @rAccountNumber nvarchar(20),
	       @rBankName nvarchar(200),
           @rBranch nvarchar(50),          
           @rEPFNumber nvarchar(20),
           @rPanNumber nvarchar(20),
           @rIsVPFDeduction bit,
           @rVPFContributionId tinyint,
           @rVPFContributionEffectiveFrom date,
           @rVPFPercentage decimal(5,2),
           @rVPFAmount decimal(22,6),
           @rESINumber nvarchar(20),        
           @rIFSCNumber nvarchar(50),           
           @rIncomeTaxStatusId int,
           @rUpdatedUserId bigint,            
           @rIncrementDate date,
           @rBasicPay decimal(12,2),
           @rPayrollId int,
           @rPayrollGroupId int,
           @rPayscale nvarchar(150)='',
           @rEPFJoinDate date = NULL,
           @rUAN nvarchar(20)=''	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY
BEGIN TRANSACTION
	DECLARE @lNextNumber BIGINT 
 	  
IF NOT EXISTS(Select 1 From sHrm.tEmployeeStatutoryAndOther Where EmployeeId = @rEmployeeId)
   BEGIN
	INSERT INTO sHrm.tEmployeeStatutoryAndOther
           (
            [EmployeeId]
           ,[EPFNumber]
           ,[IsVPFDeduction]
           ,[VPFContributionId]
           ,[VPFContributionEffectiveFrom]
           ,[VPFPercentage]
           ,[VPFAmount]
           ,[ESINumber]
           ,[BankName]
           ,[Branch]
           ,[AccountNumber]
           ,[IFSCNumber]
           ,[PanNumber]
           ,[IncomeTaxStatusId]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[IncrementDate]
           ,[BasicPay]
           ,[PayrollId]
           ,[PayrollGroupId]
           ,[Payscale]
           ,[EPFJoinDate]
           ,[UAN]
           )
     VALUES
           (
           @rEmployeeId,
           @rEPFNumber,
           @rIsVPFDeduction,
           @rVPFContributionId,
           @rVPFContributionEffectiveFrom,
           @rVPFPercentage,
           @rVPFAmount,
           @rESINumber,
           @rBankName,
           @rBranch,
           @rAccountNumber,
           @rIFSCNumber,
           @rPanNumber,
           @rIncomeTaxStatusId,
           @rUpdatedUserId,
           sCommon.fGetDate(),
           @rIncrementDate,
           @rBasicPay,
           @rPayrollId,
           @rPayrollGroupId,
           @rPayscale,
           @rEPFJoinDate,
           @rUAN
           )
     END
     ELSE
     BEGIN
      UPDATE sHrm.tEmployeeStatutoryAndOther
      SET 
		  [EPFNumber] = @rEPFNumber,
		  [IsVPFDeduction] = @rIsVPFDeduction, 
		  [VPFContributionId] = @rVPFContributionId, 
		  [VPFContributionEffectiveFrom] = @rVPFContributionEffectiveFrom, 
		  [VPFPercentage] = @rVPFPercentage, 
		  [VPFAmount] = @rVPFAmount, 
		  [ESINumber] = @rESINumber, 
		  [BankName] = @rBankName, 
		  [Branch] = @rBranch, 
		  [AccountNumber] = @rAccountNumber, 
		  [IFSCNumber] = @rIFSCNumber, 
		  [PanNumber] = @rPanNumber, 
		  [IncomeTaxStatusId] = @rIncomeTaxStatusId, 
		  [UpdatedUserId] = @rUpdatedUserId, 
		  [UpdatedDateTime] = sCommon.fGetDate(), 
		  [IncrementDate] = @rIncrementDate, 
		  [BasicPay] = @rBasicPay,
		  [PayrollId]=@rPayrollId,
          [PayrollGroupId]=@rPayrollGroupId,
          [Payscale]=@rPayscale,
          [EPFJoinDate]=@rEPFJoinDate,
          [UAN]=@rUAN
	  WHERE 
			EmployeeId = @rEmployeeId
     END    
     
	SELECT 1 AS RESULT
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1 AS RESULT
	END CATCH				
END
GO
PRINT N'Altering [sHrm].[pEmployeeStatutoryDetailGet]...';


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

BEGIN
	 SELECT 
		    [EmployeeId]
		  , [EPFNumber]
		  , [IsVPFDeduction]
		  ,ISNULL([VPFContributionId],0) AS VPFContributionId
		  ,ISNULL([VPFContributionEffectiveFrom],'1/1/0001')  AS VPFContributionEffectiveFrom
		  ,ISNULL([VPFPercentage],0) AS VPFPercentage
		  ,ISNULL([VPFAmount],0) AS VPFAmount
		  ,[ESINumber]
		  ,[BankName]
		  ,[Branch]
		  ,[AccountNumber]
		  ,[IFSCNumber]
		  ,[PanNumber]
		  ,ISNULL([IncomeTaxStatusId],0) AS IncomeTaxStatusId       
		  ,ISNULL([IncrementDate],'1/1/0001') AS IncrementDate
		  ,ISNULL([BasicPay],0) AS BasicPay
		  ,ISNULL([PayrollId],0) AS PayrollId
		  ,ISNULL([PayrollGroupId],0) AS PayrollGroupId 
		  ,ISNULL([Payscale],'') AS Payscale
		  ,ISNULL([EPFJoinDate],'1/1/0001') AS EPFJoinDate
		  ,ISNULL(UAN,'') AS UAN
	FROM 
			[sHrm].[tEmployeeStatutoryAndOther] 
			 
	Where 
			 EmployeeId = @rEmployeeId	  
END
GO
PRINT N'Altering [sHrm].[pGetCheckBoxLists]...';


GO
-- exec [sHrm].[pGetCheckBoxLists]
-- drop proc [sHrm].[pGetCheckBoxLists]
ALTER proc [sHrm].[pGetCheckBoxLists]
@rFlag int,
@rOrgId int,
@rOrgGroupId int
as
begin
	declare @lResult varchar(max)=''
	if @rFlag = 1
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tStatusMaster where StatusTypeId = 4
	end
	else if @rFlag = 2
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tReligionMaster where IsObsolete = 0 AND OrgGroupId = @rOrgGroupId
	end
	else if @rFlag = 3
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tMaritalStatusMaster where IsObsolete = 0
	end
	else if @rFlag = 4
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tGenderMaster where IsObsolete = 0
	end
	else if @rFlag = 5
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sHrm.tEmployeeDesignationMaster where IsObsolete = 0 AND OrgId = @rOrgId
	end
	else if @rFlag = 6
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sHrm.tEmployeeTypeMaster where IsObsolete = 0 AND OrgId = @rOrgId
	end
	else if @rFlag = 7
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sHrm.tEmployeeGroupMaster WHERE IsObsolete = 0
	end
	else if @rFlag = 8
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sCommon.tBloodGroupMaster where IsObsolete = 0
	end
	else if @rFlag = 9
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sSetup.tDepartmentMaster where IsObsolete = 0 AND OrgId = @rOrgId
	end
	
	else if @rFlag = 10
	begin
		select @lResult = @lResult + '&nbsp;&nbsp;<input type="checkbox" attrid="' + convert(varchar,Id) + '" />&nbsp;' + Title + '<br />'
		from sHrm.tEmployeeGradeMaster where IsObsolete = 0 AND OrgId = @rOrgId
	end
	
	select @lResult as Result
end
GO
PRINT N'Altering [sHrm].[pLeaveAdd]...';


GO
 
ALTER PROCEDURE [sHrm].[pLeaveAdd]
           
        @rId bigint,
        @rEmployeeId bigint,
        @rReportDate date,
        @rFromDate date,
        @rToDate date,
        @rLeavePeriodId tinyint,
        @rLeaveTypeId int,
        @rLeaveReson nvarchar(200),
        @rNoOfLeave decimal(5,2),
        @rBatchId int,
        @rOrgId int,
        @rCreatedUserId bigint,
        @rStatusId int,
        @rFromTime datetime,
		@rToTime datetime
AS
SET NOCOUNT ON

BEGIN

IF EXISTS (SELECT 1 FROM  sHrm.tLeaveTypeMaster WHERE Id = @rLeaveTypeId AND isLwp = 0)
BEGIN
   DECLARE @lMainLeaveTypeId tinyint
   SET @lMainLeaveTypeId =0
   SELECT @lMainLeaveTypeId = ISNULL(MainLeaveTypeId,0) FROM sHrm.tLeaveTypeMaster WHERE Id = @rLeaveTypeId
   
   DECLARE @lMaxInMonth decimal(5,2)
   DECLARE @lNumberOfLeave decimal(5,2)
   SET @lMaxInMonth =0
   SET @lNumberOfLeave =0
   
   DECLARE @lFirstDate date
   DECLARE @lLastDate date
   
   SET @lFirstDate = DATEADD(mm, DATEDIFF(mm, 0, @rFromDate), 0)
   SET @lLastDate = DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, @rFromDate) + 1, 0))
   
   SELECT @lMaxInMonth = ISNULL(LB.MaxInMonth,0) FROM sHrm.tEmployeeJobDetail EJD 
   INNER JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EJD.EmployeeId AND LB.BatchId = @rBatchId
   WHERE EJD.OrgId = @rOrgId AND LB.LeaveTypeId=@rLeaveTypeId AND EJD.EmployeeId=@rEmployeeId
   
   -- For Employee Specific 08/11/2017 - by Ramesh Gurjar
   IF(@lMaxInMonth=0)
   BEGIN
		SELECT @lMaxInMonth = ISNULL(LTGS.MaxInMonth,0) FROM sHrm.tEmployeeJobDetail EJD 
		INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON EJD.EmployeeGradeId=LTGS.EmployeeGradeId 
		WHERE LTGS.OrgId = @rOrgId 
		AND LTGS.LeaveTypeId=@rLeaveTypeId 
		AND  EJD.EmployeeId=@rEmployeeId
   END
   -- End
   
   SELECT  @lNumberOfLeave= ISNULL(SUM(L.NoOfLeave),0) 
   FROM     
   sHrm.tLeave L  
   WHERE  
   L.EmployeeId=@rEmployeeId 
   AND (L.FromDate>=@lFirstDate) AND (L.FromDate<=@lLastDate)
   AND L.LeaveTypeId=@rLeaveTypeId AND L.StatusId = 550
   GROUP BY L.EmployeeId
   
   IF (@lMaxInMonth < (@lNumberOfLeave+@rNoOfLeave) AND @lMainLeaveTypeId!=3)
   BEGIN
		SELECT -105  AS RESULT
		RETURN
   END
   END
     
   DECLARE @1Leave int
    
	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @lNextNumber bigint
	 
    IF (@rId = 0)
     BEGIN
       
       IF(@rLeavePeriodId = 2) --For Half Leave	  	
       SELECT @1Leave = SUM(NoOfLeave) from sHrm.tLeave where EmployeeId = @rEmployeeId AND OrgId = @rOrgId AND FromDate = @rFromDate 
       ELSE
         SET @1Leave = 1
     		
	   IF NOT EXISTS(SELECT 1 FROM sHrm.tLeave WHERE EmployeeId = @rEmployeeId 
	   AND(( FromDate  BETWEEN @rFromDate AND @rToDate) OR (ToDate BETWEEN @rFromDate AND @rToDate)
	   OR (@rFromDate  BETWEEN FromDate AND ToDate) OR (@rToDate BETWEEN FromDate AND ToDate)) AND OrgId = @rOrgId AND BatchId = @rBatchId AND StatusId!=551) OR @1Leave != 1
	   BEGIN
	    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tLeave', 0, 1, 1,@outNextNumber = @lNextNumber output	
	    
		  INSERT INTO [sHrm].[tLeave]
           (
            [Id]
           ,[EmployeeId]
           ,[ReportDate]
           ,[FromDate]
           ,[ToDate]
           ,[LeavePeriodId]
           ,[LeaveTypeId]
           ,[LeaveReason]
           ,NoOfLeave
           ,BatchId
           ,[OrgId]           
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[StatusId]
           ,[FromTime]
           ,[ToTime]
           )
     VALUES
           (
            @lNextNumber
           ,@rEmployeeId 
           ,@rReportDate 
           ,@rFromDate 
           ,@rToDate 
           ,@rLeavePeriodId 
           ,@rLeaveTypeId 
           ,@rLeaveReson 
           ,@rNoOfLeave
           ,@rBatchId
           ,@rOrgId 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rStatusId       
           ,@rFromTime
           ,@rToTime      
           )
            END
          ELSE
            SET @lNextNumber = -101            
          END
	ELSE
	BEGIN
	SET @lNextNumber = @rId
		UPDATE sHrm.tLeave
		SET 	 
		   [EmployeeId]= @rEmployeeId 
		  ,[ReportDate]= @rReportDate 
		  ,[FromDate]= @rFromDate 
		  ,[ToDate]= @rToDate 
		  ,[LeavePeriodId]= @rLeavePeriodId 
		  ,[LeaveTypeId]= @rLeaveTypeId 
		  ,[LeaveReason]= @rLeaveReson 
		  ,NoOfLeave = @rNoOfLeave
		  ,[OrgId]= @rOrgId        
		  ,[UpdatedUserId]= @rCreatedUserId
		  ,[UpdatedDateTime]= sCommon.fGetDate()
		  ,[FromTime] = @rFromTime
          ,[ToTime] = @rToTime    
		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 [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 
		Declare @ldate datetime,@lDays int
		declare @Days int
		Set @ldate= CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
       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].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,1 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P1,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,2 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P2,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,3 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P3,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,4 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P4,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,5 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P5,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,6 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P6,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,7 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P7,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,8 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P8,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,9 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P9,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,10 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P10,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,11 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P11,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,12 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P12,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,13 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P13,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,14 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P14,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,15 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P15,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,16 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P16,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,17 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P17,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,18 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P18,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,19 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P19,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,20 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P20,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,21 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P21,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,22 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P22,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,23 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P23,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,24 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P24,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,25 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P25,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,26 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P26,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,27 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P27,
		   	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,28 ,@rBatchId ,EM.DepartmentId ,@rOrgId )  AS P28 ,
		 case when @Days >= 29 then [sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,29 ,@rBatchId ,EM.DepartmentId ,@rOrgId ) end  AS P29,
		 case when @Days >= 30 then	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,30 ,@rBatchId ,EM.DepartmentId ,@rOrgId ) end  AS P30,
		 case when @Days >= 31 then	[sHrm].[fWeekHOffGet](EM.EmployeeId,@rForYear ,@rForMonth ,31 ,@rBatchId ,EM.DepartmentId ,@rOrgId ) end  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].[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,
		@rFromDate date,
	    @rToDate date
	
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) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) 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) 
				AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    	        AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
	   	    ) 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) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) 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) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) 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) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) 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)
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')='')) 
		   	) 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
			LEFT JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.OrgId=EM.OrgID 
			LEFT JOIN sHrm.tWorkingDays WD ON WD.EmployeeGradeId = EGM.Id
			
			
    	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 [siTax].[pForm16IncomeTaxSlabDetailGet]...';


GO
/******************************
** Name:  [siTax].[pForm16IncomeTaxSlabDetailGet]   
** Desc:  Calcalation Of Tax TaxAmount
** Auth:  Savan Vaghela
** Date:  04-Febuary-2017
** Page:  
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    06-Febuary-2017      Savan Vaghela  Create First Time
** 2    06-Febuary-2017      Savan Vaghela  configure tax exemption 
************************************************************/
--EXEC [siTax].[pForm16IncomeTaxSlabDetailGet]  1001000000154,1001000000013,1001,175000
ALTER PROCEDURE [siTax].[pForm16IncomeTaxSlabDetailGet]   
@rEmployeeId bigint,
@rAssesmentYearId bigint,
@rOrgGroupId int,
@rGrossAmount DECIMAL(18,2),
@rTaxDeducatedatsourceus192 DECIMAL(18,2)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	DECLARE @GenderId INT
	DECLARE @DateOfBirth DATE
	DECLARE @Age INT
	DECLARE @TaxPercentage DECIMAL(18,2) 
	DECLARE @TaxExeption DECIMAL(18,2)
	DECLARE @AmountFROM DECIMAL(18,2) 
	DECLARE @AmountTo DECIMAL(18,2)
	DECLARE @Count INT =0
	DECLARE @Counter INT =0
	DECLARE @TaxAmount DECIMAL(18,2)=0
	DECLARE @EducationCess DECIMAL(18,2)=0
	DECLARE @TaxPayable DECIMAL(18,2)=0
	DECLARE @ReliefUnderSection89 DECIMAL(18,2)=0
	DECLARE @TaxPayable2 DECIMAL(18,2)=0
	DECLARE @TaxSeductedAtSource192 DECIMAL(18,2)=0
	DECLARE @Balance DECIMAL(18,2)=0
	DECLARE @TaxCalculation DECIMAL(18,2)=0


	SELECT @GenderId=ISNULL(GenderId,0),@DateOfBirth=ISNULL(DateOfBirth, DATEADD(year,-30,sCommon.fGetDate())) 
	FROM [sHrm].[tEmployeePersonalDetail] 
	WHERE Employeeid=@rEmployeeId

	SET @Age= DATEDIFF(yy, @DateOfBirth, sCommon.fGetDate())
	SELECT @GenderId=ISNULL(GenderId,0),@DateOfBirth=ISNULL(DateOfBirth,sCommon.fGetDate()) 
	FROM [sHrm].[tEmployeePersonalDetail] 
	WHERE Employeeid=@rEmployeeId
	
	SET @Age= DATEDIFF(yy, @DateOfBirth, sCommon.fGetDate())
		
	
	
	DECLARE @TableIncomeTaxSlab    TABLE(RowID int Identity(1,1),AmountFROM DECIMAL(18,2),AmountTo DECIMAL(18,2),TaxPercentage DECIMAL(18,2),TaxExeption DECIMAL(18,2))
	
	INSERT INTO @TableIncomeTaxSlab
	
	SELECT AmountFROM,AmountTo,TaxPercentage,TaxExeption 
	FROM  [siTax].[tIncomeTaxSlab]  
	WHERE OrgGroupId=@rOrgGroupId AND (AssessmentYearId=@rAssesmentYearId) AND (GenderId=@GenderId) AND IsObsolete=0 AND TaxPercentage<>0.00
	ORDER BY AmountFROM

	SELECT @Count=COUNT(1) 
	FROM @TableIncomeTaxSlab 
	WHERE   @rGrossAmount>AmountFROM  

	

	SELECT @TaxCalculation=MIN(AmountFROM) 
	FROM @TableIncomeTaxSlab
	SET @TaxCalculation=ISNULL(@TaxCalculation,0)
	

	IF (@TaxCalculation<=@rGrossAmount)
		BEGIN
			SELECT @ReliefUnderSection89=SUM(TaxExeption)	FROM  [siTax].[tIncomeTaxSlab]  WHERE OrgGroupId=@rOrgGroupId AND (AssessmentYearId=@rAssesmentYearId) AND (GenderId=@GenderId) AND IsObsolete=0 AND TaxPercentage <>0.00
			DECLARE @MyTaxAmount DECIMAL(18,2)=0
			WHILE(@Count<>0)
				BEGIN
			
					SELECT @AmountFROM=AmountFROM,@AmountTo=AmountTo,@TaxPercentage=TaxPercentage,@TaxExeption =TaxExeption 
					FROM @TableIncomeTaxSlab 
					WHERE RowID=@Count
					
					IF @Counter=0
						BEGIN
							SET @MyTaxAmount=	((@rGrossAmount-@AmountFROM)*@TaxPercentage)/100
							SET @TaxAmount=@TaxAmount+@MyTaxAmount
						END
					ELSE
						BEGIN
							SET @MyTaxAmount=((@AmountTo-@AmountFROM)*@TaxPercentage)/100 
							SET @TaxAmount=@TaxAmount+@MyTaxAmount
						END
	
						SET @Count=@Count-1
						SET @Counter=@Counter+1
				END

			 SELECT 	@ReliefUnderSection89 =SUM(TaxExeption)					FROM @TableIncomeTaxSlab WHERE RowID between 1 and @Counter
			 


			SELECT @TaxSeductedAtSource192=ISNULL(SUM(Amount),0) 
			FROM [siTax].[tIncomeTaxChallan] 
			WHERE 
			IsObsolete=0 
			AND AssesmentYearId=@rAssesmentYearId 
			AND EmployeeId=@rEmployeeId 
			AND OrgGroupId=@rOrgGroupId 
	
			SET @TaxSeductedAtSource192=@TaxSeductedAtSource192+@rTaxDeducatedatsourceus192
 
			SET @EducationCess =(@TaxAmount*3)/100
			SET @TaxPayable=@TaxAmount+@EducationCess
			SET @TaxPayable2 =CASE WHEN @TaxPayable>@ReliefUnderSection89 AND @TaxAmount <= 350000  THEN  @TaxPayable-@ReliefUnderSection89 ELSE 0 END 
			--SET @TaxPayable2 =@TaxPayable
			SET @Balance=@TaxPayable2-@TaxSeductedAtSource192

			print  @TaxPayable2
			print  @TaxSeductedAtSource192
			 
		END

	SELECT @TaxAmount        AS TaxAmount
	,@EducationCess          AS EducationCess3
	,@TaxPayable			 AS TaxPayable
	,ISNULL(@ReliefUnderSection89,0) 	 AS ReliefUnderSection89
	,CASE WHEN @TaxPayable>@ReliefUnderSection89 THEN  @TaxPayable2 ELSE 0 END	 AS TaxPayable2
	,@TaxSeductedAtSource192 AS TaxSeductedAtSource192
	,@Balance                AS Balance
END
GO
PRINT N'Altering [sPayroll].[pCalculateStaticPayElement]...';


GO
ALTER PROCEDURE [sPayroll].[pCalculateStaticPayElement] 
	      
	        @rPayProcessEmployeeId bigint,
	        @rOrgGroupId int,
	        @rSalary DECIMAL(22,6),
	        @rSourceId bigint,
	        @rDeductionAmount DECIMAL(22,6),
	        @rPayrollId int,
	        @rPayrollYearId int
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lIsRoundOffToWholeNumber nvarchar(50)
	DECLARE @lRoundOffToWholeNumber int
	
	SELECT @lIsRoundOffToWholeNumber = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 248 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	IF (@lIsRoundOffToWholeNumber IS NULL) OR (@lIsRoundOffToWholeNumber = 'True')
		SET @lRoundOffToWholeNumber = 0
	ELSE
		SET @lRoundOffToWholeNumber = 2	
	
	BEGIN
	
	DECLARE @lNextNumber BIGINT 
	DECLARE @1Basic DECIMAl(22,6) 
	DECLARE @1PfSalaryLimit DECIMAL(22,6)
	DECLARE @1PayProcesdsElementId bigint
	DECLARE @1ESISalaryLimit DECIMAL(22,6) 
    DECLARE @1Tax DECIMAL(22,6)
    --DECLARE @1EmployeePfAmount Decimal(22,6)
    DECLARE @1EmployeeESIAmount Decimal(22,6)
    DECLARE @1TotalDeductionAmount DECIMAL(22,6)
    
    DECLARE @1EmployeePfPercent DECIMAL(22,2)
    DECLARE @1EmployerPfPercent DECIMAL(22,2)
    DECLARE @1EmployerFpsPercent DECIMAL(22,2)
    DECLARE @1EmployeeESIPercent DECIMAL(22,2)
    DECLARE @1EmployerESIPercent DECIMAL(22,2)
    DECLARE @1EmployeePfAmount DECIMAL(22,2)
    DECLARE @1EmployerPfAmount DECIMAL(22,2)
    DECLARE @1AdminChargesPercent DECIMAL(22,2)
    DECLARE @1EdliPercent DECIMAL(22,3)
    DECLARE @1InspectionChargesPercent DECIMAL(22,3)
    
    
    DECLARE @lEmployerFpsPercent DECIMAL(22,2)
    DECLARE @lValuesforMax DECIMAL(22,2) 
    DECLARE @1Max DECIMAL(22,2)
    DECLARE @lRestrictionEmployerFpsPercent DECIMAL(22,2)
    DECLARE @1Bal DECIMAL(22,2)
    DECLARE @lEmployerPfPercent DECIMAL(22,2)

	SET @1Tax = 0.0
	SET @1EmployeePfAmount = 0.0
	SET @1EmployeeESIAmount = 0.0
	SET @1Basic = 0.0
	SET @1PfSalaryLimit = 0.0
	
	SET @1EmployeePfPercent = 0.0
    SET @1EmployerPfPercent = 0.0
    SET @1EmployerFpsPercent = 0.0
    SET @1AdminChargesPercent = 0.0
    SET @1EdliPercent = 0.0
    SET @1InspectionChargesPercent = 0.0
    
     
    SET @lEmployerFpsPercent = 0.0
    SET @lValuesforMax = 0.0
    SET @1Max = 0.0
    SET @lRestrictionEmployerFpsPercent = 0.0
    SET @1Bal = 0.0
    SET @lEmployerPfPercent = 0.0
       
    SET @1EmployeeESIPercent = 0.0
    SET @1EmployerESIPercent = 0.0
    DECLARE @lPTPayElementId int    
    DECLARE @lPFPayElementId int
    DECLARE @lBasicPayElementId int
    DECLARE @lESIPayElementId int
    DECLARE @1EmployeePfPercentEmpSetup DECIMAL(12,2)
	
	SELECT @lPTPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 57
	SELECT @lPFPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 56
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	SELECT @lESIPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 55
	 --For Professional Tax
	 IF EXISTS (SELECT 1 FROM  sPayroll.tPayProcessElement  
				   Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPTPayElementId)     	    
		BEGIN	
		  --      Select * from sPayroll.tProfessionalTaxRange
		        
		  --      SELECT  TOP 1  Tax  FROM sPayroll.tProfessionalTaxRange 
				--where Salary < @rSalary Order By Salary Desc
		        
				SELECT  TOP 1  @1Tax = Tax  FROM sPayroll.tProfessionalTaxRange 
				where Salary <= @rSalary AND PayrollYearId = @rPayrollYearId Order By Salary Desc
		        -- Professional Tax 
				UPDATE sPayroll.tPayProcessElement  
				SET AMOUNT = @1Tax
				WHERE PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPTPayElementId	 			 
		END	
		--print 'Professional Tax Done'
	
	 --For PfElement
	 
	  IF EXISTS(SELECT 1 FROM  sPayroll.tPayProcessElement Where PayProcessEmployeeId = @rPayProcessEmployeeId AND PayElementId = @lPFPayElementId)
	  BEGIN
	  
	  -- start for age calculation
	  DECLARE @lEmployeeId bigint = 0
	  DECLARE @lPayProcessId int = 0
	  DECLARE @lSalaryMonth tinyint = 0
	  DECLARE @lSalaryYear smallint = 0  
	  DECLARE @lEmployeeAge smallint = 0  
	  DECLARE @lDateOfBirth date	
	  DECLARE @lFirstDateOfMonth date
	  DECLARE @lLastDateOfMonth date
	  
	  SELECT @lEmployeeId = EmployeeId,@lPayProcessId = PayProcessId FROM sPayroll.tPayProcessEmployee WHERE ID = @rPayProcessEmployeeId
	  SELECT @lDateOfBirth = DateOfBirth FROM sHrm.tEmployeePersonalDetail WHERE EmployeeId = @lEmployeeId
	  SELECT @lSalaryMonth = SalaryMonth,@lSalaryYear = SalaryYear  FROM sPayroll.tPayProcess WHERE Id = @lPayProcessId
	 
      SET @lFirstDateOfMonth= CAST(CAST(@lSalaryYear AS varchar) + '-' + CAST(@lSalaryMonth AS varchar) + '-' + '1' AS date)
      SET @lLastDateOfMonth=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDateOfMonth)+1,0))
      SET @lEmployeeAge = [sCommon].[fAgeAtDate] (@lDateOfBirth,@lLastDateOfMonth)
      
      -- end for age calculation
      

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


GO
-- drop procedure [sProcurement].[pStockInwardAdd_New]
ALTER PROCEDURE [sProcurement].[pStockInwardAdd_New]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rStockInwardRequestId			Int=0, 
		@rInwardByName					Nvarchar(100) = '',
		--@rToOrganizationDepartmentId	Int,
		@rToStoreLocationId				Int,
		--@rFirstAidId					Int,
		@rRemark						Nvarchar(300)='',
		@rCreatedUserId					BigInt,
		@rDetail						Nvarchar(Max),
		@rLocationId int,
		@rOrgId int,
		@rVendorId int=0,
		@rInwardDate datetime = null
		--@rOrgId int
	)
AS

SET NOCOUNT ON

BEGIN
--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 1005,@rStoreLocationId = @rToStoreLocationId, @rNextNumber  = @rNumber OUTPUT
Declare @loXML XML
SET @loXML = CAST(@rDetail AS XML)
 
	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1005,
	@rStoreLocationId = @rToStoreLocationId, @rNextNumber  = @rNumber OUTPUT
	
	SET @rNumber = ISNULL(@rNumber, '-300')
	IF @rNumber = '-300'
	BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id 
		RETURN
	END

	
 
	DECLARE @tStockInwardDetailBatch TABLE
	(
		Id						Int IDENTITY(1, 1),
		StockInwardRequestDetailId	Int, 
		StockItemId				Int, 
		StockItemName nvarchar(50),
		ItemBatch Nvarchar(300) NULL,
		ItemExpiryDate nvarchar(20) NULL,	
		InwardQuantity			Decimal(12,2),
		RequestedQuantity		Decimal(12,2),  
		InwardValue 			Decimal(12,2) 
		 
	)	
	INSERT INTO @tStockInwardDetailBatch
	Select 
		 T.c.value('@StockInwardRequestDetailId','int') AS StockInwardRequestDetailId,
            T.c.value('@StockItemId','Int') AS StockItemId,
            T.c.value('@StockItemName','nvarchar(50)') AS StockItemName,
            T.c.value('@ItemBatch','Nvarchar(300)') AS ItemBatch,
            T.c.value('@ItemExpiryDate','nvarchar(20)')   AS ItemExpiryDate,
            T.c.value('@InwardQuantity','Decimal(12,2)') AS InwardQuantity,
            T.c.value('@RequestedQuantity','Decimal(12,2)') AS RequestedQuantity,
            T.c.value('@InwardValue','Decimal(12,2)') AS InwardValue 
			 
	
	FROM 
            @loXML.nodes('/Table/StockInward')T(c)
	
	
	
	DECLARE @lNextNumberStockInward INT
 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockInward',@lNextNumber = @lNextNumberStockInward output
	Declare @lNextNumberStockInwardBatch bigint
  
	INSERT INTO sProcurement.tStockInward
		(
			Id,
			Number,
			StockInwardRequestId, 
			InwardByName,		 
			ToStoreLocationId,			 
			Remark,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			VendorId
		)
	VALUES
		(
			@lNextNumberStockInward,
			@rNumber,
		   (CASE WHEN @rStockInwardRequestId = 0 THEN NULL ELSE @rStockInwardRequestId END),	 
			@rInwardByName,		 
			@rToStoreLocationId,			 
			@rRemark,
			@rCreatedUserId,
			@rInwardDate,
			@rOrgGroupId,
			@rVendorId
		)


	DECLARE @lIntErrorCode INT, @lIntDoc INT
	EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rDetail	
		
	DECLARE @lCount int,@lIsBatchWise bit,@lbatchId int,@lNextNumberStockBatch int,@lExpiryDate date,
			@lItemId int,@lBatch nvarchar(300),@lInwardQty decimal(12,2),@lInwardValue decimal(12,2),
			@lIdCount int,@lNextNumberStockInwardDetail bigint,@lStockItemName nvarchar(50)
	Select @lCount=Count(*) from  @tStockInwardDetailBatch
	
	 
	While(@lCount>0)
	BEGIN
		  
	    Select @lItemId =StockItemId,@lBatch = [ssetup].[fPortalXMLTagsReplaceReverse](ItemBatch),@lInwardQty=InwardQuantity,@lInwardValue=InwardValue,@lIdCount=Id,@lExpiryDate =ItemExpiryDate
		,@lStockItemname=[ssetup].[fPortalXMLTagsReplaceReverse](StockItemname)
		from  @tStockInwardDetailBatch WHERE Id = @lcount
		Select @lIsBatchWise=IsBatchWiseTracking from sIp.tStockItemMaster    Where Id = @lItemId   
		
		 
		SET @lbatchId = 0
			
	    if (@lIsBatchWise=1)
		BEGIN
			Select @lbatchId= Id from sProcurement.tStockBatch    
			Where  Number =@lBatch   AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId
		END
		else 
		BEGIN
			Select @lbatchId= Id from sProcurement.tStockBatch    
			Where iSNULl( Number,'') =''  AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId
		END	
		 
		if(ISNULL(@lbatchId,0)=0)
	    BEGIN
			
		 	EXECUTE sCommon.pTableRowIdGet @rOrggroupId, 'sProcurement.tStockBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockBatch output
			INSERT INTO sProcurement.tStockBatch (Id,StoreLocationId,StockItemId,Number,ExpiryDate,AvailableQuantity,ItemRate,CreatedUserId,CreatedDateTime,OrgGroupId)
			Select @lNextNumberStockBatch,@rToStoreLocationId,@lItemId,@lBatch,@lExpiryDate ,0,0,@rCreatedUserId,getdate(),@rOrgGroupId
			
			SET @lbatchId = @lNextNumberStockBatch
			
	    End
	
		if(isnull(@lbatchId,0)>0)
		BEGIN
			 
			if Exists(Select Id from sProcurement.tStockInwardDetail   
			where  StockInwardId = @lNextNumberStockInward  and  StockItemId = @lItemId  )
			BEGIN
					 
					Select @lNextNumberStockInwardDetail= Id from  sProcurement.tStockInwardDetail
					Where  StockInwardId = @lNextNumberStockInward AND StockIteMid =@lItemId
			END
			ELSE
			BEGIN
			
				EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardDetail output
				INSERT INTO sProcurement.tStockInwardDetail
				(	
					Id,StockInwardId,StockItemId,RequestedQuantity,InwardQuantity, 
					Remark,StockInwardRequestDetailId,OrgGroupId,InwardValue
				)
				SELECT @lNextNumberStockInwardDetail ,@lNextNumberStockInward,StockItemId,RequestedQuantity,
					    InwardQuantity,@rRemark,StockInwardRequestDetailId,@rOrgGroupId,@lInwardValue
					   from @tStockInwardDetailBatch where Id=@lcount
			END
			
			
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardBatch output
							
							INsert into sProcurement.tStockInwardBatch
							(Id,StockInwardDetailId,Quantity,StockBatchId,OrgGroupId)
							Select @lNextNumberStockInwardBatch,@lNextNumberStockInwardDetail,InwardQuantity,@lbatchId,@rOrgGroupID
							from @tStockInwardDetailBatch where Id=@lcount
							
							
							Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=1010,@rSourceId=@lNextNumberStockInwardBatch,
												@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lInwardQty ,@rValue=@lInwardValue,@rIsReceipt=1,
												@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rToStoreLocationId ,@rLocationId=@rLocationId,@rItemBatchId = @lbatchId,@rItemName = @lStockItemname,@rOrgId=@rOrgId


			END
			set @lcount =@lcount-1
	END
	 
	 SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockInward AS Id 
	 
END
GO
PRINT N'Altering [sProcurement].[pStockIssueStudentAdd_New]...';


GO
/******************************************************************************
	Purpose          : To add records to sProcurement.tStockIssue table
	Created date     : 09 Jan 2012
	Author           : System Generated
	Copyright©       : Copyright © Sapphire Software
	Last Change Desc : Added @rStockIssueRequestId field
	Test script      : EXECUTE sProcurement.pStockIssueAdd @rNumber = '', @rStockIssueRequestId = 0, @rIssuedByName = '', @rToOrganizationDepartmentId = 0, @rFromStoreLocationId = 0, @rRemark = '', @rCreatedUserId = 0, @rDetail = ''
*******************************************************************************/
ALTER PROCEDURE [sProcurement].[pStockIssueStudentAdd_New]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rStockIssueRequestId			Int=0, 
		@rIssuedByName					Nvarchar(100) = '',
		@rToOrganizationDepartmentId	Int,
		@rFromStoreLocationId			Int,
		@rFirstAidId					Int,
		 
		@rCreatedUserId					BigInt,
		@rDetail						Nvarchar(Max)='',
		@rOrgId int,
		@rLocationId int,
		@rIssuedToName nvarchar(50)='',
		@rIssueToSourceTypeId int,
		@rIssueToSourceId BigInt 
	)
AS

SET NOCOUNT ON

BEGIN
EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId = 26,@rStoreLocationId = @rFromStoreLocationId, @rNextNumber  = @rNumber OUTPUT

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

IF @rNumber = '-300'
BEGIN
 
SELECT -300 AS Result, '' AS Number, 0 AS Id 
RETURN
END
 
	  DECLARE @lNextNumberStockIssue INT
	 DECLARE @loXML XML
		SET @loXML = CAST(@rDetail AS XML)
	 DECLARE @tStockIssueDetail TABLE
		(
			Id Int IDENTITY(1,1),StockItemId Int,IssuedQuantity Decimal(12,2)
		)

	INSERT INTO @tStockIssueDetail
		SELECT
		T.c.value('@StockItemId','int') AS StockItemId,
		T.c.value('@IssuedQuantity','decimal(12,2)') AS IssuedQuantity 
		FROM @loXML.nodes('/Table/StockIssue')T(c)
	 
	 BEGIN TRANSACTION
	 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockIssue',@lNextNumber = @lNextNumberStockIssue output



if @rFirstAidId < 0 
SET @rFirstAidId =  NULL

	INSERT INTO sProcurement.tStockIssue
		(
			Id,
			Number,
			StockIssueRequestId, 
			IssuedByName,
			ToOrganizationDepartmentId,
			FromStoreLocationId,
			FirstAidId,
			Remark,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			IssueToName,
			IssueToSourceTypeId,
			IssueToSourceId
		)
	VALUES
		(
			@lNextNumberStockIssue,
			@rNumber,
		   (CASE WHEN @rStockIssueRequestId = 0 THEN NULL ELSE @rStockIssueRequestId END),	 
			@rIssuedByName,
			@rToOrganizationDepartmentId,
			@rFromStoreLocationId,
			@rFirstAidId,
			'',
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rIssuedToName,
			@rIssueToSourceTypeId,
			@rIssueToSourceId
		)


	DECLARE @lNextNumberStockIssueDetail BigInt,@lQuantity decimal(12,2),@lStockItemCode nvarchar(50)
		Declare @lCOunt int , @lItemId int,@lIssueQuantity decimal(12,2),
		@lbatchId int,@lIsBatchWise bit,@lBatch nvarchar(300),@lNextNumberStockBatch int,@lNextNumberBatch int,
		@lWeightedAverageCost decimal(12,2),@lInwardValue decimal(12,2),@lStockItemName nvarchar(50),
		@lNextNumberOtherStockBatch bigint
		Select @lCOunt = count(*) from @tStockIssueDetail
		while @lcount>0
		BEGIN
			Select @lItemId = StockItemId , @lIssueQuantity = IssuedQuantity ,@lCOunt=Id
			from @tStockIssueDetail where Id=@lCOunt
			
			Select @lWeightedAverageCost=ISNULL(WeightedAverageCost,0) from sIp.tStockItemPlanning
			Where StockItemId = @lItemId AND StoreLocationId =  @rFromStoreLocationId  
			 
			Select @lQuantity=AvailableQuantity,@lbatchId=Id from sProcurement.tStockBatch where  StockItemId = @lItemId ANd StorelocationId=@rFromStoreLocationId
			  
			if(ISNULL(@lbatchId,0)=0)
			BEGIN
				ROLLBACK TRANSACTION
				Select -102 As Result,@lStockItemCode AS StockItemCode
				Return
			END 
			IF @lQuantity = 0 
			BEGIN
				ROLLBACK TRANSACTION
				Select -103 AS Result,@lStockItemCode AS StockItemCode
				return
			END
			IF @lQuantity < @lIssueQuantity 
			BEGIN
				ROLLBACK TRANSACTION
				Select -101 AS Result,@lStockItemCode AS StockItemCode
				return
			END
			
			IF Exists(Select Id from sProcurement.tStockIssueDetail where StockIssueId = @lNextNumberStockIssue and StockItemId = @lItemId)					
			BEGIN
				Select @lNextNumberStockIssueDetail= Id from sProcurement.tStockIssueDetail
				Where StockIssueId = @lNextNumberStockIssue AND StockIteMid =@lItemId					 
			END	
			ELSE
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockIssueDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockIssueDetail output

				INSERT INTO sProcurement.tStockIssueDetail
				(
					Id,StockIssueId,StockItemId,IssuedQuantity,RequestedQuantity,
					StockIssueRequestDetailId,Remark,OrgGroupId
				)
				SELECT @lNextNumberStockIssueDetail,@lNextNumberStockIssue,StockItemId,IssuedQuantity,
				0,NULL,'',@rOrgGroupId
				from @tStockIssueDetail where Id=@lcount	
			END
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockIssueBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output

			INSERT INTO sProcurement.tStockIssueBatch
			(
				Id,StockIssueDetailId,StockBatchId,Quantity,OrgGroupId
			)
		Select @lNextNumberBatch,@lNextNumberStockIssueDetail,@lbatchId,@lIssueQuantity,@rOrgID

		SET @lInwardValue = ISNULL(@lWeightedAverageCost,0) * ISNULL(@lIssueQuantity,0)
		
		Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=51,@rSourceId=@lNextNumberBatch,
			@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lIssueQuantity ,@rValue=@lInwardValue,@rIsReceipt=0,
			@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rFromStoreLocationId ,@rLocationId=@rLocationId,
			@rItemBatchId = @lbatchId,@rItemName =@lStockItemName,@rOrgId=@rOrgId
		set @lcount =@lcount-1
END
	--DECLARE @lIntErrorCode INT, @lIntDoc INT
	--EXEC @lIntErrorCode = sp_xml_preparedocument @lIntDoc OUTPUT, @rDetail	
		
	--DECLARE @tStockIssueDetail TABLE
	--(
	--Id						Int IDENTITY(0, 1),
	--StockIssueDetailId		Int, 
	--StockIssueRequestDetailId	Int, 
	--StockIssueId 			Int, 
	--StockItemId				Int, 
	--IssuedQuantity			Decimal(12,2),
	--RequestedQuantity		Decimal(12,2),  
	--Remark					Nvarchar(300)
	--)
	
	--INSERT INTO @tStockIssueDetail  
	--(  
	--	StockIssueId,
	--	StockItemId,
	--	IssuedQuantity,
	--	RequestedQuantity,
	--	StockIssueRequestDetailId, 
	--	Remark
	--)
	--SELECT	@lNextNumberStockIssue, 
	--		StockItemId,
	--		IssuedQuantity,
	--		RequestedQuantity,
	--		(CASE WHEN StockIssueRequestDetailId = 0 THEN NULL ELSE StockIssueRequestDetailId END), 			
	--		Remark
			
	--FROM OPENXML (@lIntDoc, '/Root/StockIssueDetail', 1)  
	--	WITH  
	--	(  
	--		StockItemId				Nvarchar(300)	'@StockItemId', 
	--		IssuedQuantity			Nvarchar(300)	'@IssuedQuantity', 
	--		RequestedQuantity		Nvarchar(300)	'@RequestedQuantity', 
	--		StockIssueRequestDetailId  Nvarchar(300)'@StockIssueRequestDetailId', 
	--		Remark					Nvarchar(300)	'@Remark'
	--	) XmlTable
	
	--DECLARE @lNextNumberStockIssueDetail BigInt
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockIssueDetail output
	
	
	--INSERT INTO sProcurement.tStockIssueDetail
	--	(
	--		Id,
	--		StockIssueId,
	--		StockItemId,
	--		IssuedQuantity,
	--		RequestedQuantity,
	--		StockIssueRequestDetailId, 
	--		Remark,
	--		OrgGroupId
	--	)
	--SELECT 	@lNextNumberStockIssueDetail + Id, 
	--		StockIssueId, 
	--		StockItemId, 
	--		IssuedQuantity,
	--		RequestedQuantity, 
	--		StockIssueRequestDetailId, 
	--		Remark,
	--		@rOrgGroupId
	--FROM	@tStockIssueDetail
	
	--UPDATE @tStockIssueDetail SET StockIssueDetailId = @lNextNumberStockIssueDetail + Id 
	--SELECT @lNextNumberStockIssueDetail = MAX(Id) + @lNextNumberStockIssueDetail FROM @tStockIssueDetail
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockIssueDetail', @rCurrentNumber = @lNextNumberStockIssueDetail 
	
	--DECLARE @tBatch TABLE
	--(
	--	Id						Int IDENTITY(0, 1), 
	--	StockIssueDetailId	Int,
	--	StockBatchId Int,		
	--	Quantity				Decimal(12,2),
	--	StockItemId				Int				
	--)
	
	--INSERT INTO @tBatch  
	--		(  
	--		StockIssueDetailId,	
	--		StockBatchId, 
	--		Quantity,
	--		StockItemId									
	--		)
	--SELECT	1, 
	--		StockBatchId, 
	--		Quantity,
	--		StockItemId
	--FROM OPENXML (@lIntDoc, '/Root/StockIssueDetail/StockIssueBatch', 1)  
	--	WITH  
	--	(  
	--		StockBatchId 	Nvarchar(200)	'@StockBatchId', 
	--		Quantity					Nvarchar(200)	'@Quantity',
	--		StockItemId					Nvarchar(200)	'@StockItemId' 			
	--	) XmlTable	
		
		
	--DECLARE @lNextNumberBatch BIGINT
	--EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueBatch', 0, 1, 1,@outNextNumber = @lNextNumberBatch output
	
	--INSERT INTO sProcurement.tStockIssueBatch
	--	(
	--		Id,
	--		StockIssueDetailId,
	--		StockBatchId,
	--		Quantity,
	--		OrgGroupId
	--	)
	--SELECT 		@lNextNumberBatch + TD.Id, 
	--			STD.StockIssueDetailId, 
	--			StockBatchId, 
	--			Quantity,
	--			@rOrgGroupId
	--FROM		@tStockIssueDetail STD 
	--INNER JOIN	@tBatch TD 
	--			ON TD.StockItemId = STD.StockItemId
				
	--SELECT @lNextNumberBatch = MAX(Id) + @lNextNumberBatch FROM @tBatch
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId = @rOrgGroupId, @rTableTitle = 'sProcurement.tStockIssueBatch', @rCurrentNumber = @lNextNumberBatch 
	
	SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockIssue AS Id 
		COMMIT TRANSACTION
END
GO
PRINT N'Altering [sSecurity].[pOrgGroupMobileAppGet]...';


GO

ALTER PROCEDURE  [sSecurity].[pOrgGroupMobileAppGet]

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

BEGIN 
		BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
			OGM.OrgGroupId,
			OGM.Code,
			OGM.Title,
			OGM.ApiUrl,
			OGM.IsMobileSiteAccess,
			OGM.IsStudentPortalAccess,
			OGM.ActivationDate,
			CM.Title AS CustomerName
	FROM 
	sSecurity.tOrgGroupMobileApp OGM
		LEFT JOIN sErp.tCustomerMaster CM ON  CM.OrgGroupId=OGM.OrgGroupId
			
	WHERE 
	
			((OGM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId= 0))
				AND((CM.OrgId = @rOrgId)OR (@rOrgId=0))
				AND ((OGM.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
		AND ((OGM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
    order by OGM.ActivationDate desc
END
GO
PRINT N'Altering [sStudent].[pChangeIDNoLogGet]...';


GO
ALTER PROCEDURE [sStudent].[pChangeIDNoLogGet]
	 
	@rId bigint,
	@rOrgId int  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		Select SM.Id As StudentId,CH.OldIdNo,CH.NewIdNo,SM.FirstName+' ' +SM.MiddleName+' ' +Sm.LastName AS Name,CH.CreatedDateTime
		from sStudent.tChangeIdLog CH
		INNER JOIN sStudent.tStudentMaster SM oN SM.Id=CH.StudentId
		 
		Where  ((Id=@rId) OR (@rId=0)) AND OrgId=@rOrgId
		Order by StudentId,CH.CreatedDateTime desc
END
GO
PRINT N'Altering [sStudent].[pGetDropDownLists]...';


GO
-- exec sStudent.pGetDropDownLists
-- drop proc sStudent.pGetDropDownLists
ALTER proc [sStudent].[pGetDropDownLists]
@rBatchId int,
@rOrgId int,
@rUserId bigint,
@rDepartmentId int,
@rOrgGroupBatchId int=0,
@rOrgGroupId int=0
as
begin
	declare @lStatusRes nvarchar(max)='',@lClassRes Nvarchar(max)='',@lEnrollmentStatusRes nvarchar(max)=''
	declare @lDepartmentRes nvarchar(max)='',@lDivisionRes Nvarchar(max)='',@lAvailableRes nvarchar(max)=''
	declare @lReportList nvarchar(max)='',@lExamRes nvarchar(max)='',@lGeneralExamRes nvarchar(max)='',@lcastdropdown nvarchar(max)=''
	declare @lExamReportList nvarchar(max)=''
	declare @lclassdropdown nvarchar(max)='',@lStatusdropdown nvarchar(max)='',@lGenderdropdown nvarchar(max)='',@lReligiondropdown nvarchar(max)=''
	declare @lCitydropdown nvarchar(max)='',@lAreadropdown nvarchar(max)='',@lNationalitydropdown nvarchar(max)='',@lTranspotrmodedropdown nvarchar(max)='',@lbusrouedropdown nvarchar(max)=''
	declare @lbusrotedestinationdrop nvarchar(max)='',@lblooddropdown nvarchar(max)='',@lhousedropdown nvarchar(max)='',@lmothertoungedropdown nvarchar(max)='',@lpriviousschooldropdown nvarchar(max)=''
	declare @lfatherqadrop nvarchar(max)='',@lmotherqadropdown nvarchar(max)='',@lfatherocdropdown nvarchar(max)='',@lmotherocdropdown nvarchar(max)='',@lfeescategorydropdown nvarchar(max)=''
	declare @lCustomtagdrop nvarchar(max)='',@lcustomgroupdropdown nvarchar(max)='',@lclubdropdown nvarchar(max)='',@lhosteldropdown nvarchar(max)='',@lstudentgroupdropdown nvarchar(max)=''
	declare @lstudentothergroupdropdown nvarchar(max)='',@lExaminationtypedropdown nvarchar(max)=''

	select @lDivisionRes = @lDivisionRes + '<option value="0"> -- ALL -- </option>'
	
	select @lStatusRes = @lStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lStatusRes = @lStatusRes + '<option value="1">Active</option>'
	select @lStatusRes = @lStatusRes + '<option value="2">InActive</option>'
	select @lStatusRes = @lStatusRes + '<option value="3">Left</option>'
	
	select @lClassRes = @lClassRes + '<option value="0"> -- ALL -- </option>'
	select @lClassRes = @lClassRes + '<option value="' + convert(varchar,ClassId) + '">' + ClassName + '</option>'
	from sSetup.vBatchClass where IsObsolete = 0 and BatchId = @rBatchId order by OrderIndex
	
	select @lEnrollmentStatusRes = @lEnrollmentStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lEnrollmentStatusRes = @lEnrollmentStatusRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sStudent.tEnrollmentStatusMaster where IsObsolete = 0 order by Title
	
	select @lDepartmentRes = @lDepartmentRes + '<option value="0"> -- ALL -- </option>'
	select @lDepartmentRes = @lDepartmentRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sSetup.vDepartment where IsObsolete = 0 AND OrgId = @rOrgId and UserId = @rUserId
	and (Id = @rDepartmentId or @rDepartmentId = 0) order by Title
	
	select @lAvailableRes = @lAvailableRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sStudent' AND TABLE_NAME='vStudentColumnName' AND COLUMN_NAME <> 'GR No'
	
	select @lGeneralExamRes = @lGeneralExamRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sAssessment' AND TABLE_NAME='vGeneralExamColumnName'
	
	select @lReportList = @lReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;text-align: center;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><img src="../../Images/Del.png"></a></td></tr>'
	from sStudent.tStudentCustomSearch SCS
	INNER JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1)
	AND SCS.OrgId = @rOrgId
	
	select @lExamReportList = @lExamReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>'
	from sAssessment.tGeneralExamCustomSearch SCS
	INNER JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1)
	AND SCS.OrgId = @rOrgId
	
	select @lExamRes = @lExamRes + '<option value="0"> -- ALL -- </option>'
	select @lExamRes = @lExamRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sAssessment.tExamSubGroupMaster where OrgId = @rOrgId
	
					--select @lclassdropdown=@lclassdropdown+'<option value="0"> -- ALL -- </option>'
					select @lclassdropdown = @lclassdropdown + '<option value="' + convert(varchar,DivisionId) + '">' + ClassDivisionName + '</option>'
					from sSetup.vBatchClassDivision where IsObsolete = 0 and BatchId = @rBatchId order by OrderIndex

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

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

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

					select @lCitydropdown = @lCitydropdown + '<option value="' +convert(varchar,OrgId)+ '">' + City + '</option>'
					from sStudent.vCity where OrgId = @rOrgId

					select @lAreadropdown = @lAreadropdown + '<option value="' +convert(varchar,OrgId)+ '">' + Area + '</option>'
					from sStudent.vArea where OrgId = @rOrgId

					select @lNationalitydropdown = @lNationalitydropdown + '<option value="' +convert(varchar,Id)+ '">' + Nationality + '</option>'
					from sCommon.tCountryMaster where IsObsolete = 0 
					and OrgGroupId = @rOrgGroupId

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

					select @lbusrouedropdown = @lbusrouedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sTransport.tBusRouteMaster where IsObsolete = 0  and OrgGroupBatchId = @rOrgGroupBatchId

					select @lbusrotedestinationdrop  = @lbusrotedestinationdrop  + '<option value="' +convert(varchar,BDM.Id)+ '">' + BDM.Title + '</option>'
					from sTransport.tBusRouteMaster BM inner join sTransport.tBusRouteDestinationMaster BDM ON BM.Id= BDM.BusRouteId
					where BDM.IsObsolete = 0  and OrgGroupBatchId = @rOrgGroupBatchId


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

					select @lhousedropdown = @lhousedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sActivity.tHouseMaster where IsObsolete = 0 and OrgId = @rOrgId

					select @lmothertoungedropdown = @lmothertoungedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tMotherTongueMaster where IsObsolete = 0 and OrgGroupId = @rOrgGroupId

					select @lpriviousschooldropdown = @lpriviousschooldropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tPreviousSchoolMaster where IsObsolete = 0 and OrgGroupId = @rOrgGroupId

			
		
					select @lfatherqadrop = @lfatherqadrop + '<option value="' +convert(varchar,OrgId)+ '">' + Qualification + '</option>'
					from sStudent.vQualification where OrgId = @rOrgId

					select @lmotherqadropdown  = @lmotherqadropdown  + '<option value="' +convert(varchar,OrgId)+ '">' + Qualification + '</option>'
					from sStudent.vQualification where OrgId = @rOrgId
			
			
					select @lfatherocdropdown = @lfatherocdropdown + '<option value="' +convert(varchar,OrgId)+ '">' + Occupation + '</option>'
					from sStudent.vOccupation where OrgId = @rOrgId

					select @lmotherocdropdown = @lmotherocdropdown + '<option value="' +convert(varchar,OrgId)+ '">' + Occupation + '</option>'
					from sStudent.vOccupation where OrgId = @rOrgId


					select @lfeescategorydropdown = @lfeescategorydropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tAdmissionCategoryMaster where IsObsolete = 0 and OrgGroupId = @rOrgGroupId
			
			
					select @lCustomtagdrop  = @lCustomtagdrop  + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tCustomTagMaster where IsObsolete = 0  and OrgGroupId = @rOrgGroupId

					select @lcustomgroupdropdown  = @lcustomgroupdropdown  + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommunication.tCustomGroup where  OrgGroupId = @rOrgGroupId

					select @lclubdropdown   = @lclubdropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sActivity.tClubMaster where  OrgGroupId = @rOrgGroupId

					select @lhosteldropdown   = @lhosteldropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sHostel.tHostelMaster where  OrgGroupId = @rOrgGroupId

					select @lstudentgroupdropdown   = @lstudentgroupdropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tStudentGroupMaster  where  OrgGroupId = @rOrgGroupId

					select @lstudentothergroupdropdown   = @lstudentothergroupdropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tStudentOtherGroupMaster where  OrgGroupId = @rOrgGroupId

					select @lExaminationtypedropdown    = @lExaminationtypedropdown    + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sFee.tExemptionTypeMaster where  OrgGroupId = @rOrgGroupId
			
								 

	select @lStatusRes as StatusRes,@lClassRes as ClassRes,@lDivisionRes as DivisionRes,
	@lEnrollmentStatusRes as EnrollStatusRes,@lDepartmentRes as DepartmentRes,
	@lAvailableRes as AvailableRes,@lReportList as ReportList,@lExamRes as ExamRes,
	@lGeneralExamRes as GeneralExamAvailRes,@lExamReportList as ExamReportList,@lclassdropdown as classChechboxlist,@lStatusdropdown As statusChechboxlist,
	@lGenderdropdown As Gendercheckboxlist,@lReligiondropdown As Religionchklist,@lcastdropdown as castcategorychklist,@lCitydropdown as Citychklist,
	@lAreadropdown AS Areachklist,@lNationalitydropdown As Nationalitychklist,@lTranspotrmodedropdown AS Transportmodechklist,@lbusrouedropdown AS busroutechklist,
	@lbusrotedestinationdrop AS Busroutedestinationchklist,@lblooddropdown AS bloodgrpchklist,@lhousedropdown AS Housechklist,
	@lmothertoungedropdown AS Mothertoungechklist,@lpriviousschooldropdown AS priviousschoolchklist,@lfatherqadrop  AS fatherqachklist,
	@lmotherqadropdown AS motherqachklist,@lfatherocdropdown AS fatherocuupationchklist,@lmotherocdropdown AS motherocuupationchklist,@lfeescategorydropdown AS feescategorychklist,
	@lCustomtagdrop AS customtaghklist,@lcustomgroupdropdown AS customgroupchklist,@lclubdropdown  AS clubchklist,@lhosteldropdown AS Hostelchklist,
	@lstudentgroupdropdown AS studentgroupchklist,@lstudentothergroupdropdown AS studentothergroupchklist,@lExaminationtypedropdown  as ExaminationTypechklist
end
GO
PRINT N'Altering [sStudent].[pIDNoGenerationUpdate]...';


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

		   DECLARE @lCode nvarchar(20)
		   SELECT @lCode=Code FROM sStudent.tStudentMaster WHERE Code=@rIDNo AND OrgId=@rOrgId AND Id<>@rStudentId
		   IF @lCode IS NOT NULL
		   BEGIN
					SELECT -103 AS Result,@lCode AS Code
					RETURN
		   END 
		   
		 --  IF EXISTS(SELECT @lCode=Code FROM sStudent.tStudentMaster WHERE Code=@rIDNo AND OrgId=@rOrgId AND Id<>@rStudentId)
			--	BEGIN
			--	SELECT -103 AS RESULT
			--	RETURN
			--END 
	BEGIN TRY
	 BEGIN TRANSACTION	
	 BEGIN
	    UPDATE  sStudent.tStudentMaster
	    SET
		    Code=@rIDNo,
			Number = (CASE WHEN @rIsNumber = 0 THEN Number WHEN @rIsNumber = 1 THEN @rIDNo END), 
			RecordStatusId = @rRecordStatusId,				  
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
	      WHERE Id = @rStudentId 	   
	 END  
		SELECT 1 AS RESULT
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
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,
			[sStudent].[fStudentNameGet](SD.FirstName , SD.MiddleName, SD.LastName,OM.StudentNameFormatId ) AS Name,	
			--SD.FirstName + ' ' + SD.MiddleName + ' ' + SD.LastName As Name,		 
			SD.StatusId,
			SD.DateOfBirth,		
			SD.BloodGroup,
			ISNULL(SD.PresentStreetone,'') AS PresentStreetone,
			ISNULL(SD.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(SD.PresentStreetThree,'') AS PresentStreetThree,
		    ISNULL(SD.PresentCity,'') AS PresentCity,
		    ISNULL(SD.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,
			ISNULL(RT.DropPoint,'') AS DropPoint,
			
			@lIcardBorder AS IcardBorder,
			HM.ColorCode,
			OM.OrgLogo,
			OM.SmallAddress1,
			--@lSUIdBarcode AS IsBarcodeBasedOnSUId,
			CASE WHEN @lSUIdBarcode = 'True' THEN SD.SUId  ELSE SD.Code END AS BarcodeNumber,
			 ISNULL(SD.EmergencyStreetOne,'') AS EmergencyStreetOne,
	         ISNULL(SD.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
	        ISNULL(SD.EmergencyStreetThree,'') AS EmergencyStreetThree,
	        ISNULL(SD.EmergencyCountry,'') AS EmergencyCountry,
	        ISNULL(SD.EmergencyState,'') As EmergencyState,
	        ISNULL(SD.EmergencyCity,'') AS EmergencyCity,
	        ISNULL(SD.EmergencyZipCode,'') as EmergencyZipCode,
	        SD.EmergencyContactNo AS EmergencyContactNo,
			ISNULL(SD.SUId,'') As SUId,
			ISNULL(RT.RouteNumber,0) AS RouteNumber,
			@rIsShowBarcode As IsShowBarcode,
			SD.Name,
			SM.Title AS Stream,
			SD.AdmissionDate,
			ISNULL(DM.Title,'') AS DepartmentName,
			SD.FatherPhoto,
			SD.MotherPhoto,
			SD.RelativePhoto,
			TM.Title AS TransPortMode,
			@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,ISNULL(BRDM1.Title,'')As DropPoint FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AT.PickupDestinationId
			LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AT.DropDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND  AT.SourceTypeId=2003 AND ((BRM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))AND BRM.Id=BRDM1.BusRouteId) RT
			ON RT.SourceId = SD.StudentId AND ((SD.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		 
			--LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId =SD.StudentId 
			--LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id =AR.PickupDestinationId 
			--LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id =BRDM.BusRouteId  AND(( BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			LEFT JOIN sStudent.tICardOrg ICO ON SD.OrgId = ICO.OrgId
			LEFT JOIN sSetup.tStreamMaster SM ON SM.Id=SD.StreamId
			LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id=SD.DepartmentId
			LEFT JOIN sStudent.tStudentOther SO ON SD.StudentId = SO.StudentId
			LEFT JOIN sCommon.tTransportModeMaster TM ON so.TransportModeId = TM.Id
			
	
			--LEFT JOIN sSetup.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].[pRptStudentStrengthGet]...';


GO
 

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

BEGIN 
	SELECT 
			Distinct Dept.Id AS DepartmentId,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			
			--(
			--select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			--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
			--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	  --      WHERE  BM.OrgGroupBatchId = @rOrgGroupBatchId  AND 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 
			--)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
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND
			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.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			--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 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	  --      WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId  AND 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 
			--) AS NewBoys,
			
						(
			SELECT COUNT(A.Id) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			INNER JOIN sStudent.tStudentMaster S  ON S.Id = A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId 
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId			 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND
			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 
			AND S.StatusId = 1
			) AS NewBoys,
			
			--(
			--select count(A.Id) FROM sStudent.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			--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 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	  --      WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId  AND 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 
			--) 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 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND
			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.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			--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 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	  --      WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId  AND 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 
			--) 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 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND 
			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.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			--	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 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			--	WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId  
			--	AND	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
				
			--) 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 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND 
			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.tStudentAdmission SA INNER JOIN sStudent.tAcademic A
			--	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
			--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			--	WHERE BM.OrgGroupBatchId = @rOrgGroupBatchId  
			--	AND	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
			--) 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=SA.StudentId
			INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 			 
			WHERE 
			BM.OrgGroupBatchId = @rOrgGroupBatchId AND 
			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,
			@rStatus AS StatusCheck,
			@rStatusClass AS StatusClass
			FROM 
			
			--sStudent.tAcademic A INNER JOIN 
			sSetup.tDivisionMaster DM  
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId 
			--AND DM.Id=A.DivisionId AND CM.Id=A.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BC.BatchId = BM.Id
			
			
			--INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
			
	WHERE 
		 DM.OrgId=@rOrgId
		--AND	A.BatchId = @rBatchId 
		
		AND ((DM.ClassId=@rClassId) OR (@rClassId=0))
		AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0))
		AND ((Dept.Id=@rDepartmentId) OR (@rDepartmentId=0))
		AND	BM.OrgGroupBatchId = @rOrgGroupBatchId 
		
	
END
GO
PRINT N'Altering [sStudent].[pStudentCollegeDetailAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentCollegeDetailAdd]
	 
	@rStudentId [bigint],
	 
	@rSSCBoard [nvarchar](200)  ,
	@rSSCSchool [nvarchar](200)  ,
	@rSSCPassingYear [nvarchar](10)  ,
	@rSSCObtainMarks [decimal](10, 2)  ,
	@rSSCOutOfMarks [decimal](10, 2)  ,
	@rSSCPercentage [decimal](10, 2)  ,
	@rSSCMathMarks [decimal](10, 2) ,
	@rSSCMathOutOfMarks [decimal](10, 2)  ,
	@rSSCPercentile [decimal](10, 2)  ,
	@rSSCGrade [nvarchar](20)  ,
	@rHSCBoard [nvarchar](200)  ,
	@rHSCSchool [nvarchar](200)  ,
	@rHSCPassingYear [nvarchar](10)  ,
	@rHSCObtainMarks [decimal](10, 2)  ,
	@rHSCOutOfMarks [decimal](10, 2)  ,
	@rHSCPercentage [decimal](10, 2)  ,
	@rHSCPhysicsMarks [decimal](10, 2)  ,
	@rHSCPhysicsOutOfMarks [decimal](10, 2)  ,
	@rHSCChemistryMarks [decimal](10, 2)  ,
	@rHSCChemistryOutOfMarks [decimal](10, 2)  ,
	@rHSCMathMarks [decimal](10, 2)  ,
	@rHSCMathOutOfMarks [decimal](10, 2)  ,
	@rHSCBiologyMarks [decimal](10, 2)  ,
	@rHSCBiologyOutOfMarks [decimal](10, 2)  ,
	@rPCMMarks [decimal](10, 2)  ,
	@rPCBMarks [decimal](10, 2)  ,
	@rJEERollNo [nvarchar](20)  ,
	@rJEEMeritNo [nvarchar](20)  ,
	@rJEEMeritMarks [decimal](10, 2)  ,
	@rJEEOutOfMarks [decimal](10, 2)  ,
	@rDiplomaBoard [nvarchar](200)  ,
	@rDiplomaCollege [nvarchar](200)  ,
	@rDiplomaPassingYear [nvarchar](10)  ,
	@rDiplomaObtainMarks [decimal](10, 2)  ,
	@rDiplomaOutOfMarks [decimal](10, 2)  ,
	@rDiplomaPercentage [decimal](10, 2)  ,
	@rApplicationId [nvarchar](20)  ,
	@rAdmissionRound [nvarchar](20)  ,
	@rMaritalStatusId tinyint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

 
	
	 BEGIN TRANSACTION	
 IF NOT EXISTS (Select 1 FROM sStudent.tCollegeDetail Where StudentId = @rStudentId)
BEGIN

	 


INSERT INTO  [sStudent].[tCollegeDetail]
           ( 
           StudentId,
		[SSCBoard]
      ,[SSCSchool]
      ,[SSCPassingYear]
      ,[SSCObtainMarks]
      ,[SSCOutOfMarks]
      ,[SSCPercentage]
      ,[SSCMathMarks]
      ,[SSCMathOutOfMarks]
      ,[SSCPercentile]
      ,[SSCGrade]      
      ,[HSCBoard]
      ,[HSCSchool]
      ,[HSCPassingYear]
      ,[HSCObtainMarks]
      ,[HSCOutOfMarks]
      ,[HSCPercentage]
      ,[HSCPhysicsMarks]
      ,[HSCPhysicsOutOfMarks]
      ,[HSCChemistryMarks]
      ,[HSCChemistryOutOfMarks]
      ,[HSCMathMarks]
      ,[HSCMathOutOfMarks]
      ,[HSCBiologyMarks]
      ,[HSCBiologyOutOfMarks]
      ,[PCMMarks]
      ,[PCBMarks]
      ,[JEERollNo]
      ,[JEEMeritNo]
      ,[JEEMeritMarks]
      ,[JEEOutOfMarks]
      ,[DiplomaBoard]
      ,[DiplomaCollege]
      ,[DiplomaPassingYear]
      ,[DiplomaObtainMarks]
      ,[DiplomaOutOfMarks]
      ,[DiplomaPercentage]
      ,[ApplicationNo]
      ,[AdmissionRound],
      MaritalStatusId
           )
   Values
   (
		@rStudentId,
	    @rSSCBoard
      , @rSSCSchool
      , @rSSCPassingYear
      , @rSSCObtainMarks
      , @rSSCOutOfMarks
      , @rSSCPercentage
      , @rSSCMathMarks
      , @rSSCMathOutOfMarks
      , @rSSCPercentile
      , @rSSCGrade
      , @rHSCBoard
      , @rHSCSchool
      , @rHSCPassingYear
      , @rHSCObtainMarks
      , @rHSCOutOfMarks
      , @rHSCPercentage
      , @rHSCPhysicsMarks
      , @rHSCPhysicsOutOfMarks
      , @rHSCChemistryMarks
      , @rHSCChemistryOutOfMarks
      , @rHSCMathMarks
      , @rHSCMathOutOfMarks
      , @rHSCBiologyMarks
      , @rHSCBiologyOutOfMarks
      , @rPCMMarks
      , @rPCBMarks
      , @rJEERollNo
      , @rJEEMeritNo
      , @rJEEMeritMarks
      , @rJEEOutOfMarks
      , @rDiplomaBoard
      , @rDiplomaCollege
      , @rDiplomaPassingYear
      , @rDiplomaObtainMarks
      , @rDiplomaOutOfMarks
      , @rDiplomaPercentage
      , @rApplicationId
      , @rAdmissionRound,
      @rMaritalStatusId
   )
		             
	END	 
	 ELSE
	 BEGIN
	 
	    UPDATE  sStudent.tCollegeDetail
	  
			 SET 
				     [SSCBoard]=@rSSCBoard
      ,[SSCSchool]=@rSSCSchool
      ,[SSCPassingYear]=@rSSCPassingYear
      ,[SSCObtainMarks]=@rSSCObtainMarks
      ,[SSCOutOfMarks]=@rSSCOutOfMarks
      ,[SSCPercentage]=@rSSCPercentage
      ,[SSCMathMarks]=@rSSCMathMarks
      ,[SSCPercentile]=@rSSCPercentile
      ,[SSCGrade]=@rSSCGrade
      ,[SSCMathOutOfMarks]=@rSSCMathOutOfMarks
      ,[HSCBoard]=@rHSCBoard
      ,[HSCSchool]=@rHSCSchool
      ,[HSCPassingYear]=@rHSCPassingYear
      ,[HSCObtainMarks]=@rHSCObtainMarks
      ,[HSCOutOfMarks]=@rHSCOutOfMarks
      ,[HSCPercentage]=@rHSCPercentage
      ,[HSCPhysicsMarks]=@rHSCPhysicsMarks
      ,[HSCPhysicsOutOfMarks]=@rHSCPhysicsOutOfMarks
      ,[HSCChemistryMarks]=@rHSCChemistryMarks
      ,[HSCChemistryOutOfMarks]=@rHSCChemistryOutOfMarks
      ,[HSCMathMarks]=@rHSCMathMarks
      ,[HSCMathOutOfMarks]=@rHSCMathOutOfMarks
      ,[HSCBiologyMarks]=@rHSCBiologyMarks
      ,[HSCBiologyOutOfMarks]=@rHSCBiologyOutOfMarks
      ,[PCMMarks]=@rPCMMarks
      ,[PCBMarks]=@rPCBMarks
      ,[JEERollNo]=@rJEERollNo
      ,[JEEMeritNo]=@rJEEMeritNo
      ,[JEEMeritMarks]=@rJEEMeritMarks
      ,[JEEOutOfMarks]=@rJEEOutOfMarks
      ,[DiplomaBoard]=@rDiplomaBoard
      ,[DiplomaCollege]=@rDiplomaCollege
      ,[DiplomaPassingYear]=@rDiplomaPassingYear
      ,[DiplomaObtainMarks]=@rDiplomaObtainMarks
      ,[DiplomaOutOfMarks]=@rDiplomaOutOfMarks
      ,[DiplomaPercentage]=@rDiplomaPercentage
      ,[ApplicationNo]=@rApplicationId
      ,[AdmissionRound]=@rAdmissionRound,
		MaritalStatusId =@rMaritalStatusId
			
	      WHERE [StudentId] = @rStudentId	   
	      
	      
	 END  
		SELECT @rStudentId AS Result
	
		COMMIT TRANSACTION
		
	 
 
END
GO
PRINT N'Altering [sStudent].[pStudentCollegeDetailGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentCollegeDetailGet]
	 
	 @rStudentId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 
	
	SELECT 
		[StudentId]
       
      ,[SSCBoard]
      ,[SSCSchool]
      ,[SSCPassingYear]
      ,ISNULL(SSCObtainMarks,0) AS SSCObtainMarks
      ,ISNULL(SSCOutOfMarks,0) AS SSCOutOfMarks
      ,ISNULL(SSCPercentage,0) AS SSCPercentage
      ,ISNULL(SSCMathMarks,0)AS SSCMathMarks
      ,ISNULL(SSCMathOutOfMarks,0) SSCMathOutOfMarks
      ,ISNULL (SSCPercentile, 0) AS SSCPercentile
      ,ISNULL (SSCGrade, '') AS SSCGrade
      ,[HSCBoard]
      ,[HSCSchool]
      ,[HSCPassingYear]
      ,ISNULL(HSCObtainMarks,0) HSCObtainMarks
      ,ISNULL(HSCOutOfMarks,0) HSCOutOfMarks
      ,ISNULL(HSCPercentage,0) HSCPercentage
      ,ISNULL(HSCPhysicsMarks,0) HSCPhysicsMarks
      ,ISNULL(HSCPhysicsOutOfMarks,0) HSCPhysicsOutOfMarks
      ,ISNULL(HSCChemistryMarks,0) HSCChemistryMarks
      ,ISNULL(HSCChemistryOutOfMarks,0) HSCChemistryOutOfMarks
      ,ISNULL(HSCMathMarks,0) HSCMathMarks
      ,ISNULL(HSCMathOutOfMarks,0) HSCMathOutOfMarks
      ,ISNULL(HSCBiologyMarks,0) HSCBiologyMarks
      ,ISNULL(HSCBiologyOutOfMarks,0) HSCBiologyOutOfMarks
      ,ISNULL(PCMMarks,0) PCMMarks
      ,ISNULL(PCBMarks,0) PCBMarks
      ,[JEERollNo]
      ,[JEEMeritNo]
      ,ISNULL(JEEMeritMarks,0) JEEMeritMarks
      ,ISNULL(JEEOutOfMarks,0) JEEOutOfMarks
      ,[DiplomaBoard]
      ,[DiplomaCollege]
      ,[DiplomaPassingYear]
      ,ISNULL(DiplomaObtainMarks,0) DiplomaObtainMarks
      ,ISNULL(DiplomaOutOfMarks,0) DiplomaOutOfMarks
      ,ISNULL(DiplomaPercentage,0) DiplomaPercentage
      ,[ApplicationNo]
      ,ISNULL(AdmissionRound,0) AdmissionRound,
      ISNULL(MaritalStatusId,0) AS MaritalStatusId
			
			
			
      
  FROM 
          sStudent.tCollegeDetail
             
  WHERE 
		(StudentId = @rStudentId)
		 
		
END
GO
PRINT N'Altering [sStudent].[pStudentCustomSearchGet]...';


GO
-- exec [sStudent].[pStudentCustomSearchGet]
-- drop proc [sStudent].[pStudentCustomSearchGet]
ALTER PROCEDURE [sStudent].[pStudentCustomSearchGet]
(
	@rPageIndex int = null,
	@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) = '',
	@rLCNumber nvarchar(20) = ''
 )
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'
	
	
	If @rDOBToDate <> '9999-12-31'
		SET @rDOBToDate = DATEADD(d,1,@rDOBToDate)
	If @rDOAToDate <> '9999-12-31'
		SET @rDOAToDate = DATEADD(d,1,@rDOAToDate)
	If @rDOLToDate <> '9999-12-31'
		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='')
	AND ((SCS.LCNumber=@rLCNumber)OR (@rLCNumber=''))
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'PhysicalDeformityRemark','PysicalDeformityRemark')
	SET @rOrderBy=Replace(@rOrderBy,'IsPhysicalDeformity','IsPysicalDeformity')
	
	SET @sql='SELECT StudentId,Code AS Code,Name,ClassName1 AS ClassName,StatusName,
	ParentContactNo
	FROM sStudent.tTempStudent1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	create table #STUDENTTEMP
	(
		tid int identity(1,1),t_StudentId bigint
	)
	select @Sql = 'insert into #STUDENTTEMP
	SELECT StudentId FROM sStudent.tTempStudent1 ORDER BY ' + @rOrderBy
	
	exec (@Sql)
	
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	declare @lTotalRecords int,@lPageSize int = 10,@lResult nvarchar(max) = '',@lPaging nvarchar(max) = ''
	
	select @lTotalRecords = COUNT(*) FROM #STUDENTTEMP
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex, @lTotalRecords, @lPageSize)
	
	select @lResult = @lResult + '<tr><td><a style="cursor:pointer;" onclick="SelectStudent(' + convert(varchar,StudentId) + ',''' + isnull(Code,'') + ''')">Select</a></td>
	<td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td>
	<td>' + isnull(ClassName,'') + '-' + isnull(DivisionName,'') + '</td><td>' + isnull(StatusName,'') + '</td></tr>'	
	from sStudent.tTempStudent1,#STUDENTTEMP
	where t_StudentId = StudentId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	order by tid
	
	select @lResult as StudentList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	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].[pStudentDataModify]...';


GO

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

--BEGIN TRY
--BEGIN TRANSACTION

        --CategoryId
        --Communication = 1,
        --Other = 2,
        --Admission = 3,
        --Family = 4,
        --Health = 5,
        --AcademicDetail = 6,
        --General = 7
        --CustomDetail = 8
        --Sibling = 9

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup' 
			 OR @rSubCategoryField = 'TransportMode' OR @rSubCategoryField = 'House'
			OR @rSubCategoryField = 'Quota' 
			OR @rSubCategoryField = 'Nationality' OR @rSubCategoryField = 'AdmissionStandard' OR  @rSubCategoryField = 'AdmissionCategory' OR @rSubCategoryField = 'AdmissionQuota')
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	
	IF(	@rSubCategoryField = 'CasteCategory' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast') + 'Id'
	END
	
	IF(	@rSubCategoryField = 'FamilyCaste' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')  
	END
	
	IF(	@rSubCategoryField = 'StudentGroup' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'StudentGroup','StudentGroupId')  
	END
	IF(	@rSubCategoryField = 'StudentOtherGroup' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'StudentOtherGroup','StudentOtherGroupId')  
	END
	
	IF(@rSubCategoryField = 'FeeCategory' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'FeeCategory','AdmissionCategory') + 'Id'
	END
	
	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)  
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication) 
		
		set @sql='INSERT INTO sStudent.tStudentCommunication 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentCommunication set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentCommunication SC 
					INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentOther) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
			set @sql='INSERT INTO sStudent.tStudentOther 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sStudent.tStudentOther SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			set @sql='INSERT INTO sStudent.tStudentOther 
						(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
						SELECT
							LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
						FROM
							ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	    
	Else IF(@rCategoryId= 3)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		set @sql='UPDATE sStudent.tStudentAdmission set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentAdmission SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'AdmissionDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdmission SET '+@rSubCategoryField+' = null WHERE AdmissionDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
 
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
		set @sql='INSERT INTO sStudent.tStudentFamily 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentFamily set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentFamily SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'FatherDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE FatherDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'MotherDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE MotherDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END

		IF(@rSubCategoryField = 'RelativeDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE RelativeDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END		
				
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
    Else IF(@rCategoryId= 5)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentHealth) 
		
		set @sql='INSERT INTO sStudent.tStudentHealth 
					(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentHealth set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentHealth SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END		 
	 
	 Else IF(@rCategoryId= 6)
	    BEGIN
		insert into ListofData
		select E.Id,0,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT AcademicId FROM sStudent.tAcademicDetail) 
		
		set @sql='INSERT INTO sStudent.tAcademicDetail 
					(AcademicId,'+@rSubCategoryField+')
					SELECT
						LD.Id,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tAcademicDetail set '+@rSubCategoryField+' = LD.SubCategory
					from sStudent.tAcademicDetail AD 
					INNER JOIN ListofData LD ON AD.AcademicId=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'BatchAdmissionDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tAcademicDetail SET '+@rSubCategoryField+' = NULL WHERE BatchAdmissionDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	Else IF(@rCategoryId= 7)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
		
		--set @sql='INSERT INTO sStudent.tStudentMaster 
		--			(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
		--			SELECT
		--				LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
		--			FROM
		--				ListofData LD WHERE LD.IsExist=1'				
		--Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentMaster SA 
					INNER JOIN ListofData LD ON SA.Id=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END			 
	 
	 
	 Else IF(@rCategoryId= 8)
	     BEGIN
	     
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
		set @sql='INSERT INTO sStudent.tStudentAdditional
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentAdditional set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentAdditional SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
					
		Exec sp_executesql @sql
					
		IF(@rSubCategoryField = 'PassportIssueDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdditional SET '+@rSubCategoryField+' = null WHERE PassportIssueDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'PassportExpiryDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdditional SET '+@rSubCategoryField+' = null WHERE PassportExpiryDate=''1900-01-01'''
			Exec sp_executesql @sql
		END						
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	     
	 Else IF(@rCategoryId= 9)
	    BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(200)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
		set @sql='INSERT INTO sStudent.tStudentSibling
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentSibling set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentSibling SS 
					INNER JOIN ListofData LD ON SS.StudentId=LD.StudentId AND IsExist=0'
					
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH

GO
PRINT N'Altering [sStudent].[pStudentDelete]...';


GO
 
 
ALTER PROCEDURE [sStudent].[pStudentDelete]
	 @rId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION SD	
					Delete from sStudent.tStudentAdmission where StudentId=@rId
					Delete from sStudent.tStudentCommunication where StudentId=@rId
					Delete from sStudent.tStudentImages where StudentId=@rId
					Delete from sStudent.tStudentFamily where StudentId=@rId
					Delete from sStudent.tStudentOther where StudentId=@rId
					Delete from sStudent.tStudentHealth where StudentId=@rId

					Delete from sStudent.tStudentAdditional where StudentId=@rId
					Delete from sStudent.tStudentSibling where StudentId=@rId
					Delete from sStudent.tCollegeDetail where StudentId=@rId

					Delete from sSecurity.tDivisionPermission Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003)
					Delete from sSecurity.tUserPreference Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003)
					Delete from sSecurity.tUserProfile Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003)
					Delete from sSecurity.tUserRole Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003)			
					Delete from sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003

					DELETE FROM sStudent.tLinkSibling WHERE StudentId = @rId
					DELETE FROM sStudent.tLinkSibling WHERE LinkedStudentId = @rId
				
					--Delete from sStudent.tAcademic where studentId=@rId
					Delete from sStudent.tStudentMaster where Id=@rId
					----- Start Hostel
					Delete from sHostel.tAssignRoom where SourceId=@rId AND SourceTypeId=2003
					Delete from sHostel.tAssignRoomAsset where SourceId=@rId AND SourceTypeId=2003
					Delete from sHostel.tAttendanceRegister where StudentId=@rId 
					Delete from sHostel.tChangeRoom where SourceId=@rId AND SourceTypeId=2003
					Delete from sHostel.tHostelAdmission where SourceId=@rId AND SourceTypeId=2003
					Delete from sHostel.tAssignRoomAsset where SourceId=@rId AND SourceTypeId=2003
					Delete from sHostel.tAttendanceRegister where StudentId=@rId 
					Delete from sHostel.tHostelDepositAdd where StudentId=@rId 
					Delete from sHostel.tHostelDepositAdjustment where StudentId=@rId 
					Delete from sHostel.tHostelDepositRefund where StudentId=@rId 
					Delete from sHostel.tHostelStudentGatePass where StudentId=@rId 
					Delete from sHostel.tVisitorGatePass where WhomToMeetSourceId=@rId  AND WhomToMeetSourceTypeId=2003
					-- END Hostel
					----- Start Transport
					Delete from sTransport.tAssignRoute where SourceId=@rId AND SourceTypeId=2003
					Delete from sTransport.tAttendanceRegister where SourceId=@rId AND SourceTypeId=2003
					--End Transport
					--Start Library
					DELETE FROM sLibrary.tBookLog where ReaderSourceTypeId=2003 AND ReaderSourceId=@rId
					DELETE FROM sLibrary.tLibraryAttendance WHERE SourceTypeId=2003 AND SourceId=@rId
					--End Library
					--start canteen
					DELETE  cd from sCanteen.tCanteenIssueDetail CD INNER JOIN sCanteen.tCanteenIssue C ON C.Id=CD.CanteenIssueId
					WHERE  C.SourceId=@rId AND C.SourceTypeId=2003
					DELETE FROM sCanteen.tCanteenIssue 	WHERE SourceId=@rId AND SourceTypeId=2003
					--End Canteen
					DELETE FROM  sStudent.tStudentDocument where studentId = @rId
			
		COMMIT TRANSACTION	SD
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION SD
	END CATCH	
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
			@rBuilder1 As Builder1,
			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.SSCPercentile,0) AS SSCPercentile,
	       ISNULL(CD.SSCGrade,0) AS SSCGrade,
	       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].[pStudentMasterAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentMasterAdd]
	 
	@rId bigint,
	@rCode nvarchar(20),
	@rRegistrationNumber nvarchar(20),
	@rNumber bigint,
	@rFirstName nvarchar(100),
	@rMiddleName nvarchar(100),
	@rLastName nvarchar(100),
	@rOrgId int,
	--@rDepartmentId int,
	@rAdmissionCategoryId int,
	@rStatusId smallint,
	@rRecordStatusId smallint,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupBatchId int =0,
	@OutStudentId BIGINT = NULL OUTPUT,
	@rSUId nvarchar(20) = '',
	@rOrgGroupId int = 0,
	@rMobileNo nvarchar(50)='',
	@rStudentGroupId int=0,
	@rStudentOtherGroupId int=0,
	@rDateOfBirth Date=NULL,
    @rGenderId int=0 
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	Declare @lStudCap int,@lOrgStudentCap int
	--IF(@rNumber=0)
	--SET @rNumber=NULL
	IF(@rId=0)
	BEGIN		 
	 
		--IF((@rCode = Null) OR (@rCode = ''))	
		--BEGIN

		--	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2001,@rStoreLocationId = 0, @rNextNumber = @rCode OUTPUT

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

		--	IF @rCode = '-300'
		--	BEGIN
		--		 SELECT -300 AS Result, '' AS Code, 0 AS Id 
		--		 RETURN
		--	END
		--END
		--ELSE
		--BEGIN
			Select @lStudCap=ISNULL(NoOfStudent,0)+ISNULL(StudentExtraCap,0) from
			sSetup.tOrgGroupSetting Where OrgGroupId= @rOrgGroupId
			
			Select @lOrgStudentCap=[sSetup].[fStudentCapGet](@rOrgGroupBatchId)
			 
			IF(@lOrgStudentCap >= @lStudCap )
			BEGIN
				Select -111 AS RESULT, '' AS Code, @lStudCap AS Id 
				Return
			END
		
			IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
					   WHERE SM.SUId=@rSUId AND OM.OrgGroupId=@rOrgGroupId)
			BEGIN
				SELECT -101 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
			ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId)
			BEGIN
				SELECT -100 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
			ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE ISNULL(@rRegistrationNumber,'')!='' AND RegistrationNumber=@rRegistrationNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -200 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
		--END
	END
	ELSE
	BEGIN
		DECLARE @lReferenceSourceId bigint=0
		SELECT @lReferenceSourceId = ISNULL(ReferenceSourceId,0)  FROM sStudent.tStudentMaster WHERE Id = @rId
		
		IF(@lReferenceSourceId=0)
			SELECT @lReferenceSourceId = Id FROM sStudent.tStudentMaster WHERE ReferenceSourceId = @rId
		IF(@lReferenceSourceId = 0)
		BEGIN 
			IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
						   WHERE SM.SUId=@rSUId AND OM.OrgGroupId=@rOrgGroupId AND SM.Id!=@rId)
			BEGIN
				SELECT -101 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
		END
		 
		IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId AND Id!=@rId)
		BEGIN
			SELECT -100 AS RESULT, '' AS Code, 0 AS Id 
			RETURN
		END 
		ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE RegistrationNumber=@rRegistrationNumber AND OrgId=@rOrgId AND Id!=@rId)
		BEGIN
			SELECT -200 AS RESULT, '' AS Code, 0 AS Id 
			RETURN
		END 
	END
	
	
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	IF(@rId=0)
	BEGIN	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	IF(@rNumber=0)
	BEGIN
	SET @rNumber=@lNextNumber
	END
	INSERT INTO sStudent.tStudentMaster
		(
			Id,
			Code,
			Number,
			RegistrationNumber,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			--DepartmentId,
			AdmissionCategoryId,
			StatusId,
			RecordStatusId,
			CreatedUserId,
			CreatedDateTime,
		    SUId,
		    StudentGroupId,
		    StudentOtherGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rNumber,
			@rRegistrationNumber,
			@rFirstName,
			@rMiddleName,
			@rLastName,
			@rOrgId,
			--@rDepartmentId,
			@rAdmissionCategoryId,
			@rStatusId,
			@rRecordStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSUId,
			@rStudentGroupId ,
			@rStudentOtherGroupId 
		)
		
		INSERT INTO sStudent.tStudentOther
		(
			StudentId,
			DateOfBirth,
			GenderId,
			CreatedUserId,
			CreatedDateTime
		)
		VALUES
		(
			@lNextNumber,
			@rDateOfBirth,
			@rGenderId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		IF(@rMobileNo!='')
		BEGIN
			INSERT INTO sStudent.tStudentCommunication
			(
				StudentId,
				ParentContactNo,
				CreatedUserId,
				CreatedDateTime
			)
			VALUES
			(
				@lNextNumber,
				@rMobileNo,
				@rCreatedUserId,
				sCommon.fGetDate()
			)
		END
		      
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
			IF(@rNumber=0)
			BEGIN
			SET  @rNumber=(SELECT ISnull(Number,0) FROM sStudent.tStudentMaster WHERE  Id=@rId)
			IF(@rNumber=0)
			SET @rNumber=@lNextNumber
			END
	    UPDATE  sStudent.tStudentMaster
	    SET
			Code=@rCode,
			Number=@rNumber,
			RegistrationNumber=@rRegistrationNumber,
			FirstName=@rFirstName,
			MiddleName=@rMiddleName,
			LastName=@rLastName,
			--OrgId=@rOrgId,
			--DepartmentId=@rDepartmentId,
			AdmissionCategoryId=@rAdmissionCategoryId,
			StatusId=@rStatusId,
			RecordStatusId=@rRecordStatusId,
	        UpdatedUserId=@rUpdatedUserId,
	        UpdatedDateTime=sCommon.fGetDate(),
			SUId=@rSUId,
			StudentGroupId=@rStudentGroupId ,
		    StudentOtherGroupId=@rStudentOtherGroupId
	      
	      WHERE Id = @rId 
	      
	    UPDATE  sStudent.tStudentOther
		SET
			DateOfBirth=@rDateOfBirth,
			GenderId=@rGenderId,
	        UpdatedUserId=@rUpdatedUserId,
	        UpdatedDateTime=sCommon.fGetDate()
	      WHERE StudentId = @rId 
	     
	     
	     IF(@rStatusId=3)
		BEGIN
		    UPDATE sSecurity.tUser
			   SET IsObsolete=1 
			WHERE SourceTypeId=2003 AND SourceId=@rId
		END
	 END  
	 
		SET @OutStudentId = @lNextNumber
	  SELECT 1 AS Result, @rCode AS Code, @lNextNumber AS Id 
		--SELECT @lNextNumber AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sTimetable].[pImportTeacherWorkLoad]...';


GO

ALTER PROCEDURE [sTimetable].[pImportTeacherWorkLoad]
	  
	 
	@rIsTeacherWorkLoad bit=0,
	@rTimeTableSchemaId int,
	@rBatchId int,
	@rCreatedUserId bigint,
	@rOrgId int
	
 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

  
BEGIN
	BEGIN TRY
	 
BEGIN	
  
	
--	 ELSE
--BEGIN
--	DECLARE @lDWLNoOfLecture AS smallint
--	DECLARE @lTWLNoOfLecture AS smallint
--	select 
--	@lDWLNoOfLecture=DWL.NoOfLecture,
--	@lTWLNoOfLecture=SUM(TWL.NoOfLecture) 
--	from
--	sTimetable.tDivisionWorkLoad DWL
--	INNER JOIN sTimetable.tTeacherWorkLoad TWL
--	ON DWL.DivisionId=TWL.DivisionId AND DWL.SubjectId=TWL.SubjectId 
--	WHERE DWL.DivisionId=@rDivisionId AND DWL.SubjectId=@rSubjectId 
--	AND TWL.TimeTableSchemaId=@rTimeTableSchemaId
--	GROUP BY DWL.NoOfLecture
	

--	 IF(@lDWLNoOfLecture<@lTWLNoOfLecture+@rNoOfLecture)
--	BEGIN
--	SELECT -102 AS RESULT
--	RETURN
--	  END
--	  END
	 
	
	 BEGIN 
	--IF (@rIsTeacherWorkLoad=0)
	--  BEGIN
	 --DELETE FROM sTimetable.tTeacherWorkLoad 
		--		 WHERE DivisionId=@rDivisionId AND SubjectId=@rSubjectId
				 
		--END			 
 
 
 -- if multiple teacher for same division and subject it can not identify the no of lecture for it
 -- so it can not make auto entry,delete the multiple teacher first to import
 	IF EXISTS(Select count(EmployeeId)
		from sAcademic.tTeacherSubjectDivision TSD 
		    INNER JOIN  sHRM.tEmployeeMaster EM ON TSD.EmployeeID =EM.Id AND EM.OrgID =@rOrgId
			INNER JOIN sTimetable.tDivisionWorkLoad  DWL ON DWL.DivisionId = TSD.DivisionId AND DWL.SUBJECTID = TSD.SubjectId 
	        INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = TSD.DivisionId  
		 WHERE  DWL.TimeTableSchemaId =@rTimeTableSchemaId 
		 AND DM.OrgId=@rOrgId AND DWL.NoOfLecture<>0
		 GROUP BY TSD.DivisionId,TSD.SubjectId Having COUNT(EmployeeId ) > 1)
		 BEGIN
		 SELECT - 101
		 return 
		 END
	
	DELETE TWL From sTimetable.tTeacherWorkLoad TWL 
			INNER JOIN sTimetable.tDivisionWorkLoad  DWL ON DWL.DivisionId = TWL.DivisionId AND DWL.SUBJECTID = TWL.SubjectId 
	        INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = TWL.DivisionId  
		 WHERE  DWL.TimeTableSchemaId =@rTimeTableSchemaId AND DM.OrgId=@rOrgId
		
	
	 INSERT INTO sTimetable.tTeacherWorkLoad
		(
			EmployeeId,
			BatchId,
			DivisionId,
			SubjectId,
			NoOfLecture,
			CreatedUserId,
			CreatedDateTime,
			TimeTableSchemaId
			)
	 
		Select
			 TSD.EmployeeId,
			 @rBatchId,
			 TSD.DivisionId,
			 TSD.SubjectId,
			 DWL.NoOfLecture,
			 @rCreatedUserId,
			 sCommon.fGetDate(),
			 @rTimeTableSchemaId
		from sAcademic.tTeacherSubjectDivision TSD 
		    INNER JOIN  sHRM.tEmployeeMaster EM ON TSD.EmployeeID =EM.Id AND EM.OrgID =@rOrgId
			INNER JOIN sTimetable.tDivisionWorkLoad  DWL ON DWL.DivisionId = TSD.DivisionId AND DWL.SUBJECTID = TSD.SubjectId 
	        INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = TSD.DivisionId  
		 WHERE  DWL.TimeTableSchemaId =@rTimeTableSchemaId 
		 AND DM.OrgId=@rOrgId AND DWL.NoOfLecture<>0
		
        SELECT 1 AS Result
	  END
END

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


GO
 
 

 
ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

	  --@rBuilder1 nvarchar(max)='',
	  --@rBuilder2 nvarchar(max)='', 
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rEmployeeId bigint,
	  @rTimeTableSchemaId int,
	  @rReportId int=0
	
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

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

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code 
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code
	
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  --ORDER BY DV.OrderIndex
	  )
	  A
			RIGHT JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			WHERE TimeTableSchemaId=@rTimeTableSchemaId ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
 ELSE
 BEGIN
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	 CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code 
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code
	
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	 
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
		END
END
GO
PRINT N'Altering [sTimetable].[pRptFreeTeacherTimetableGet]...';


GO

ALTER PROCEDURE [sTimetable].[pRptFreeTeacherTimetableGet]

	  --@rBuilder1 nvarchar(max)='',
	  --@rBuilder2 nvarchar(max)='', 
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rEmployeeId bigint,
	  @rTimeTableSchemaId int,
	  @rReportId int=0
	
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN   
 
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	'' AS EmployeeName,  
	--CASE WHEN A.TimeTableID is null THEN ISNULL(A.Subject,'FREE') ELSE '' END AS Subject,
	CASE WHEN A.EmployeeId=0 THEN 'Free' ELSE '' END AS Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	'' AS ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code 
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	ISNULL(Em.ShortName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code
	
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	
	WHERE  1=1
	--(ClassId = @rClassId OR @rClassId=0)
	 -- AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR TT.EmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  --ORDER BY DV.OrderIndex
	  )
	  A
			--RIGHT JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			--INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			--WHERE TimeTableSchemaId=@rTimeTableSchemaId ) L
			--ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId
		 
END
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

DELETE FROM sAlert.tMailTypeMaster
DELETE FROM sAlert.tSMSVendorMaster
DELETE FROM sCommon.tWeekOffRules

DELETE FROM sSecurity.tScreenHelp
DELETE FROM sSystem.tSettingInfo

DELETE FROM sProcurement.tOtherLocationSourceTypeMaster

END
GO
PRINT N'Altering [sTransport].[pStudentpickupListGet]...';


GO
ALTER PROC [sTransport].[pStudentpickupListGet]
	
	@rBusRouteId int=0,
	@rPickupid int,
	@rOrgGroupBatchId int,
	@rOrgId int,
	@rTransportId int

AS
BEGIN
	DECLARE @lTotalMarks decimal=0,@lTotalObtain decimal=0,@lResultStatus nvarchar(50)='' ,@lResultGrade nvarchar(10)='',@lRankNumber int=0,@lPercentage decimal=0,@lPercentile decimal=0
	DECLARE @lPickGrid VARCHAR(max)=''
	SELECT  @lPickGrid = @lPickGrid + '<tr>
	<td align="left" scope="col">' + ISNULL(VA.code,'')+ '</td>
	<td align="left" scope="col">' + isnull(VA.Name,'') + '</td>
	<td align="left" scope="col">' + ISNULL(VA.SUId,'')+ '</td>
	<td align="left" scope="col">' + ISNULL(BRDM.Title,'')+ '</td>
	  <td scope="col" align="center"><a href="javascript:;" 
    onclick="DeleteStudentDetail(this,' + convert(varchar,isnull(AR.SourceId,0)) + ');" class="fas fa-trash"></a></td></tr>'	
 From
 sTransport.tAssignRoute AR 
 INNER JOIN sStudent.vStudentAcademic VA ON VA.StudentId=AR.SourceId 
 INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
 INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BRDM.BusRouteId
 WHERE  BRDM.BusRouteId= @rBusRouteId AND VA.OrgId=@rOrgId AND VA.OrgGroupBatchId=@rOrgGroupBatchId
 AND B.TransportId= @rTransportId AND AR.SourceTypeId=2003
 AND ((BRDM.Id=@rPickupid) OR (@rPickupid=0))
	select isnull(@lPickGrid,'') as PickGrid
END
GO
PRINT N'Creating [sAcademic].[pGetLessonPlanApi]...';


GO
CREATE PROCEDURE [sAcademic].[pGetLessonPlanApi]

	 @rAcademicId bigint,
	 @rBatchId int,
	 @rDivisionId int,
	 @rSubjectId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			TM.Title AS TopicName,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			LP.StartDate,
			LP.EndDate,
			--LP.IsCompleted,			
			CASE WHEN (LP.IsCompleted = 'True') THEN  'Completed' ELSE 'InCompleted' END AS IsCompleted,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice
			
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN  sAcademic.tTopicMaster TM ON TM.Id = LP.TopicId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = @rSubjectId
			INNER JOIN sStudent.tAcademic AM ON AM.BatchId = @rBatchId AND AM.DivisionId = @rDivisionId
		
	WHERE 
			((LP.DivisionId = @rDivisionId)  OR (LP.DivisionId = 0))
			AND ((LP.BatchId = @rBatchId) OR (LP.BatchId = 0))
			AND ((SM.Id = @rSubjectId) OR (SM.Id = 0))
			AND AM.Id = @rAcademicId
		
	ORDER BY SM.Id
	
END
GO
PRINT N'Creating [sAccounting].[pRptVoucherEntryApproveGet]...';


GO



CREATE PROCEDURE [sAccounting].[pRptVoucherEntryApproveGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rTransactionId bigint,
	 @rAccountingYearId int,
	 @rTransactionDate date,
	 @rOrgGroupId int,
	 @rAccountId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN  
	 
  SELECT    @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			T.Id AS Id,
			T.Narration,
			T.TransactionDate,
			T.VoucherNumber,
			TD.Amount,
			TD.Id as TransactionDetailId,
			LM.Title AS Ledger,
			VTM.Title AS VoucherType,
			TD.TransactionTypeId ,
			(CASE WHEN TD.Amount > 0 THEN TD.Amount
			ELSE 0 END) DebitAmount,
			(CASE WHEN TD.Amount < 0 THEN -1 * TD.Amount
			ELSE 0 END) CreditAmount,
			AM.ReportOrgTitle As OrgTitle,
			AM.SmallAddress1 AS SmallAddress1,
			AM.SmallAddress2 AS SmallAddress2
			
			  
  FROM 
       sAccounting.tTransactionApprove T
       INNER JOIN sAccounting.tTransactionApproveDetail TD ON T.Id=TD.TransactionId
       LEFT JOIN sAccounting.tLedgerMaster LM On LM.Id=TD.LedgerId
       LEFT JOIN sAccounting.tVoucherTypeMaster VTM ON VTM.Id=T.VoucherTypeId
       LEFT JOIN sAccounting.tAccountMaster AM ON AM.Id=T.AccountId
      
      
  WHERE 
			(T.Id=@rTransactionId OR @rTransactionId = 0 )  
			AND (T.AccountingYearId=@rAccountingYearId)  AND LM.AccountingYearId = @rAccountingYearId
			ANd (T.TransactionDate=@rTransactionDate OR ISNULL(@rTransactionDate,'')='1900-01-01')     
			AND (T.OrgGroupId=@rOrgGroupId)
			AND (T.AccountId=@rAccountId )  
   Order By T.VoucherTypeId,T.VoucherNumber
END
GO
PRINT N'Creating [sAppraisal].[pConductViewGet]...';


GO

CREATE PROCEDURE [sAppraisal].[pConductViewGet]
	
	@rEmployeeId BIGINT=null,
	@rBatchId INT
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
		CONVERT(VARCHAR,CND.ConductDate,103)ConductDate
		,CTM.Title AS ConductType
		,CND.Title
		,CND.Remark 
		FROM [sAppraisal].[tConduct] AS CND
		INNER JOIN [sAppraisal].[tConductTypeMaster]       AS CTM ON CTM.Id=CND.ConductTypeId
		INNER JOIN [sAppraisal].[tConductIndicatorMaster]  AS CIM ON CIM.Id=CTM.ConductIndicatorId
	

	WHERE		((CND.BatchId=@rBatchId))
			AND ((CND.EmployeeId = @rEmployeeId) )
		
	ORDER BY 
	CND.ConductDate

END
GO
PRINT N'Creating [sBiometric].[pBiometricReportDataDateWise]...';


GO
CREATE PROCEDURE [sBiometric].[pBiometricReportDataDateWise]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rToDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId int = 0,
	 @rForYear int=0,
	 @rForMonth int=0,
	 @rIsFirstIn bit=0,
	 @rIsLastOut bit=0,
	 @rIsOT bit=0,
	 @rIsLateBy	bit=0,
	 @rIsEarlyBy bit=0,
	 @rIsDuration  bit=0,
	 @rGradeId nvarchar(200) = '0'
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

DECLARE @TableEmployee TABLE (Id int Identity,EmployeeID BigINT, OrganizationDepartmentId int, EmployeeTypeId Int)
INSERT INTO @TableEmployee
SELECT EM.Id AS EmployeeId,ED.OrganizationDepartmentId,ED.EmployeeTypeId from shrm.tEmployeeMaster EM 
LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = EM.Id 
Where (ED.OrganizationDepartmentId =@rOrganizationDepartmentId Or @rOrganizationDepartmentId= 0 )
AND (ED.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0 )
AND  EM.ORgId = @rOrgId 


DECLARE @lCount int
DECLARE @lCount1 int
Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lBatchID int
DECLARE @lEmployeeId bigint
DECLARE @lEmpCount int

DECLARE @TempDate TABLE(Id int identity,Idate date)
insert into @TempDate
SELECT  TOP (DATEDIFF(DAY, @rFromDate, @rToDate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @rFromDate)
FROM    sys.all_objects a CROSS JOIN sys.all_objects b;

CREATE TABLE #TempMonthTrans (Id int Identity,EmployeeId bigint,Attn_Date DateTime,DayNumber nvarchar(8),PresentStatus nvarchar(25),
		FirstIn nvarchar(20),LastOut nvarchar(20),OverTime nvarchar(20),LateBy nvarchar(20),Duration nvarchar(20),EarlyBy nvarchar(20))


SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1

Select @lCount = Max(Id) from @TempDate
Select @lEmpCount = Max(Id) from @TableEmployee

While (@lEmpCount > 0)
	BEGIN
		SELECT @lEmployeeId = EmployeeId From @TableEmployee Where Id = @lEmpCount	
	set @lCount1 = 0
	while (@lCount1 <= @lCount)
	begin		
		Select @lDate = Idate from @TempDate Where Id = @lCount1
		Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)
		set @lQuery = 'INSERT INTO #TempMonthTrans
						SELECT ' + convert(nvarchar(15),@lEmployeeId) + ',''' + convert(nvarchar(15),@lDate) + ''',
						substring(DATENAME( dw, ''' + convert(nvarchar(15),@lDate) + '''),1,3) AS DN1,
						CAse When [sHrm].[fWeekHOffHolidayGet](' + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',ED.OrganizationDepartmentId,' + convert(nvarchar(15),@rOrgId) + ') != ''-'' 
						Then [sHrm].[fWeekHOffHolidayGet](' + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',0,' + convert(nvarchar(15),@rOrgId) + ') 
						Else D'+convert(nvarchar(15),@lDay)+' End D'+convert(nvarchar(15),@lDay)+',D'+convert(nvarchar(15),@lDay)+'_IN,D'+convert(nvarchar(15),@lDay)+'_OUT,D'+convert(nvarchar(15),@lDay)+'_O,D'+convert(nvarchar(15),@lDay)+'_L,D'+convert(nvarchar(15),@lDay)+'_T,D'+convert(nvarchar(15),@lDay)+'_E 
						FROM sBiometric.tMonthTrans T1 
						LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId						
						WHERE T1.EmployeeId =' + convert(nvarchar(15),@lEmployeeId) + ' AND ATTN_DT >= cast(rtrim(YEAR(''' + convert(nvarchar(15),@lDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@lDate) + ''') *100+ 01) as datetime) 
						AND ATTN_DT <= cast(rtrim(YEAR(''' + convert(nvarchar(15),@lDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@lDate) + ''') *100+ 01) as datetime)'
			execute (@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1	
	END
	
	
	
	SET @strQuery = 'select Day(T.Attn_Date), T.*,isnull(A.TotAbsent,0) AS TotAbsent,isnull(TotEarly,0) + isnull(TotPresent,0) AS TotPresent,A1.TotWeekOff,
	isnull(TotHalfDay,0) AS TotHalfDay,Isnull(TotHoliday,0) AS TotHoliday,Isnull(CLLeave,0) AS CLLeave,Isnull(LeaveCode,'''') as LeaveCode,
	Emp.Code AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,
	DM.Displaytitle DeptName,
	' + convert(nvarchar(10),@rIsFirstIn) + ' AS IsFirstIn,
	' + convert(nvarchar(10),@rIsLastOut) + ' AS IsLastOut,
	' +  convert(nvarchar(10),@rIsOT) + ' AS IsOT,
	' +  convert(nvarchar(10),@rIsLateBy) + '	AS IsLateBy,
	' +  convert(nvarchar(10),@rIsEarlyBy) + ' AS IsEarlyBy,
	' +  convert(nvarchar(10),@rIsDuration) + '  AS IsDuration
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId
	LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Emp.Id 
	LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
	LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId 
	LEFT Join (Select COUNT(*) AS TotPresent,EmployeeId from #TempMonthTrans Where PresentStatus IN (''P'') group by EmployeeId,PresentStatus) A4 ON A4.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotEarly,EmployeeId from #TempMonthTrans Where PresentStatus IN (''E'') group by EmployeeId,PresentStatus) A6 ON A6.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotAbsent,EmployeeId from #TempMonthTrans Where PresentStatus Like ''A'' group by EmployeeId,PresentStatus) A ON A.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotWeekOff,EmployeeId from #TempMonthTrans Where PresentStatus Like ''W'' group by EmployeeId,PresentStatus) A1 ON A1.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like ''HD'' group by EmployeeId,PresentStatus) A3 ON A3.EmployeeId = T.employeeID
    LEFT Join (Select COUNT(*) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like ''H'' group by EmployeeId,PresentStatus) A5 ON A5.EmployeeId = T.employeeID		
	LEFT Join (Select sum(NoOfLeave) AS CLLeave,EmployeeId,LT.Code as LeaveCode from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId 
	Where FromDate>=''' + Convert(nvarchar(12),@rFromDate) + ''' AND FromDate<=''' + Convert(nvarchar(12),@rToDate) + ''' GRoup By EmployeeId,LT.Code ) AS LV ON LV.EmployeeId = T.EmployeeId
	WHERE 1=1 and (ED.EmployeeGradeId in (' + convert(nvarchar(100),@rGRadeId) + ') OR ' + convert(nvarchar(100),@rGRadeId) + ' = 0 )' 
	
	execute (@strQuery)
	
	DROP TABLE #TempMonthTrans
	--select  
	--@rBuilder1 as Builder1,
	--@rBuilder2 as Builder2,
	--'' as Attn_Date,
	--'' as EmployeeId,
	--'' as Attn_Date,
	--'' as DayNumber ,
	--'' as PresentStatus ,
	--'' as FirstIn,
	--'' as LastOut,
	--'' as OverTime,
	--'' as LateBy,
	--'' as Duration,
	--'' as EarlyBy,
	--'' as TotPresent,
	--'' as TotWeekOff,
	--'' as TotHalfDay,
	--'' as TotHoliday,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as IsFirstIn,
	--'' as IsLastOut,
	--'' as IsOT,
	--'' as IsLateBy,
	--'' as IsEarlyBy,
	--'' as IsDuration
END
GO
PRINT N'Creating [sConfig].[pConfigurationValueGet]...';


GO
CREATE PROCEDURE [sConfig].[pConfigurationValueGet] 
			
			@rOrgGroupId int,
			@rOrgId int,
			@rUserId bigint
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
		CM.ItemKey AS ItemKey,ISNULL(CS.ItemValue,CM.ItemValue) AS ItemValue
	FROM 
		sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=1016 AND SourceId = @rOrgId 
	WHERE 
		CM.ConfigurationLevelId = 1

	UNION ALL

	SELECT 
		CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)
	FROM 
		sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=95 AND SourceId = @rUserId  
	WHERE 
		CM.ConfigurationLevelId = 4

	UNION ALL

	SELECT 
		CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  
	FROM 
		sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=2010 AND SourceId = @rOrgGroupId  
	WHERE 
		CM.ConfigurationLevelId = 5
	
	UNION ALL

	SELECT 
		CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue)  
	FROM 
		sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id 
	WHERE 
		CM.ConfigurationLevelId = 6
END
GO
PRINT N'Creating [sHrm].[pEmployeeAttendanceViewGet]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeAttendanceViewGet]
	 
	@rForYear  bigint,
	@rBatchId int,
	@rOrgId int,
	@rEmployeeId bigint
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
       SELECT  
         DateName( month , DateAdd( month , WD.ForMonth , -1 )) As NameofMonth,
         ISNULL(WD.TotalDays,0) AS TotalDays,
         ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays,
         --ISNULL(AT.LWP,0) AS LWP,         
         ISNULL(AT.PaidLeave,0) AS PaidLeave,
         CONVERT(DECIMAL(12,2),(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
		  ISNULL(AT.TotalWorkingDays,0) -(CONVERT(DECIMAL(12,2),(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)))) AS AbsentDays
     

        FROM 
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND  WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId		 
		AND AT.ForMonth=WD.ForMonth AND AT.ForYear=@rForYear AND AT.BatchId = @rBatchId
    	WHERE EM.OrgID = @rOrgId 
		 AND EM.EmployeeId=@rEmployeeId AND AT.EmployeeId=@rEmployeeId
	    -- AND EM.EmployeeId=1101000000039 AND AT.EmployeeId=1101000000039
    	ORDER BY EM.Code
END
GO
PRINT N'Creating [sHrm].[pRpt EmpLeavePresenceOLD]...';


GO

 
CREATE PROCEDURE [sHrm].[pRpt EmpLeavePresenceOLD]
	 
		@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,
		@rFromDate date,
	    @rToDate date
	
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,
			ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays,
			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) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) 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) 
				AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    	        AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
	   	    ) 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) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) 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) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) 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) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) 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)
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')='')) 
		   	) 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
			LEFT JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.OrgId=EM.OrgID 
			LEFT JOIN sHrm.tWorkingDays WD ON WD.EmployeeGradeId = EGM.Id
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=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 ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		ORDER BY EM.Code
END
GO
PRINT N'Creating [sHrm].[pRptEmpLeavePresence]...';


GO

 
CREATE PROCEDURE [sHrm].[pRptEmpLeavePresence]
	 
		@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,
		@rFromDate date = null,
	    @rToDate date=null
	
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,
			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,
			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) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) 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) 
				AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    	        AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
	   	    ) 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) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) 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) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) 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) 
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
		   	) 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)
					AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    				AND ((L.ToDate<=@rToDate) OR (ISNULL(@rToDate,'')='')) 
		   	) 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
			inner JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.OrgId=EM.OrgID AND EM.EmployeeGradeId = EGM.Id 
			LEFT JOIN sHrm.tWorkingDays WD ON WD.EmployeeGradeId = EGM.Id AND
			WD.ForYear = @rForYear AND WD.forMonth = @rForMonth
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			AND AT.ForYear = @rForYear AND AT.forMonth = @rForMonth
			
			
    	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'Creating [sSecurity].[pAppPermissionGet]...';


GO
CREATE PROCEDURE [sSecurity].[pAppPermissionGet]
	@rOrgGroupId [int],
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@rOrgGroupId)
	BEGIN
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(20075,20086,20094,20107,20126,20171,20184,20538,20561,20983,30032)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(20075,20086,20094,20107,20126,20171,20184,20538,20561,20983,30032)
		) TP 
		GROUP BY TP.TaskId
	END
END
GO
PRINT N'Creating [sSecurity].[pRolewisePermissionGet]...';


GO
CREATE PROCEDURE [sSecurity].[pRolewisePermissionGet]
	
	@rModuleId smallint,
	@rResourceTypeId smallint,
	@rTaskId smallint,		
	@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		SELECT  
			R.Id,
			R.Title,
			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.tRole R
			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL)
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId 
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId=@rTaskId
				AND OT.OrgGroupId = R.OrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id	
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId		
		ORDER BY 			
			T.ModuleId
END
GO
PRINT N'Creating [sSecurity].[pTaskPermissionGet]...';


GO
CREATE PROCEDURE [sSecurity].[pTaskPermissionGet]
	
	@rModuleId smallint,
	@rResourceTypeId smallint,
	@rTaskId smallint,		
	@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		SELECT  
			R.Id,
			R.Title,
			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.tRole R
			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL)
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId 
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)
			LEFT JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id 
				AND OT.OrgGroupId = @rOrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId		
		ORDER BY 			
			T.ModuleId
END
GO
PRINT N'Creating [sSetup].[pPortalAssignRouteUpdate]...';


GO
CREATE PROCEDURE [sSetup].[pPortalAssignRouteUpdate]
	 
	@rStrXml [nvarchar](max),
	@rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	
	 
	 DELETE AR FROM sTransport.tAssignRoute AR 
	 INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId 
	 INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId 
	 WHERE BRM.OrgGroupBatchId = @rOrgGroupBatchId
	 
	 BEGIN	
		
		 INSERT INTO sTransport.tAssignRoute
		(
			[SourceTypeId],
			[SourceId],
			[PickupDestinationId],
			[DropDestinationId] 
			)
		SELECT		
			[SourceTypeId],
			[SourceId],
			[PickupDestinationId],
			[DropDestinationId]
			 
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[SourceTypeId] [smallint],
				[SourceId] [bigint],
				[PickupDestinationId] [int],
				[DropDestinationId] [int]
			  )  
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalBusRouteDestinationMasterUpdate]...';


GO
CREATE PROCEDURE [sSetup].[pPortalBusRouteDestinationMasterUpdate]
	 
	@rStrXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sTransport.tBusRouteDestinationMaster
		SET
			[Id]=A.Id,
			[BusRouteId]=A.BusRouteId,
			[Title]=A.Title,
			[Amount]=A.Amount,
			[OrderIndex]=A.OrderIndex,
			[IsObsolete]=A.IsObsolete,
			[CreatedUserId]=A.CreatedUserId,
			[CreatedDateTime]=A.CreatedDateTime,
			[UpdatedUserId]=A.UpdatedUserId,
			[UpdatedDateTime]=A.UpdatedDateTime,
			[OrgGroupId]=A.OrgGroupId,
			[PickupTime]=A.PickupTime,
			[DropTime]=A.DropTime,
			[OldImportBusRouteDestinationId]=A.OldImportBusRouteDestinationId
		 
		 FROM
		 (
		SELECT		
			[Id],
			[BusRouteId],
			[Title],
			[Amount],
			[OrderIndex],
			[IsObsolete],
			[CreatedUserId],
			[CreatedDateTime],
			[UpdatedUserId],
			[UpdatedDateTime],
			[OrgGroupId],
			[PickupTime],
			[DropTime],
			[OldImportBusRouteDestinationId]
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [int],
				[BusRouteId] [int],
				[Title] [nvarchar](10),
				[Amount] [decimal](12,2),
				[OrderIndex] [smallint],
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[OrgGroupId] [int],
				[PickupTime] [nvarchar](50),
				[DropTime] [nvarchar](50),
				[OldImportBusRouteDestinationId] [int]
			  )) A
			  WHERE sTransport.tBusRouteDestinationMaster.Id = A.Id
		
		
		
		 INSERT INTO sTransport.tBusRouteDestinationMaster
		(
			[Id],
			[BusRouteId],
			[Title],
			[Amount],
			[OrderIndex],
			[IsObsolete],
			[CreatedUserId],
			[CreatedDateTime],
			[UpdatedUserId],
			[UpdatedDateTime],
			[OrgGroupId],
			[PickupTime],
			[DropTime],
			[OldImportBusRouteDestinationId]
			)
		SELECT		
			A.[Id],
			A.[BusRouteId],
			A.[Title],
			A.[Amount],
			A.[OrderIndex],
			A.[IsObsolete],
			A.[CreatedUserId],
			A.[CreatedDateTime],
			A.[UpdatedUserId],
			A.[UpdatedDateTime],
			A.[OrgGroupId],
			A.[PickupTime],
			A.[DropTime],
			A.[OldImportBusRouteDestinationId]
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [int],
				[BusRouteId] [int],
				[Title] [nvarchar](10),
				[Amount] [decimal](12,2),
				[OrderIndex] [smallint],
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[OrgGroupId] [int],
				[PickupTime] [nvarchar](50),
				[DropTime] [nvarchar](50),
				[OldImportBusRouteDestinationId] [int]
			  ) A LEFT JOIN sTransport.tBusRouteDestinationMaster BM
			  ON A.Id = BM.Id WHERE BM.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalBusRouteMasterUpdate]...';


GO
CREATE PROCEDURE [sSetup].[pPortalBusRouteMasterUpdate]
	 
	@rStrXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sTransport.tBusRouteMaster
		SET
			[Id]=A.Id,
			[Title]=A.Title,
			[Remark]=A.Remark,
			[DriverName]=A.DriverName,
			[DriverMobileNo]=A.DriverMobileNo,
			[ConductorName]=A.ConductorName,
			[ConductorMobileNo]=A.ConductorMobileNo,
			[VehicleId]=A.VehicleId,
			[OrderIndex]=A.OrderIndex,
			[IsObsolete]=A.IsObsolete,
			[CreatedUserId]=A.CreatedUserId,
			[CreatedDateTime]=A.CreatedDateTime,
			[UpdatedUserId]=A.UpdatedUserId,
			[UpdatedDateTime]=A.UpdatedDateTime,
			[OrgGroupBatchId]=A.OrgGroupBatchId,
			[OrgGroupId]=A.OrgGroupId,
			[RouteCode]=A.RouteCode,
			[RouteNumber]=A.RouteNumber,
			[TransportId]=A.TransportId,
			[OldImportBusRouteId]=A.OldImportBusRouteId,
			[VTSSubUserName]=A.VTSSubUserName,
			[VTSSubUserPassword]=A.VTSSubUserPassword
		 
		 FROM
		 (
		SELECT		
			[Id],
			[Title],
			[Remark],
			[DriverName],
			[DriverMobileNo],
			[ConductorName],
			[ConductorMobileNo],
			[VehicleId],
			[OrderIndex],
			[IsObsolete],
			[CreatedUserId],
			[CreatedDateTime],
			[UpdatedUserId],
			[UpdatedDateTime],
			[OrgGroupBatchId],
			[OrgGroupId],
			[RouteCode],
			[RouteNumber],
			[TransportId],
			[OldImportBusRouteId],
			[VTSSubUserName],
			[VTSSubUserPassword]
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [int],
				[Title] [nvarchar](100),
				[Remark] [nvarchar](100),
				[DriverName] [nvarchar](50),
				[DriverMobileNo] [nvarchar](20),
				[ConductorName] [nvarchar](50),
				[ConductorMobileNo] [nvarchar](20),
				[VehicleId] [int],
				[OrderIndex] [smallint],
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[OrgGroupBatchId] [int],
				[OrgGroupId] [int],
				[RouteCode] [nvarchar](50),
				[RouteNumber] [int],
				[TransportId] [int],
				[OldImportBusRouteId] [int],
				[VTSSubUserName] [nvarchar](50),
				[VTSSubUserPassword] [nvarchar](50)
			  )) A
			  WHERE sTransport.tBusRouteMaster.Id = A.Id
		
		
		
		 INSERT INTO sTransport.tBusRouteMaster
		(
			[Id],
			[Title],
			[Remark],
			[DriverName],
			[DriverMobileNo],
			[ConductorName],
			[ConductorMobileNo],
			[VehicleId],
			[OrderIndex],
			[IsObsolete],
			[CreatedUserId],
			[CreatedDateTime],
			[UpdatedUserId],
			[UpdatedDateTime],
			[OrgGroupBatchId],
			[OrgGroupId],
			[RouteCode],
			[RouteNumber],
			[TransportId],
			[OldImportBusRouteId],
			[VTSSubUserName],
			[VTSSubUserPassword]
			)
		SELECT		
			A.[Id],
			A.[Title],
			A.[Remark],
			A.[DriverName],
			A.[DriverMobileNo],
			A.[ConductorName],
			A.[ConductorMobileNo],
			A.[VehicleId],
			A.[OrderIndex],
			A.[IsObsolete],
			A.[CreatedUserId],
			A.[CreatedDateTime],
			A.[UpdatedUserId],
			A.[UpdatedDateTime],
			A.[OrgGroupBatchId],
			A.[OrgGroupId],
			A.[RouteCode],
			A.[RouteNumber],
			A.[TransportId],
			A.[OldImportBusRouteId],
			A.[VTSSubUserName],
			A.[VTSSubUserPassword]
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [int],
				[Title] [nvarchar](100),
				[Remark] [nvarchar](100),
				[DriverName] [nvarchar](50),
				[DriverMobileNo] [nvarchar](20),
				[ConductorName] [nvarchar](50),
				[ConductorMobileNo] [nvarchar](20),
				[VehicleId] [int],
				[OrderIndex] [smallint],
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[OrgGroupBatchId] [int],
				[OrgGroupId] [int],
				[RouteCode] [nvarchar](50),
				[RouteNumber] [int],
				[TransportId] [int],
				[OldImportBusRouteId] [int],
				[VTSSubUserName] [nvarchar](50),
				[VTSSubUserPassword] [nvarchar](50)
			  ) A LEFT JOIN sTransport.tBusRouteMaster BM
			  ON A.Id = BM.Id WHERE BM.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalFuelTypeMasterUpdate]...';


GO
CREATE PROCEDURE [sSetup].[pPortalFuelTypeMasterUpdate]
	 
	@rStrXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sTransport.tFuelTypeMaster
		SET
			[OrgGroupId] = A.OrgGroupId,
	        [Id] = A.Id,
			[Code] = A.Code,
			[Title] = A.Title,
			[IsObsolete] = A.IsObsolete,
			[CreatedUserId] = A.CreatedUserId,
			[CreatedDateTime] = A.CreatedDateTime,
			[UpdatedUserId] = A.UpdatedUserId,
			[UpdatedDateTime] = A.UpdatedDateTime
		 
		 FROM
		 (
		SELECT		
			[OrgGroupId],
	        [Id],
			[Code],
			[Title],
			[IsObsolete],
			[CreatedUserId],
			[CreatedDateTime],
			[UpdatedUserId],
			[UpdatedDateTime]
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgGroupId] [smallint],
				[Id] [int],
				[Code] [nvarchar](20),
				[Title] [nvarchar](100),
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  )) A
			  WHERE sTransport.tFuelTypeMaster.Id = A.Id
		
		
		
		 INSERT INTO sTransport.tFuelTypeMaster
		(
			[OrgGroupId],
	        [Id],
			[Code],
			[Title],
			[IsObsolete],
			[CreatedUserId],
			[CreatedDateTime],
			[UpdatedUserId],
			[UpdatedDateTime]
			)
		SELECT		
			A.[OrgGroupId],
	        A.[Id],
			A.[Code],
			A.[Title],
			A.[IsObsolete],
			A.[CreatedUserId],
			A.[CreatedDateTime],
			A.[UpdatedUserId],
			A.[UpdatedDateTime]
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgGroupId] [smallint],
				[Id] [int],
				[Code] [nvarchar](20),
				[Title] [nvarchar](100),
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  ) A LEFT JOIN sTransport.tFuelTypeMaster BM
			  ON A.Id = BM.Id WHERE BM.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalTransportMasterUpdate]...';


GO
CREATE PROCEDURE [sSetup].[pPortalTransportMasterUpdate]
	 
	@rStrXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sTransport.tTransportMaster
		SET
			[OrgGroupId] = A.OrgGroupId,
	        [Id] = A.Id,
			[Number] = A.Number,
			[Code] = A.Code,
			[Title] = A.Title,
			[IsObsolete] = A.IsObsolete,
			[CreatedUserId] = A.CreatedUserId,
			[CreatedDateTime] = A.CreatedDateTime,
			[UpdatedUserId] = A.UpdatedUserId,
			[UpdatedDateTime] = A.UpdatedDateTime
		 
		 FROM
		 (
		SELECT		
			[OrgGroupId],
	        [Id],
			[Number],
			[Code],
			[Title],
			[IsObsolete],
			[CreatedUserId],
			[CreatedDateTime],
			[UpdatedUserId],
			[UpdatedDateTime]
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgGroupId] [smallint],
				[Id] [int],
				[Number] [int],
				[Code] [nvarchar](20),
				[Title] [nvarchar](100),
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  )) A
			  WHERE sTransport.tTransportMaster.Id = A.Id
		
		
		
		 INSERT INTO sTransport.tTransportMaster
		(
			[OrgGroupId],
	        [Id],
			[Number],
			[Code],
			[Title],
			[IsObsolete],
			[CreatedUserId],
			[CreatedDateTime],
			[UpdatedUserId],
			[UpdatedDateTime]
			)
		SELECT		
			A.[OrgGroupId],
	        A.[Id],
			A.[Number],
			A.[Code],
			A.[Title],
			A.[IsObsolete],
			A.[CreatedUserId],
			A.[CreatedDateTime],
			A.[UpdatedUserId],
			A.[UpdatedDateTime]
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgGroupId] [smallint],
				[Id] [int],
				[Number] [int],
				[Code] [nvarchar](20),
				[Title] [nvarchar](100),
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  ) A LEFT JOIN sTransport.tTransportMaster BM
			  ON A.Id = BM.Id WHERE BM.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalVehicleMasterUpdate]...';


GO
CREATE PROCEDURE [sSetup].[pPortalVehicleMasterUpdate]
	 
	@rStrXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sTransport.tVehicleMaster
		SET
			[Id]=A.Id,
			[Title]=A.Title,
			[RegistrationNumber]=A.RegistrationNumber,
			[NoOfSeats]=A.NoOfSeats,
			[IsObsolete]=A.IsObsolete,
			[CreatedUserId]=A.CreatedUserId,
			[CreatedDateTime]=A.CreatedDateTime,
			[UpdatedUserId]=A.UpdatedUserId,
			[UpdatedDateTime]=A.UpdatedDateTime,
			[OrgGroupId]=A.OrgGroupId,
			[LastServiceDate]=A.LastServiceDate,
			[NextServiceDate]=A.NextServiceDate,
			[FuelTypeId]=A.FuelTypeId,
			[ServiceCenter]=A.ServiceCenter,
			[ServiceCenterContact]=A.ServiceCenterContact,
			[VehicleTypeId]=A.VehicleTypeId,
			[TransportId]=A.TransportId
				 
		 FROM
		 (
		SELECT		
			[Id],
			[Title],
			[RegistrationNumber],
			[NoOfSeats],
			[IsObsolete],
			[CreatedUserId],
			[CreatedDateTime],
			[UpdatedUserId],
			[UpdatedDateTime],
			[OrgGroupId],
			[LastServiceDate],
			[NextServiceDate],
			[FuelTypeId],
			[ServiceCenter],
			[ServiceCenterContact],
			[VehicleTypeId],
			[TransportId]
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [int],
				[Title] [nvarchar](100),
				[RegistrationNumber] [nvarchar](100),
				[NoOfSeats] [tinyint],
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[OrgGroupId] [smallint],
				[LastServiceDate] [date],
				[NextServiceDate] [date],
				[FuelTypeId] [int],
				[ServiceCenter] [nvarchar](200),
				[ServiceCenterContact] [nvarchar](50),
				[VehicleTypeId] [int],
				[TransportId] [int]
			  )) A
			  WHERE sTransport.tVehicleMaster.Id = A.Id
		
		
		
		 INSERT INTO sTransport.tVehicleMaster
		(
			[Id],
			[Title],
			[RegistrationNumber],
			[NoOfSeats],
			[IsObsolete],
			[CreatedUserId],
			[CreatedDateTime],
			[UpdatedUserId],
			[UpdatedDateTime],
			[OrgGroupId],
			[LastServiceDate],
			[NextServiceDate],
			[FuelTypeId],
			[ServiceCenter],
			[ServiceCenterContact],
			[VehicleTypeId],
			[TransportId]
			)
		SELECT		
			A.[Id],
			A.[Title],
			A.[RegistrationNumber],
			A.[NoOfSeats],
			A.[IsObsolete],
			A.[CreatedUserId],
			A.[CreatedDateTime],
			A.[UpdatedUserId],
			A.[UpdatedDateTime],
			A.[OrgGroupId],
			A.[LastServiceDate],
			A.[NextServiceDate],
			A.[FuelTypeId],
			A.[ServiceCenter],
			A.[ServiceCenterContact],
			A.[VehicleTypeId],
			A.[TransportId]
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [int],
				[Title] [nvarchar](100),
				[RegistrationNumber] [nvarchar](100),
				[NoOfSeats] [tinyint],
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[OrgGroupId] [smallint],
				[LastServiceDate] [date],
				[NextServiceDate] [date],
				[FuelTypeId] [int],
				[ServiceCenter] [nvarchar](200),
				[ServiceCenterContact] [nvarchar](50),
				[VehicleTypeId] [int],
				[TransportId] [int]
			  ) A LEFT JOIN sTransport.tVehicleMaster BM
			  ON A.Id = BM.Id WHERE BM.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sSetup].[pPortalVehicleTypeMasterUpdate]...';


GO
CREATE  PROCEDURE [sSetup].[pPortalVehicleTypeMasterUpdate]
	 
	@rStrXml [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sTransport.tVehicleTypeMaster
		SET
			[OrgGroupId] = A.OrgGroupId,
	        [Id] = A.Id,
			[Code] = A.Code,
			[Title] = A.Title,
			[IsObsolete] = A.IsObsolete,
			[CreatedUserId] = A.CreatedUserId,
			[CreatedDateTime] = A.CreatedDateTime,
			[UpdatedUserId] = A.UpdatedUserId,
			[UpdatedDateTime] = A.UpdatedDateTime
		 
		 FROM
		 (
		SELECT		
			[OrgGroupId],
	        [Id],
			[Code],
			[Title],
			[IsObsolete],
			[CreatedUserId],
			[CreatedDateTime],
			[UpdatedUserId],
			[UpdatedDateTime]
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgGroupId] [smallint],
				[Id] [int],
				[Code] [nvarchar](20),
				[Title] [nvarchar](100),
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  )) A
			  WHERE sTransport.tVehicleTypeMaster.Id = A.Id
		
		
		
		 INSERT INTO sTransport.tVehicleTypeMaster
		(
			[OrgGroupId],
	        [Id],
			[Code],
			[Title],
			[IsObsolete],
			[CreatedUserId],
			[CreatedDateTime],
			[UpdatedUserId],
			[UpdatedDateTime]
			)
		SELECT		
			A.[OrgGroupId],
	        A.[Id],
			A.[Code],
			A.[Title],
			A.[IsObsolete],
			A.[CreatedUserId],
			A.[CreatedDateTime],
			A.[UpdatedUserId],
			A.[UpdatedDateTime]
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgGroupId] [smallint],
				[Id] [int],
				[Code] [nvarchar](20),
				[Title] [nvarchar](100),
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  ) A LEFT JOIN sTransport.tVehicleTypeMaster BM
			  ON A.Id = BM.Id WHERE BM.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sTimetable].[pRptFreePeriodLectureWiseTimetableGet]...';


GO

CREATE PROCEDURE [sTimetable].[pRptFreePeriodLectureWiseTimetableGet]
	  
	@rTimeTableSchemaId int		 
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 
			DECLARE @lCount int			
			DECLARE @lDayCount smallint
			DECLARE @lEmployeeId bigint
			DECLARE @lDayId int,@lLectureNumber Int
			DECLARE @EmployeeIdList nvarchar(500)
			
  
			
			--INSERT INTO @TimeTableEmp SELECT DISTINCT EmployeeId FROM sTimeTable.tTimetable 
			--WHERE TimeTableSchemaId = @rTimeTableSchemaId  and EmployeeId <> 0
			
			DECLARE @DayMaster TABLE (Id int identity,DayId INT ,LectureNumber Int)
			Insert Into  @DayMaster SELECT DISTINCT TT.DayId,TT.LectureNumber FROM sTimetable.tTimeTable TT
			--INNER JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
			WHERE TimeTableSchemaId=@rTimeTableSchemaId ORDER BY DayId,LectureNumber

			Select @lDayCount = Max(Id) From @DayMaster
			
						
While @lDayCount >  0
  BEGIN			
		SELECT @lDayId=DayId,@lLectureNumber=LectureNumber FROM @DayMaster WHERE Id=@lDayCount  
		
		DECLARE @TimeTableEmp TABLE (Id INT identity, EmployeeId Bigint)
		Insert into @TimeTableEmp SELECT Distinct EmployeeId from sTimetable.tTimeTable 
		WHERE LectureNumber= @lLectureNumber AND DayId= @lDayId     AND TimeTableSchemaId =@rTimeTableSchemaId				
					
		DECLARE @FreeLectureTable TABLE (Id int identity,EmployeeId nvarchar(1000),DayId int ,LectureNumber int)			
		Insert Into  @FreeLectureTable Select Distinct  stuff((
			Select ',' + REplace(EM.FirstName,'''','') + ' '+ REplace(EM.LastName,'''','')
			From sTimetable.tTimeTable TT
			Inner Join sHRM.tEmployeeMaster EM ON EM.Id =TT.EmployeeId
			Where EmployeeId not in (select EmployeeID from @TimeTableEmp) AND LectureNumber= @lLectureNumber AND DayId= @lDayId      
				  for xml path('')),1,1,'') as userlist,Dayid,LectureNumber
			From sTimetable.tTimeTable WHERE LectureNumber= @lLectureNumber AND DayId= @lDayId      
			Group By EmployeeId,LectureNumber,DayId
		
	  SET @lDayCount = @lDayCount - 1
END  

Select Temp.EmployeeId,Temp.DayId,DM.Title,Temp.LectureNumber From @FreeLectureTable Temp 
inner join sCommon.tDayMaster DM ON DM.Id = Temp.DayId
ORDER By DM.Id,Temp.LectureNumber
	
END
GO

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