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

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


GO
ALTER TABLE [sAcademic].[tLessonPlan]
    ADD [SubTopic] NVARCHAR (1000) NULL;


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


GO
ALTER TABLE [sAcademic].[tPreLessonPlan]
    ADD [TopicId]  INT             NULL,
        [SubTopic] NVARCHAR (1000) NULL;


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


GO
ALTER TABLE [sErp].[tLeadMaster]
    ADD [district]             NVARCHAR (50)  NULL,
        [ContactPerson2]       NVARCHAR (100) NULL,
        [ContactMobileNo2]     NVARCHAR (50)  NULL,
        [ContactDesignation2]  NVARCHAR (100) NULL,
        [ContactEmail2]        NVARCHAR (100) NULL,
        [ContactPerson3]       NVARCHAR (100) NULL,
        [ContactMobileNo3]     NVARCHAR (50)  NULL,
        [ContactDesignation3]  NVARCHAR (100) NULL,
        [ContactEmail3]        NVARCHAR (100) NULL,
        [ContactPerson4]       NVARCHAR (100) NULL,
        [ContactMobileNo4]     NVARCHAR (50)  NULL,
        [ContactDesignation4]  NVARCHAR (100) NULL,
        [ContactEmail4]        NVARCHAR (100) NULL,
        [ContactPerson5]       NVARCHAR (100) NULL,
        [ContactMobileNo5]     NVARCHAR (50)  NULL,
        [ContactDesignation5]  NVARCHAR (100) NULL,
        [ContactEmail5]        NVARCHAR (100) NULL,
        [LeadChannelPartnerId] INT            NULL;


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


GO
ALTER TABLE [sFee].[tFeeFollowup]
    ADD [NextFollowupDate] DATE NULL;


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


GO
ALTER TABLE [sFee].[tReceiptBookMaster]
    ADD [IsDisplayTransportDetail] BIT NULL;


GO
PRINT N'Altering [sOp].[tGatewayConfiguration]...';


GO
ALTER TABLE [sOp].[tGatewayConfiguration]
    ADD [IsObsolete] BIT NULL;


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


GO
ALTER TABLE [sOp].[tGatewayProduct]
    ADD [PayUMoneyAUTHHEADER] NVARCHAR (50) NULL;


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


GO
ALTER TABLE [sProcurement].[tStockAdjustment]
    ADD [TransactionDate] DATE NULL;


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


GO
ALTER TABLE [sProcurement].[tStockInward]
    ADD [TransactionDate] DATE NULL;


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


GO
ALTER TABLE [sProcurement].[tStockInwardReturn]
    ADD [TransactionDate] DATE NULL;


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


GO
ALTER TABLE [sProcurement].[tStockIssue]
    ADD [TransactionDate] DATE NULL;


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


GO
ALTER TABLE [sProcurement].[tStockIssueReturn]
    ADD [TransactionDate] DATE NULL;


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


GO
ALTER TABLE [sProcurement].[tStockReset]
    ADD [TransactionDate] DATE NULL;


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


GO
ALTER TABLE [sSetup].[tOrganizationMaster]
    ADD [district] NVARCHAR (50) NULL;


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


GO
CREATE TABLE [sErp].[tLeadChannelPartnerMaster] (
    [Id]              INT            NOT NULL,
    [OrgId]           SMALLINT       NULL,
    [Title]           NVARCHAR (200) NOT NULL,
    [IsActive]        BIT            NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);


GO
PRINT N'Creating PK_tChannelPartnerMaster_1...';


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


GO
PRINT N'Creating PK_tOtherLocationSourceTypeMaster...';


GO
ALTER TABLE [sProcurement].[tOtherLocationSourceTypeMaster]
    ADD CONSTRAINT [PK_tOtherLocationSourceTypeMaster] 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

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   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 AND EA.SourceTypeId = 2005 WHERE ES.BatchId = @rBatchId AND ((DM.Id=@rClassId) OR (@rClassId=0)) 
			AND (@lDate BETWEEN ES.FromDate AND ES.ToDate) AND ES.IsHoliday=1)  
	BEGIN
		 SET @rStatus = 'H'	
	END
	
	-- Student First Week Off Rule
	if @StudentFirstWeekOffRule = 1 
	BEGIN
		if(@lWeekOff = @lWeekDay1)
		BEGIN
			Set @rStatus = 'W'
		END		
	END
	Else if @StudentFirstWeekOffRule = 2 
	BEGIN				     
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'			
			END
		END
	END
	else if @StudentFirstWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentFirstWeekOffRule = 4
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'			
			END
		END
	END
	else if @StudentFirstWeekOffRule = 5
	BEGIN
		if @WeekNumber = 2 or @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'			
			END
		END
	END
	else if @StudentFirstWeekOffRule = 6
	BEGIN
		if @WeekNumber = 1
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentFirstWeekOffRule = 7
	BEGIN
		if @WeekNumber = 2
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentFirstWeekOffRule = 8
	BEGIN
		if @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentFirstWeekOffRule = 9
	BEGIN
		if @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	
	-- Student Second Week Off Rule   
	if @StudentSecondWeekOffRule = 1 
	BEGIN	 
		if(@lWeekOff = @lWeekDay2)
		BEGIN
			Set @rStatus = 'W'
		END			
	END
	Else if @StudentSecondWeekOffRule = 2 
	BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN			 
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentSecondWeekOffRule = 3
	BEGIN
		
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentSecondWeekOffRule = 4
	BEGIN
	
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentSecondWeekOffRule = 5
	BEGIN
	
		if @WeekNumber = 2 or @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentSecondWeekOffRule = 6
	BEGIN
	
		if @WeekNumber = 1
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentSecondWeekOffRule = 7
	BEGIN
		if @WeekNumber = 2
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentSecondWeekOffRule = 8
	BEGIN
		if @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	else if @StudentSecondWeekOffRule = 9
	BEGIN
		if @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @rStatus = 'W'				
			END
		END
	END
	END
	RETURN @rStatus	
END
GO
PRINT N'Altering [sHrm].[fMonthWiseNoOfLeave]...';


GO
ALTER FUNCTION [sHrm].[fMonthWiseNoOfLeave](@rType bit, @rFromDate Date,@rTodate Date,@rForMonth int,@rForYear int, @rLeavePeriodId int,@rLaveTypeId int)
RETURNS  DECIMAL(12,2)       

  WITH EXECUTE AS CALLER
AS 
BEGIN    
         DECLARE @rTempFromDate date
		 DECLARE @rDays  DECIMAL(12,2)
         DECLARE @rIsLWP bit
         
         SELECT @rIsLWP = IsLWP from sHrm.tLeaveTypeMaster Where Id = @rLaveTypeId
         
         IF(@rIsLWP = @rType)
		 BEGIN
			 SET @rTempFromDate = @rFromDate
		 
			IF(DATEPART(MONTH,@rFromDate) = DATEPART(MONTH,@rTodate)) 
				SET @rTempFromDate = @rFromDate
			ELSE IF(DATEPART(MONTH,@rFromDate) = @rForMonth)
				SET @rTempFromDate = @rFromDate
			ELSE IF(DATEPART(MONTH,@rToDate) = @rForMonth) 
			BEGIN
				SELECT @rTempFromDate = CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@rToDate)-1),@rToDate),101) 
			END
		 
			;WITH c(d) AS
			(
				SELECT TOP (DATEDIFF(DAY, @rTempFromDate, @rTodate)+1)
				DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY name)-1, @rTempFromDate)
				FROM sys.all_columns
				WHERE DATEPART(MONTH,@rTempFromDate)=@rForMonth 
			) 
			SELECT    
			@rDays = COUNT(*)
			FROM c WHERE DATEPART(MONTH,(DATEADD(MONTH, DATEDIFF(MONTH, 0, d), 0))) = @rForMonth
			AND DATEPART(YEAR,(DATEADD(MONTH, DATEDIFF(MONTH, 0, d), 0))) = @rForYear
			GROUP BY DATEDIFF(MONTH, 0, d)	 
    
			IF(@rLeavePeriodId = 2)
			   SET  @rDays = (@rDays /2)
			IF(@rLeavePeriodId = 3)
			   SET  @rDays = (@rDays /4)
			END
		ELSE
		BEGIN
			SET @rDays = 0
		END
		RETURN  @rDays
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)
	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   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 AND EA.SourceTypeId = 2004 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'	
	END	
		
	-- Emp First Week Of fRule
	if @EmpFirstWeekOffRule = 1 
	BEGIN
		if(@lWeekOff = @lWeekDay1)
		BEGIN	
			Set @lStatus = 'W'
		END 					 
	END
	Else if @EmpFirstWeekOffRule = 2 
		BEGIN
		IF @WeekNumber = 2 or @WeekNumber = 4 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'				
			END
		END
		END
	else if @EmpFirstWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'							 
			END
	END
	END
	else if @EmpFirstWeekOffRule = 4
	BEGIN
		   
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
		if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'			
			END
	END
	END
	else if @EmpFirstWeekOffRule = 5
	BEGIN		   
		if @WeekNumber = 2 or @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
			END	
		END
	END
	else if @EmpFirstWeekOffRule = 6
	BEGIN		   
		if @WeekNumber = 1
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
			END
		END	
	 END
	else if @EmpFirstWeekOffRule = 7
	BEGIN		   
		if @WeekNumber = 2
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
			END
		END
	END	
	else if @EmpFirstWeekOffRule = 8
	BEGIN
		   
		if @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'				
			END
		END
	END
	else if @EmpFirstWeekOffRule = 9
	BEGIN		   
		if @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay1)
			BEGIN
				Set @lStatus = 'W'
			END
		END
	END
	
	-- Emp Second Week Off Rule
	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'
			END
		END
	END
	else if @EmpSecondWeekOffRule = 3
	BEGIN
		if @WeekNumber = 1 or @WeekNumber = 3 
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
			END
		END	
	END
	else if @EmpSecondWeekOffRule = 4
	BEGIN
		 
		if @WeekNumber = 1 or @WeekNumber = 3 or @WeekNumber = 5
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
			END	
		END
	END
	else if @EmpSecondWeekOffRule = 5
	BEGIN		 
		if @WeekNumber = 2 or @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
			END	
		END
	END
	else if @EmpSecondWeekOffRule = 6
	BEGIN		 
		if @WeekNumber = 1
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'				
			END
		END				
	END
	else if @EmpSecondWeekOffRule = 7
	BEGIN		 
		if @WeekNumber = 2
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'				
			END
		END
	END
	else if @EmpSecondWeekOffRule = 8
	BEGIN		 
		if @WeekNumber = 3
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
			END				
		END
	END
	else if @EmpSecondWeekOffRule = 9
	BEGIN		 
		if @WeekNumber = 4
		BEGIN
			if(@lWeekOff = @lWeekDay2)
			BEGIN
				Set @lStatus = 'W'
			END
		END
	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
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 [sConfig].[fDisplayFieldLessionGet]...';


GO


ALTER FUNCTION [sConfig].[fDisplayFieldLessionGet](@rOrgId int)
RETURNS  @List TABLE (
		 IsObjective bit,
		 IsSummary bit,
		 IsLearningExperience bit,
		 IsEssentialMaterial bit,
		 IsToolsTechniques bit,
		 IsIndicativeHomework bit,
		 IsAssessmentQuestion bit,
		 IsTeacherExample bit,
		 IsGuidedPractice bit,
		 IsIndependentPractice bit,
		 IsSubTopicSelect bit,
		 IsSubTopicText bit,
		 OrgId smallint 
		 
)  WITH EXECUTE AS CALLER
AS 
BEGIN

    declare @rIsObjective bit 
	declare @rIsSummary bit 
    declare @rIsLearningExperience bit
    declare @rIsEssentialMaterial bit 
    declare @rIsToolsTechniques bit
    declare @rIsIndicativeHomework bit 
    declare @rIsAssessmentQuestion bit 
    declare @rIsTeacherExample bit 
    declare @rIsGuidedPractice bit 
    declare @rIsIndependentPractice bit
    declare @rIsSubTopicSelect bit
    declare @rIsSubTopicText bit
   
	select @rIsObjective=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 201
	select @rIsSummary=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 203
	select @rIsLearningExperience =DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 202
	select @rIsEssentialMaterial=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 204
	select @rIsToolsTechniques=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 205
	select @rIsIndicativeHomework=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 206
	select @rIsAssessmentQuestion=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 207
	select @rIsTeacherExample=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 208
	select @rIsGuidedPractice=DisplayFieldId FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 209
	select @rIsIndependentPractice=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 210
	select @rIsSubTopicSelect=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 211
	select @rIsSubTopicText=DisplayFieldId  FROM sConfig.tDisplayFieldOrg where orgId = @rOrgId and DisplayFieldId = 212
	 	
	INSERT INTO @List 
	SELECT 
		
		   (CASE WHEN @rIsObjective Is Null THEN  0 ELSE 1 END) AS IsObjective,
		   (CASE WHEN @rIsSummary Is Null THEN 0 ELSE 1 END)AS IsSummary,
		   (CASE WHEN @rIsLearningExperience Is Null THEN 0 ELSE 1 END)AS IsLearningExperience,
		   (CASE WHEN @rIsEssentialMaterial Is Null THEN 0  ELSE 1 END)AS IsEssentialMaterial,
		   (CASE WHEN @rIsToolsTechniques Is Null THEN 0  ELSE 1 END)AS IsToolsTechniques,
		   (CASE WHEN @rIsIndicativeHomework Is Null THEN 0  ELSE 1 END)AS IsIndicativeHomework,
		   (CASE WHEN @rIsAssessmentQuestion Is Null THEN 0  ELSE 1 END)AS IsAssessmentQuestion ,
		   (CASE WHEN @rIsTeacherExample Is Null THEN 0 ELSE  1 END)AS  IsTeacherExample,
		   (CASE WHEN @rIsGuidedPractice Is Null THEN 0  ELSE 1 END)AS IsGuidedPractice,
		   (CASE WHEN @rIsIndependentPractice Is Null THEN 0 ELSE  1 END)AS IsIndependentPractice,
		   (CASE WHEN @rIsSubTopicSelect Is Null THEN 0 ELSE  1 END)AS IsSubTopicSelect,
		   (CASE WHEN @rIsSubTopicText Is Null THEN 0 ELSE  1 END)AS IsSubTopicText,
		   @rOrgId AS OrgId		  
	 
    RETURN  
    
END
GO
PRINT N'Altering [sStudent].[vStudentColumnName]...';


GO

























/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sStudent].[vStudentColumnName]  
  
AS 
 
 
SELECT 	
	  --SA.AcademicId,	  
	  --SA.ClassId,
	  --SA.DivisionId,
	  SA.RollNo,
	  --SA.OrgId,
	  --SA.BatchId,
	  BM.Title AS Batch,
	  --SA.StudentId,
	  SA.SUId,
	  SA.Code AS [ID No],
	  SA.Code AS [GR No],
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  --SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      SO.DateOfBirth,
      SO.BirthdateInWord,
      --SO.TransportModeId,
      TM.Title AS TransportMode,
      --SO.GenderId,
      GM.Title AS Gender,
      --SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast As FamilyCaste,
      --SO.FamilySubCast,
      --SO.CastCategoryId,
      
      CCM.Title AS CasteCategory,
      --SO.ReligionId,
      RM.Title AS Religion,
      --SO.HouseId,
      HM.Title AS House,
      --SO.MotherTongueId,
      MTM.Title AS MotherTongue,
      --SO.NationalityId,
      NM.Title AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity AS IsPhysicalDeformity,
      SH.PysicalDeformityRemark AS PhysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
      SC.StudentEmail,
	  --AR.PickupDestinationId AS BusRouteDestinationId,
	  BDM.Title AS BusRouteDestination,
	  SF.FatherName,
	  SF.FatherDateOfBirth,	 
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome,
	  SF.MotherName,
	  SF.MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
      SF.MotherOfficeAddress,
      SF.MotherIncome,      
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  SAD.AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
	  SAD.LeftDate,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.BankAccountNumber,
	  AD.BankName,
	  AD.BankBranch,
	  AD.BankIFSCCode,
	  BSM.Title AS StudentBatchStatus,
	  AD.Class9BoardRegistrationNumber,
	  AD.Class11BoardRegistrationNumber,
	  AD.PassportNumber,
	  AD.PassportType,
	  AD.PassportCountryCode,
	  AD.PassportIssueDate,
	  AD.PassportExpiryDate,
	  SS.SiblingName1,
	  SS.SiblingInstitue1,
	  SS.SiblingClass1,
	  SS.SiblingAge1,
	  SS.SiblingRelation1,
	  SS.SiblingName2,
	  SS.SiblingInstitue2,
	  SS.SiblingClass2,
	  SS.SiblingAge2,
	  SS.SiblingRelation2,
	  SS.SiblingName3,
	  SS.SiblingInstitue3,
	  SS.SiblingClass3,
	  SS.SiblingAge3,
	  SS.SiblingRelation3,
	  CD.SSCBoard,
	  CD.SSCSchool,
	  CD.SSCPassingYear,
	  CD.SSCObtainMarks,
	  CD.SSCOutOfMarks,
	  CD.SSCPercentage,
	  CD.SSCMathMarks,
	  CD.SSCMathOutOfMarks,
	  CD.HSCBoard,
	  CD.HSCSchool,
	  CD.HSCPassingYear,
	  CD.HSCObtainMarks,
	  CD.HSCOutOfMarks,
	  CD.HSCPercentage,
	  
	  CD.HSCBiologyMarks,
	  CD.HSCBiologyOutOfMarks,
	 
	  CD.HSCChemistryMarks,
	  CD.HSCChemistryOutOfMarks,
	  CD.HSCMathMarks,
	  CD.HSCMathOutOfMarks,
	  cd.HSCPhysicsMarks,
	  CD.HSCPhysicsOutOfMarks,
	  CD.PCMMarks,
	  CD.PCBMarks,
	  CD.JEERollNo,
	  CD.JEEMeritNo,
	  CD.JEEMeritMarks,
	  CD.JEEOutOfMarks,
	  CD.DiplomaBoard,
	  CD.DiplomaCollege,
	  CD.DiplomaPassingYear,
	  CD.DiplomaObtainMarks,
	  CD.DiplomaOutOfMarks,
	  CD.DiplomaPercentage,
	  CD.ApplicationNo,
	  CD.AdmissionRound,
	  CD.MaritalStatusId,
	  ISNULL(HHM.Title,'') AS HostelName,
	  ISNULL(HRM.Title,'') AS Room,
	  ISNULL(HBM.Title,'') AS BuildingName,
	  ISNULL(HAR.BedNumber,'') AS BedNumber,
	  ISNULL(SGM.Title,'') AS StudentGroup,
	  ISNULL(SGMO.Title,'') AS StudentOtherGroup,
	  SO.BirthState,
	  SO.BirthCountry,
	  ISNULL(BDM.PickupTime,'') AS PickupTime,
	  ISNULL(BDM.DropTime,'') AS DropTime,
	  ISNULL(BRM.Title,'') AS BusRoute,
	  ISNULL(SAD.PreviousStandard,'') AS PreviousStandard,
	  ISNULL(So.ReferenceRemark,'') AS ReferenceRemark,
	  ISNULL(SAD.LCNumber,'') AS LCNumber,
	  CM.Title AS AdmissionStandard
  FROM sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SAD.AdmissionStandardId
	INNER JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	INNER JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	INNER JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	INNER JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	INNER JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	INNER JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	INNER JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	INNER JOIN sCommon.tCountryMaster NM ON NM.Id=SO.NationalityId
	INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	INNER JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	INNER JOIN sStudent.tStudentadditional AD ON AD.StudentId= SA.StudentId
	INNER JOIN sStudent.tStudentBatchStatus SBS ON SBS.AcademicId = SA.AcademicId
	INNER JOIN sStudent.tBatchStatusMaster BSM ON BSM.Id = SBS.BatchStatusId
	INNER JOIN sStudent.tStudentSibling SS ON SS.StudentId= SA.StudentId
	INNER JOIN sStudent.tCollegeDetail CD ON CD.StudentId = SA.StudentId
	INNER JOIN sHostel.tAssignRoom HAR ON HAR.SourceId = SA.StudentId
	INNER JOIN sHostel.tRoomMaster HRM ON HRM.Id = HAR.RoomId
	INNER JOIN sHostel.tBuildingMaster HBM ON HBM.HostelId = HRM.HostelId
	INNER JOIN sHostel.tHostelMaster HHM ON HHM.Id = HRM.HostelId
	INNER JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SA.StudentGroupId
	INNER JOIN sStudent.tStudentOtherGroupMaster SGMO ON SGMO.Id = SA.StudentOtherGroupId
    INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId
GO
PRINT N'Altering [sStudent].[vStudentCustomSearch]...';


GO






 
ALTER VIEW [sStudent].[vStudentCustomSearch]  
  
AS  
  
SELECT 	
	  SA.AcademicId,	  
	  SA.ClassId,
	  SA.DivisionId,
	  SA.RollNo,
	  SA.OrgId,
	  SA.BatchId,
	  BM.Title AS Batch,
	  SA.StudentId,
	  SA.SUId,
	  SA.Code,
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      CONVERT(VARCHAR(10), SO.DateOfBirth, 111) AS DateOfBirth,
      SO.BirthdateInWord,
      SO.TransportModeId,
      TM.Title AS TransportMode,
      SO.GenderId,
      GM.Title AS Gender,
      SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast AS FamilyCaste,
      SO.FamilySubCast,
      
      
      SO.CastCategoryId,
      CCM.Title AS CasteCategory,
      SO.ReligionId,
      RM.Title AS Religion,
      SO.HouseId,
      HM.Title AS House,
      SO.MotherTongueId,
     SO.MotherTongue AS MotherTongue,
      SO.NationalityId,
      NM.Nationality AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity,
      SH.PysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
      SC.StudentEmail,
	  RT.BusRouteDestinationId AS BusRouteDestinationId,
	  RT.BusRouteDestination AS BusRouteDestination,
	  SF.FatherName,
	  CONVERT(VARCHAR(10), SF.FatherDateOfBirth, 111)AS FatherDateOfBirth,
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome,
	  SF.MotherName,
	 CONVERT(VARCHAR(10),  SF.MotherDateOfBirth,111) AS MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
      SF.MotherOfficeAddress,
      SF.MotherIncome,      
	  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  CONVERT(VARCHAR(10), SAD.AdmissionDate, 111) AS AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
	  CONVERT(VARCHAR(10),SAD.LeftDate, 111) AS LeftDate,
	  SA.IsBlackList,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.RepeatCount,
	  ADI.BankAccountNumber,
	  ADi.BankBranch,
	  ADI.BankIFSCCode,
	  ADI.BankName,
	  ESM.Title AS StudentBatchStatus,
	  EnrollmentStatusId AS StudentStatusId,
	  ADI.Class9BoardRegistrationNumber,
	  ADI.Class11BoardRegistrationNumber,
	  ADI.PassportNumber,
	  ADI.PassportType,
	  ADI.PassportCountryCode,
	CONVERT(VARCHAR(10),ADI.PassportIssueDate,111) AS PassportIssueDate,
	  ADI.PassportExpiryDate,
	  '' SiblingName1,
	  '' SiblingInstitue1,
	  '' SiblingClass1,
	  '' SiblingAge1,
	  '' SiblingRelation1,
	  '' SiblingName2,
	  '' SiblingInstitue2,
	  '' SiblingClass2,
	  '' SiblingAge2,
	  '' SiblingRelation2,
	  '' SiblingName3,
	  '' SiblingInstitue3,
	  '' SiblingClass3,
	  '' SiblingAge3,
	  '' SiblingRelation3,
	  ISNULL(HHM.Title,'') AS HostelName,
	  ISNULL(HRM.Title,'') AS Room,
	  ISNULL(HBM.Title,'') AS BuildingName,
	  ISNULL(HAR.BedNumber,'') AS BedNumber,
	  
	  ISNULL(SM.StudentGroupId,0) AS StudentGroupId,
	  ISNULL(SM.StudentOtherGroupId,0) AS StudentOtherGroupId,
	  
	  SGM.Title AS StudentGroup,
	  SOGM.Title AS StudentOtherGroup,
	  SO.BirthState,
	  So.BirthCountry,
	  ISNULL(RT.BusRouteId,0) AS BusRouteId,
	  ISNULL(RT.PickupTime,'') AS PickupTime,
	  ISNULL(RT.Droptime,'') AS Droptime,
	  ISNULL(RT.BusRoute,'' )AS BusRoute,
	   CD.SSCBoard,
	   CD.SSCSchool,
	  CD.SSCPassingYear,
	  CD.SSCObtainMarks,
	  CD.SSCOutOfMarks,
	  CD.SSCPercentage,
	  CD.SSCMathMarks,
	  CD.SSCMathOutOfMarks,
	  CD.HSCBoard,
	  CD.HSCSchool,
	  CD.HSCPassingYear,
	  CD.HSCObtainMarks,
	  CD.HSCOutOfMarks,
	  CD.HSCPercentage,
	  
	  CD.HSCBiologyMarks,
	  CD.HSCBiologyOutOfMarks,
	 
	  CD.HSCChemistryMarks,
	  CD.HSCChemistryOutOfMarks,
	  CD.HSCMathMarks,
	  CD.HSCMathOutOfMarks,
	  cd.HSCPhysicsMarks,
	  CD.HSCPhysicsOutOfMarks,
	  CD.PCMMarks,
	  CD.PCBMarks,
	  CD.JEERollNo,
	  CD.JEEMeritNo,
	  CD.JEEMeritMarks,
	  CD.JEEOutOfMarks,
	  CD.DiplomaBoard,
	  CD.DiplomaCollege,
	  CD.DiplomaPassingYear,
	  CD.DiplomaObtainMarks,
	  CD.DiplomaOutOfMarks,
	  CD.DiplomaPercentage,
	  CD.ApplicationNo,
	  CD.AdmissionRound,
	  CD.MaritalStatusId,
	  EX.Id As ExemptionTypeId,
	  SAD.PreviousStandard,
	  SO.ReferenceRemark,
	  SAD.LCNumber,
	  CM.Title AS AdmissionStandard
	  	  	   
  FROM sStudent.vStudentAcademic SA
    INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId
	LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SAD.AdmissionStandardId
	LEFT JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	--LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	LEFT JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	LEFT JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	LEFT JOIN sCommon.tCountryMaster NM ON NM.Id=SO.NationalityId
	--LEFT JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	LEFT JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = SA.AcademicId
	LEFT JOIN sStudent.tStudentadditional ADI ON ADI.StudentId = SA.StudentId
	LEFT JOIN sStudent.tEnrollmentStatusMaster ESM ON ESM.Id = SM.EnrollmentStatusId
	--LEFT JOIN sStudent.tStudentSibling SS ON SS.StudentId = SA.StudentId
	LEFT JOIN sHostel.tAssignRoom HAR ON HAR.SourceId = SM.Id AND HAR.OrgGroupBatchId = SA.OrgGroupBatchId
	LEFT JOIN sHostel.tRoomMaster HRM ON HRM.Id = HAR.RoomId
	LEFT JOIN sHostel.tBuildingMaster HBM ON HRM.BuildingId = HBM.Id 
	LEFT JOIN sHostel.tHostelMaster HHM ON HHM.Id = HRM.HostelId
	
	LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id=SM.StudentGroupId
	LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id=SM.StudentOtherGroupId
	--LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId
	LEFT JOIN sStudent.tCollegeDetail CD ON CD.StudentId = SA.StudentId
	LEFT JOIN sFee.tExemptionTypeMaster EX ON Ex.Id=SA.ExemptionTypeId
   LEFT JOIN
	(SELECT AR.SourceId,AR.PickupDestinationId AS BusRouteDestinationId,BDM.Title AS BusRouteDestination, ISNULL(BRM.Id,0) AS BusRouteId,
	  ISNULL(BDM.PickupTime,'') AS PickupTime,
	  ISNULL(BDM.Droptime,'') AS Droptime,
	  ISNULL(BRM.Title,'' )AS BusRoute,BRM.OrgGroupBatchId FROM sTransport.tAssignRoute AR 
    INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId AND  AR.SourceTypeId=2003  )  RT 
   
    ON RT.SourceId = SA.StudentId     AND RT.OrgGroupBatchId =SA.OrgGroupBatchId
GO
PRINT N'Altering [sStudent].[vStudentVerification]...';


GO










 
ALTER VIEW [sStudent].[vStudentVerification]  
  
AS  
 
SELECT 
	  A.Id AS AcademicId,	  
	  A.ClassId,
	  A.DivisionId,
	  A.RollNo,
	  A.OrgId,
	  A.BatchId,
	  SM.Id AS StudentId,
	  SM.Code,
	  ISNULL(SM.Number,0) AS Number,
	  SM.RegistrationNumber,
	  SM.FirstName,
	  SM.MiddleName,
	  SM.LastName,
	    SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,	   
	  SM.RecordStatusId,	  
	  DM.InchargeEmployeeId, 
	  BM.OrgGroupBatchId,	  
	  SM.AdmissionCategoryId,
	  DM.OrderIndex DivisionOrder,
	  BM.IsActive AS IsActiveBatch,
	  BM.Title AS BatchName,
	  SM.IsBlackList,
	  SM.BlackListReason,
	  CM.OrderIndex AS ClassOrderIndex,
	  ISNULL(A.ExemptionTypeId,0) AS ExemptionTypeId,
	  ISNULL(SM.SUId,'') AS SUId ,
	  SA.AdmissionDate,
	  SA.PreviousSchool,
	  SO.DateOfBirth,
	  SO.BirthPlace,
	  GEN.Title As Gender,
	  SO.FamilyCast,
	  CC.Title As CastCatagory,
	  SO.MotherTongue,
	  --NM.Title AS Nationality,
	  SF.FatherName,
	 SF.FatherContactNo,
	 sf.MotherName,
	 SF.MotherContactNo,
	 SC.PresentStreetOne,
	 SC.PresentStreetTwo,
	 SC.PresentStreetThree,
	 SC.StudentContactNo,
	 SO.UIDNumber,
	 SO.AdhaarNumber,
	 STA.BankBranch,
	 STA.BankAccountNumber,
	 STA.BankName,
	 STA.BankIFSCCode,
	Dept.ID as DepartmentId,
	  SA.ADMISSIONStandardId,
	  NM.OrgGroupId,
	   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	   R.Title As Religion,
	   SC.StudentEmail,
	   CON.Nationality,
	   SO.BirthState,
	   SO.BirthCountry
	  
	  
	  
  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 sStudent.tStudentAdmission SA ON SA.StudentID=SM.Id   
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SM.Id
	INNER JOIN sCommon.tGenderMaster GEN ON GEN.Id=SO.GenderId
	LEFT JOIN sCommon.tCastCategoryMaster CC oN CC.Id=SO.CastCategoryId
	LEFT JOIN sCommon.tCountryMaster NM ON NM.Id=SO.NationalityId 
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =SM.Id
	LEFT JOIN sStudent.tStudentAdditional STA ON STA.StudentId=Sm.Id
	INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=Cm.DepartmentId
	LEFT JOIN sCommon.tReligionMaster R ON R.id=SO.ReligionId
 INNER JOIN sSetup.tOrganizationMaster OM
	    ON SM.OrgId = OM.Id
	LEFT JOIN sCommon.tCountryMaster CON ON CON.ID = SO.NationalityID
GO

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


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanAdd]
	 
        @rId bigint=0,
        @rTopicId int,
        @rDivisionId int, 
        @rNoOfPeriodRequired smallint,
        @rObjective nvarchar(200),
        @rIndicativeHomework nvarchar(200),
        @rSummary nvarchar(200),
        @rStartDate date='',
        @rEndDate date='',
        @rIsCompleted bit=0,
        @rEmployeeId bigint,
        @rBatchId int,
        @rCreatedUserId bigint,
        @rOrgId smallint,
        @rLearningExperience nvarchar(1000)='',
        @rToolsAndTechniques nvarchar(500)='',
        @rEssentialMaterial nvarchar(500)='',
		@rAssessmentQuestion	nvarchar(1000)='',	
		@rTeacherExample	nvarchar(1000)='',
		@rGuidedPractice	nvarchar(1000)='',
		@rIndependentPractice	nvarchar(1000)	='',
		@rSubTopic nvarchar(1000)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	
	--IF(@rId = 0)	
	--BEGIN
	--	--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId)
	--	--	BEGIN
	--	--	select -102 as Result
	--	--	RETURN
	--	--END 
	
	--	If Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
	--END
	--ELSE
	--BEGIN
	--	--If Exists(select Id from sCommunication.tNews where Code=@rCode AND OrgGroupBatchId=@rOrgGroupBatchId AND Id<>@rId)
	--	--Begin
	--	--	select -102 as Result
	--	--	RETURN
	--	--End
	--	If  Exists(select Id from sAcademic.tTopicMaster where Number=@rNumber AND OrgId=@rOrgId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	
	
	 
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tLessonPlan
		(
			Id,
			TopicId,
			DivisionId,
			NoOfPeriodRequired,
			Objective,
			IndicativeHomework,
			Summary,
			StartDate,
			EndDate,
			IsCompleted,
			EmployeeId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			LearningExperience,
			ToolsAndTechniques,
			EssentialMaterial,
			AssessmentQuestion,
			TeacherExample,
			GuidedPractice,
			IndependentPractice,
			SubTopic
		)
	VALUES
		(
			@lNextNumber,
			@rTopicId,
			@rDivisionId,
			@rNoOfPeriodRequired,
			@rObjective,
			@rIndicativeHomework,
			@rSummary,
			@rStartDate,
			@rEndDate,
			@rIsCompleted,
			@rEmployeeId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLearningExperience,
			@rToolsAndTechniques,
			@rEssentialMaterial,
			@rAssessmentQuestion,
			@rTeacherExample,
			@rGuidedPractice,
			@rIndependentPractice,
			@rSubTopic
			
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tLessonPlan
	    SET
			TopicId=@rTopicId,
			DivisionId=@rDivisionId,
			NoOfPeriodRequired=@rNoOfPeriodRequired,
			Objective=@rObjective,
			IndicativeHomework=@rIndicativeHomework,
			Summary=@rSummary,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			IsCompleted=@rIsCompleted,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			LearningExperience = @rLearningExperience,
			ToolsAndTechniques = @rToolsAndTechniques,
			EssentialMaterial =@rEssentialMaterial,
			EmployeeId = @rEmployeeId,
			AssessmentQuestion=@rAssessmentQuestion,
			TeacherExample=@rTeacherExample,
			GuidedPractice=@rGuidedPractice,
			IndependentPractice=@rIndependentPractice,
			SubTopic=@rSubTopic	
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	 
END
GO
PRINT N'Altering [sAcademic].[pLessonPlanCopy]...';


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanCopy]
	 
        
        @rFromDivisionId int, 
        @rToDivisionId int, 
        @rEmployeeId bigint,
        @rBatchId int,
        @rOrgId int
         
  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 DECLARE @lNextNumber bigint
	 
	 Delete from sAcademic.tLessonPlan where DivisionId = @rToDivisionId AND EmployeeId =@rEmployeeId AND BatchId=@rBatchId
	 
	 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
	 
		Insert into sAcademic.tLessonPlan
		(
		Id,
		DivisionId,
		TopicId,
		NoOfPeriodRequired,
		Objective,
		IndicativeHomework,
		Summary,
		StartDate,
		EndDate,
		IsCompleted,
		EmployeeId,
		BatchId,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		 UpdatedDateTime,
		LearningExperience,
		ToolsAndTechniques,
		EssentialMaterial,
		SubTopic
		)
		Select 
		@lNextNumber,
		@rToDivisionId,
		TopicId,
		NoOfPeriodRequired,
		Objective,
		IndicativeHomework,
		Summary,
		StartDate,
		EndDate,
		IsCompleted,
		EmployeeId,
		BatchId,
		CreatedUserId,
		sCommon.fGetDate(),
		UpdatedUserId,
		sCommon.fGetDate(),
		LearningExperience,
		ToolsAndTechniques,
		EssentialMaterial,
		SubTopic
		from sAcademic.tLessonPlan where DivisionId =@rFromDivisionId AND EmployeeId =@rEmployeeId
		
		Select 1 as result
		
END
GO
PRINT N'Altering [sAcademic].[pLessonPlanGet]...';


GO
ALTER PROCEDURE [sAcademic].[pLessonPlanGet]

	 @rId bigint,
	 @rClassId int,
	 @rSubjectId int,
	 @rDivisionId int,
	 @rIsCompleted bit=0,
	 @rBatchId int,
	 @rEmployeeId bigint,
	 @rDepartmentid int=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			DISTINCT (LP.Id),
			TM.ClassId,
		    LP.DivisionId,
			TM.SubjectId,
			LP.TopicId,
			LP.NoOfPeriodRequired,
			LP.Objective,
			LP.IndicativeHomework,
			LP.Summary,
			ISNULL(LP.StartDate,'') AS StartDate ,
			ISNULL(LP.EndDate,'') AS EndDate,
			LP.IsCompleted,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			TM.Title AS TopicName,
			vTSD.ClassTitle+' - '+ vTSD.DivisionTitle AS ClassDivisionName,
			 
			vTSD.SubjectName,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS  EmployeeName,
			LP.LearningExperience,
			LP.ToolsAndTechniques,
			LP.EssentialMaterial,
			LP.AssessmentQuestion,
			LP.TeacherExample,
			LP.GuidedPractice,
			LP.IndependentPractice,
			LP.SubTopic
	FROM 
			sAcademic.tLessonPlan LP
			INNER JOIN sAcademic.tTopicMaster TM ON TM.Id=LP.TopicId
			
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId			
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.DivisionId = LP.DivisionId
			AND vTSD.ClassId = TM.ClassId 
			AND vTSD.SubjectId = TM.SubjectId 
			AND vTSD.EmployeeId = LP.EmployeeId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
			(LP.BatchId = @rBatchId) 
			AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
			AND ((LP.Id = @rId) OR (@rId = 0))
			AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((LP.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
			AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
			Order by id 
END
GO
PRINT N'Altering [sAcademic].[pPreLessonPlanAdd]...';


GO
ALTER PROCEDURE [sAcademic].[pPreLessonPlanAdd]
	 
        @rId bigint=0,
        @rClassId int,
        @rSubjectId int,
        @rEmployeeId bigint,
        @rObjective nvarchar(200),
        @rSummary nvarchar(200),
        @rStartDate date='',
        @rEndDate date='',
        @rBatchId int,
        @rCreatedUserId bigint,
        @rOrgId smallint,
        @rSubTopic nvarchar(1000),
        @rTopicId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		 
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tPreLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sAcademic.tPreLessonPlan
		(
			Id,
			ClassId,
			SubjectId,
			EmployeeId,		
			Objective,
			Summary,
			StartDate,
			EndDate,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			SubTopic,
			TopicId
		)
	VALUES
		(
			@lNextNumber,
			@rClassId,
			@rSubjectId,
			@rEmployeeId,
			@rObjective,
			@rSummary,
			@rStartDate,
			@rEndDate,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSubTopic,
			@rTopicId
			
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAcademic.tPreLessonPlan
	    SET
			ClassId=@rClassId,
			SubjectId=@rSubjectId,			
			EmployeeId = @rEmployeeId,
			Objective=@rObjective,
			SubTopic=@rSubTopic,
			TopicId=@rTopicId,
			Summary=@rSummary,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate()
			
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	 
END
GO
PRINT N'Altering [sAcademic].[pPreLessonPlanCopy]...';


GO
ALTER PROCEDURE [sAcademic].[pPreLessonPlanCopy]
	 
        
        @rFromClassId int, 
        @rToClassId int, 
        @rEmployeeId bigint,
        @rBatchId int,
        @rOrgId int
  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 DECLARE @lNextNumber bigint
	 
	 --Delete from sAcademic.tPreLessonPlan where ClassId=@rToClassId AND EmployeeId =@rEmployeeId AND BatchId=@rBatchId
	 
	 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAcademic.tPreLessonPlan', 0, 1, 1,@outNextNumber = @lNextNumber output
	 
		Insert into sAcademic.tPreLessonPlan
		(
		Id,
		Objective,
		ClassId,
		Summary,
		StartDate,
		EndDate,
		EmployeeId,
		BatchId,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime,
		SubTopic
		)
		Select 
		@lNextNumber,
		Objective,
		@rToClassId,
		Summary,
		StartDate,
		EndDate,
		EmployeeId,
		BatchId,
		CreatedUserId,
		sCommon.fGetDate(),
		UpdatedUserId,
		sCommon.fGetDate(),
		SubTopic
		from sAcademic.tPreLessonPlan where EmployeeId =@rEmployeeId
		
		Select 1 as result
		
END
GO
PRINT N'Altering [sAcademic].[pPreLessonPlanGet]...';


GO
ALTER PROCEDURE [sAcademic].[pPreLessonPlanGet]

	 @rId bigint,
	 @rClassId int,
	 @rSubjectId int,
	 @rEmployeeId bigint,
	 @rBatchId int
	 --@rName bigint
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	SELECT 
			DISTINCT(LP.Id),
			LP.ClassId,
			LP.SubjectId,
		    vTSD.ClassTitle AS ClassTitle,
			LP.EmployeeId,
			LP.Objective,
			LP.Summary,
			LP.BatchId,
			ISNULL(LP.StartDate,'') AS StartDate, 
			EM.FirstName+' '+EM.LastName AS Name,
			LP.SubTopic,
			LP.TopicId
			
	FROM 
			sAcademic.tPreLessonPlan LP
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = LP.SubjectId
		    		AND vTSD.ClassId = LP.ClassId 
			AND vTSD.EmployeeId = LP.EmployeeId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = vTSD.ClassId
	WHERE 
		  (LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId=0))
		AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((vTSD.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((LP.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		--AND ((EM.FirstName = @rName ) OR (@rName = 0)) 
		--AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		--AND ((CM.DepartmentId = @rDepartmentid) OR (@rDepartmentid=0))
		Order by Id 
END
GO
PRINT N'Altering [sAcademic].[pRptPreLessonPlanGet]...';


GO

ALTER PROCEDURE [sAcademic].[pRptPreLessonPlanGet]

	 
	 @rClassId int,
	 @rSubjectId int,
	 @rBatchId int,
	 @rEmployeeId bigint,
	 @rStartDate date='',
	 @rEndDate date=''
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	SELECT 
			DISTINCT LP.Id,
			LP.ClassId,
			LP.SubjectId,
			--vTSD.DivisionId AS DivisionId,
			LP.Objective,
			LP.Summary,
			LP.StartDate,
			LP.EndDate,
			LP.EmployeeId,
			LP.BatchId,
			LP.CreatedUserId,
			LP.CreatedDateTime,
			vTSD.ClassTitle AS ClassDivisionName,
			vTSD.SubjectName,
			EM.FirstName+' '+EM.LastName AS Name,
			
		  datepart(MONTH,Lp.StartDate) AS MonthId,
		  datename(MONTH,Lp.StartDate) AS Monthname
			
	FROM 
			sAcademic.tPreLessonPlan LP
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LP.EmployeeId
			 INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = LP.SubjectId
			AND vTSD.ClassId = LP.ClassId 
			AND vTSD.EmployeeId = LP.EmployeeId
	WHERE 
		(LP.BatchId = @rBatchId) 
		AND ((LP.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		--AND ((LP.Id = @rId) OR (@rId = 0))
		AND ((LP.ClassId = @rClassId) OR (@rClassId = 0))
		--AND ((vTSD.ClassTitle = @rClassTitle) OR (@rClassTitle = 0))
		AND ((LP.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		--AND ((LP.IsCompleted='False') OR (LP.IsCompleted=@rIsCompleted))
		AND ((LP.StartDate >= @rStartDate) OR (@rStartDate= ''))
		AND ((LP.StartDate <= @rEndDate)  OR (@rEndDate= ''))
 
		
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 
	L.LedgerTypeId,
	 @rBuilder1 AS Builder1
	,@rBuilder2 AS Builder2,
	T.Id AS TransactionId,	
	--ISNULL(CASE WHEN TD.TransactionTypeId = 1 THEN -1 * SUM(TD.AMOUNT) END,0) AS CREDIT1,
	--ISNULL(CASE WHEN TD.TransactionTypeId = 2 THEN SUM(TD.AMOUNT) END,0) AS DEBIT,
	CAse When L.LedgerTypeId = 1 then 
   -1 * Isnull((select sum(TD1.Amount)  from
	sAccounting.tTransaction T1 
	INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id AND T1.Id=T.Id 
	AND TD1.TransactionTypeId = 1 
	WHERE (L.LedgerTypeId = 1 ANd TD1.LedgerId =TD.LedgerId) OR (L.LedgerTypeId = 2 AND TD1.LedgerId =@rLedgerId )
	GROUP BY 	TD1.LedgerId,T1.TransactionDate,T1.VoucherNumber,T1.Id,
				TD1.TransactionTypeId,T1.VoucherTypeId,T1.Narration,
				T1.ChequeNo
	),0) else 0 end as Credit ,
	--CAse When L.LedgerTypeId = 1 then 0 end as debit,

	Case When L.LedgerTypeId = 2 then 
	-1 * isnull((select sum(TD1.Amount)  from
	sAccounting.tTransaction T1 
	INNER JOIN sAccounting.tTransactionDetail TD1 ON TD1.TransactionId=T1.Id AND T1.Id=T.Id  
	--AND TD1.TransactionTypeId = 2
	WHERE (L.LedgerTypeId = 1 ANd TD1.LedgerId =TD.LedgerId) 
	 OR(L.LedgerTypeId = 2 AND TD1.LedgerId =@rLedgerId )
	GROUP BY 	TD1.LedgerId,T1.TransactionDate,T1.VoucherNumber,T1.Id,
				TD1.TransactionTypeId,T1.VoucherTypeId,T1.Narration,
				T1.ChequeNo
	),0) else 0 end as Debit,
	--CAse When L.LedgerTypeId = 2 then 0 end as Credit,


	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 TD1.TRansactionTypeID <> L.LedgerTypeId )
	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,L.LedgerTypeId
   order by T.TransactionDate,T.VoucherNumber
END
GO
PRINT N'Altering [sAssessment].[pExamCombineMarkEntryGet]...';


GO
ALTER PROCEDURE [sAssessment].[pExamCombineMarkEntryGet]
	
	 @rExamId int,
	 @rAcademicId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

IF EXISTS (SELECT ID from sAssessment.tExamCombine where ExamId = @rExamId)
BEGIN
select  
(case WHEN A.Maxi = 0 then 0
else
ISNULL((A.Obtain*ED.Maximum)/A.Maxi,0) END) AS Obtain,


@rAcademicId AS AcademicId,
ED.Id AS ExamDetailID,
ED.ExamId,
--CONVERT(bit, 1) AS  IsPresent

-- Edited By Kundan
-- Uncomment code due to at Time of Result generate 
-- Absent Student status auto update as Present cause default present status pass 1 (as above comment)
ISNULL((select IsPresent from sAssessment.tResultDetail rd1 
		   inner join sAssessment.tResult r1 on r1.Id=rd1.ResultId and r1.ExamId=@rExamId and r1.AcademicId=@rAcademicId
		   and rd1.ExamDetailId=ED.Id ),0)  AS IsPresent

from
(

SELECT 
	CASE WHEN ECS.ExamId IS nULL THEN
		Sum(Obtain*weightage/100) 
	ELSE
		Sum(Obtain*Subjectweightage/100) 
	END  AS Obtain,
	CASE WHEN ECS.ExamId IS nULL THEN
		Sum(Maximum*weightage/100) 
	ELSE
		Sum(Maximum*Subjectweightage/100) 
	END	AS Maxi,
	
RM.AcademicId,ED.ClassSubjectId
FROM sAssessment.tResult RM 
	INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=RM.Id
	INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId=ED.Id
	INNER JOIN sAssessment.tExamCombine EC ON ED.ExamId=EC.SubExamId
	INNER JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  	
    LEFT JOIN sAssessment.tExamCombineSubject ECS ON ECS.ExamId  = EC.ExamId 
    AND ECS.SubExamId = EC.SubExamId AND ECS.ClassSubjectId = ED.ClassSubjectId AND ECS.Subjectweightage > 0     
	WHERE EC.ExamId=@rExamId 
	
GROUP BY RM.AcademicId,ED.ClassSubjectId,ECS.ExamId having RM.AcademicId=@rAcademicId

) AS A
INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId=A.ClassSubjectId
Where ED.ExamId =@rExamId
END
		
END
GO
PRINT N'Altering [sAssessment].[pRptSubjectResultListFloating]...';


GO


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

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

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

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


GO
ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]
     @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,
	 @rStatus int=0 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

--Select * from sAttendance.tTempAttendance

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 @lOrgId  int
--DECLARE @lSchoolRemark1  nvarchar(500)
--DECLARE @lSchoolRemark2  nvarchar(500)
--DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

SELECT  @lOrgId=RG.OrgId,
--@lSchoolRemark1 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark1,'')  ELSE RG.SchoolRemark1 END,
--@lSchoolRemark2= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark2,'')  ELSE RG.SchoolRemark2 END,
--@lSchoolRemark3 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark3,'')  ELSE RG.SchoolRemark3 END,
@lSchoolRequiredSignature= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRequiredSignature,'')  ELSE RG.SchoolRequiredSignature END 
 
FROM sCommon.tReportRemarkGroupMaster RGM LEFT JOIN sCommon.tReportRemarkGroupOrg RG ON RGM.Id = RG.ReportRemarkGroupId AND RG.OrgId = @rOrgId AND RG.ReportRemarkGroupId=1 where RGM.Id=1
 
-- select @lSchoolRequiredSignature as sig
 	Declare @Days int 
 	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
BEGIN 
	 CREATE Table #AttendanceRegistertempTable
(
	TID int identity(1,1),
	ClassDivisionTitle Nvarchar(500),
	Code nvarchar(500),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(500),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(500),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(500),
	DivisionName nvarchar(500),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	EmployeeName nvarchar(500),
	DateOfBirth date,
	Religion nvarchar(500),
	MotherName nvarchar(500),
	FamilyCast nvarchar(100)
)
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,
	EmployeeName,
	DateOfBirth,
	Religion,
	MotherName,
	FamilyCast
)
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,
	@lSchoolRequiredSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 EM.FirstName+' ' + EM.LastName AS EmployeeName,
	 SO.DateOfBirth,
	 RE.Title As Religion,
	 Sf.MotherName,
	 SO.FamilyCast
	 --,
	 --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
            INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN  sStudent.tStudentFamily SF ON Sf.StudentId=Sa.StudentID
            LEFT JOIN sCommon.tReligionMaster RE On RE.Id=SO.ReligionId
            
             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))
	           AND ((SA.StatusId=@rStatus)OR (@rStatus=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

 

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(ABU.AUCount,0) AS AbsentUpto,
			ISNULL(TC.TCount,0) AS AttendanceCount,
		    ISNULL(AC.ACount,0) As  AbsentCount,
		    ISNULL(PC.PCount,0) As  PresentUpto,	    
		    
		    ClassOrderIndex,
		    DivisionOrderIndex,
		    FooterSignature,
			(ISNULL(TotalPresent,0) + ISNULL(TC.TCount,0)) AS TotalPresent,
			 
			  [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,1 ,@rBatchId ,@rDivisionId , isnull([1],''),@rOrgId )  AS P1,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,2 ,@rBatchId ,@rDivisionId , isnull([2],''),@rOrgId )  AS P2,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,3 ,@rBatchId ,@rDivisionId , isnull([3],''),@rOrgId )  AS P3,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,4 ,@rBatchId ,@rDivisionId , isnull([4],''),@rOrgId )  AS P4,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,5 ,@rBatchId ,@rDivisionId , isnull([5],''),@rOrgId )  AS P5,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,6 ,@rBatchId ,@rDivisionId , isnull([6],''),@rOrgId ) AS P6,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,7 ,@rBatchId ,@rDivisionId , isnull([7],''),@rOrgId ) AS P7,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,8 ,@rBatchId ,@rDivisionId , isnull([8],''),@rOrgId ) AS P8,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,9 ,@rBatchId ,@rDivisionId , isnull([9],''),@rOrgId ) AS P9,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,10 ,@rBatchId ,@rDivisionId , isnull([10],''),@rOrgId ) AS P10,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,11 ,@rBatchId ,@rDivisionId , isnull([11],''),@rOrgId ) AS P11,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,12 ,@rBatchId ,@rDivisionId , isnull([12],''),@rOrgId ) AS P12,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,13 ,@rBatchId ,@rDivisionId , isnull([13],''),@rOrgId ) AS P13,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,14 ,@rBatchId ,@rDivisionId , isnull([14],''),@rOrgId ) AS P14,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,15 ,@rBatchId ,@rDivisionId , isnull([15],''),@rOrgId ) AS P15,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,16 ,@rBatchId ,@rDivisionId , isnull([16],''),@rOrgId ) AS P16,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,17 ,@rBatchId ,@rDivisionId , isnull([17],''),@rOrgId ) AS P17,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,18 ,@rBatchId ,@rDivisionId , isnull([18],''),@rOrgId ) AS P18,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,19 ,@rBatchId ,@rDivisionId , isnull([19],''),@rOrgId ) AS P19,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,20 ,@rBatchId ,@rDivisionId , isnull([20],''),@rOrgId ) AS P20,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,21 ,@rBatchId ,@rDivisionId , isnull([21],''),@rOrgId ) AS P21,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,22 ,@rBatchId ,@rDivisionId , isnull([22],''),@rOrgId ) AS P22,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,23 ,@rBatchId ,@rDivisionId , isnull([23],''),@rOrgId ) AS P23,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,24 ,@rBatchId ,@rDivisionId , isnull([24],''),@rOrgId ) AS P24,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,25 ,@rBatchId ,@rDivisionId , isnull([25],''),@rOrgId ) AS P25,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,26 ,@rBatchId ,@rDivisionId , isnull([26],''),@rOrgId ) AS P26,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,27 ,@rBatchId ,@rDivisionId , isnull([27],''),@rOrgId ) AS P27,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,28 ,@rBatchId ,@rDivisionId , isnull([28],''),@rOrgId ) AS P28,
			CASE WHEN @Days>=29 THEN  [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,29 ,@rBatchId ,@rDivisionId , isnull([29],''),@rOrgId ) end AS P29,
			CASE WHEN @Days>=30 THEN [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,30 ,@rBatchId ,@rDivisionId , isnull([30],''),@rOrgId ) end AS P30,
			CASE WHEN @Days>=31 THEN [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,31 ,@rBatchId ,@rDivisionId , isnull([31],''),@rOrgId )  end AS P31,
			
	 	--	 isnull([1],'') AS P1,
			--isnull([2],'') AS P2,
			--isnull([3],'') AS P3,
			--isnull([4],'') AS P4,
			--isnull([5],'') AS P5,
			--isnull([6],'') AS P6,
			--isnull([7],'') AS P7,
			--isnull([8],'') AS P8,
			--isnull([9],'') AS P9,
			--isnull([10],'') AS P10,
			--isnull([11],'') AS P11,
			--isnull([12],'') AS P12,
			--isnull([13],'') AS P13,
			--isnull([14],'') AS P14,
			--isnull([15],'') AS P15,
			--isnull([16],'') AS P16,
			--isnull([17],'') AS P17,
			--isnull([18],'') AS P18,
			--isnull([19],'') AS P19,
			--isnull([20],'') AS P20,
			--isnull([21],'') AS P21,
			--isnull([22],'') AS P22,
			--isnull([23],'') AS P23,
			--isnull([24],'') AS P24,
			--isnull([25],'') AS P25,
			--isnull([26],'') AS P26,
			--isnull([27],'') AS P27,
			--isnull([28],'') AS P28,
			--isnull([29],'') AS P29,
			--isnull([30],'') AS P30,
			--isnull([31],'') AS P31, 
			 EmployeeName ,
 
             sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth,
              DateOfBirth,Religion,MotherName,FamilyCast
--,
--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 'LC' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'EL' 
			      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,EmployeeName,
		DateOfBirth,Religion,MotherName,FamilyCast
      -- 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 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
            
			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 AUCount  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
    ) ABU ON ABU.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS TotalPresent  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.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
    ) AA ON AA.AcademicId = PivotTable.AcademicId
 
    ORDER BY RollNo;
 

select * from #TempDaysTempTable
 				
drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	
	
END
GO
PRINT N'Altering [sAttendance].[pAttenanceRegisterGetNew]...';


GO
 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 [sAttendance].[pRptDailyAttendanceList]...';


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


GO
ALTER PROCEDURE [sAttendance].[pStudentRegisterGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rAttendanceDate date,
		 @rSubjectId int,
		 @rSubjectBatchId int,
		 @rRepeatCount tinyint,
	 	 @rBatchId int,
	 	 @rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
IF @rSubjectBatchId=0
BEGIN
	IF @rRepeatCount=0
	BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			ISNULL(SO.GenderId,0) AS GenderId,
			ISNULL(GM.Title,'') AS Gender
  FROM 
            sStudent.vStudentAcademic SA 
            LEFT JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId
            LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      --AND (SA.StatusId != 3)
      AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
  ELSE
  BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId 
			
  FROM 
            sStudent.vStudentAcademic SA 
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.RepeatCount,0)=@rRepeatCount) OR (@rRepeatCount=0))
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      --AND (SA.StatusId != 3)
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
       AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
END
ELSE
BEGIN
	IF @rRepeatCount=0
	BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId 
			
  FROM 
            sStudent.vStudentAcademic SA
             INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
		INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
			AND SBS.BatchId=@rBatchId AND SBS.SubjectBatchId=@rSubjectBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      --AND (SA.StatusId != 3)
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
  ELSE
  BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId
			
  FROM 
            sStudent.vStudentAcademic SA 
             INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.RepeatCount,0)=@rRepeatCount) OR (@rRepeatCount=0))
		INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
			AND SBS.BatchId=@rBatchId AND SBS.SubjectBatchId=@rSubjectBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
      --AND (SA.StatusId != 3)
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
END
END
GO
PRINT N'Altering [sBiometric].[pBiometricReportDataDateWise]...';


GO
ALTER 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 = 1
	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) + ') Not in (''-'',''XX'') 
						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(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') 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

	LEFT Join (select   distinct  EmployeeId,
    ISNULL( stuff((
        select Distinct '','' + LT.Code + '':'' + Convert(nvarchar(10),Sum(NoOfLeave)) 
        from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
        where  (FromDate >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''')) 
        AND (ToDate <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
        AND L.EmployeeId = L1.EmployeeId AND L.StatusId= 550
        group by LT.Code
        for xml path('''')
    ),1,1,''''),'''') as LeaveCode1
	from shrm.tLeave L1 
	inner join shrm.tLeaveTypeMaster LT ON LT.Id=L1.LeaveTypeId AND L1.StatusId=550
	group by EmployeeId,LT.Code) AS LV1 ON LV1.EmployeeId = T.EmployeeId 
	WHERE  (len((''' + @rGRadeId + '''))= 1 AND EmployeeGradeId > 0 ) Or
   (len((''' + @rGRadeId + ''')) > 1 AND EmployeeGradeId in(' + convert(nvarchar(100),@rGRadeId) + ')) Order By T.EmployeeId,T.Attn_Date' 
	--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'Altering [sCertificate].[pRptLeavingCertificateGet]...';


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

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

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


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


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

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


GO
 

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

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


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

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

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

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

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

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

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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


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

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

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

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

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

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

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

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


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

DELETE FROM 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 [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,
          ISNULL(Remark,'') AS 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,
          ISNULL(Remark,'') AS 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,
          ISNULL(Remark,'') AS 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 [sEis].[pRptInquiryAdmissionGet]...';


GO

ALTER PROCEDURE [sEis].[pRptInquiryAdmissionGet]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rClassId int=0,
	@rDivisionId int=0,
	@rDepartmentId int=0,
	@rOrgMainGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgSubGroupId int=0,
	@rOrgId smallint=0,
	@rStrOrgMainGroupId nvarchar(max)='',
	@rStrOrgSubGroupId nvarchar(max)='',
	@rStrOrgId nvarchar(max)='',
	@rStrDepartmentId nvarchar(max)='',
	@rStrClassId nvarchar(max)='',
	@rClusterId int ,
	@rIsTestMainGroup bit =0,
	@rIsTestSubGroup bit =0,	
	@rIsTestOrg bit=0,
	@rIsTestDepartment bit=0,
	@rIsTestClass bit=0,
	@rIsTestDivision bit=0,
	@rReportId int =0,
	@rIsDisplayOrgGroup bit=0,
	@rIsDisplayGender bit=0,
	@rBatchGroupId int =0,
	@rStatusId int=0,
	@rStudentStatusId int=0,
	@rClusterOrgGroupId int=0,
	@rClusterOrgMainGroupId int=0,
	@rClusterOrgSubGroupId int=0,
	@rToDate datetime='',
	@rFromDate datetime='',
	@rClusterBatchGroupId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestClass AS IsTestClass,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			COM.Id AS ClusterMainGroupId,
			COM.Title AS ClusterMainGroupTitle,
			COSG.Id AS ClusterSubGroupId,
			COSG.Title AS ClusterSubGroupTitle,
			CM.DepartmentId,
			DM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			(select COUNT(AI.Id) FROM sAdmission.tAdmissionInquiry AI 
			 INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			 INNER JOIN sEis.tClusterBatchGroupMapping CBM ON CBM.OrgGroupBatchId=BM.OrgGroupBatchId
			 INNER JOIN sEis.tClusterBatchGroupMaster CBGM ON CBGM.Id=CBM.ClusterBatchGroupId
			 INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId   AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			  WHERE CBGM.ClusterId=@rClusterId 
			  AND  (CBM.ClusterBatchGroupId = @rClusterBatchGroupId)
			  AND AI.InquiryDate >= @rFromDate 
			  AND AI.InquiryDate <= @rToDate AND AI.ForClassId = CM.Id
			 AND  BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			 ) NoOfInquiry, 

		    (select COUNT(A.Id) FROM sStudent.tStudentAdmission SA 
			INNER JOIN sStudent.tAcademic A ON SA.StudentId = A.StudentId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			AND SA.AdmissionStandardId = A.ClassId
			INNER JOIN sEis.tClusterBatchGroupMapping CBM ON CBM.OrgGroupBatchId=BM.OrgGroupBatchId
			INNER JOIN sEis.tClusterBatchGroupMaster CBGM ON CBGM.Id=CBM.ClusterBatchGroupId
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id=BM.BatchGroupId   AND ((BGM.Id=@rBatchGroupId) OR (@rBatchGroupId=0))
			WHERE  CBGM.ClusterId=@rClusterId  
		    AND  CBM.ClusterBatchGroupId = @rClusterBatchGroupId
			AND SA.AdmissionDate >= @rFromDate 
			AND SA.AdmissionDate <= @rToDate 
			AND BM.IsActive = CASE WHEN @rStatusId =1 THEN 1 WHEN @rStatusId=2 THEN 0 ELSE BM.IsActive END
			AND A.ClassId =CM.Id  ) AS NoOfAdmission
 
	FROM 
			sSetup.tClassMaster CM						
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId
			INNER JOIN sEis.tClusterOrgSubGroupMapping CO ON CO.OrgId=DM.OrgId
			INNER JOIN sEis.tClusterOrgSubGroupMaster COSG ON COSG.Id = CO.ClusterOrgSubGroupId
			INNER JOIN sEis.tClusterOrgMainGroupMaster COM ON COM.Id=COSG.EisOrgMainGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CO.OrgId
			INNER JOIN sEis.tClusterOrgGroup CG ON CG.OrgGroupId= OM.OrgGroupId
			INNER JOIN sEis.tClusterMaster CMM ON CMM.Id=COM.ClusterId
			INNER JOIN sEis.tClusterBatchGroupMaster CBGM ON CBGM.ClusterId=CMM.Id
			INNER JOIn sEis.tClusterBatchGroupMapping CBM ON CBM.ClusterBatchGroupId=CBGM.Id
			INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id = CBM.OrgGroupBatchId AND OG.Id=OBM.OrgGroupId
			
	WHERE 
	        ((CM.Id=@rClassId) OR (@rClassId=0))
			AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(	@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit ( @rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
		    AND	CG.ClusterId = @rClusterId AND	COM.ClusterId = @rClusterId AND	COSG.ClusterId = @rClusterId AND CMM.ID = @rClusterId AND CBGM.ClusterId = @rClusterId
			AND CBGM.Id=@rClusterBatchGroupId
			AND((COM.Id=@rClusterOrgMainGroupId) OR @rClusterOrgMainGroupId=0)
			AND ((CG.OrgGroupId=@rClusterOrgGroupId) OR @rClusterOrgGroupId=0)
			AND ((COSG.Id=@rClusterOrgSubGroupId) OR @rClusterOrgSubGroupId=0)
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering [sErp].[pLeadFollowupGet]...';


GO
ALTER PROCEDURE [sErp].[pLeadFollowupGet]
	
	
	 @rId bigint = 0,
	 @rFromDate date='',
	 @rToDate date='',
	 @rOrgId bigint=0,	
	 @rLeadId bigint=0,
	 @rEmpId bigint =0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
	LF.Id,
	LF.LeadId,
	ISNULL(LF.FollowupDate,'') AS  FollowupDate,
	LF.FollowupRemark,
	LF.FollowupEmployeeId,
	LM.Title AS Lead,
	
	ISNULL(LM.NextFollowupDate,'0001/01/01') AS NextFollowupDate,
	LM.OrgId,
	OM.DisplayTitle AS OrgName,
	EM.FirstName +' '+ MiddleName +' '+ LastName AS EmployeeName
	
  FROM 
                 sErp.tLeadFollowup LF
                 LEFT JOIN sErp.tLeadMaster LM ON LM.Id=LF.LeadId   AND ((LM.OrgId=@rOrgId) OR (@rOrgId=0))
				LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=LM.OrgId
				INNer JOIN sHrm.tEmployeeMaster EM ON EM.Id=LF.FollowupEmployeeId
  WHERE  
      ((LF.Id = @rId) OR (@rId = 0))
      AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	  AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))	
	  AND ((LF.LeadId = @rLeadId) OR (@rLeadId = 0))
	  AND ((LF.FollowupEmployeeId = @rEmpId) OR (@rEmpId = 0))
	  --AND ((LF.LeadId = @rLeadId) OR (@rLeadId = 0))
	  Order by LF.FollowupDate  
END
GO
PRINT N'Altering [sErp].[pLeadMasterAdd]...';


GO
ALTER PROCEDURE [sErp].[pLeadMasterAdd]
	 @rOrgId smallint,
	 @rId int, 
	 @rLeadAffiliationId smallint,
	 @rTitle nvarchar(200),	
	 @rStreetDetail nvarchar(300),
	 @rAreaName nvarchar(100),
	 @rCityName nvarchar(100),
	 @rStateId int,
	 @rCountryId int,
	 @rVcpId int,
	 @rdistrict nvarchar(50),
	 @rZipCode nvarchar(20),
	 @rWebsite nvarchar(100),
	 @rPhoneNo nvarchar(50),
	 @rMobileNo nvarchar(50),
	 @rContactPerson nvarchar(100),
	 @rContactMobileNo nvarchar(50),
	 @rContactDesignation nvarchar(100),
	 @rLeadStatusId tinyint,
	 @rLeadSourceId tinyint,
	 @rLeadOwnerEmployeeId bigint,
	 @rCreatedUserId bigint, 
	 @rUpdatedUserId bigint ,
	 @rNextFollowupDate date,
	 @rNextFollowupRemark  nvarchar(200),
	 @rEmail nvarchar(100),
	 @rContactEmail nvarchar(100),
	 @rContactPerson2 nvarchar(100),
	 @rContactMobileNo2 nvarchar(50),
	 @rContactDesignation2 nvarchar(100),
	 @rContactEmail2 nvarchar(100),
	   @rContactPerson3 nvarchar(100),
	 @rContactMobileNo3 nvarchar(50),
	 @rContactDesignation3 nvarchar(100),
	 @rContactEmail3 nvarchar(100),
	   @rContactPerson4 nvarchar(100),
	 @rContactMobileNo4 nvarchar(50),
	 @rContactDesignation4 nvarchar(100),
	 @rContactEmail4 nvarchar(100),
	   @rContactPerson5 nvarchar(100),
	 @rContactMobileNo5 nvarchar(50),
	 @rContactDesignation5 nvarchar(100),
	 @rContactEmail5 nvarchar(100)
	      	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sErp.tChannelMaster where Code=@rCode AND OrgId=@rOrgId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sErp.tLeadMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sErp.tChannelMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sErp.tLeadMaster where Title=@rTitle  AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tLeadMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tLeadMaster
		(
			Id
      ,OrgId
      ,LeadAffiliationId
      ,Title
      ,StreetDetail
      ,AreaName
      ,CityName
      ,StateId
      ,CountryId
      ,ZipCode
      ,district
      ,Website
      ,PhoneNo
      ,MobileNo,
      Email
      ,ContactPerson
      ,ContactMobileNo,
      ContactEmail
      ,ContactDesignation
      ,LeadStatusId
      ,LeadSourceId
      ,LeadOwnerEmployeeId
      ,CreatedUserId
      ,CreatedDateTime
      ,UpdatedUserId
      ,UpdatedDateTime
      ,NextFollowupDate
      ,NextFollowupRemark
       ,ContactPerson2
      ,ContactMobileNo2
      ,ContactDesignation2
      ,ContactEmail2
      ,ContactPerson3
      ,ContactMobileNo3
      ,ContactDesignation3
      ,ContactEmail3
      ,ContactPerson4
      ,ContactMobileNo4
      ,ContactDesignation4
      ,ContactEmail4
      ,ContactPerson5
      ,ContactMobileNo5
      ,ContactDesignation5
      ,ContactEmail5
      ,LeadChannelPartnerId
		)
	VALUES
		(
		 @lNextNumber
      , @rOrgId
      , @rLeadAffiliationId
      , @rTitle
      , @rStreetDetail
      , @rAreaName
      , @rCityName
      , @rStateId
      , @rCountryId
      , @rZipCode
      ,@rdistrict
      , @rWebsite
      , @rPhoneNo
      , @rMobileNo,
      @rEmail
      , @rContactPerson
      , @rContactMobileNo
	  ,@rContactEmail
      , @rContactDesignation
      , @rLeadStatusId
      , @rLeadSourceId
      , @rLeadOwnerEmployeeId
      , @rCreatedUserId
      , sCommon.fGetDate()
      , @rUpdatedUserId
      , sCommon.fGetDate()
      , @rNextFollowupDate
      , @rNextFollowupRemark
	  , @rContactPerson2
      , @rContactMobileNo2
      , @rContactDesignation2
      , @rContactEmail2
      , @rContactPerson3
      , @rContactMobileNo3
      , @rContactDesignation3
      , @rContactEmail3
      , @rContactPerson4
      , @rContactMobileNo4
      , @rContactDesignation4
      , @rContactEmail4
      , @rContactPerson5
      , @rContactMobileNo5
      , @rContactDesignation5
      , @rContactEmail5
	  , @rVcpId
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tLeadMaster
	    SET
	    
	     LeadAffiliationId=@rLeadAffiliationId
      ,Title=@rTitle
      ,StreetDetail=@rStreetDetail
      ,AreaName=@rAreaName
      ,CityName=@rCityName
      ,StateId=@rStateId
      ,CountryId=@rCountryId
      ,ZipCode=@rZipCode
      ,district =@rdistrict
      ,Website=@rWebsite
      ,PhoneNo=@rPhoneNo
      ,MobileNo=@rMobileNo,
      EMail=@rEmail
      ,ContactPerson=@rContactPerson
      ,ContactMobileNo=@rContactMobileNo
      ,ContactDesignation=@rContactDesignation
      ,LeadStatusId=@rLeadStatusId
      ,LeadSourceId=@rLeadSourceId
      ,LeadOwnerEmployeeId=@rLeadOwnerEmployeeId      
      ,UpdatedUserId=@rUpdatedUserId
      ,UpdatedDateTime=sCommon.fGetDate()
      ,NextFollowupDate=@rNextFollowupDate
      ,NextFollowupRemark=@rNextFollowupRemark
      ,ContactPerson2=@rContactPerson2
      ,ContactMobileNo2=@rContactMobileNo2
      ,ContactDesignation2=@rContactDesignation2
      ,ContactEmail2 = @rContactEmail2
	  ,ContactPerson3=@rContactPerson3
      ,ContactMobileNo3=@rContactMobileNo3
      ,ContactDesignation3=@rContactDesignation3
      ,ContactEmail3 = @rContactEmail3
	  ,ContactPerson4=@rContactPerson4
      ,ContactMobileNo4=@rContactMobileNo4
      ,ContactDesignation4=@rContactDesignation4
      ,ContactEmail4 = @rContactEmail4
      ,ContactPerson5=@rContactPerson5
      ,ContactMobileNo5=@rContactMobileNo5
      ,ContactDesignation5=@rContactDesignation5
      ,ContactEmail5 = @rContactEmail5
	  ,LeadChannelPartnerId = @rVcpId  
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

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


GO
ALTER PROCEDURE [sErp].[pLeadMasterGet]
@rId int,
		@rOrgId smallint=0,
		@rLeadAffiliationId smallint,
		@rTitle nvarchar(200) =null,
		@rAreaName nvarchar(100) =null,
		@rCityName nvarchar(100) =null,
		@rDistrict nvarchar(50) = null,
		@rStateId int =0,
		@rCountryId int=0,
		@rLeadStatusId tinyint,
		@rLeadSourceId tinyint,
		@rLeadOwnerEmployeeId bigint,
		@rFromDate date,
		@rToDate date,
		@rIsWildCardSearch bit,
		@rVcpId int =0
		

	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
IF @rIsWildCardSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
	      LM.Id,
	      LM.OrgId,
	      ISNULL(LM.LeadAffiliationId,0) As LeadAffiliationId,
	      LAM.Title AS Affiliation,
	      LM.Title,
	      LM.StreetDetail,
	      LM.AreaName,
	      LM.CityName,
	     ISNULl( LM.StateId,0) AS StateId,
	      SM.Title AS StateName,
	    ISNULl(  LM.CountryId,0) AS CountryId,
	      CM.Title AS Country,
	      LM.Website,
	      ISNULl(LM.LeadStatusId,0)AS LeadStatusId ,
	      LSM.Title AS LeadStatus,
	      ISNULL(LM.LeadSourceId,0) As LeadSourceId,
	      LS.Title AS LeadSource,
	      ISNULl(LM.LeadOwnerEmployeeId,0) AS LeadOwnerEmployeeId,
	      EM.FirstName +' '+ MiddleName +' '+ LastName AS LeadOwner,
	      LM.NextFollowupDate,
	      LM.NextFollowupRemark,
	      LM.ContactPerson,
	      LM.ContactMobileNo,
	      LM.ContactDesignation,
	      LM.ZipCode,
	      LM.PhoneNo,
	      LM.MobileNo,
	      LM.Email AS EMail,
	      LM.ContactEmail,
	      LM.district,
	      LM.ContactPerson2,
	      LM.ContactMobileNo2,
	      LM.ContactDesignation2,
		  LM.ContactEmail2,
		   LM.ContactPerson3,
	      LM.ContactMobileNo3,
	      LM.ContactDesignation3,
		  LM.ContactEmail3,
		   LM.ContactPerson4,
	      LM.ContactMobileNo4,
	      LM.ContactDesignation4,
		  LM.ContactEmail4,
		   LM.ContactPerson5,
	      LM.ContactMobileNo5,
	      LM.ContactDesignation5,
		  LM.ContactEmail5,
		  LM.LeadChannelPartnerId
				    
	FROM 
			sErp.tLeadMaster LM
			LEFT JOIN sErp.tLeadAffiliationMaster LAM ON LAM.Id=LM.LeadAffiliationId
			LEFT JOIN sErp.tLeadSourceMaster LS ON  LS.Id=LM.LeadSourceId
			LEFT JOIN sErp.tLeadStatusMaster LSM ON LSM.Id=LM.LeadStatusId
			LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LM.LeadOwnerEmployeeId
			LEFT JOIN sCommon.tCountryMaster CM ON  CM.Id = LM.CountryId
			LEFT JOIN sCommon.tStateMaster SM ON SM.Id=LM.StateId
			
	WHERE 
	(LM.OrgId = @rOrgId)	
		AND	((LM.Id = @rId) OR (@rId = 0))	
	AND ((LM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND ((LM.AreaName Like @rAreaName)OR(ISNULL(@rAreaName,'') = ''))
	AND ((LM.CityName Like @rCityName)OR(ISNULL(@rCityName,'') = ''))
	AND	((LM.StateId = @rStateId) OR (@rStateId = 0))
	AND ((LM.district Like @rDistrict) OR (ISNULL(@rDistrict,'') = ''))
	AND	((LM.CountryId = @rCountryId) OR (@rCountryId = 0))
	AND	((LM.LeadChannelPartnerId = @rVcpId) OR (@rVcpId = 0))
	AND	((LM.LeadAffiliationId = @rLeadAffiliationId) OR (@rLeadAffiliationId = 0))
	AND	((LM.LeadStatusId = @rLeadStatusId) OR (@rLeadStatusId = 0))
	AND	((LM.LeadSourceId = @rLeadSourceId) OR (@rLeadSourceId = 0))
	AND	((LM.LeadOwnerEmployeeId = @rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId = 0))
	AND ((LM.NextFollowupDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((LM.NextFollowupDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	--AND	((LM.NextFollowupDate = @rNextFollowupDate) OR (@rNextFollowupDate = 0))
	
			
	
		
		ORDER BY LM.CreatedDateTime DESC
END
GO
PRINT N'Altering [sFee].[pFeeFollowupAdd]...';


GO
ALTER PROCEDURE [sFee].[pFeeFollowupAdd]
		
		@rId	bigint,	
		@rReceiptBookId	int,
		@rAcademicId bigint,
		@rFollowupDate	date=NULL,
		@rFollowupRemark	nvarchar(150),
		@rCreatedUserId	bigint,
		@rHandledBy	nvarchar(100),	
		@rOrgId smallint,
		@rNextFollowupDate date=NULL
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		BEGIN TRY
		BEGIN TRANSACTION	
		IF(@rId = 0)	
		BEGIN
			DECLARE @lNextNumber BIGINT 
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tFeeFollowup', 0, 1, 1,@outNextNumber = @lNextNumber output
				
			INSERT INTO sFee.tFeeFollowup
			(
				Id,
				ReceiptBookId,
				AcademicId,
				FollowupDate,
				FollowupRemark,
				CreatedUserId,
				CreatedDateTime,
				HandledBy,
				NextFollowupDate
			)
			VALUES
			(
				@lNextNumber,
				@rReceiptBookId,
				@rAcademicId,
				@rFollowupDate,
				@rFollowupRemark,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rHandledBy,
				@rNextFollowupDate
			)
			
			SELECT 1 AS Result         
		END	 
		ELSE
		BEGIN
			SET @lNextNumber = @rId
			UPDATE  sFee.tFeeFollowup
			SET
				 ReceiptBookId=@rReceiptBookId,
				 AcademicId = @rAcademicId,
				 FollowupDate=@rFollowupDate,
				 FollowupRemark=@rFollowupRemark,
				 UpdatedUserId=@rCreatedUserId,
				 HandledBy=@rHandledBy,
				 UpdatedDateTime=sCommon.fGetDate(),
				 NextFollowupDate=@rNextFollowupDate
			WHERE Id = @rId 	   
			
			SELECT 11 AS Result      
		END 
		 
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeeFollowupGet]...';


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

BEGIN 
	SELECT 
		FF.Id,
		vSA.Code,
		FF.ReceiptBookId,
		ISNULL(FF.FollowupDate,'') AS  FollowupDate,
		FF.FollowupRemark,
		FF.HandledBy,
		vSA.Name,
		ISNULL(FF.NextFollowupDate,'') AS NextFollowupDate,
		vSA.OrgId,
		OM.DisplayTitle AS OrgName,
		vSA.RollNo,
		vSA.ParentContactNo,
		ClassDivision,
		DM.OrderIndex  AS DivisionOrderIndex,
		vSA.AcademicId
	FROM 
		sFee.tFeeFollowup FF
		INNER JOIN sStudent.vStudentAllDetail vSA ON  vSA.AcademicId = FF.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vSA.OrgId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vSA.DivisionId
	WHERE  
		(FF.Id = @rId OR @rId = 0)
		AND (FF.FollowupDate>= @rFromDate OR ISNULL(@rFromDate,'')='')
		AND (FF.FollowupDate<= @rToDate OR ISNULL(@rToDate,'')='')
		AND (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (FF.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
	ORDER BY FF.FollowupDate  
END
GO
PRINT N'Altering [sFee].[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='',
		@rFromNextFollowupDate date='',
		@rToNextFollowupDate 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,			 
				Temp.ReceiptBookId,
				Temp.AcademicId,
				DivisionId,
				ClassDivision,
				RollNo, 
				Name,
				Code,
				ReceiptBookTitle,
				OrgName,
				SUM(PendingAmount) AS PendingAmount, 
				[sFee].[fPendingFeeNamesGet](Temp.AcademicId,Temp.ReceiptBookId,	@p) AS PendingFeeName,
				ReceiptOrderIndex,
				BatchId,
				BatchName,
				'' AS SUId,
				FF.NextFollowupDate
			FROM @p Temp
			LEFT JOIN 
			(
				SELECT AcademicId,ReceiptBookId,NextFollowupDate 
				FROM 
				(
				SELECT AcademicId,ReceiptBookId,NextFollowupDate, 
				ROW_NUMBER() OVER(PARTITION BY AcademicId,ReceiptBookId ORDER BY NextFollowupDate DESC) AS RowNumber
				FROM sFee.tFeeFollowup FF 
				) AS T
				WHERE RowNumber = 1 
			) FF ON FF.AcademicId = Temp.AcademicId AND FF.ReceiptBookId = Temp.ReceiptBookId
		WHERE 
			((FF.NextFollowupDate >= @rFromNextFollowupDate) OR (ISNULL(@rFromNextFollowupDate,'') = ''))
			AND ((FF.NextFollowupDate <= @rToNextFollowupDate) OR (ISNULL(@rToNextFollowupDate,'') = ''))
			GROUP BY 
			OrgId,Temp.AcademicId,Temp.ReceiptBookId,DivisionId,BatchId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,
			OrgName,ReceiptOrderIndex,BatchName,FF.NextFollowupDate
			ORDER BY Temp.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,    
			FS.FeeDuration AS FeeDuration,
			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN  FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN  FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
	        ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue ,
	        SF.FatherName,
	        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 [sFee].[pRptTransportFeePendingWithFeeNameGet]...';


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


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

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

			SELECT
			P.OrgId,			 
			P.ReceiptBookId,
			P.AcademicId,
			P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,ReceiptBookTitle,OrgName,
			SUM(P.PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](P.AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			P.ReceiptOrderIndex,
			BR.Id AS BusRouteId,
			BR.Title AS BusRoute,
			BD.Title AS BusDestination
			
			FROM @p P INNER JOIN sStudent.vStudentAcademic VA ON p.AcademicId=VA.AcademicId
			INNER JOIN sTransport.tAssignRoute AR oN VA.StudentId = AR.SourceId AND SourceTypeId = 2003
			INNER JOIN sTransport.tBusRouteDestinationMaster BD ON BD.Id = AR.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster BR ON BR.Id = BD.BusRouteId 
			AND BR.OrgGroupBatchId = @rOrgGroupBatchId
			GROUP By P.ReceiptBookId,P.OrgId,P.AcademicId,P.DivisionId,
			P.ClassDivision,P.RollNo, P.Name,P.Code,
			P.ReceiptBookTitle,P.OrgName,P.ReceiptOrderIndex,BR.Title,BD.Title,BR.Id	
			ORDER BY P.AcademicId
 
END
GO
PRINT N'Altering [sFrontOffice].[pEmployeeGatePassGet]...';


GO


ALTER PROCEDURE [sFrontOffice].[pEmployeeGatePassGet]
          
           @rId int,
           @rOrgId int=0,
           @rFromGatePassDate datetime='',
           @rToGatePassDate datetime='',
           @rEntryModeStatusId smallint=0,
           @rCode nvarchar(20)='',
           @rOrgGroupId int=0,
           @rReportId int=0
           
AS
SET NOCOUNT ON
BEGIN
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId
		SELECT  
			EG.Id,
			EM.Code,
			EM.FirstName+' '+EM.MiddleName+' '+EM.LastName AS Name,
			EG.EmployeeId,
			EG.ReasonOfGatePass,
			EG.GatePassDate,
			EG.GatePassTime,
			EG.EntryModeStatusId,
			SM.Title AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			ISNULL(U.DisplayTitle,'') AS UserName,
			EI.EmployeePhoto,
			Remark,
			@GatePassConfig AS ConfigValue
		
		FROM 
		    sFrontOffice.tEmployeeGatePass EG 
		    INNER JOIN  sHrm.tEmployeeMaster EM ON EG.EmployeeId = EM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=EG.OrgId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=EG.EntryModeStatusId
			LEFT JOIN sSecurity.tUser U	ON U.Id=EG.CreatedUserId
			--INNER JOIN sSecurity.tUserOrganization UO ON U.Id = @rUserId
		    LEFT JOIN  sHrm.tEmployeeImages EI ON EI.EmployeeId=EM.Id
			
		WHERE 
			OM.OrgGroupId=@rOrgGroupId
		    AND ((EG.Id=@rId) OR (@rId=0))
			AND ((EG.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((EG.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((EG.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((EG.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((EM.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			ORDER BY EG.GatePassDate,EG.GatePassTime DESC
END
GO
PRINT N'Altering [sFrontOffice].[pStudentGatePassGet]...';


GO


ALTER PROCEDURE [sFrontOffice].[pStudentGatePassGet]
          
           @rId int,
           @rOrgId int=0,
           @rFromGatePassDate datetime='',
           @rToGatePassDate datetime='',
           @rEntryModeStatusId smallint=0,
           @rCode nvarchar(20)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int=0,
           @rUserId bigint= 0 
AS
SET NOCOUNT ON
BEGIN
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId
		
		SELECT  
			SGP.Id,
			vSA.Code,
			vSA.FirstName+' '+vSA.LastName AS Name,
			VSA.ClassName+' - '+VSA.DivisionName AS Class,
			SGP.AcademicId,
			ISNULL(SGP.RelationshipId,0) AS RelationshipId,
			RM.Title AS Relationship,
			SGP.Relation,
			SGP.VisitorName,
			ISNULL(SGP.VisitorMobile,0) As VisitorMobile,
			SGP.ReasonOfGatePass,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SGP.VisitorPhoto		
			ELSE ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
			--ISNULL(SGP.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
			ISNULL(SGP.GatePassDate,'') As GatePassDate,
			ISNULL(SGP.GatePassTime,'') As GatePassTime,
			ISNULL(SGP.EntryModeStatusId,0) AS EntryModeStatusId,
			ISNULL(SM.Title,'')  AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			(CASE  WHEN @rIsPrintView=1 THEN 
				SI.StudentPhoto		
			ELSE ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS StudentPhoto,
			--ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(U.DisplayTitle,'') AS UserName,
			vSA.SUId,
			Remark,
			@GatePassConfig AS ConfigValue
		FROM 
		    sStudent.vStudentAcademic vSA
			INNER JOIN sFrontOffice.tStudentGatePass SGP ON SGP.AcademicId = vSA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			INNER JOIN sCommon.tRelationshipMaster RM ON RM.Id=SGP.RelationshipId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=SGP.EntryModeStatusId
			INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId = SGP.OrgId AND UO.UserId = @rUserId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=vSA.StudentId
			LEFT JOIN sSecurity.tUser U	ON U.Id=SGP.CreatedUserId
			
		WHERE 
		  ((SGP.Id=@rId) OR (@rId=0))
			AND ((SGP.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SGP.GatePassDate>=@rFromGatePassDate) OR (ISNULL(@rFromGatePassDate,'')=''))
			AND ((SGP.GatePassDate<=@rToGatePassDate) OR (ISNULL(@rToGatePassDate,'')=''))
			AND ((SGP.EntryModeStatusId=@rEntryModeStatusId) OR (@rEntryModeStatusId=0))
			AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
			AND (OM.OrgGroupId=@rOrgGroupId)		 
			--AND vSA.IsActiveBatch=1
			ORDER BY SGP.GatePassDate,SGP.GatePassTime DESC
			
END
GO
PRINT N'Altering [sHrm].[pEmployeeAttendanceGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeAttendanceGet]
	 
	@rForYear  bigint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
BEGIN 
	SELECT  
		EM.Code AS EmployeeCode,
		EM.EmployeeName,   
		EM.EmployeeId,
		ISNULL(EM.EmployeeGrade,'') AS EmployeeGrade,
		ISNULL(WD.TotalDays,0) AS TotalDays,
		ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays,
		(ISNULL(AT.TotalWorkingDays,0) - (ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0))) AS PresentDays,
		(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS PayrollDays,
		(ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)) AS LWP,
		ISNULL(AT.PaidLeave,0) AS PaidLeave,
		ISNULL(AT.LWP,0) AS UnPaidLeave
	FROM 
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId		 
		AND AT.ForMonth=@rForMonth AND AT.ForYear=@rForYear AND AT.BatchId = @rBatchId
	WHERE 
		EM.OrgID = @rOrgId 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
		AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	ORDER BY 
		EM.Code
END
GO
PRINT N'Altering [sHrm].[pEmployeeDataModify]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeDataModify]	 
	@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

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup'
	OR @rSubCategoryField = 'MaritalStatus' OR @rSubCategoryField = 'OrganizationDepartment' OR @rSubCategoryField = 'EmployeeType'
			OR @rSubCategoryField = 'EmployeeGroup' OR @rSubCategoryField = 'EmployeeGrade' OR @rSubCategoryField = 'Relationship' OR  @rSubCategoryField = 'EmployeeDesignation'
			OR  @rSubCategoryField = 'Payroll' OR  @rSubCategoryField = 'PayrollGroup' 
			)
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	ELSE IF (@rSubCategoryField = 'CasteCategory' )
		BEGIN
			SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')+'Id'
		END
		
	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,EmployeeId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications) 
		
		set @sql='INSERT INTO sHrm.tEmployeeCommunications 
					(EmployeeId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql
		set @sql='UPDATE sHrm.tEmployeeCommunications set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeCommunications EC 
					INNER JOIN ListofData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END
	    
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
					
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	Else IF(@rCategoryId= 3)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
	
		set @sql='UPDATE sHrm.tEmployeeJobDetail set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeJobDetail EJ 
					INNER JOIN ListofData LD ON EJ.EmployeeId=LD.EmployeeId'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'DateOfJoining' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfJoining=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'DateOfleaving' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfleaving=''1900-01-01'''
			Exec sp_executesql @sql
		END

		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeMaster) 
		
		
		set @sql='UPDATE sHrm.tEmployeeMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeMaster HEM 
					INNER JOIN ListofData LD ON HEM.Id=LD.EmployeeId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			SELECT 1 AS StatusId
	    END
	    
	    Else IF(@rCategoryId= 5)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,E.SubCategory,E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 
						
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeStatutoryAndOther) 
		
		set @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
					(EmployeeId,'+@rSubCategoryField+',IsVPFDeduction,UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,0,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql			
		
		
		IF(@rSubCategoryField = 'EPFJoinDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE EPFJoinDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE IF(@rSubCategoryField = 'IncrementDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE IncrementDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'

			Exec sp_executesql @sql
		END
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	    
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	Drop Table ListofData
	--	SELECT -1 AS Result
	--END CATCH
GO
PRINT N'Altering [sHrm].[pEmployeeProfileGet]...';


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

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


GO

ALTER PROCEDURE [sLibrary].[pRptBookListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookSubject nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150)='',
	 @rIsDetail bit=0,
	 @rFromPurchaseDate date='',
	 @rToPurchaseDate date=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 

			BEGIN	  
			SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
			SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
			SET @rBookSubject = sCommon.fSearchStringGet(@rBookSubject)
			SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
			SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
			SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
			SET @rBookDepartment = sCommon.fSearchStringGet(@rBookDepartment)
	        END

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BM.Code,
			BM.Title As BookTitle,
			BM.Publisher,BM.Supplier,
			BM.BookSubject,
			BM.BookLanguage,
			BM.BookCustomTag,
			BM.BookCustomTag,
			BM.Location,
			BM.ISBNNumber,
			 LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2,
	       CASE WHEN BM.BookDepartment is null THEN 'Blank'
	            WHEN BM.BookDepartment='' THEN 'Blank'  ELSE BM.BookDepartment END AS  BookDepartment,
	        BM.NoOfCopies,
	        @rIsDetail AS IsDetail,
	        LM.Code AS LibraryCode,	       
	        BM.AccessionNo AS AccessionNo
			
	FROM 
			sLibrary.tBookMaster BM
			 LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
			
			
	WHERE 
			BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookSubject like @rBookSubject) OR (@rBookSubject=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.BookDepartment like @rBookDepartment) OR (@rBookDepartment=''))
		AND ((BM.PurchaseDate >= @rFromPurchaseDate) OR (ISNULL(@rFromPurchaseDate,'') = ''))
		AND ((BM.PurchaseDate <= @rToPurchaseDate) OR (ISNULL(@rToPurchaseDate,'') ='') OR (BM.PurchaseDate is null))
	END
GO
PRINT N'Altering [sOp].[pGatewayConfigurationAdd]...';


GO
ALTER PROCEDURE [sOp].[pGatewayConfigurationAdd]
	
	@rId int,
	@rOrgGroupId smallint,
	@rPaymentGatewayId smallint,
	@rGatewayURL nvarchar(1000),
	@rServerPort nvarchar(50),
	@rLoginId nvarchar(50),
	@rLoginPassword nvarchar(50),
	@rProductId nvarchar(100),
	@rTermsCondition nvarchar(max)='',
	@rPrivacyPolicy nvarchar(max)='',
	@rPaymentPolicy nvarchar(max)='',
	@rDisclaimer nvarchar(max)='',
	@rContactUs nvarchar(max)='',
	@rAboutUs nvarchar(max)='',
	@rIsObsolete bit=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION	
	
	DECLARE @lNextNumber INT     
	IF(@rId = 0)	
	BEGIN
		
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sOp.tGatewayConfiguration', 0, 1, 1,@outNextNumber = @lNextNumber output

		INSERT INTO sOp.tGatewayConfiguration
			(
				Id,
				OrgGroupId,
				PaymentGatewayId,
				GatewayURL,
				ServerPort,
				LoginId,
				LoginPassword,
				ProductId,
				TermsCondition,
				PrivacyPolicy,
				PaymentPolicy,
				Disclaimer,
				ContactUs,
				AboutUs,
				IsObsolete
			)
		VALUES
			(
				@lNextNumber,
				@rOrgGroupId,
				@rPaymentGatewayId,
				@rGatewayURL,
				@rServerPort,
				@rLoginId,
				@rLoginPassword,
				@rProductId,
				@rTermsCondition,
				@rPrivacyPolicy,
				@rPaymentPolicy,
				@rDisclaimer,
				@rContactUs,
				@rAboutUs,
				@rIsObsolete
			)

	END 
	ELSE
	BEGIN

		SET @lNextNumber = @rId
	    UPDATE  sOp.tGatewayConfiguration
	    SET
			PaymentGatewayId=@rPaymentGatewayId,
			GatewayURL=@rGatewayURL,
			ServerPort=@rServerPort,
			LoginId=@rLoginId,
			LoginPassword=@rLoginPassword,
			ProductId=@rProductId,
			TermsCondition=@rTermsCondition,
			PrivacyPolicy=@rPrivacyPolicy,
			PaymentPolicy=@rPaymentPolicy,
			Disclaimer=@rDisclaimer,
			ContactUs=@rContactUs,
			AboutUs=@rAboutUs,
			IsObsolete=@rIsObsolete
	     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 [sOp].[pGatewayConfigurationGet]...';


GO
ALTER PROCEDURE [sOp].[pGatewayConfigurationGet]
	 
	 @rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	SELECT
			ISNULL(GC.Id,0) AS Id,
			GC.OrgGroupId,
			GC.PaymentGatewayId,
			GC.GatewayURL,
			GC.ServerPort,
			GC.LoginId,
			GC.LoginPassword,
			GC.ProductId,
			ISNULL(TermsCondition,'') AS TermsCondition,
			ISNULL(PrivacyPolicy,'') AS PrivacyPolicy,
			ISNULL(PaymentPolicy,'') AS PaymentPolicy,
			ISNULL(Disclaimer,'') AS Disclaimer,
			ISNULL(ContactUs,'') AS ContactUs,
			ISNULL(AboutUs,'') AS AboutUs,
			ISNULL(IsObsolete,'') AS IsObsolete
	FROM
			sOp.tGatewayConfiguration GC
	WHERE 
			GC.OrgGroupId=@rOrgGroupId
END
GO
PRINT N'Altering [sOp].[pGatewayProductAdd]...';


GO
ALTER PROCEDURE [sOp].[pGatewayProductAdd]
	 
        @rId int,
	    @rGatewayConfigurationId int,
		@rTitle nvarchar(150),
		@rGatewayURL nvarchar(1000),
		@rServerPort nvarchar(50),
		@rLoginId nvarchar(50),
		@rLoginPassword nvarchar(50),
		@rProductId nvarchar(100),
		@rOrgGroupId int,
		@rCCAvenueMerchantID nvarchar(50)='',
		@rCCAvenueAccessCode nvarchar(100)='',
		@rCCAvenueWorkingKey nvarchar(100)='',
		@rCCAvenueWhitelistURL nvarchar(500)='',
		@rCCAvenueSubAccountId nvarchar(100)='',
		
		@rAtomReqHashKey nvarchar(100)='',
		@rAtomRespHashKey nvarchar(100)='',
		@rPaytmMID nvarchar(50)='',
		@rPaytmMerchantKey nvarchar(50)='',
		@rPaytmChannelId nvarchar(20)='',
		@rPaytmIndustryTypeId nvarchar(20)='',
		@rPaytmWebsite nvarchar(20)='',
		@rPaytmStatusCheckURL nvarchar(500)='',
		@rPayUMoneyMERCHANTID nvarchar(20)='',
		@rPayUMoneyMERCHANTKEY nvarchar(20)='',
		@rPayUMoneySALT nvarchar(20)='',
		@rPayUMoneyHASHSEQUENCE nvarchar(200)='',
		@rPayUMoneyAUTHHEADER nvarchar(50)=''
		
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY

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

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

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sOp.tGatewayProduct', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO [sOp].[tGatewayProduct]
		(
			[Id],
			[GatewayConfigurationId],
			[Title],
			[GatewayURL],
			[ServerPort],
			[LoginId],
			[LoginPassword],
			[ProductId],
			[CCAvenueMerchantID],
			[CCAvenueAccessCode],
			[CCAvenueWorkingKey],
			[CCAvenueWhitelistURL],
			[CCAvenueSubAccountId],
			[AtomReqHashKey],
			[AtomRespHashKey],
			[PaytmMID],
			[PaytmMerchantKey],
			[PaytmChannelId],
			[PaytmIndustryTypeId],
			[PaytmWebsite],
			[PaytmStatusCheckURL],
			[PayUMoneyMERCHANTID],
			[PayUMoneyMERCHANTKEY],
			[PayUMoneySALT],
			[PayUMoneyHASHSEQUENCE],
			[PayUMoneyAUTHHEADER]
		)
	VALUES
		(
			@lNextNumber,
			@rGatewayConfigurationId,
			@rTitle,
			@rGatewayURL,
			@rServerPort,
			@rLoginId,
			@rLoginPassword,
			@rProductId,
			@rCCAvenueMerchantID,
			@rCCAvenueAccessCode,
			@rCCAvenueWorkingKey,
			@rCCAvenueWhitelistURL,
			@rCCAvenueSubAccountId,
			@rAtomReqHashKey,
			@rAtomRespHashKey,
			@rPaytmMID,
			@rPaytmMerchantKey,
			@rPaytmChannelId,
			@rPaytmIndustryTypeId,
			@rPaytmWebsite,
			@rPaytmStatusCheckURL,
			@rPayUMoneyMERCHANTID,
			@rPayUMoneyMERCHANTKEY,
			@rPayUMoneySALT,
			@rPayUMoneyHASHSEQUENCE,
			@rPayUMoneyAUTHHEADER
		)
		    SELECT 1 AS Result
	END	 
ELSE
	 BEGIN
		SET @lNextNumber = @rId
	    UPDATE  [sOp].[tGatewayProduct]
	    SET
			[GatewayConfigurationId]=@rGatewayConfigurationId,
			[Title]=@rTitle,
			[GatewayURL]=@rGatewayURL,
			[ServerPort]=@rServerPort,
			[LoginId]=@rLoginId,
			[LoginPassword]=@rLoginPassword,
			[ProductId]=@rProductId,
			[CCAvenueMerchantID]=@rCCAvenueMerchantID,
			[CCAvenueAccessCode]=@rCCAvenueAccessCode,
			[CCAvenueWorkingKey]=@rCCAvenueWorkingKey,
			[CCAvenueWhitelistURL]=@rCCAvenueWhitelistURL,
			[CCAvenueSubAccountId]=@rCCAvenueSubAccountId,
			[AtomReqHashKey]=@rAtomReqHashKey,
			[AtomRespHashKey]=@rAtomRespHashKey,
			[PaytmMID]=@rPaytmMID,
			[PaytmMerchantKey]=@rPaytmMerchantKey,
			[PaytmChannelId]=@rPaytmChannelId,
			[PaytmIndustryTypeId]=@rPaytmIndustryTypeId,
			[PaytmWebsite]=@rPaytmWebsite,
			[PaytmStatusCheckURL]=@rPaytmStatusCheckURL,
			[PayUMoneyMERCHANTID]=@rPayUMoneyMERCHANTID,
			[PayUMoneyMERCHANTKEY]=@rPayUMoneyMERCHANTKEY,
			[PayUMoneySALT]=@rPayUMoneySALT,
			[PayUMoneyHASHSEQUENCE]=@rPayUMoneyHASHSEQUENCE,
			[PayUMoneyAUTHHEADER]=@rPayUMoneyAUTHHEADER
	    WHERE Id = @rId
	    SELECT 11 AS Result
	 END  	

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


GO
ALTER PROCEDURE [sOp].[pGatewayProductGet]

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

BEGIN 
	BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	END
	
	SELECT 
			GP.Id,
			GP.GatewayConfigurationId,
			PGM.Title AS PaymentGatewayName,
			GP.Title AS GatewayProductName,
			ISNULL(GP.GatewayURL,'') AS GatewayURL,
			ISNULL(GP.ServerPort,'') AS ServerPort,
			ISNULL(GP.LoginId,'') AS LoginId,
			ISNULL(GP.LoginPassword,'') AS LoginPassword,
			ISNULL(GP.ProductId,'') AS ProductId,
			
			ISNULL(GP.CCAvenueMerchantID,'') AS CCAvenueMerchantID,
			ISNULL(GP.CCAvenueAccessCode,'') AS CCAvenueAccessCode,
			ISNULL(GP.CCAvenueWorkingKey,'') AS CCAvenueWorkingKey,
			ISNULL(GP.CCAvenueWhitelistURL,'') AS CCAvenueWhitelistURL,
			ISNULL(GP.CCAvenueSubAccountId,'') AS CCAvenueSubAccountId,
			
			ISNULL(GP.AtomReqHashKey,'') AS AtomReqHashKey,
			ISNULL(GP.AtomRespHashKey,'') AS AtomRespHashKey,
			ISNULL(GP.PaytmMID,'') AS PaytmMID,
			ISNULL(GP.PaytmMerchantKey,'') AS PaytmMerchantKey,
			ISNULL(GP.PaytmChannelId,'') AS PaytmChannelId,
			ISNULL(GP.PaytmIndustryTypeId,'') AS PaytmIndustryTypeId,
			ISNULL(GP.PaytmWebsite,'') AS PaytmWebsite,
			ISNULL(GP.PaytmStatusCheckURL,'') AS PaytmStatusCheckURL,
			ISNULL(GP.PayUMoneyMERCHANTID,'') AS PayUMoneyMERCHANTID,
			ISNULL(GP.PayUMoneyMERCHANTKEY,'') AS PayUMoneyMERCHANTKEY,
			ISNULL(GP.PayUMoneySALT,'') AS PayUMoneySALT,
			ISNULL(GP.PayUMoneyHASHSEQUENCE,'') AS PayUMoneyHASHSEQUENCE,
			ISNULL(GP.PayUMoneyAUTHHEADER,'') AS PayUMoneyAUTHHEADER
	FROM 
			[sOp].[tGatewayProduct] GP
			INNER JOIN [sOp].[tGatewayConfiguration] GC ON GC.Id = GP.GatewayConfigurationId
			INNER JOIN [sOp].[tPaymentGatewayMaster] PGM ON PGM.Id = GC.PaymentGatewayId
	WHERE 
			(GC.OrgGroupId = @rOrgGroupId)
			AND	((GP.Id = @rId) OR (@rId = 0))
			AND	((GP.GatewayConfigurationId = @rGatewayConfigurationId) OR (@rGatewayConfigurationId = 0))
			AND ((GP.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ISNULL(GC.IsObsolete,0) = 0
END
GO
PRINT N'Altering [sPayroll].[pPayProcessElementGet]...';


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

BEGIN 
	     SELECT 
			 PPE.PayElementId,
			 PE.Title AS PayElement,
			 PPE.Amount,
			 PET.Title AS PayElementType,
			 PayElementTypeId,
			 PPE.PayProcessEmployeeId,
			 ISNULL(PE.IsIncludeInTotal,0) AS IsIncludeInTotal
		 FROM 
			 sPayroll.tPayProcessElement PPE 
			 INNER JOIN sPayroll.tPayElement PE ON PPE.PayElementId = PE.ID
			 INNER JOIN sPayroll.tPayElementType PET ON PET.Id = PE.PayElementTypeId
			 
		 WHERE PayProcessEmployeeId = @rPayProcessEmployeeId
		 AND PE.IsIncludeInPaySlip = 1
			 ORDER BY SortOrder
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeeSalaryDetail]...';


GO
ALTER PROCEDURE [sPayroll].[pRptEmployeeSalaryDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rReportId smallint=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	
	
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))

	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		EM.EmployeeDesignation,
		EM.EmployeeGrade,
		ESO.EPFNumber,
		ESO.PanNumber,
		PPE.TotalEarning,		
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		PE.Amount As PPEAmount,
		P.Title AS PayElementTitle,
		P.ID AS PayElementId,
		P.PayElementTypeId,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber, 
		MM.Title AS MonthName,
		P.Title AS PayElementName,
		P.Code AS PayElementCode,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.WorkingDays else 0 END) AS WorkingDays,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.Lwp else 0 END) AS Lwp,
		(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.PaidLeave,0) else 0 END) AS PaidLeave,
		P.SortOrder,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		PPE.GrossBasic,
		P.PayElementDefaultId,
		ISNULL(EPD.Qualification,'') AS Qualification,
		EJD.DateOfJoining AS DateOfAppointment,
		ISNULL(ESO.PayScale,'') AS PayScale,
		EPD.DateOfBirth,
		ISNULL(ROG.SelectableField,'') AS SelectableField,
		RGO.SchoolRequiredSignature ,
		RGO.SchoolRemark1,
		ISNULL(ESO.BasicPay,0) AS BasicPay,
		DAY(DATEADD(DD,-1,DATEADD(mm, DATEDIFF(mm, 0, CONVERT(DATE,CONVERT(nvarchar,PP.SalaryMonth) +'/01/'+CONVERT(nvarchar,PP.SalaryYear)) ) + 1, 0))) AS MonthDay
	FROM 
	sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	LEFT JOIN sCommon.tReportOrgGroup ROG ON ROG.OrgGroupId=PY.OrgGroupId
	LEFT JOIN sCommon.tReportRemarkGroupOrg RGO ON RGO.OrgId = tEM.OrgID AND RGO.ReportRemarkGroupId =  4
where 
      (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND (P.IsObsolete=0)
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (ROG.ReportId = @rReportId OR @rReportId = 0) 
	  AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
      AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
END
GO
PRINT N'Altering [sPayroll].[pRptPayElementwiseSummaryDetail]...';


GO
 
ALTER PROCEDURE [sPayroll].[pRptPayElementwiseSummaryDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rPayElementId int,
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,	
	 @rPayElementTypeId int=0,
	 @rMonths nvarchar(50)=''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lBasicPayElementId int
	DECLARE @lProfessionalTaxPayElementId int
	
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1
	SELECT @lProfessionalTaxPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 57
	
	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	SELECT 
	
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,	
	PE.Amount,
	P.Id AS PayElementId, 
	P.Title AS PayElementName,
	P.Code AS PayElementCode,
	EM.EmployeeId,
	tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
	EM.Code,
	EM.EmployeeDesignation,
	PP.SalaryMonth,
	PP.SalaryYear,
	MM.Title AS MonthName,
	PY.Title AS PayrollYearName,
	P.SortOrder,
	P.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	PPE.TotalEarning,		
	PPE.TotalDeduction,
	PPE.NetAmount,
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
	(CASE WHEN (PayElementId = @lBasicPayElementId And @rPayElementTypeId <> 2) 
	 THEN PPE.TotalDeduction WHEN PayElementId = @lProfessionalTaxPayElementId And @rPayElementTypeId = 2 
	 THEN PPE.TotalDeduction ELSE 0 END) AS TotalDeductionTotal,	 
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
	PGM.Id AS PayrollGroupId,
	PGM.Title AS PayrollGroupName,
	PPE.GrossBasic ,
	P.PayElementDefaultId,
	ISNULL(PPE.WorkingDays,0) AS WorkingDays,
	ISNULL(PPE.Lwp,0) AS Lwp

	FROM sPayroll.tPayProcessEmployee PPE
		INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
WHERE 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (P.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
END
GO
PRINT N'Altering [sPayroll].[pRptPFDetail]...';


GO
ALTER PROCEDURE [sPayroll].[pRptPFDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

	SELECT 
	
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    ISNULL(A.WorkingDays,0) AS WorkingDays,
	    ISNULL(A.Amount,0) AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		FROM sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
END
GO
PRINT N'Altering [sProcurement].[pRptStockInward]...';


GO
ALTER PROCEDURE [sProcurement].[pRptStockInward]
 
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

   SELECT  
				SIM.Code AS ItemNumber,
				SIM.Title AS ItemName,		
				SI.InwardByName,	
				SI.Number, 	
				case when SI.TransactionDate is not null then  SI.TransactionDate else SI.CreatedDateTime end AS IssuedDate,
		
				ID.InwardQuantity,
				ID.RequestedQuantity,
				
				LM.Title AS FromLocation,
				UOM.Title AS UOM,
				Id.InwardValue		
				
    
    
		FROM  sProcurement.tStockInward SI		
		INNER JOIN sProcurement.tStockInwardDetail ID
		ON SI.Id = ID.StockInwardId
		 
		INNER JOIN sIp.tStoreLocationMaster LM
		ON SI.ToStoreLocationId = LM.Id  
		INNER JOIN sIp.tStockItemMaster SIM
		ON ID.StockItemId  = SIM.Id 
		INNER JOIN sFinanceCommon.tStockUomMaster UOM  
		ON SIM.IssueStockUomId = UOM.Id  	
		
		
		WHERE SI.Id = @rId 
			
END
GO
PRINT N'Altering [sProcurement].[pRptStockInwardReturn]...';


GO

ALTER PROCEDURE [sProcurement].[pRptStockInwardReturn]
 
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	
 SELECT SIR.Id,
		SIR.Number,
		ISNULL(SIR.ReturnByName,'') AS ReturnByName,
		SIR.FromStoreLocationId,
		SIR.Remark,
		SIR.StockInwardId,
		SIRB.StockInwardBatchId,
		SIRB.Quantity,
		SIM.Code AS StockItemCode,
		SIM.Title AS StockItemName,
		SIM.Id AS StockItemId,
		SIB.StockBatchId AS BatchId,
		SIR.CreatedUserId,
		SI.Number AS InwardNumber,
		SIND.InwardQuantity,
		SIND.InwardValue,
		RM.Title AS ReasonName,
		case when SIR.TransactionDate is not null then SIR.TransactionDate else SIR.CreatedDateTime end as CreatedDateTime

FROM sProcurement.tStockInwardReturn SIR 
INNER JOIN sProcurement.tStockInwardReturnBatch SIRB ON SIRB.StockInwardReturnId=SIR.Id
INNER JOIN sProcurement.tStockInwardBatch SIB ON SIB.Id=SIRB.StockInwardBatchId
INNER JOIN sProcurement.tStockInwardDetail SIND ON SIND.Id=SIB.StockInwardDetailId
INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
INNER JOIN sProcurement.tStockInward SI ON SI.Id=SIR.StockInwardId
INNER JOIN sCommon.tReasonMaster RM ON RM.Id=SIRB.ReasonId
		 
		WHERE SIR.Id = @rId 
			
END
GO
PRINT N'Altering [sProcurement].[pRptStockIssueReturn]...';


GO

ALTER PROCEDURE [sProcurement].[pRptStockIssueReturn]
 
	@rId [int] = 0
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	
	
 SELECT SIR.Id,
		SIR.Number,
		ISNULL(SIR.ReturnedByName,'') AS ReturnedByName,
		SIR.ToStoreLocationId,
		SIR.Remark,
		SIR.StockIssueId,
		SIRB.StockIssueBatchId,
		SIRB.ReturnQuantity,
		SIM.Code AS StockItemCode,
		SIM.Title AS StockItemName,
		SIM.Id AS StockItemId,
		SIB.StockBatchId AS BatchId,
		SIR.CreatedUserId,
		SI.Number AS InwardNumber,
		SIND.IssuedQuantity, 
		RM.Title AS ReasonName,
		case when SIR.TransactionDate is not null then SIR.TransactionDate else SIR.CreatedDateTime end as CreatedDateTime
		

FROM sProcurement.tStockIssueReturn SIR 
INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SIR.Id
INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id=SIRB.StockIssueBatchId
INNER JOIN sProcurement.tStockIssueDetail SIND ON SIND.Id=SIB.StockIssueDetailId
INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
INNER JOIN sProcurement.tStockIssue SI ON SI.Id=SIR.StockIssueId
INNER JOIN sCommon.tReasonMaster RM ON RM.Id=SIRB.ReasonId
		 
		WHERE SIR.Id = @rId 
			
END
GO
PRINT N'Altering [sProcurement].[pRptStockItemWiseTransaction]...';


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

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

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

		
			
				
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Inward' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 case when s.TransactionDate is not null then s.TransactionDate  else 	 WAC.CreatedDateTime end  as 'Date'
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		inner join sProcurement.tStockInward s on s.Id = WAC.SourceId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 1010)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 11) OR (ISNULL(@rFilterId,  0) = 0))
		
		
					
				
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Issue' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 case when s.TransactionDate is not null then s.TransactionDate  else 	 WAC.CreatedDateTime end  as 'Date'
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		inner join sProcurement.tStockIssue s on s.Id = WAC.SourceId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 51)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 1) OR (ISNULL(@rFilterId,  0) = 0))
		
		
					
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Transfer' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 WAC.CreatedDateTime as 'Date'
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		inner join sProcurement.tStockTransfer s on s.Id = WAC.SourceId 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 52)
	    AND WAC.StoreLocationId= @rStoreLocationId 
	    AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')
		
		AND ((@rFilterId = 2) OR (ISNULL(@rFilterId,  0) = 0))
		
		
						
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Freeze Adjustmnet' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 WAC.CreatedDateTime   as 'Date'
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 104)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 10) OR (ISNULL(@rFilterId,  0) = 0))
		
		
		
							
UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Dispense' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 WAC.CreatedDateTime as 'Date'
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 48)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 3) OR (ISNULL(@rFilterId,  0) = 0))
		
		UNION ALL
			
	SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Inward Return' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 case when s.TransactionDate is not null then s.TransactionDate  else 	 WAC.CreatedDateTime end  as 'Date'
		 
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		inner join  sProcurement.tStockInwardReturn s on s.Id = WAC.SourceId  
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 1013)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 12) OR (ISNULL(@rFilterId,  0) = 0))

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

	
Union All 
		
		SELECT 
		
			WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Adjustment' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		---(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 case when s.TransactionDate is not null then s.TransactionDate  else 	 WAC.CreatedDateTime end  as 'Date'
		  
		FROM sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId 
		AND SIM.StoreLocationId=@rStoreLocationId
		inner join  sProcurement.tStockAdjustment s on s.Id = WAC.SourceId 
		
		WHERE SIM.IsObsolete=0 AND (WAC.SourceTypeId = 50)
		AND WAC.StoreLocationId= @rStoreLocationId AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (ISNULL(SIM.Code,'') IN (SELECT item FROM  sCommon.fnsplit(@rItemCode,',')) OR @rItemCode='')
		AND ((@rFilterId = 9) OR (ISNULL(@rFilterId,  0) = 0))
		AND ((SIM.Title LIKE @rItemName) OR (ISNULL(@rItemName, '') = ''))
		
			
UNION ALL
		
		
		SELECT
	WAC.Id,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	SIM.Id AS StockItemId,
	SIM.Code AS ItemCode,
		 SIM.Title AS ItemName,
		 'Stock Reset' AS TransactionType,
		 Case WHEN WAC.IsReceipt = 0 THEN WAC.Quantity END AS QtyOut,
		 Case WHEN WAC.IsReceipt = 1 THEN WAC.Quantity END AS QtyIn,
		 WAC.WeightedAverageCost,
		--(WAC.WeightedAverageCost) * (WAC.ClosingQuantity) AS Amount,
		 WAC.ClosingValue AS Amount,
		 WAC.CreatedDateTime,
		 WAC.ClosingQuantity AS StoreLocationClosingQuantity,
		 WAC.CreatedDateTime as 'Date'
	FROM 
		sIp.tWeightedAverageCostLog WAC
		INNER JOIN sIp.vExtStockItemMaster SIM ON SIM.Id=WAC.ItemSourceId AND SIM.StoreLocationId=@rStoreLocationId
		 
				
	   WHERE	     
	     SIM.IsObsolete=0	     
	    AND (WAC.SourceTypeId = 2028)
		AND WAC.StoreLocationId= @rStoreLocationId 
		AND (WAC.OrgGroupId = @rOrgId)
		AND ((WAC.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((WAC.CreatedDateTime < DateAdd(day, 1, @rToDate)) OR (ISNULL(@rToDate,'') = ''))
		AND (SIM.ItemMainGroupId = @rMainGroupId OR @rMainGroupId=0)
		AND (SIM.ItemSubGroupId = @rSubGroupId OR @rSubGroupId=0)
		AND (SIM.Id=@rId OR @rId = 0)
		AND (SIM.Code like @rItemCode OR @rItemCode = '')
		AND (SIM.Title like @rItemName OR @rItemName = '')		
		AND ((@rFilterId = 12) OR (ISNULL(@rFilterId,  0) = 0))
		
		
      Order by WAC.Id	desc	
END

 




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


GO

ALTER PROCEDURE [sProcurement].[pStockAdjustmentAdd]  
	@rOrgGroupId int,
	@rNumber [nvarchar](20),
	@rCreatedUserId [bigint],
	@rStoreLocationId int,
	@rResult [int] = 0 OUTPUT,
	@rAdjDate datetime = null	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber INT
	DECLARE @loNextNumber nVarchar(20)
	DECLARE @lAdjustmentNumber nVarchar(20)
	 
	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sProcurement.tStockAdjustment',@lNextNumber = @lNextNumber output

    EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgGroupId, @rPrefixFunctionalityId  =  27,@rStoreLocationId = @rStorelocationId, @rNextNumber  =  @loNextNumber OUTPUT
    
 --SET @loNextNumber = NULL

    
    SET @lAdjustmentNumber  =  ISNULL(@loNextNumber, '-200')

--SELECT @lAppNumber

SET @rResult  =  -200 
IF (@lAdjustmentNumber <> '-200')
 BEGIN	
 SET @rResult  =  0
--SELECT @rNumber = ISNULL(max(Number),0)   FROM sProcurement.tStockAdjustment WHERE FromStoreLocationId = @rStoreLocationId
--SET @rNumber = @rNumber + 1
	INSERT INTO sProcurement.tStockAdjustment
		(
			Id,
			Number,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			FromStoreLocationId,
			TransactionDate
		)
	VALUES
		(
			@lNextNumber,
			@lAdjustmentNumber,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgGroupId,
			@rStoreLocationId,
			@rAdjDate
		)
		SET @rResult  =  @lNextNumber 
	
	END

		
END
GO
PRINT N'Altering [sProcurement].[pStockAdjustmentGet]...';


GO
ALTER PROCEDURE [sProcurement].[pStockAdjustmentGet]
	@rOrgGroupId int,
	@rId [int] = 0,
	@rFromStoreLocationId [int] = 0,
	@rAdjustmentNumber [nvarchar](20) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT Id AdjustmentId,
			Number AdjustmentNumber,
			CreatedUserId,
			CreatedDateTime,
			case when TransactionDate is not null then TransactionDate else CreatedDateTime end as 'TransactionDate'
	   FROM sProcurement.tStockAdjustment
	 
	  	WHERE ((Id = @rId) OR (@rId = 0))
				        AND ((Number = @rAdjustmentNumber)OR(ISNULL(@rAdjustmentNumber,'') = '' ))
				        AND OrgGroupId = @rOrgGroupId
				        AND ((FromStoreLocationId = @rFromStoreLocationId) OR (@rFromStoreLocationId = 0))
					    
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,
		@rCreatedOnDate 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,
			TransactionDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			VendorId
		)
	VALUES
		(
			@lNextNumberStockInward,
			@rNumber,
		   (CASE WHEN @rStockInwardRequestId = 0 THEN NULL ELSE @rStockInwardRequestId END),	 
			@rInwardByName,		 
			@rToStoreLocationId,			 
			@rRemark,
			@rInwardDate,
			@rCreatedUserId,
			@rCreatedOnDate,
			@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].[pStockInwardGet]...';


GO
ALTER PROCEDURE [sProcurement].[pStockInwardGet]
	@rOrgGroupId int,
	@rId [int] = 0,
	@rNumber [nvarchar](20) = '',
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
SELECT		SI.Id,
			SI.Number,
			SI.StockInwardRequestId,
			SI.InwardByName,
			--SI.ToOrganizationDepartmentId,
			SI.ToStoreLocationId,
			--ISNULL(SI.FirstAidId,0) As FirstAidId,
			SI.Remark,
			SI.CreatedUserId			AS UserId,
			case when SI.TransactionDate is not null  then SI.TransactionDate else  SI.CreatedDateTime End AS InwardDate,
			SLM.Code					AS ToStoreLocationCode,
			--ODM.Title					AS ToOrganizationDepartmentCode,
			--ISNULL(FAM.Title,'')        AS FirstAid,
			SIReq.Number				AS RequestNumber,
			SIReq.CreatedDateTime		AS RequestedDate,
			ISNULL(SI.VendorId,0) As VendorId ,
			ISNULL(VM.Code,'') AS VendorCode,
			 SI.CreatedDateTime  as TranjactionDate 
			
			
FROM		sProcurement.tStockInward SI
INNER JOIN	sIp.tStoreLocationMaster SLM
			ON SLM.Id = SI.ToStoreLocationId 		
LEFT JOIN	sProcurement.tStockInwardRequest SIReq
			ON SIReq.Id = SI.StockInwardRequestId
LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id=SI.VendorID			

WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId
AND			SI.ToStoreLocationId = @rStoreLocationId


SELECT		SIDe.Id,
			SIDe.StockInwardId,
			SIDe.StockItemId,
			SIDe.RequestedQuantity,
			SIDe.InwardQuantity,
			SIDe.InwardValue,
			SIDe.Remark,
			SIM.Code				AS StockItemCode,
			SIM.Title				AS StockItemName,
			SUMa.Code				AS UOM,
			SIM.IsBatchWiseTracking
 
FROM		sProcurement.tStockInwardDetail SIDe
INNER JOIN	sProcurement.tStockInward SI
			ON SI.Id = SIDe.StockInwardId
INNER JOIN	sIp.tStockItemMaster SIM
			ON SIM.Id = SIDe.StockItemId 
INNER JOIN  sFinanceCommon.tStockUomMaster SUMa
			ON SUMa.Id = SIM.IssueStockUomId
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId
AND			SI.ToStoreLocationId = @rStoreLocationId


SELECT	SIB.Id,
			SIB.StockInwardDetailId,
			SIB.StockBatchId,
			SIB.Quantity,
			SB.Number AS BatchName,
			SB.ExpiryDate, 
			SB.AvailableQuantity
FROM		sProcurement.tStockInwardBatch SIB
INNER JOIN	sProcurement.tStockInwardDetail SIDe
			ON SIDe.Id = SIB.StockInwardDetailId
INNER JOIN	sProcurement.tStockInward SI
			ON SI.Id = SIDe.StockInwardId
INNER JOIN	sProcurement.tStockBatch SB
			ON SB.Id = SIB.StockBatchId
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId
AND			SI.ToStoreLocationId = @rStoreLocationId

END
GO
PRINT N'Altering [sProcurement].[pStockInwardReturnAdd_New]...';


GO

ALTER PROCEDURE [sProcurement].[pStockInwardReturnAdd_New]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rReturnByName					Nvarchar(100) = '',
		@rFromStoreLocationId				Int,
		@rRemark						Nvarchar(300),
		@rCreatedUserId					BigInt,
		@rStockInwardId					int,
	   @rDetail						Nvarchar(Max),
	   @rLocationId int ,
	   @rOrgId int,
	   @rInwardReturnDate DateTime = null
	    
	)
AS

SET NOCOUNT ON

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

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

--IF @rNumber = '-300'
--BEGIN

----IF @rStockInwardRequestId = 0
----SET @rStockInwardRequestId = NULL
----SELECT -300 AS Result, 0 AS PrescriptionID, '' AS PrescriptionNumber
--SELECT -300 AS Result, '' AS Number, 0 AS Id 
--RETURN
--END
EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1006,
		@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

--select @rNumber = ISNULL(max(convert(int,Number)),0) FROM sProcurement.tStockInwardReturn WHERE FromStoreLocationId = @rFromStoreLocationId
--select @rNumber = convert(int,@rNumber) + 1 

DECLARE @loXML XML
		SET @loXML = CAST(@rDetail AS XML)
		Declare @tStockInwardReturnDetail TABLE
		(
			ID int IDENTITY(1,1),StockInwardBatchId bigint,
			Quantity decimal(12,2),ReasonId int,
			StockItemId int,StockItemName nvarchar(50),
			StockBatchId int
		)
		INSERT INTO @tStockInwardReturnDetail
		SELECT T.c.value('@StockInwardBatchId','bigint') AS StockInwardBatchId,
		T.c.value('@Quantity','nvarchar(20)')   AS Quantity,
		T.c.value('@ReasonId','Decimal(12,2)') AS ReasonId,
		T.c.value('@StockItemId','int') AS StockItemId,
		T.c.value('@StockItemName','nvarchar(50)')As StockItemName,
		T.c.value('@StockBatchId','int') AS StockBatchId
		FROM @loXML.nodes('/Table/StockInwardReturnDetail')T(c)
		
		BEGIN TRANSACTION
		DECLARE @lNextNumberStockInwardReturn BIGINT
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardReturn', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardReturn output
		 
		INSERT INTO sProcurement.tStockInwardReturn
		(
			Id,Number,ReturnByName,FromStoreLocationId,Remark,
			StockInwardId,CreatedUserId,CreatedDateTime,OrgGroupId,TransactionDate
		)
		VALUES
		(
			@lNextNumberStockInwardReturn,@rNumber,
			@rReturnByName,@rFromStoreLocationId,@rRemark,
			@rStockInwardId,@rCreatedUserId,sCommon.fGetDate(),
			@rOrgGroupId,@rInwardReturnDate
		)
		Declare @lStockInwardBatchId bigint,@lQuantity decimal(12,2),@lCount int,@lReasonId int,
		@lNextNumberInwardReturnBatch bigint,@lBatchId int,@lStockItemId int,@lStockItemName nvarchar(50),
		@lStockBatchId int,@lWeightedAverageCost decimal(12,2),@lInwardValue decimal(12,2)
		Select @lCount = COUNT(*) from @tStockInwardReturnDetail
		While (@lCount>0)
		BEGIN
			Select @lStockInwardBatchId=StockInwardBatchId,@lQuantity=Quantity,@lReasonId=ReasonId,
			@lStockItemId=StockItemId,@lStockItemName =StockitemName,@lStockBatchId =StockBatchId from @tStockInwardReturnDetail where ID=@lCount
			
			Select @lWeightedAverageCost=ISNULL(WeightedAverageCost,0) from sIp.tStockItemPlanning
			Where StockItemId = @lStockItemId AND StoreLocationId = @rFromStoreLocationId
			
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardReturnBatch', 0, 1, 1,@outNextNumber = @lNextNumberInwardReturnBatch output
			INSERT INTO sProcurement.tStockInwardReturnBatch
			(
				Id,StockInwardReturnId,StockInwardBatchId,Quantity,OrgGroupId,ReasonId
			)
			
			Values
			(
				@lNextNumberInwardReturnBatch,@lNextNumberStockInwardReturn,
				@lStockInwardBatchId,@lQuantity,@rOrgGroupId,@lReasonId
			)
			SET @lInwardValue = ISNULL(@lWeightedAverageCost,0) * ISNULL(@lQuantity,0)
			EXEC sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId=@rOrgGroupId,@rSourceTypeId=1013,
			@rSourceId=@lNextNumberInwardReturnBatch,@rItemSourceTypeId=34,
			@rItemSourceId=@lStockItemId,@rQuantity=@lQuantity,@rValue=@lInwardValue,
			@rIsReceipt=0,@rCreatedUserId=@rCreatedUserId,@rStoreLocationId=@rfromStoreLocationId,
			@rLocationId=@rLocationId,@rItemBatchId=@lStockBatchId,@rItemName=@lStockItemName,@rOrgId=@rOrgId	
		
			set @lCount =@lCount-1
		END
		 
		 
		
--SELECT @rNumber = ISNULL(max(Number),0)   FROM sProcurement.tStockInwardReturn WHERE FromStoreLocationId = @rFromStoreLocationId
--SET @rNumber = @rNumber + 1

--	DECLARE @lNextNumberStockInwardReturn INT
--	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardReturn', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardReturn output
	
--	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sHostel.tHostelMaster',@lNextNumber = @lNextNumberStockInwardReturn output
 
--	INSERT INTO sProcurement.tStockInwardReturn
--		(
--			Id,
--			Number,
--			ReturnByName, 
--			FromStoreLocationId,		 	 
--			Remark,
--			StockInwardId,
--			CreatedUserId,
--			CreatedDateTime,
--			OrgGroupId
--		)
--	VALUES
--		(
--			@lNextNumberStockInwardReturn,
--			@rNumber,
--			@rReturnByName,		 
--			@rFromStoreLocationId,			 
--			@rRemark,
--			@rStockInwardId,
--			@rCreatedUserId,
--			sCommon.fGetDate(),
--			@rOrgGroupId
--		)


	SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockInwardReturn AS Id 
	COMMIT TRANSACTION
END
GO
PRINT N'Altering [sProcurement].[pStockInwardReturnDataGet]...';


GO
ALTER PROCEDURE [sProcurement].[pStockInwardReturnDataGet]
	
	@rNumber [nvarchar](30) = '',
	@rStoreLocationId int 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN
 

	 SELECT SIR.Id,
		SIR.Number,
		ISNULL(SIR.ReturnByName,'') AS ReturnByName,
		SIR.FromStoreLocationId,
		SIR.Remark,
		SIR.StockInwardId,
		SIRB.StockInwardBatchId,
		SIRB.Quantity,
		SIM.Code AS StockItemCode,
		SIM.Title AS StockItemName,
		SIM.Id AS StockItemId,
		SIB.StockBatchId AS StockBatchId,
		SIR.CreatedUserId,
		SI.Number AS InwardNumber,
		SIRB.ReasonId,
		case when  SIR.TransactionDate is not null then SIR.TransactionDate else SIR.CreatedDateTime end  as TransactionDate,
		(SELECT ISNULL(SUM(SIRB.Quantity),0) FROM sProcurement.tStockInwardReturn SIR 
		INNER JOIN sProcurement.tStockInwardReturnBatch SIRB ON SIRB.StockInwardReturnId=SIR.Id WHERE SIR.StockInwardId=SI.Id AND SIRB.StockInwardBatchId=SIB.Id) AS ReturnedQuantity


FROM sProcurement.tStockInwardReturn SIR 
INNER JOIN sProcurement.tStockInwardReturnBatch SIRB ON SIRB.StockInwardReturnId=SIR.Id
INNER JOIN sProcurement.tStockInwardBatch SIB ON SIB.Id=SIRB.StockInwardBatchId
INNER JOIN sProcurement.tStockInwardDetail SIND ON SIND.Id=SIB.StockInwardDetailId
INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
INNER JOIN sProcurement.tStockInward SI ON SI.Id=SIR.StockInwardId
 
	   	WHERE ((SIR.Number = @rNumber) OR (@rNumber = ''))
	   	AND SIR.FromStoreLocationId = @rStoreLocationId
	   	
	   	
--	   	 SELECT SIR.Id,
--		SIR.Number,
--		ISNULL(SIR.ReturnByName,'') AS ReturnByName,
--		SIR.FromStoreLocationId,
--		SIR.Remark,
--		SIR.StockInwardId,
--		SIRB.StockInwardBatchId,
--		SIRB.Quantity,
--		SIM.Code AS StockItemCode,
--		SIM.Title AS StockItemName,
--		SIM.Id AS StockItemId,
--		SIB.StockBatchId AS StockBatchId,
--		SIR.CreatedUserId,
--		SIND.InwardQuantity,
--		SIND.InwardValue,
--		SI.Number AS InwardNumber,
--		SIRB.ReasonId,
--		SIRB.Id AS StockInwardReturnBatchId,
--		(SELECT ISNULL(SUM(SIRB.Quantity),0) FROM sProcurement.tStockInwardReturn SIR 
--		INNER JOIN sProcurement.tStockInwardReturnBatch SIRB ON SIRB.StockInwardReturnId=SIR.Id WHERE SIR.StockInwardId=SI.Id AND SIRB.StockInwardBatchId=SIB.Id) AS ReturnedQuantity

--FROM sProcurement.tStockInwardReturn SIR 
--INNER JOIN sProcurement.tStockInwardReturnBatch SIRB ON SIRB.StockInwardReturnId=SIR.Id
--INNER JOIN sProcurement.tStockInwardBatch SIB ON SIB.Id=SIRB.StockInwardBatchId
--INNER JOIN sProcurement.tStockInwardDetail SIND ON SIND.Id=SIB.StockInwardDetailId
--INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
--INNER JOIN sProcurement.tStockInward SI ON SI.Id=SIR.StockInwardId
 
--	   	WHERE ((SIR.Number = @rNumber) OR (@rNumber = ''))
--	   		AND SIR.FromStoreLocationId = @rStoreLocationId
	   	
	   	
	   	
	
END
GO
PRINT N'Altering [sProcurement].[pStockIssGet]...';


GO
 
ALTER PROCEDURE [sProcurement].[pStockIssGet]
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	  
SELECT		
SI.Id,SI.Number,isnull(SI.StockIssueRequestId,0) as StockIssueRequestId,
SI.IssuedByName,
case when SI.TransactionDate is not null  then SI.TransactionDate else  SI.CreatedDateTime End 
AS IssuedDate,
 SI.CreatedDateTime  as TranjactionDate 
FROM sProcurement.tStockIssue SI 
WHERE ((Number like '%' + @rNumber + '%') OR (@rNumber = '*'))
AND  OrgGroupId = @rOrgGroupId
AND (( Convert(Date,CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
AND (( Convert(Date,CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
AND SI.FromStoreLocationId=@rStoreLocationId 
Order by SI.CreatedDateTime desc
END
GO
PRINT N'Altering [sProcurement].[pStockIssue_Get]...';


GO

ALTER PROCEDURE [sProcurement].[pStockIssue_Get]
	@rOrgGroupId int,
	@rId [int] = 0,
	@rNumber [nvarchar](20) = '',
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
SELECT		 
		SIDE.Id,
		SIDE.RequestedQuantity,
		SIDE.IssuedQuantity,
		SIDE.Remark,
		SIM.Code AS StockItemCode,
		SIM.TItle As StockItemName,
		SUMa.Code AS UOM,
		isnull(SB.Number,'') AS Number,
		isnull(SB.ExpiryDate,'') as ExpiryDate , 
		SB.AvailableQuantity,
		SIM.ID AS StockItemID,
		SI.ToOrganizationdepartmentid,
		SI.IssuedByName,
		case when SI.TransactionDate is not null then  SI.TransactionDate  else  SI.CreatedDateTime end as 'TransactionDate',
		SI.CreatedDateTime,
		SI.IssueToName,
		SIReq.Number AS 'reqnumb',
		SIReq.CreatedDateTime as 'ReqDate'

		
			
			
FROM		
		sProcurement.tStockIssueDetail SIDE
		INNER JOIN sProcurement.tStockIssue SI ON SI.ID= SIDE.StockIssueId
		INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SIDE.StockItemID
		INNER JOIN  sFinanceCommon.tStockUomMaster SUMa ON SUMa.Id = SIM.IssueStockUomId
		LEFT JOIN sProcurement.tStockIssueBatch SIB ON SIB.StockIssueDetailId= SIDE.Id
		LEFT JOIN	sProcurement.tStockBatch SB ON SB.Id = SIB.StockBatchId AND SB.Number!=''
		LEFT JOIN	sProcurement.tStockIssueRequest SIReq ON SIReq.Id = SI.StockIssueRequestId
WHERE		
		SI.ID=@rId
		AND ((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
		AND SI.OrgGroupId = @rOrgGroupId
		AND SI.FromStoreLocationId  = @rStoreLocationId
END
GO
PRINT N'Altering [sProcurement].[pStockIssueAdd_New]...';


GO

ALTER PROCEDURE [sProcurement].[pStockIssueAdd_New]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rStockIssueRequestId			Int=0, 
		@rIssuedByName					Nvarchar(100) = '',
		@rToOrganizationDepartmentId	Int,
		@rFromStoreLocationId			Int,
		@rFirstAidId					Int,
		@rRemark						Nvarchar(300),
		@rCreatedUserId					BigInt,
		@rDetail						Nvarchar(Max),
		@rOrgId int,
		@rLocationId int,
		@rIssuedToName nvarchar(50)='',
		@rIssueDate datetime = null,
		@rCreatedOnDate datetime = null
	)
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),StockIssueRequestDetailId int,StockItemId Int,StockItemName nvarchar(50),
			StockItemCode nvarchar(50),IssuedQuantity Decimal(12,2),RequestedQuantity Decimal(12,2),
			ItemBatch Nvarchar(300) NULL,StockBatchId int 
		)

	INSERT INTO @tStockIssueDetail
		SELECT
		(
			CASE WHEN T.c.value('@StockIssueRequestDetailId','Nvarchar(300)') = 0 THEN 
				NULL
			ELSE T.c.value('@StockIssueRequestDetailId','Nvarchar(300)') END
		),
		T.c.value('@StockItemId','int') AS StockItemId,
		T.c.value('@StockItemCode','nvarchar(50)') AS StockItemCode,
		T.c.value('@StockItemName','nvarchar(50)') AS StockItemName,
		T.c.value('@IssuedQuantity','decimal(12,2)') AS IssuedQuantity,
		T.c.value('@RequestedQuantity','decimal(12,2)') AS RequestedQuantity,
		T.c.value('@ItemBatch','Nvarchar(300)') AS ItemBatch,
		T.c.value('@StockBatchId','int') AS StockBatchId
		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,
			TransactionDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			IssueToName
		)
	VALUES
		(
			@lNextNumberStockIssue,
			@rNumber,
		   (CASE WHEN @rStockIssueRequestId = 0 THEN NULL ELSE @rStockIssueRequestId END),	 
			@rIssuedByName,
			@rToOrganizationDepartmentId,
			@rFromStoreLocationId,
			@rFirstAidId,
			@rRemark,
			@rIssueDate,
			@rCreatedUserId,
			@rCreatedOnDate,
			@rOrgGroupId,
			@rIssuedToName
		)


	DECLARE @lNextNumberStockIssueDetail BigInt,@lQuantity decimal(12,2),@lStockItemCode nvarchar(50)
		Declare @lCOunt int , @lItemId int,@lIssueQuantity decimal(12,2),@lRequestedQuantity 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 , 
			@lRequestedQuantity=RequestedQuantity,@lCOunt=Id,@lBatch=ItemBatch,
			@lStockItemCode=StockItemCode,@lBatchId=StockBatchId,@lStockItemName=StockItemName
			from @tStockIssueDetail where Id=@lCOunt
			
			Select @lIsBatchWise=IsBatchWiseTracking from sIp.tStockItemMaster Where Id = @lItemId   
			Select @lWeightedAverageCost=ISNULL(WeightedAverageCost,0) from sIp.tStockItemPlanning
			Where StockItemId = @lItemId AND StoreLocationId =  @rFromStoreLocationId  
			
			Select @lQuantity=AvailableQuantity from sProcurement.tStockBatch where Id =@lBatchId
			AND StockItemId = @lItemId ANd StorelocationId=@rFromStoreLocationId
			
			if(ISNULL(@lbatchId,0)=0)
			BEGIN
				ROLLBACK TRANSACTION
				Select -102 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,
				RequestedQuantity,StockIssueRequestDetailId,@rRemark,@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 [sProcurement].[pStockIssueRequestDetailGet]...';


GO
ALTER PROCEDURE [sProcurement].[pStockIssueRequestDetailGet]
	@rOrgGroupId int,
	@rStockIssueRequestId [int] = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
			ISNULL(SIRD.Id,0) As ID,
			ISNULL(SIRD.StockIssueRequestId,0) AS StockIssueRequestId ,
			SIRD.StockItemId,
			ISNULL(SIRD.RequestedQuantity,0) As RequestedQuantity,
			SIRD.Remark,
			SIRD.UpdatedUserID,
			SIRD.UpdatedDateTime,
			SIM.Code ItemCode,
			SIM.Title ItemTitle,
			SU.Code UomCode,
			SU.Title UomTitle,
			ISNULL(SU.Id,0)AS  IssueStockUomId,
			SIM.IsBatchWiseTracking,
			SIM.Code StockItemCode,
			SIM.Title StockItemName,
			SU.Title Uom,
		    '' as Number,
			SIRD.IssuedQuantity,
			SIR.Number,
			SIR.CreatedDateTime as 'ReqDate'
			 
			
 
	   FROM 
			sProcurement.tStockIssueRequestDetail SIRD
	   INNER JOIN  sIP.tStockItemMaster SIM
		ON SIM.Id = SIRD.StockItemId
		INNER JOIN sFinanceCommon.tStockUomMaster  SU
		ON SU.Id = SIM.IssueStockUomId
		INNER JOIN sProcurement.tStockIssueRequest SIR ON SIR.ID=SIRD.StockIssueRequestId
		--INNER JOIN sProcurement.tStockBatch SB ON SB.StockItemID = SIM.Id AND SB.Number!=''
	  WHERE ((SIRD.StockIssueRequestId = @rStockIssueRequestId) OR (@rStockIssueRequestId = 0))
	  AND SIRD.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Altering [sProcurement].[pStockIssueReturnAdd_New]...';


GO
ALTER PROCEDURE [sProcurement].[pStockIssueReturnAdd_New]
	(
		@rOrgGroupId [int],
		@rNumber						Nvarchar(20) = '',
		@rReturnByName					Nvarchar(100) = '',
		@rFromStoreLocationId				Int,
		@rRemark						Nvarchar(300),
		@rCreatedUserId					BigInt,
		@rStockIssueId				int,
	   @rDetail						Nvarchar(Max),
	   @rLocationId int ,
	   @rOrgId int,
	   @rIssueReturnDate DateTime = null
	    
	)
AS

SET NOCOUNT ON

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

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

--IF @rNumber = '-300'
--BEGIN

----IF @rStockInwardRequestId = 0
----SET @rStockInwardRequestId = NULL
----SELECT -300 AS Result, 0 AS PrescriptionID, '' AS PrescriptionNumber
--SELECT -300 AS Result, '' AS Number, 0 AS Id 
--RETURN
--END
EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 53,
		@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
 
--select @rNumber = ISNULL(max(convert(int,Number)),0) FROM sProcurement.tStockInwardReturn WHERE FromStoreLocationId = @rFromStoreLocationId
--select @rNumber = convert(int,@rNumber) + 1 

DECLARE @loXML XML
		SET @loXML = CAST(@rDetail AS XML)
		Declare @tStockIssueReturnDetail TABLE
		(
			ID int IDENTITY(1,1),StockIssueBatchId bigint,
			Quantity decimal(12,2),ReasonId int,
			StockItemId int,StockItemName nvarchar(50),
			StockBatchId int
		)
		INSERT INTO @tStockIssueReturnDetail
		SELECT T.c.value('@StockIssueBatchId','bigint') AS StockIssueBatchId,
		T.c.value('@Quantity','nvarchar(20)')   AS Quantity,
		T.c.value('@ReasonId','Decimal(12,2)') AS ReasonId,
		T.c.value('@StockItemId','int') AS StockItemId,
		T.c.value('@StockItemName','nvarchar(50)')As StockItemName,
		T.c.value('@StockBatchId','int') AS StockBatchId
		FROM @loXML.nodes('/Table/StockIssueReturnDetail')T(c)
		
		BEGIN TRANSACTION
		DECLARE @lNextNumberStockIssueReturn BIGINT
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueReturn', 0, 1, 1,@outNextNumber = @lNextNumberStockIssueReturn output
		 
		INSERT INTO sProcurement.tStockIssueReturn
		(
			Id,Number,ReturnedByName,ToStoreLocationId,Remark,
			StockIssueId,CreatedUserId,CreatedDateTime,OrgGroupId,TransactionDate
		)
		VALUES
		(
			@lNextNumberStockIssueReturn,@rNumber,
			@rReturnByName,@rFromStoreLocationId,@rRemark,
			@rStockIssueId,@rCreatedUserId,sCommon.fGetDate(),
			@rOrgGroupId,@rIssueReturnDate
		)
		Declare @lStockIssueBatchId bigint,@lQuantity decimal(12,2),@lCount int,@lReasonId int,
		@lNextNumberIssueReturnBatch bigint,@lBatchId int,@lStockItemId int,@lStockItemName nvarchar(50),
		@lStockBatchId int,@lWeightedAverageCost decimal(12,2),@lIssueValue decimal(12,2)
		Select @lCount = COUNT(*) from @tStockIssueReturnDetail
		 
		While (@lCount>0)
		BEGIN
			 
			Select @lStockIssueBatchId=StockIssueBatchId,@lQuantity=Quantity,@lReasonId=ReasonId,
			@lStockItemId=StockItemId,@lStockItemName =StockitemName,@lStockBatchId =StockBatchId from @tStockIssueReturnDetail where ID=@lCount
			
			Select @lWeightedAverageCost=ISNULL(WeightedAverageCost,0) from sIp.tStockItemPlanning
			Where StockItemId = @lStockItemId AND StoreLocationId = @rFromStoreLocationId
			
			EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockIssueReturnBatch', 0, 1, 1,@outNextNumber = @lNextNumberIssueReturnBatch output
			INSERT INTO sProcurement.tStockIssueReturnBatch
			(
				Id,StockIssueReturnId,StockIssueBatchId,ReturnQuantity,OrgGroupId,ReasonId,CreatedDateTime
			)
			
			Values
			(
				@lNextNumberIssueReturnBatch,@lNextNumberStockIssueReturn,
				@lStockIssueBatchId,@lQuantity,@rOrgGroupId,@lReasonId ,sCommon.fGetDate()
			)
			SET @lIssueValue = ISNULL(@lWeightedAverageCost,0) * ISNULL(@lQuantity,0)
			  
			EXEC sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId=@rOrgGroupId,@rSourceTypeId=1012,
			@rSourceId=@lNextNumberIssueReturnBatch,@rItemSourceTypeId=34,
			@rItemSourceId=@lStockItemId,@rQuantity=@lQuantity,@rValue=@lIssueValue,
			@rIsReceipt=1,@rCreatedUserId=@rCreatedUserId,@rStoreLocationId=@rfromStoreLocationId,
			@rLocationId=@rLocationId,@rItemBatchId=@lStockBatchId,@rItemName=@lStockItemName,@rOrgId=@rOrgId	
		
			set @lCount =@lCount-1
		END	
		 
		 
		
--SELECT @rNumber = ISNULL(max(Number),0)   FROM sProcurement.tStockInwardReturn WHERE FromStoreLocationId = @rFromStoreLocationId
--SET @rNumber = @rNumber + 1

--	DECLARE @lNextNumberStockInwardReturn INT
--	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockInwardReturn', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardReturn output
	
--	EXECUTE [sCommon].[pGetIntMaxIdForOrgGroup] @rOrgGroupId, 'sHostel.tHostelMaster',@lNextNumber = @lNextNumberStockInwardReturn output
 
--	INSERT INTO sProcurement.tStockInwardReturn
--		(
--			Id,
--			Number,
--			ReturnByName, 
--			FromStoreLocationId,		 	 
--			Remark,
--			StockInwardId,
--			CreatedUserId,
--			CreatedDateTime,
--			OrgGroupId
--		)
--	VALUES
--		(
--			@lNextNumberStockInwardReturn,
--			@rNumber,
--			@rReturnByName,		 
--			@rFromStoreLocationId,			 
--			@rRemark,
--			@rStockInwardId,
--			@rCreatedUserId,
--			sCommon.fGetDate(),
--			@rOrgGroupId
--		)


	SELECT 1 AS Result, @rNumber AS Number, @lNextNumberStockIssueReturn AS Id 
	COMMIT TRANSACTION
END
GO
PRINT N'Altering [sProcurement].[pStockIssueReturnDataGet]...';


GO
 

ALTER PROCEDURE [sProcurement].[pStockIssueReturnDataGet]
@rNumber [nvarchar](30) = '',
@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


	 SELECT SIR.Id,
		SIR.Number,
		ISNULL(SIR.ReturnedByName,'') AS ReturnedByName,
		SIR.ToStoreLocationId,
		SIR.Remark,
		SIR.StockIssueId,
		SIRB.StockIssueBatchId,
		SIRB.ReturnQuantity,
		SIM.Code AS StockItemCode,
		SIM.Title AS StockItemName,
		SIM.Id AS StockItemId,
		SIB.StockBatchId AS StockBatchId,
		SIR.CreatedUserId,
		SI.Number AS IssueNumber,
		SIRB.ReasonId,
		case when SIR.TransactionDate is not null  then SIR.TransactionDate else SIR.CreatedDateTime end as TransactionDate,
		(SELECT ISNULL(SUM(SIRB.ReturnQuantity),0) FROM sProcurement.tStockIssueReturn SIR 
		INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SIR.Id WHERE SIR.StockIssueId=SI.Id AND SIRB.StockIssueBatchId=SIB.Id) AS ReturnedQuantity


FROM sProcurement.tStockIssueReturn SIR 
INNER JOIN sProcurement.tStockIssueReturnBatch SIRB ON SIRB.StockIssueReturnId=SIR.Id
INNER JOIN sProcurement.tStockIssueBatch SIB ON SIB.Id=SIRB.StockIssueBatchId
INNER JOIN sProcurement.tStockIssueDetail SIND ON SIND.Id=SIB.StockIssueDetailId
INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id=SIND.StockItemId
INNER JOIN sProcurement.tStockIssue SI ON SI.Id=SIR.StockIssueId
 
	   	WHERE ((SIR.Number = @rNumber) OR (@rNumber = ''))
	   	AND SIR.ToStoreLocationId = @rStoreLocationId
	   	
END
GO
PRINT N'Altering [sProcurement].[pStockResetAdd_New]...';


GO

ALTER PROCEDURE [sProcurement].[pStockResetAdd_New]
(
@rOrgGroupId [smallint],
@rNumber Nvarchar(max) = '',
@rResetByName Nvarchar(max) = '',
@rToStoreLocationId	Int,
@rRemark Nvarchar(max),
@rCreatedUserId	BigInt,
@rDetail Nvarchar(Max),
@rLocationId int,
@rOrgId int,
@rTranjectionDate datetime = null,
@rResetDate  datetime = null

)
AS
SET NOCOUNT ON
BEGIN
  BEGIN TRY	    
	DECLARE @loXML XML
	SET @loXML = CAST(@rDetail AS XML)

	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1007,
	@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 @tStockResetDetailBatch TABLE
	(
		Id Int IDENTITY(1, 1),	 
		StockItemId bigint,
		StockItemName nvarchar(max),
		ItemBatch Nvarchar(max) NULL,
		ItemExpiryDate Date NULL,	
		ResetQuantity Decimal(12,2),
		RequestedQuantity Decimal(12,2),
		ResetValue Decimal(12,2)
	)	
    INSERT INTO @tStockResetDetailBatch
    SELECT
            T.c.value('@StockItemId','bigint') AS StockItemId,
            T.c.value('@StockItemName','nvarchar(max)') AS StockItemname,
            T.c.value('@ItemBatch','Nvarchar(max)') AS ItemBatch,
            T.c.value('@ItemExpiryDate','Date')   AS ItemExpiryDate,
            T.c.value('@ResetQuantity','Decimal(12,2)') AS ResetQuantity,
            T.c.value('@RequestedQuantity','Decimal(12,2)') AS RequestedQuantity,
            T.c.value('@ResetValue','Decimal(12,2)') AS ResetValue 
    FROM 
            @loXML.nodes('/Table/StockReset')T(c)


  BEGIN TRANSACTION
   
	DECLARE @lNextNumberStockReset bigint,@lNextNumberStockResetBatch bigint
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockReset', 0, 1, 1,@outNextNumber = @lNextNumberStockReset output

	INSERT INTO sProcurement.tStockReset
	(
		Id,Number,ResetByName,ToStoreLocationId,Remark,CreatedUserId,CreatedDateTime,OrgGroupId,TransactionDate
	)
	VALUES
	(
		@lNextNumberStockReset,@rNumber,
		@rResetByName,@rToStoreLocationId,@rRemark,@rCreatedUserId,@rResetDate,
		@rOrgGroupId,@rTranjectionDate
	)
            
	declare @lCount int,@lIsBatchWise bit,@lbatchId int,@lNextNumberStockBatch int,@lExpiryDate date
	Declare @lItemId int,@lBatch nvarchar(300),@lResetQty decimal(12,2),@lResetValue decimal(12,2),@lIdCount int,@lAvaliableStock decimal(12,2),@lMainQty decimal(12,2) 
	DECLARE @lStockItemname nvarchar(max)
	select @lCount=COUNT(*) from @tStockResetDetailBatch 
		 
	while @lcount > 0
	BEGIN
					 
		Select @lItemId =StockItemId,@lBatch = ItemBatch,@lResetQty=ResetQuantity,@lResetValue=ResetValue,@lIdCount=Id,@lExpiryDate =ItemExpiryDate 
		,@lStockItemname=StockItemname
		from  @tStockResetDetailBatch 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 --AND @lIdCount=@lcount
				 
			END
			else 
			BEGIN
				
				Select @lbatchId= Id from sProcurement.tStockBatch    
				Where iSNULl( Number,'') =''  AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId--AND  @lIdCount=@lcount
			 
			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,CreatedUserId,CreatedDateTime,OrgGroupId,ItemRate)
				Select @lNextNumberStockBatch,@rToStoreLocationId,@lItemId,@lBatch,@lExpiryDate ,@lResetQty,@rCreatedUserId,getdate(),@rOrgGroupId,@lResetValue
				--from @tStockResetDetailBatch where Id=@lcount
				
				 SET @lbatchId = @lNextNumberStockBatch
				 
				 
			END 
			 	 
			 if(@lbatchId>0)
			BEGIN
					 
				Select  @lAvaliableStock =  isnull(SUM(AvailableQuantity),0)  from sProcurement.tStockBatch  where OrgGroupId=@rOrgId and StockItemId=@lItemId and Id= @lbatchId
					 
				 EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sProcurement.tStockResetBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockResetBatch output
				
						INsert into sProcurement.tStockResetBatch(Id,StockResetId,Quantity,StockBatchId,OrgGroupId,UnitCost)
						Select @lNextNumberStockResetBatch,@lNextNumberStockReset,ResetQuantity,@lbatchId,@rOrgGroupId,ResetValue
						from @tStockResetDetailBatch where Id=@lcount
			 
			 if(@lAvaliableStock > @lResetQty)
					BEGIN	
					--out Stock
						
						set @lMainQty = @lAvaliableStock - @lResetQty
						Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=2028,@rSourceId=@lNextNumberStockResetBatch,
								@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lMainQty ,@rValue=@lResetValue,@rIsReceipt=0,
								@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rToStoreLocationId
								,@rLocationId=@rLocationId,@rItemBatchId = @lbatchId,@rItemName = @lStockItemname ,@rOrgId=@rOrgId
							   ,@rPhysicalQuantity = @lResetQty	
							   
				    END
				    else
				    BEGIN	
				    -- in stock
				    
						set @lMainQty = @lResetQty - @lAvaliableStock 
				    Exec sIp.pWeightedAverageCostLogAdd_New @rOrgGroupId =@rOrgGroupId,@rSourceTypeId=2028,@rSourceId=@lNextNumberStockResetBatch,
								@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lMainQty ,@rValue=@lResetValue,@rIsReceipt=1,
								@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rToStoreLocationId 
								,@rLocationId=@rLocationId,@rItemBatchId = @lbatchId,@rItemName = @lStockItemname,@rOrgId=@rOrgId
								,@rPhysicalQuantity = @lResetQty
				    END
								
						 
			 END
			set @lcount =@lcount-1
		END
		
		SELECT 1 AS RESULT , @rNumber as Number,@lNextNumberStockReset as Id
		 COMMIT TRANSACTION
        END TRY
         
        BEGIN CATCH
        IF @@TRANCOUNT > 0  
		ROLLBACK TRANSACTION
		 
		SELECT -1 AS RESULT , @rNumber as Number,@lNextNumberStockReset as Id
	    END CATCH	
END
GO
PRINT N'Altering [sProcurement].[pStockResetGet]...';


GO

ALTER PROCEDURE [sProcurement].[pStockResetGet]
	@rOrgGroupId smallint,
	@rId bigint = 0,
	@rNumber [nvarchar](20) = ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	  
SELECT		SI.Id,
			SI.Number,
			SI.ResetByName,
			SI.ToStoreLocationId,			
			SI.Remark,
			SI.CreatedUserId			AS UserId,
			case when SI.TransactionDate is not null then SI.TransactionDate else  SI.CreatedDateTime end AS ResetDate,
			SLM.Code					AS ToStoreLocationCode,
			SI.CreatedDateTime as 'TranjectionDate'
			
FROM		sProcurement.tStockReset SI
INNER JOIN	sIp.tStoreLocationMaster SLM
			ON SLM.Id = SI.ToStoreLocationId 		
			
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId





SELECT	SIB.Id,			
			SIB.StockBatchId,
			SIB.Quantity,
			SB.Number,
			ISNULL(SB.ExpiryDate,'') AS ExpiryDate, 
			SB.AvailableQuantity
			
			
			
FROM		sProcurement.tStockResetBatch SIB
INNER JOIN	sProcurement.tStockReset SI
			ON SI.Id = SIB.StockResetId
INNER JOIN	sProcurement.tStockBatch SB
			ON SB.Id = SIB.StockBatchId
WHERE		((SI.Id = @rId) OR (@rId = 0))
AND			((SI.Number = @rNumber) OR (ISNULL(@rNumber, '') = ''))
AND        SI.OrgGroupId = @rOrgGroupId

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


GO
ALTER PROCEDURE [sSecurity].[pOrgGroupMobileAppDetailAdd]
	@rOrgGroupId	int,
	@rApplicationName	nvarchar(100),
	--@rPrivacyPolicyURL	nvarchar(300),
	@rAndroidPackageName	nvarchar(200),
	@rAndroidLink	nvarchar(300),
	@rAndroidStatus	bit,
	@rAndroidLastVersionCode	int,
	@rAndroidLastVersionName	nvarchar(20),
	@rAndroidLastRealeaseDate	date,
	@riOSBundleIdentifier	nvarchar(200),
	@riOSLink	nvarchar(300),
	@riOSStatus	bit,
	@riOSLastVersionCode	int,
	@riOSLastVersionName	nvarchar(20),
	@riOSLastRealeaseDate	date,
	@riOSExpireDate	date
	   	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
			 BEGIN TRANSACTION	

	If NOT Exists(select 1 from [sSecurity].[tOrgGroupMobileAppDetail] where OrgGroupId=@rOrgGroupId)
	BEGIN
	INSERT INTO sSecurity.tOrgGroupMobileAppDetail
		(
			OrgGroupId,
			ApplicationName,
			--PrivacyPolicyURL,
			AndroidPackageName,
			AndroidLink,
			AndroidStatus,
			AndroidLastVersionCode,
			AndroidLastVersionName,
			AndroidLastRealeaseDate,
			iOSBundleIdentifier,
			iOSLink,
			iOSStatus,
			iOSLastVersionCode,
			iOSLastVersionName,
			iOSLastRealeaseDate,
			iOSExpireDate
		)
	VALUES
		(
			@rOrgGroupId,
			@rApplicationName,
			--@rPrivacyPolicyURL,
			@rAndroidPackageName,
			@rAndroidLink,
			@rAndroidStatus,
			@rAndroidLastVersionCode,
			@rAndroidLastVersionName,
			@rAndroidLastRealeaseDate,
			@riOSBundleIdentifier,
			@riOSLink,
			@riOSStatus,
			@riOSLastVersionCode,
			@riOSLastVersionName,
			@riOSLastRealeaseDate,
			@riOSExpireDate
		)
		    SELECT 1 AS Result
	END	 

ELSE
	 BEGIN
	 UPDATE  sSecurity.tOrgGroupMobileAppDetail
	    SET 
	      
			ApplicationName=@rApplicationName,
			--PrivacyPolicyURL=@rPrivacyPolicyURL,
			AndroidPackageName=@rAndroidPackageName,
			AndroidLink=@rAndroidLink,
			AndroidStatus=@rAndroidStatus,
			AndroidLastVersionCode=@rAndroidLastVersionCode,
			AndroidLastVersionName=@rAndroidLastVersionName,
			AndroidLastRealeaseDate=@rAndroidLastRealeaseDate,
			iOSBundleIdentifier=@riOSBundleIdentifier,
			iOSLink=@riOSLink,
			iOSStatus=@riOSStatus,
			iOSLastVersionCode=@riOSLastVersionCode,
			iOSLastVersionName=@riOSLastVersionName,
			iOSLastRealeaseDate=@riOSLastRealeaseDate,
			iOSExpireDate=@riOSExpireDate
	      WHERE OrgGroupId = @rOrgGroupId
	      SELECT 11 AS Result
	 END  	

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


GO
 
ALTER PROCEDURE  [sSecurity].[pOrgGroupMobileAppDetailGet]

		@rOrgGroupId int,		
		@rApplicationName nvarchar(100),
		@rAndroidStatus int,
		@rIOSStatus int
		--@rPrivacyPolicyURL nvarchar(300), 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		BEGIN
		SET @rApplicationName = sCommon.fSearchStringGet(@rApplicationName)		
	    END	
		IF (@rAndroidStatus != -1)
		BEGIN 
			SELECT 
				OGM.*
			FROM 
				sSecurity.tOrgGroupMobileAppDetail  OGM
			WHERE 
				((OGM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId= 0))
				AND ((OGM.ApplicationName like @rApplicationName) OR (ISNULL(@rApplicationName,'') = ''))
				AND (OGM.AndroidStatus = @rAndroidStatus)
				--AND ((OGM.PrivacyPolicyURL like @rPrivacyPolicyURL) OR (ISNULL(@rPrivacyPolicyURL,'') = ''))
			ORDER BY OGM.AndroidLastRealeaseDate DESC
		END
		ELSE IF (@rIOSStatus != -1)
		BEGIN 
			SELECT 
				OGM.*
			FROM 
				sSecurity.tOrgGroupMobileAppDetail  OGM
			WHERE 
				((OGM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId= 0))
				AND ((OGM.ApplicationName like @rApplicationName) OR (ISNULL(@rApplicationName,'') = ''))
				AND (OGM.iOSStatus = @rIOSStatus)
				--AND ((OGM.PrivacyPolicyURL like @rPrivacyPolicyURL) OR (ISNULL(@rPrivacyPolicyURL,'') = ''))
			ORDER BY OGM.AndroidLastRealeaseDate DESC
		END
		ELSE IF (@rAndroidStatus != -1 AND @rIOSStatus != -1)
		BEGIN 
			SELECT 
				OGM.*
			FROM 
				sSecurity.tOrgGroupMobileAppDetail  OGM
			WHERE 
				((OGM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId= 0))
				AND ((OGM.ApplicationName like @rApplicationName) OR (ISNULL(@rApplicationName,'') = ''))
				AND (OGM.AndroidStatus = @rAndroidStatus)
				AND (OGM.iOSStatus = @rIOSStatus)
				--AND ((OGM.PrivacyPolicyURL like @rPrivacyPolicyURL) OR (ISNULL(@rPrivacyPolicyURL,'') = ''))
			ORDER BY OGM.AndroidLastRealeaseDate DESC
		END
		ELSE
		BEGIN
			SELECT 
				OGM.*
			FROM 
			sSecurity.tOrgGroupMobileAppDetail  OGM
			WHERE 
				((OGM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId= 0))
				AND ((OGM.ApplicationName like @rApplicationName) OR (ISNULL(@rApplicationName,'') = ''))						
				--AND ((OGM.PrivacyPolicyURL like @rPrivacyPolicyURL) OR (ISNULL(@rPrivacyPolicyURL,'') = ''))
			ORDER BY OGM.AndroidLastRealeaseDate DESC
	    END
END
GO
PRINT N'Altering [sSecurity].[pScreenHelpGet]...';


GO
ALTER PROCEDURE [sSecurity].[pScreenHelpGet]
	 @rScreenId int = 0,
	 @rHelpDescription nvarchar(max)='',
	 @rModuleId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 
	SELECT 
	
		ScreenId, HelpDescription,SC.Title,CM.Title As Module,ST.Id As TaskId, CM.Id As ModuleId
      
  FROM 
         [sSecurity].[tScreenHelp]  SH
		 INNER JOIN     [sSecurity].[tScreen]  SC ON SC.Id=SH.ScreenId 
		 INNER JOIN    [sSecurity].[tTask] ST ON ST.Id = SC.TaskId
		 INNER JOIN sCommon.tModuleMaster CM ON CM.Id = ST.ModuleId 
  WHERE   
            ((SH.ScreenId = @rScreenId) OR (@rScreenId = 0))
            AND ((ST.ModuleId  = @rModuleId) OR (@rModuleId = 0))
		    AND ((SC.Title=@rHelpDescription) Or (@rHelpDescription=''))
			AND SC.iSObsolete=0
	      order by SC.OrderIndex desc
	      
END
GO
PRINT N'Altering [sSetup].[pPortalEventScheduleAdd]...';


GO
ALTER PROCEDURE [sSetup].[pPortalEventScheduleAdd]
	
	@rStrXml nvarchar(MAX),
    @rBatchId 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
	
	 BEGIN TRANSACTION 
	 BEGIN
	 
	 DELETE FROM sActivity.tEventSchedule WHERE BatchId=@rBatchId
	 
	 INSERT INTO sActivity.tEventSchedule 
		(
			Id,
			BatchId,
			FromDate,
			ToDate,
			Title,
			Remark,
			IsCommonForAll,
			IsHoliday,
			IsEnrollment,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			EventTypeId
			)
		SELECT		
			Id,
			BatchId,
			FromDate,
			ToDate,
			sSetup.fPortalXMLTagsReplaceReverse(Title),
			sSetup.fPortalXMLTagsReplaceReverse(Remark),
			IsCommonForAll,
			IsHoliday,
			IsEnrollment,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			EventTypeId
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				Id int,
				BatchId int,
				FromDate date,
				ToDate date,
				Title nvarchar(100),
				Remark nvarchar(100),
				IsCommonForAll bit,
				IsHoliday bit,
				IsEnrollment bit,
				CreatedUserId bigint,
				CreatedDateTime datetime,
				UpdatedUserId bigint,
				UpdatedDateTime datetime,
				EventTypeId int
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pIDNoGenerationGet]...';


GO
ALTER PROCEDURE [sStudent].[pIDNoGenerationGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rRecordStatusId smallint=0,
	 @rOrgId smallint,
	 @rBatchId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			SO.AcademicId,
			SO.StudentId,
			SO.GenderId,
			SO.ClassId,
			SO.DivisionId,
			SO.RecordStatusId,
			SO.RollNo AS RollNo,
			SO.Code,
			SO.Number,
			SO.FirstName,
			SO.LastName,
			[sStudent].[fStudentNameGet](SO.FirstName , SO.MiddleName, So.LastName,OM.StudentNameFormatId ) AS Name,
			SO.ClassName+'-'+SO.DivisionName AS ClassDivisionName,
			Sm.Title,
			SA.AdmissionDate
			
  FROM 
			[sStudent].[vStudentOther]  SO
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=SO.StudentId
			INNER JOIN sSetup.tOrganizationMaster OM
			ON SO.OrgId = OM.Id
			INNER JOIN sCommon.tStatusMaster SM ON Sm.Id=SO.RecordStatusId
		
  WHERE 
			(SO.ClassId=@rClassId OR @rClassId=0)
			AND (SO.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND (SO.RecordStatusId=@rRecordStatusId OR @rRecordStatusId=0)
			AND SO.BatchId=@rBatchId
			AND SO.OrgId=@rOrgId order by SO.DivisionId,SO.RollNo
END
GO
PRINT N'Altering [sStudent].[pMyClassGet]...';


GO
ALTER PROCEDURE [sStudent].[pMyClassGet]
	 
	 @rSourceId bigint,
	 @rOrgId int,
	 @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lDivisionId int
BEGIN 

SELECT @lDivisionId=DivisionId From sStudent.tAcademic Where StudentId=@rSourceId AND OrgId=@rOrgId AND BatchId=@rBatchId
	
		SELECT
				vSF.AcademicId,
				vSF.Name,
				vSF.ClassName+ ' - '+vSF.DivisionName AS ClassDiv,
				vSF.RollNo,
				ISNULL(vSF.StudentPhoto,0) AS StudentPhoto,
				ISNULL(vSF.ParentContactNo,'') ParentContactNo,
				ISNULL(SO.GenderId,0) AS GenderId,
				ISNULL(GM.Title,'') AS Gender
		FROM 
				sStudent.vStudentFull vSF
				LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = vSF.StudentId
				LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		WHERE 
		
		(vSF.OrgId=@rOrgId)
		AND (vSF.BatchId=@rBatchId)
		AND (vSF.DivisionId=@lDivisionId)
		AND (vSF.StatusId=1)
		
		Order by vSF.RollNo
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) = '',
	@rStudentNotAssigned int
 )
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)
	
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent2')
 BEGIN		
	DROP Table sStudent.tTempStudent2
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent3')
 BEGIN
	DROP Table sStudent.tTempStudent3
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent4')
 BEGIN
	DROP Table sStudent.tTempStudent4
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent8')
 BEGIN
	DROP Table sStudent.tTempStudent8
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent9')
 BEGIN	
	DROP Table sStudent.tTempStudent9
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent10')
 BEGIN
	DROP Table sStudent.tTempStudent10
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent11')
 BEGIN
	DROP Table sStudent.tTempStudent11
 END
 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent1')
 BEGIN
	DROP Table sStudent.tTempStudent1
 END





	-- 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
	-- Not Assign	
	IF (@rStudentNotAssigned <> 0)
	BEGIN
		IF @rStudentNotAssigned = 1  -- Hostel Not Assign
		BEGIN
		 IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='sStudent.tTempStudent11')
		 Begin
			SELECT DISTINCT SM.Id AS StudentId7
			INTO sStudent.tTempStudent11
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND SM.OrgId = @rOrgId AND A.BatchId=@BatchId AND A.StudentID Not in 
			(
			SElect SourceId from sHostel.tAssignRoom AR 
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE SM.OrgId = @rOrgId 
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId=''))
		 end
		END 

		IF @rStudentNotAssigned = 2 -- Transport Not Assign
		BEGIN
			 IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='sStudent.tTempStudent11')
			 Begin
				SELECT DISTINCT SM.Id AS StudentId7
				INTO sStudent.tTempStudent11
				FROM sStudent.tStudentMaster SM
				INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND SM.OrgId = @rOrgId AND A.BatchId=@BatchId AND A.StudentID Not in
				(Select SourceId FRom sTransport.tAssignRoute AT
				INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId AND AT.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId 
				AND  (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
				AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)))
				WHERE SM.OrgId = @rOrgId
			END			
		END 
		
	END
	ELSE
	BEGIN		
		SELECT DISTINCT NULL AS StudentId7 INTO sStudent.tTempStudent11
	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 = ''
	INNER JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId7 OR @rStudentNotAssigned = 0
			
	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
	DROP Table sStudent.tTempStudent11
END
GO
PRINT N'Altering [sStudent].[pValidateImportStudent]...';


GO
ALTER PROCEDURE [sStudent].[pValidateImportStudent]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lSUIdActivate nvarchar(50)=''
DECLARE @lIsActivateUniqueId bit = 0
DECLARE @lOrgGroupId int = 0
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
SELECT @lSUIdActivate = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 167 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	
IF (@lSUIdActivate = '') OR (@lSUIdActivate = 'False')
	SET @lIsActivateUniqueId = 0
ELSE
	SET @lIsActivateUniqueId = 1	

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),
        @lClass nvarchar(100),
        @lDivision nvarchar(100),        
        @lRegistrationNumber nvarchar(20),  
        @lAdmissionDate nvarchar(15),        
        @lDOB nvarchar(15),             
        @1ReturnCode int = 1,
        @1ExistStudentCode nvarchar(max) = '',
        @1ExistStudentRegistrationNumber nvarchar(max) = '',
        @1ValidAdmissionDate nvarchar(max) = '',
        @1ValidDOB nvarchar(max) = '',
        @1DuplicateStudentCode nvarchar(max) = '',
        @1DuplicateStudentRegistrationNumber nvarchar(max) = '',
        @lSUId nvarchar(20),
        @1ExistStudentSUId nvarchar(max) = '',
        @1DuplicateStudentSUId nvarchar(max) = '',
        @lLeftDate nvarchar(15),
        @lLCDate nvarchar(15),
        @1ValidLeftDate nvarchar(max) = '',
        @1ValidLCDate nvarchar(max) = '',
        @lStatusId smallint
        
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(50),
        RegistrationNumber nvarchar(20),
        FirstName nvarchar(100),
        LastName nvarchar(100),
		Class nvarchar(100),
		Division nvarchar(100),
		AdmissionStandard nvarchar(100),
		AdmissionDate nvarchar(15),
        DOB nvarchar(15),
        Gender nvarchar(10),
        --AdmissionCategory nvarchar(100),
		Religion nvarchar(100),
		CastCategory nvarchar(100),
        SUId nvarchar(20),
        LeftDate nvarchar(15),
        LCDate nvarchar(15),
        LeftStandard nvarchar(100),
        StatusId smallint
        --Id1 bigint NULL,
        --departmentId int NULL
 
  )
  INSERT INTO #tTable1
	(
	    Code,
	    RegistrationNumber, 
	    FirstName,
	    LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    Religion,
	    CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId
    ) 
   SELECT
        Code,
	    RegistrationNumber, 
	    FirstName,
	    LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    Religion,
	    CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        Code nvarchar(50) '@Code',
        RegistrationNumber nvarchar(20) '@RegistrationNumber',
        FirstName nvarchar(100) '@FirstName',
        LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		Division nvarchar(100) '@Division',
		AdmissionStandard nvarchar(100) '@AdmissionStandard',
		AdmissionDate nvarchar(15) '@AdmissionDate',
		DOB nvarchar(15) '@DOB',
		Gender nvarchar(10) '@Gender',
		--AdmissionCategory nvarchar(100) '@AdmissionCategory',
		Religion nvarchar(100) '@Religion',
		CastCategory nvarchar(100) '@CastCategory',
		SUId nvarchar(20) '@SUId',
		LeftDate nvarchar(15) '@LeftDate',
		LCDate nvarchar(15) '@LCDate',
		LeftStandard nvarchar(100) '@LeftStandard',
		StatusId smallint '@StatusId'
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
  BEGIN
  
       SELECT         
         
         @lCode = Code, 
         @lRegistrationNumber = RegistrationNumber,
         @lAdmissionDate = AdmissionDate,
         @lDOB=DOB,
         @lSUId = SUId,
         @lLeftDate = LeftDate,
         @lLCDate = LCDate,
         @lStatusId = StatusId
        FROM #tTable1 WHERE Id = @lCount 
     
    IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
          BEGIN
  			    SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
	       END	  
	IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId))         
          BEGIN
  			    SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
	       END	         
	IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
          BEGIN
				IF(ISNULL(@lRegistrationNumber,'')!='')
				BEGIN
  					SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
				END
	       END
	IF(ISDATE(@lAdmissionDate) = 0 AND @lAdmissionDate!='')
	BEGIN
		SET @1ValidAdmissionDate=@1ValidAdmissionDate + @lCode + '-' + @lAdmissionDate+','
	END
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB + @lCode + '-' + @lDOB+','
	END
	
	IF(ISDATE(@lLeftDate) = 0 AND @lLeftDate!='')
	BEGIN
		SET @1ValidLeftDate=@1ValidLeftDate + @lCode + '-' + @lLeftDate+','
	END
	
	IF(ISDATE(@lLCDate) = 0 AND @lLCDate!='')
	BEGIN
		SET @1ValidLCDate=@1ValidLCDate + @lCode + '-' + @lLCDate+','
	END
	
     SET @lCount = @lCount - 1	
   END	
   
   SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
		BEGIN
			SELECT         
         
			 @lClass = Class, 
			 @lDivision = Division
     
			FROM #tTable1 WHERE Id = @lCount
			
			IF NOT EXISTS (SELECT 1 FROM sSetup.tDivisionMaster DM 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId 
						WHERE CM.Title COLLATE DATABASE_DEFAULT =@lClass COLLATE DATABASE_DEFAULT AND DM.Title COLLATE DATABASE_DEFAULT =@lDivision COLLATE DATABASE_DEFAULT AND DM.OrgId=@rOrgId)	
			BEGIN
				
				SELECT 'Enter proper value for Division ' + @lClass + ' ' + @lDivision AS StudentCode
				RETURN
			END
			SET @lCount = @lCount - 1	
		END
   	
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'ID No Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number IS NULL OR Number='')
		--BEGIN
		--	SELECT 'Number Should not be empty' AS StudentCode
		--END
		--ELSE IF EXISTS(SELECT 1 FROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		--BEGIN
		--	SELECT 'Surname Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'First Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Class Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Division IS NULL OR Division COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Division Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard IS NULL OR AdmissionStandard='')
		--BEGIN
		--	SELECT 'Admission Standard Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender='')
		BEGIN
			SELECT 'Gender Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionCategory IS NULL OR AdmissionCategory='')
		--BEGIN
		--	SELECT 'Admission Category Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionDate IS NULL OR AdmissionDate COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Admission Date Should not be empty or check the date format' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId))
		BEGIN
			SELECT 'Enter proper value for Class as per Institute Setup > Class Master' AS StudentCode
		END				
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard  COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND AdmissionStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId))
		BEGIN
			SELECT 'Enter proper value for Admission Class as per Admin Tool > Institute Setup > Class Master' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Religion COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Religion COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tReligionMaster WHERE OrgGroupId=@rOrgGroupId))
		BEGIN
			SELECT 'Enter proper value / Check spelling for Religion per Admin Tool > Master > Religion Master' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tGenderMaster))
		BEGIN
			SELECT 'Enter proper value / Check spelling for gender ( Male / Female )' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE CastCategory COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND CastCategory COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tCastCategoryMaster))
		BEGIN
			SELECT 'Enter proper value for Cast Category (OBC,SC,ST,GENERAL)' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1)
		BEGIN
			SELECT 'Left Date Should not be empty or check the date format' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LCDate IS NULL OR LCDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1)
		BEGIN
			SELECT 'LC Date Should not be empty or check the date format' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE  LeftStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId) AND @lLeftDate!='')
		--BEGIN
		--	SELECT 'Enter proper value for Left Standard as per Institute Setup > Class Master' AS StudentCode
		--END	
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT)
		--BEGIN
		--	SELECT 'LeftDate Should not be empty or check the date format' AS StudentCode
		--END
		ELSE
		BEGIN
		SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'') + Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
		SELECT @1DuplicateStudentSUId=COALESCE(@1DuplicateStudentSUId ,'') + SUId + ',' FROM #tTable1 GROUP BY SUId HAVING ( COUNT(SUId) > 1 )	
			IF(@1DuplicateStudentSUId IS NOT NULL AND @1DuplicateStudentSUId != '' AND @lIsActivateUniqueId=1)
				BEGIN
					SET @1DuplicateStudentSUId = 'Duplicate SUId ' + @1DuplicateStudentSUId
					SELECT @1DuplicateStudentSUId AS StudentCode
				END
			ELSE IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
				BEGIN
					SET @1DuplicateStudentCode = 'Duplicate Code ' + @1DuplicateStudentCode
					SELECT @1DuplicateStudentCode AS StudentCode
				END
			ELSE
				BEGIN
				SELECT @1DuplicateStudentRegistrationNumber=COALESCE(@1DuplicateStudentRegistrationNumber ,'') + CONVERT(VARCHAR(20),RegistrationNumber) + ',' FROM #tTable1 GROUP BY RegistrationNumber HAVING ( COUNT(RegistrationNumber) > 1 AND ISNULL(RegistrationNumber,'')!='')	
				IF(@1DuplicateStudentRegistrationNumber IS NOT NULL AND @1DuplicateStudentRegistrationNumber  COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
				BEGIN
					SET @1DuplicateStudentRegistrationNumber = 'Duplicate Registration Number ' + @1DuplicateStudentRegistrationNumber
					SELECT @1DuplicateStudentRegistrationNumber AS StudentCode
				END
		ELSE IF((@1ExistStudentSUId IS NULL OR @1ExistStudentSUId = '' OR @lIsActivateUniqueId=0) AND (@1ExistStudentCode IS NULL OR @1ExistStudentCode = '') AND (@1ExistStudentRegistrationNumber IS NULL OR @1ExistStudentRegistrationNumber = '')
		AND (@1ValidAdmissionDate IS NULL OR @1ValidAdmissionDate = '') AND (@1ValidDOB IS NULL OR @1ValidDOB = ''))
		BEGIN
			SELECT '' AS StudentCode
		END
		ELSE IF (@1ExistStudentSUId IS NOT NULL AND @1ExistStudentSUId != '' AND @lIsActivateUniqueId=1)
		BEGIN
			SET @1ExistStudentSUId = 'Exist SUId ' + @1ExistStudentSUId
			Select @1ExistStudentSUId AS StudentCode
		END
		ELSE IF (@1ExistStudentCode IS NOT NULL AND @1ExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1ExistStudentCode = 'Exist Code ' + @1ExistStudentCode
			Select @1ExistStudentCode AS StudentCode
		END
		ELSE IF (@1ExistStudentRegistrationNumber IS NOT NULL AND @1ExistStudentRegistrationNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1ExistStudentRegistrationNumber = 'Exist Registration Number ' + @1ExistStudentRegistrationNumber
			Select @1ExistStudentRegistrationNumber AS StudentCode
		END
		ELSE IF (@1ValidAdmissionDate IS NOT NULL AND @1ValidAdmissionDate != '')
		BEGIN
			SET @1ValidAdmissionDate = 'Wrong Admission Date ' + @1ValidAdmissionDate
			Select @1ValidAdmissionDate AS StudentCode
		END
		ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
		BEGIN
			SET @1ValidDOB = 'Wrong DOB ' + @1ValidDOB
			Select @1ValidDOB AS StudentCode
		END
		ELSE IF (@1ValidLeftDate IS NOT NULL AND @1ValidLeftDate != '' AND @lLCDate!='')
		BEGIN
			SET @1ValidLeftDate = 'Wrong LeftDate ' + @1ValidLeftDate
			Select @1ValidLeftDate AS StudentCode
		END
		ELSE IF (@1ValidLCDate IS NOT NULL AND @1ValidLCDate != '' AND @lLCDate!='')
		BEGIN
			SET @1ValidLCDate = 'Wrong LCDate ' + @1ValidLCDate
			Select @1ValidLCDate AS StudentCode
		END
		END
		END
END
GO
PRINT N'Altering [sStudent].[pXMLChangeStudentClassAdd]...';


GO
ALTER PROCEDURE [sStudent].[pXMLChangeStudentClassAdd]
( @rXmlDoc nvarchar(MAX)='', @rOrgId smallint, 
@rBatchId int, @rClassId int 
--@rDivisionId int 
) AS SET NOCOUNT ON DECLARE @intDoc INT  
DECLARE @lNextNumber BIGINT  
DECLARE @idoc int 
DECLARE @doc nvarchar(max)  
SET @doc =@rXmlDoc EXEC sp_xml_preparedocument @idoc OUTPUT, @doc BEGIN  
DECLARE @NodeName nVARCHAR(100),@lExistCode nvarchar(max)  
SET @NodeName = '/Students/Students'  -- SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')  
   
EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tAcademic', 0, 1, 1,@outNextNumber = @lNextNumber output  
  
  
 IF EXISTS(SELECT SM.Code  
 from  
 (  
   SELECT StudentId FROM  
   OPENXML (@idoc,@nodename, 2)  
   WITH (  
     StudentId bigint)   
 )E  
 INNER JOIN sStudent.tStudentMaster SM ON SM.Id=E.StudentId   
 INNER JOIN sStudent.tAcademic A ON A.StudentId=SM.Id    
 Where A.ClassID =@rClassId  AND A.BatchId=@rBatchId AND SM.OrgId=@rOrgId  
 )  
   
 BEGIN  
  SELECT @lExistCode  = COALESCE(@lExistCode ,'') + CONVERT(VARCHAR(15),SM.Code) + ' , '   
  from  
  (  
    SELECT StudentId FROM  
    OPENXML (@idoc, @nodename, 2)  
    WITH (  
      StudentId bigint)   
  )E  
  INNER JOIN sStudent.tStudentMaster SM ON SM.Id=E.StudentId    
  INNER JOIN sStudent.tAcademic A ON A.StudentId=SM.Id    
   Where A.ClassID =@rClassId  AND A.BatchId=@rBatchId AND SM.OrgId=@rOrgId  
  SELECT @lExistCode  
   RETURN  
 END  
  INSERT INTO sStudent.tAcademic (   Id,   StudentId,  
  ClassId,  
  DivisionId,  
  RollNo,  
  OrgId,  
  BatchId,  
  CreatedUserId,  
  CreatedDateTime ) SELECT  
  @lNextNumber+ ROW_NUMBER() OVER(ORDER BY StudentId),  
  StudentId,  
  @rClassId,  
  DivisionId,  
  RollNo,  
  @rOrgId,  
  @rBatchId,  
  CreatedUserId,  
  sCommon.fgetdate()  
FROM OPENXML (@idoc, @NodeName, 2)  
WITH  
(  
  StudentId bigint,  
  DivisionId int,  
  RollNo int,  
  CreatedUserId bigint  
)    
  
 SELECT @lNextNumber = MAX(ID) FROM sStudent.tAcademic Where OrgId=@rOrgId  
    EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sStudent.tAcademic', @rCurrentNumber = @lNextNumber   
  
 EXEC sp_xml_removedocument @idoc  
  
Select 101 AS Result  
--END  
END
GO
PRINT N'Altering [sTally].[pReceiptPostingGet]...';


GO
ALTER PROCEDURE [sTally].[pReceiptPostingGet]

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

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


GO
CREATE PROCEDURE [sActivity].[pImportEvent]
       
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rBatchId int,
	@rCreatedUserId bigint 	  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lCount int,@intDoc INT,@lInterrorCode INT,@loXML XML,
			@lTitle nvarchar(100),
			@lFromDate date,
			@lToDate date,
			@lRemark nvarchar(200),
			@lEventTypeId int,			
			@lIsHoliday bit,
			@lBatchId int	
	
	SET @loXML = CAST(@rXmldoc AS XML)
	
	
	CREATE TABLE #tTable1 (
	Id bigint identity,
	Title nvarchar(100) ,
	FromDate date ,
	ToDate date ,
	Remark nvarchar(200),
	EventTypeId int ,	
	IsHoliday bit,
	BatchId int)
	
	INSERT INTO #tTable1(
		Title,
		FromDate,
		ToDate,
		Remark, 
		EventTypeId,
		IsHoliday,
		BatchId )
	SELECT
		 T.c.value('@Title','nvarchar(100)') AS Title,
		 T.c.value('@FromDate','date') AS FromDate,
		 T.c.value('@ToDate','date') AS ToDate,
		 T.c.value('@Remark','nvarchar(200)') AS Remark,
		 T.c.value('@EventTypeId','int') AS EventTypeId,
		-- T.c.value('@IsHoliday','bit') AS IsHoliday,
		 CASE WHEN (T.c.value('@IsHoliday','bit') = 1) THEN  'True' ELSE 'False' END AS IsHoliday,
		 @rBatchId
		 
	FROM @loXML.nodes('/Table/ImportEvent')T(c)
	
	
	
SELECT @lCount =  COUNT(Id) FROM #tTable1
	
	
WHILE @lCount > 0 

BEGIN				
	
SELECT	
		@lTitle = Title,
		@lFromDate = FromDate,
		@lToDate = ToDate,
		@lRemark = Remark,
		@lEventTypeId = EventTypeId,
		@lIsHoliday = IsHoliday,
		@lBatchId = BatchId
			
											 	 
FROM #tTable1 WHERE Id = @lCount 

	IF EXISTS(SELECT Id FROM sActivity.tEventSchedule WHERE Title=@lTitle AND BatchId = @rBatchId)
		BEGIN
			UPDATE sActivity.tEventSchedule
			SET	
				Title = @lTitle,				
				FromDate = @lFromDate,			
				ToDate = @lToDate,
				Remark = @lRemark,
				EventTypeId = @lEventTypeId,
				IsHoliday = @lIsHoliday 
			WHERE 
				Title=@lTitle AND BatchId = @rBatchId			
		END
		ELSE
		BEGIN
			DECLARE @lNextNumber BIGINT	
			EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sActivity.tEventSchedule', 0, 101, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sActivity.tEventSchedule
				(
					Id,		
					Title,
					FromDate,
					ToDate,
					Remark,
					EventTypeId,
					IsHoliday,
					BatchId,
					IsCommonForAll,
					IsEnrollment,
					CreatedUserId,
					CreatedDateTime
				)
			VALUES
				(
					@lNextNumber,
					@lTitle,					
					@lFromDate,
					@lToDate,
					@lRemark,
					@lEventTypeId,
					@lIsHoliday,
					@rBatchId,
					0,
					0,
					@rCreatedUserId,
					sCommon.fGetDate()
				)	
		END
		SET @lCount = @lCount - 1
	SELECT 1 AS Result, '' AS ResultDetail				

 END
END
GO
PRINT N'Creating [sAttendance].[pStudentAttendance]...';


GO


 CREATE PROCEDURE [sAttendance].[pStudentAttendance]
	 
	 
	 @rOrgId int,
	 @rOrgGroupBatchId int,
	 @rUserSourceId bigint
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN
 
	Select
		MR.TotalCount,
		MR.AbsentCount,
		MR.AttendanceCount, 
		MR.PresentCount, 		
		MR.AveragePresence
		
	From
		sStudent.vStudentAcademic SA		
		INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SA.AcademicId		
		
	Where
		SA.OrgId = @rOrgId And SA.OrgGroupBatchId=@rOrgGroupBatchId
		And SA.InchargeEmployeeId = @rUserSourceId
			
END
GO
PRINT N'Creating [sErp].[pVcpMasterAdd]...';


GO

CREATE PROCEDURE [sErp].[pVcpMasterAdd]
	 @rOrgId smallint,
	 @rId int, 
	 @rTitle nvarchar(200),	
	 @rCreatedUserId bigint, 
	 @rUpdatedUserId bigint ,
	 @rIsActive bit = 0
	      	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sErp.tChannelMaster where Code=@rCode AND OrgId=@rOrgId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sErp.tLeadChannelPartnerMaster where Title=@rTitle AND OrgId=@rOrgId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sErp.tChannelMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sErp.tLeadChannelPartnerMaster where Title=@rTitle  AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tLeadChannelPartnerMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sErp.tLeadChannelPartnerMaster
		(
			Id
      ,OrgId
      ,Title
      ,IsActive
      ,CreatedUserId
      ,CreatedDateTime
      ,UpdatedUserId
      ,UpdatedDateTime
      
		)
	VALUES
		(
		 @lNextNumber
      , @rOrgId
      , @rTitle
      , @rIsActive
      , @rCreatedUserId
      , sCommon.fGetDate()
      , @rUpdatedUserId
      , sCommon.fGetDate()
      
		)
		    SELECT 1 AS Result
	END	 
	
	ELSE
	
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sErp.tLeadChannelPartnerMaster
	    SET
      Title=@rTitle
      ,IsActive = @rIsActive
      ,UpdatedUserId=@rUpdatedUserId
      ,UpdatedDateTime=sCommon.fGetDate()
     
	      
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	

	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sErp].[pVcpMasterGet]...';


GO


CREATE PROCEDURE [sErp].[pVcpMasterGet]
@rId int,
		@rOrgId smallint=0,
		@rTitle nvarchar(200) =null,
		@rIsWildCardSearch bit

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
IF @rIsWildCardSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT 
	      LCM.Id,
	      LCM.OrgId,
	      LCM.Title,	  
	      LCM.IsActive  
	FROM 
			sErp.tLeadChannelPartnerMaster LCM
	WHERE 
	(LCM.OrgId = @rOrgId)	
		AND	((LCM.Id = @rId) OR (@rId = 0))	
	AND ((LCM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		ORDER BY LCM.CreatedDateTime DESC
END
GO
PRINT N'Creating [sPayroll].[pRptPFECRFormat]...';


GO
CREATE PROCEDURE [sPayroll].[pRptPFECRFormat]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)
-- For report
	SELECT 
	
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    ISNULL(A.WorkingDays,0) AS WorkingDays,
	    ISNULL(A.Amount,0) AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    ISNULL(A.TotalEarning,0) AS TotalEarning
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId,PPE.TotalEarning
		FROM sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 

-- For Notepad report
		
SELECT 
		ISNULL(ESO.UAN,'') AS UAN,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		ISNULL(A.TotalEarning,0) AS TotalEarning,
		ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit1,
		ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit2,
		ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit3,
		ISNULL(PFPro.EmployeePfAmount,0) AS EmployeePfAmount,
		ISNULL(PFPro.EmployerFpsAmount,0) AS EmployerFpsAmount,
		ISNULL(PFPro.EmployeePfAmount,0) - ISNULL(PFPro.EmployerFpsAmount,0) AS EPFEPS,
		0 AS NCPDays,
		0 AS RefundAdv
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId,PPE.TotalEarning
		FROM sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 		
		
END
GO

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