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

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


GO
ALTER TABLE [sAcademic].[tOnlineLearning]
    ADD [CoTeacherEmployee1StartDateTime] DATETIME NULL,
        [CoTeacherEmployee1EndDateTime]   DATETIME NULL,
        [CoTeacherEmployee2StartDateTime] DATETIME NULL,
        [CoTeacherEmployee2EndDateTime]   DATETIME NULL;


GO
PRINT N'Starting rebuilding table [sAcademic].[tOnlineLearningAssignmentHistory]...';


GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

CREATE TABLE [sAcademic].[tmp_ms_xx_tOnlineLearningAssignmentHistory] (
    [AutoId]           BIGINT          NOT NULL,
    [OnlineLearningId] BIGINT          NOT NULL,
    [AssignmentPath]   NVARCHAR (1000) NOT NULL
);

ALTER TABLE [sAcademic].[tmp_ms_xx_tOnlineLearningAssignmentHistory]
    ADD CONSTRAINT [tmp_ms_xx_clusteredindex_PK_tOnlineLearningAssignmentHistory_1] PRIMARY KEY CLUSTERED ([AutoId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);

IF EXISTS (SELECT TOP 1 1
           FROM   [sAcademic].[tOnlineLearningAssignmentHistory])
    BEGIN
        INSERT INTO [sAcademic].[tmp_ms_xx_tOnlineLearningAssignmentHistory] ([AutoId], [OnlineLearningId], [AssignmentPath])
        SELECT   [AutoId],
                 [OnlineLearningId],
                 [AssignmentPath]
        FROM     [sAcademic].[tOnlineLearningAssignmentHistory]
        ORDER BY [AutoId] ASC;
    END

DROP TABLE [sAcademic].[tOnlineLearningAssignmentHistory];

EXECUTE sp_rename N'[sAcademic].[tmp_ms_xx_tOnlineLearningAssignmentHistory]', N'tOnlineLearningAssignmentHistory';

EXECUTE sp_rename N'[sAcademic].[tmp_ms_xx_clusteredindex_PK_tOnlineLearningAssignmentHistory_1]', N'PK_tOnlineLearningAssignmentHistory_1', N'OBJECT';

COMMIT TRANSACTION;

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;


GO
PRINT N'Altering [sCommon].[tUploadDocument]...';


GO
ALTER TABLE [sCommon].[tUploadDocument]
    ADD [DocumentSize] DECIMAL (12, 2) NULL;


GO
PRINT N'Altering [sCommon].[tUploadFunctionalityMaster]...';


GO
ALTER TABLE [sCommon].[tUploadFunctionalityMaster] ALTER COLUMN [Code] NVARCHAR (50) NULL;


GO
PRINT N'Altering [sConfig].[tConfigurationMaster]...';


GO
ALTER TABLE [sConfig].[tConfigurationMaster] ALTER COLUMN [ItemValue] NVARCHAR (200) NULL;


GO
PRINT N'Altering [sConfig].[tConfigurationValue]...';


GO
ALTER TABLE [sConfig].[tConfigurationValue] ALTER COLUMN [ItemValue] NVARCHAR (200) NULL;


GO
PRINT N'Creating [dbo].[tTest]...';


GO
CREATE TABLE [dbo].[tTest] (
    [Id] SMALLINT NOT NULL
);


GO
PRINT N'Creating [sAcademic].[tClassworkViewHistory]...';


GO

PRINT N'Creating PK_tClassworkViewHistory_1...';


GO

PRINT N'Creating [sAlert].[tWhatsAppLogHistory]...';


GO

PRINT N'Creating PK__tWhatsAp__6B23290527ED6813...';


GO

PRINT N'Creating [sAudit].[tActivityLogHistory]...';


GO

PRINT N'Creating [sAudit].[tOperationLogHistory]...';


GO

PRINT N'Creating PK_tOperationLogHistory...';


GO

PRINT N'Creating [sCommunication].[tAssignmentViewHistory]...';


GO

PRINT N'Creating [sCommunication].[tCircularViewHistory]...';


GO

PRINT N'Creating [sCommunication].[tFollowup]...';


GO
CREATE TABLE [sCommunication].[tFollowup] (
    [AutoId]              BIGINT         IDENTITY (1, 1) NOT NULL,
    [FollowupNumber]      INT            NOT NULL,
    [FollowupTypeId]      BIGINT         NOT NULL,
    [FollowupDate]        DATE           NOT NULL,
    [FollowupTime]        TIME (7)       NOT NULL,
    [FollowupDuration]    INT            NOT NULL,
    [RelationId]          TINYINT        NOT NULL,
    [AcademicId]          BIGINT         NOT NULL,
    [FollowupRemark]      NVARCHAR (500) NOT NULL,
    [FollowupOtherRemark] NVARCHAR (500) NOT NULL,
    [FollowupRelationId]  BIGINT         NOT NULL,
    [FollowupHandleById]  BIGINT         NOT NULL
);


GO
PRINT N'Creating PK_tFollowup...';


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


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


GO
CREATE TABLE [sCommunication].[tFollowupTypeAssignedTo] (
    [SourceTypeId]   SMALLINT NOT NULL,
    [SourceId]       BIGINT   NOT NULL,
    [FollowupTypeId] BIGINT   NOT NULL
);


GO
PRINT N'Creating [sCommunication].[tFollowupTypeAssignedTo].[UK_tFollowupTypeAssignedTo]...';


GO
CREATE UNIQUE NONCLUSTERED INDEX [UK_tFollowupTypeAssignedTo]
    ON [sCommunication].[tFollowupTypeAssignedTo]([SourceTypeId] ASC, [SourceId] ASC, [FollowupTypeId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


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


GO
CREATE TABLE [sCommunication].[tFollowupTypeMaster] (
    [Id]              BIGINT         NOT NULL,
    [Code]            NVARCHAR (100) NOT NULL,
    [Title]           NVARCHAR (200) NOT NULL,
    [OrderIndex]      INT            NOT NULL,
    [IsPublish]       BIT            NOT NULL,
    [IsObsolete]      BIT            NOT NULL,
    [OrgGroupId]      SMALLINT       NOT NULL,
    [CreatedUserId]   BIGINT         NOT NULL,
    [CreatedDateTime] DATETIME       NOT NULL,
    [UpdatedUserId]   BIGINT         NULL,
    [UpdatedDateTime] DATETIME       NULL
);


GO
PRINT N'Creating PK_tFollowupTypeMaster_1...';


GO
ALTER TABLE [sCommunication].[tFollowupTypeMaster]
    ADD CONSTRAINT [PK_tFollowupTypeMaster_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 [sHrm].[tLeaveBalanceLogHistory]...';


GO
CREATE TABLE [sHrm].[tLeaveBalanceLogHistory] (
    [Id]                 BIGINT         NOT NULL,
    [EmployeeId]         BIGINT         NOT NULL,
    [LeaveTypeId]        INT            NOT NULL,
    [BalanceLeave]       DECIMAL (8, 2) NOT NULL,
    [LeaveTransactionId] TINYINT        NOT NULL,
    [TransactionLeave]   DECIMAL (8, 2) NOT NULL,
    [Remark]             NVARCHAR (200) NULL,
    [BatchId]            INT            NOT NULL,
    [CreatedUserId]      BIGINT         NOT NULL,
    [CreatedDateTime]    DATETIME       NOT NULL
);


GO
PRINT N'Creating PK_tLeaveBalanceLogHistory...';


GO
ALTER TABLE [sHrm].[tLeaveBalanceLogHistory]
    ADD CONSTRAINT [PK_tLeaveBalanceLogHistory] 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 [sLibrary].[tBookLogHistory]...';


GO
CREATE TABLE [sLibrary].[tBookLogHistory] (
    [Id]                   BIGINT         NOT NULL,
    [ReaderSourceTypeId]   SMALLINT       NULL,
    [ReaderSourceId]       BIGINT         NULL,
    [ResourceSourceTypeId] SMALLINT       NOT NULL,
    [ResourceSourceId]     BIGINT         NOT NULL,
    [LogDate]              DATE           NOT NULL,
    [DueDate]              DATE           NOT NULL,
    [StatusId]             SMALLINT       NOT NULL,
    [Remark]               NVARCHAR (150) NULL,
    [IsCurrentStatus]      BIT            NOT NULL,
    [BatchId]              INT            NOT NULL,
    [OrgId]                SMALLINT       NOT NULL,
    [CreatedUserId]        BIGINT         NOT NULL,
    [CreatedDateTime]      DATETIME       NOT NULL,
    [UpdatedUserId]        BIGINT         NULL,
    [UpdatedDateTime]      DATETIME       NULL,
    [LibraryId]            INT            NULL,
    [ReturnDate]           DATE           NULL,
    [BookActionStatusId]   TINYINT        NULL
);


GO
PRINT N'Creating PK_tBookLogHistory...';


GO
ALTER TABLE [sLibrary].[tBookLogHistory]
    ADD CONSTRAINT [PK_tBookLogHistory] 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 [sRecruitment].[tRecruitmentStatusLogHistory]...';


GO
CREATE TABLE [sRecruitment].[tRecruitmentStatusLogHistory] (
    [OrgGroupId]          INT            NOT NULL,
    [CandidateId]         BIGINT         NOT NULL,
    [RecruitmentStatusId] TINYINT        NOT NULL,
    [Remark]              NVARCHAR (100) NULL,
    [CreatedUserId]       BIGINT         NOT NULL,
    [CreatedDateTime]     DATETIME       NOT NULL
);


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


GO

PRINT N'Creating PK_tBackupLogHistory...';


GO


 
GO
PRINT N'Dropping [sFee].[fPendingFeeAmountGet]...';


GO
DROP FUNCTION [sFee].[fPendingFeeAmountGet];


GO
PRINT N'Creating [sFee].[fPendingFeeAmountGet]...';


GO
 

CREATE FUNCTION [sFee].[fPendingFeeAmountGet] (@rAcademicId bigint, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int, @rMonthId int, @rUptoDate Date,@rReceiptBookId int,@rFeeId nvarchar(max)='')
RETURNS nvarchar(2000) WITH EXECUTE AS CALLER
AS 
BEGIN

    DECLARE @rReceiptDetail nvarchar(2000)
    DECLARE @lClassId int 
    DECLARE @lDivisionId int 
    DECLARE @lAdmissionCategoryId int
    
    SELECT @lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId 
	FROM sStudent.vStudentAcademic
	WHERE AcademicId = @rAcademicId AND BatchId=@rBatchId AND OrgId = @rOrgId AND OrgGroupBatchId=@rOrgGroupBatchId
    
    (
    SELECT 
		@rReceiptDetail = SUM(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))
    FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND Month(FS1.StartDate) = @rMonthId 
				AND SA1.AcademicId = @rAcademicId
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			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=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND Month(FS1.StartDate) = @rMonthId 
				AND SA1.AcademicId = @rAcademicId
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId
		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=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND Month(FS.StartDate) = @rMonthId 
				AND SA1.AcademicId = @rAcademicId
				AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (FS.StartDate <= @rUptoDate)
			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)
			)
	RETURN ISNULL(LEFT(@rReceiptDetail,LEN(@rReceiptDetail)-3),0) 
			
END
GO

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


GO
 
ALTER PROCEDURE [sAcademic].[pMeetingAccountGet]

	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rEmployeeId bigint = 0,
	 @rOrgGroupId smallint,
	 @rMeetingProviderId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	if(@rId = 0)
	BEGIN 
	
	SELECT 
			OMA.Id,
			OMA.AccountName,
			OMA.AccountEmailId,
			ISNULL(EM.EmployeeName,'') as EmployeeName,
			DM.Title as MeetingProvider,
			OMA.WebAPIKey,
			OMA.WebAPISecret
	  FROM 
			sAcademic.tOnlineMeetingAccount OMA
			LEFT JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OMA.EmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON OMA.MeetingProviderId = DM.Id AND DM.DataTypeId = 8
	  WHERE 
  
				((OMA.AccountName like @rTitle) OR (ISNULL(@rTitle,'') = ''))
				AND OMA.OrgGroupId = @rOrgGroupId
				AND ((OMA.MeetingProviderId = @rMeetingProviderId) OR (ISNULL(@rMeetingProviderId,0) = 0))
	 
	END
	ELSE
	BEGIN
		SELECT 
			OMA.Id,
			OMA.EmployeeId as EmployeeId,
			EM.EmployeeCode as EmployeeCode,
			OMA.AccountName as AccountName,
			OMA.AccountEmailId as AccountEmailId,
			OMA.AccountPassword as AccountPassword,
			OMA.APIKey as APIKey,
			OMA.APISecret as APISecret,
			OMA.WebAPIKey as WebAPIKey,
			OMA.WebAPISecret as WebAPISecret,
			OMA.MeetingProviderId as MeetingProviderId,
			DM.Title as MeetingProvider,
			OMA.JWTToken as JWTToken
	  FROM 
			sAcademic.tOnlineMeetingAccount OMA
			INNER JOIN sCommon.tDataMaster DM ON OMA.MeetingProviderId = DM.Id AND DM.DataTypeId = 8
			LEFT JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OMA.EmployeeId
	  WHERE 
			(OMA.Id = @rId) AND OMA.OrgGroupId = @rOrgGroupId
			AND ((OMA.MeetingProviderId = @rMeetingProviderId) OR (ISNULL(@rMeetingProviderId,0) = 0))
	END
END
GO
PRINT N'Altering [sAcademic].[pOnlineLearningGet]...';


GO
 
 -- exec [sAcademic].[pOnlineLearningGet] 1101000000438,'','','',0,0,0,0,0,-1,110100110
ALTER PROCEDURE [sAcademic].[pOnlineLearningGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rFromDate date = '',
	 @rToDate date = '',
	 @rClassId int = 0,
	 @rSubjectId int = 0,
	 @rTopicId int = 0,
	 @rEmployeeId bigint = 0,
	 @rLearningTypeId int = 0,
	 @rIsCompleted int = -1,
	 @rBatchId int,
	 @rType int = 0,
	 @rUserId bigint = 0,
	 @rOnlineMeetingAccountId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
if(@rType = 0)
BEGIN
	if(@rId = 0)
	BEGIN 
	
	SELECT
			OL.Id,
			SM.Title as Subject,
			ISNULL(CM.DisplayTitle,'') as Class,
			ISNULL(TM.Title,'') as Topic,
			--EM.FirstName +' ' +EM.LastName as Teacher,
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS Teacher,
			DM.Title as LearningType,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDateTime,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDateTime,
			OL.IsCompleted as Status,
		    ISNULL(OL.Title,'') as Title,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tClassMaster CM ON OLS.SourceId = CM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tDivisionMaster DM ON OLS.SourceId = DM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2005
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as Source ,
			  OL.StartDateTime AS TeacherStartDateTime,
			  OL.EndDateTime AS TeacherEndDateTime,
			  (SELECT ISNULL(ISNULL(FirstName, ' ') + ' ' + ISNULL(LastName, ' '), ' ') FROM sHrm.tEmployeeMaster WHERE Id = OL.CoTeacherEmployeeId1) AS CoTeacherEmployee1,
			  (SELECT ISNULL(ISNULL(FirstName, ' ') + ' ' + ISNULL(LastName, ' '), ' ') FROM sHrm.tEmployeeMaster WHERE Id = OL.CoTeacherEmployeeId2) AS CoTeacherEmployee2,
			  OL.CoTeacherEmployee1StartDateTime,
			  OL.CoTeacherEmployee1EndDateTime,
			  OL.CoTeacherEmployee2StartDateTime,
			  OL.CoTeacherEmployee2EndDateTime
	  FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN (SELECT DISTINCT OM.Id FROM sSetup.vUserOrganization OM 
			WHERE ((OM.UserId = @rUserId) OR (@rUserId = 0)) ) A ON A.Id = EM.OrgID
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
 	  WHERE 
				((OL.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OL.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((OL.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			AND ((OL.TopicId = @rTopicId) OR (@rTopicId = 0))
			AND ((OL.TeacherEmployeeId = @rEmployeeId) OR (@rEmployeeId = -1))
			AND ((OL.LearningTypeId = @rLearningTypeId) OR (@rLearningTypeId = 0))
			AND ((CONVERT(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
			AND (OL.BatchId = @rBatchId)
			AND ((OL.MeetingAccountId = @rOnlineMeetingAccountId) OR (@rOnlineMeetingAccountId = 0))
	 ORDER BY
			OL.StartDate desc
		
	END
	ELSE
	BEGIN
		SELECT 
			OL.Id,
			SM.Title as Subject,
			SM.Id as SubjectId,
			ISNULL(CM.Title,'') as Class,
			ISNULL(CM.Id,0) as ClassId,
			ISNULL(TM.Title,'') as Topic,
			ISNULL(TM.Id,0) as TopicId,
			EM.FirstName +' '+ EM.LastName as Teacher,
			Em.Id as TeacherId,
			DM.Title as LearningType,
			DM.Id as LearningTypeId,
			CONVERT(NVARCHAR,OL.StartDate) as StartDate,
			CONVERT(NVARCHAR,OL.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OL.EndDate) as EndDate,
			CONVERT(NVARCHAR,OL.EndTime,108) as EndTime,
			OL.IsCompleted as Status,
			OL.LecturePath,
			OL.Title as LearningTitle,
			OL.Description,
			OL.IsDisplayMeetingId,
			OL.MeetingId,
			OL.MeetingPassword,
			ISNULL(OL.IsTrackAttendance,0) as IsTrackAttendance,
			ISNULL(OL.IsAssignment,0) as IsAssignment,
			ISNULL(OL.IsSubmitAssignment,0) as IsSubmitAssignment,
			ISNULL(OL.IsTakeTest,0) as IsTakeTest,
			ISNULL(OL.IsReference,0) as IsReference,
			ISNULL(OL.IsResource,0) as IsResource,
			ISNULL(OL.IsCompleted,0) as IsCompleted,
			ISNULL(OL.IsMeetingStarted,0) as IsMeetingStarted,
			ISNULL(TestM.Id,0) AS TestId,
			ISNULL(TestM.Title,'')AS Test,
			ISNULL(OMS.IsOnParticipantVideo,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) AS IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) AS IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) AS IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) AS IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) AS IsOnHostscreenShare,
			ISNULL(OL.MeetingAccountId,0) AS MeetingAccountId,
			ISNULL(OL.IsMeetingCreated,0) AS IsMeetingCreated,
			ISNULL(OL.AssignmentRemark,'') AS AssignmentRemark,
			ISNULL(OL.IsTrackAssignmentView,0) as IsTrackAssignmentView,
			ISNULL(OL.CoTeacherEmployeeId1,0) as CoTeacherEmployeeId1,
			ISNULL(OL.CoTeacherEmployeeId2,0) as CoTeacherEmployeeId2,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			(Select EmployeeName FROM sHrm.vExtEmployee  WHERE  EmployeeId = ISNULL(OL.CoTeacherEmployeeId1,0)) AS CoTeacherEmployee1,
			(Select EmployeeName FROM sHrm.vExtEmployee  WHERE EmployeeId = ISNULL(OL.CoTeacherEmployeeId2,0)) AS CoTeacherEmployee2,
			ISNULL(CONVERT(NVARCHAR,OL.AssignmentSubmissionEndDate),'') As SubmissionEndDate,
			OL.StartDateTime AS TeacherStartDateTime,
			OL.EndDateTime AS TeacherEndDateTime,
			ISNULL(OL.IsRecording,0) AS IsRecording,
			BM.Id AS BatchId,
			BM.Title AS BatchName,
			OM.Id AS OrgId,
			OM.Title AS OrganizationName
	  FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			LEFT JOIN sEExam.tTestMaster TestM ON OL.ClassId=TestM.ClassId AND OL.TestId=TestM.Id
			LEFT JOIN sAcademic.tOnlineMeetingSettings OMS ON OMS.OnlineLearningId = OL.Id 
			INNER JOIN sSetup.tBatchMaster BM ON OL.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON BM.OrgId=OM.Id
	  WHERE 
			(OL.Id = @rId) AND (OL.BatchId = @rBatchId)
	END
END
ELSE IF(@rType = 1)
BEGIN
		if(@rId = 0)
	BEGIN 
	
	SELECT 
			OL.Id,
			SM.Title as Subject,
			ISNULL(CM.DisplayTitle,'') as Class,
			ISNULL(TM.Title,'') as Topic,
			EM.FirstName +' '+ EM.LastName as Teacher,
			DM.Title as LearningType,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDateTime,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDateTime,
			OL.IsCompleted as Status,
		    ISNULL(OL.Title,'') as Title,
			OL.StartDateTime AS TeacherStartDateTime,
			OL.EndDateTime AS TeacherEndDateTime
	  FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
	  WHERE 
  
				((OL.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OL.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((OL.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			AND ((OL.TopicId = @rTopicId) OR (@rTopicId = 0))
			AND ((OL.TeacherEmployeeId = @rEmployeeId) OR (@rEmployeeId = -1))
			AND ((OL.LearningTypeId = @rLearningTypeId) OR (@rLearningTypeId = 0))
			AND ((CONVERT(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
			AND (OL.BatchId = @rBatchId)
			AND OL.IsCompleted <> 721			
	 ORDER BY
			
			OL.StartDate desc
		
	END
	ELSE
	BEGIN
		SELECT 
			OL.Id,
			SM.Title as Subject,
			SM.Id as SubjectId,
			ISNULL(CM.Title,'') as Class,
			ISNULL(CM.Id,0) as ClassId,
			ISNULL(TM.Title,'') as Topic,
			ISNULL(TM.Id,0) as TopicId,
			EM.EmployeeName as Teacher,
			Em.EmployeeId as TeacherId,
			DM.Title as LearningType,
			DM.Id as LearningTypeId,
			CONVERT(NVARCHAR,OL.StartDate) as StartDate,
			CONVERT(NVARCHAR,OL.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OL.EndDate) as EndDate,
			CONVERT(NVARCHAR,OL.EndTime,108) as EndTime,
			OL.IsCompleted as Status,
			OL.LecturePath,
			OL.Title as LearningTitle,
			OL.Description,
			OL.IsDisplayMeetingId,
			OL.MeetingId,
			OL.MeetingPassword,
			ISNULL(OL.IsTrackAttendance,0) as IsTrackAttendance,
			ISNULL(OL.IsAssignment,0) as IsAssignment,
			ISNULL(OL.IsSubmitAssignment,0) as IsSubmitAssignment,
			ISNULL(OL.IsTakeTest,0) as IsTakeTest,
			ISNULL(OL.IsReference,0) as IsReference,
			ISNULL(OL.IsResource,0) as IsResource,
			ISNULL(OL.IsCompleted,0) as IsCompleted,
			ISNULL(OL.IsMeetingStarted,0) as IsMeetingStarted,
			ISNULL(TestM.Id,0) AS TestId,
			ISNULL(TestM.Title,'')AS Test,
			ISNULL(OMS.IsOnParticipantVideo,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) AS IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) AS IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) AS IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) AS IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) AS IsOnHostscreenShare,
			ISNULL(OL.MeetingAccountId,0) AS MeetingAccountId,
			ISNULL(OL.IsMeetingCreated,0) AS IsMeetingCreated,
			ISNULL(OL.AssignmentRemark,'') AS AssignmentRemark,
			ISNULL(OL.IsTrackAssignmentView,0) as IsTrackAssignmentView,
			ISNULL(OL.CoTeacherEmployeeId1,0) as CoTeacherEmployeeId1,
			ISNULL(OL.CoTeacherEmployeeId2,0) as CoTeacherEmployeeId2,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			(Select EmployeeName FROM sHrm.vExtEmployee  WHERE  EmployeeId = ISNULL(OL.CoTeacherEmployeeId1,0)) AS CoTeacherEmployee1,
			(Select EmployeeName FROM sHrm.vExtEmployee  WHERE EmployeeId = ISNULL(OL.CoTeacherEmployeeId2,0)) AS CoTeacherEmployee2,
			ISNULL(CONVERT(NVARCHAR,OL.AssignmentSubmissionEndDate),'') As SubmissionEndDate,
			OL.StartDateTime AS TeacherStartDateTime,
			OL.EndDateTime AS TeacherEndDateTime,
			ISNULL(OL.IsRecording,0) AS IsRecording,
			BM.Id AS BatchId,
			BM.Title AS BatchName,
			OM.Id AS OrgId,
			OM.Title AS OrganizationName
	  FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OL.TeacherEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			LEFT JOIN sEExam.tTestMaster TestM ON OL.ClassId=TestM.ClassId AND OL.TestId=TestM.Id
			LEFT JOIN sAcademic.tOnlineMeetingSettings OMS ON OMS.OnlineLearningId = OL.Id 
			INNER JOIN sSetup.tBatchMaster BM ON OL.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON BM.OrgId=OM.Id
	  WHERE 
			(OL.Id = @rId) AND (OL.BatchId = @rBatchId) AND OL.IsCompleted <> 721
	END
END
END
GO
PRINT N'Altering [sAcademic].[pOnlineLearningTeacherStudentDetailListGet]...';


GO
 
ALTER PROCEDURE [sAcademic].[pOnlineLearningTeacherStudentDetailListGet]
	 @rId BigInt ,
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rOrgGroupBatchId int
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	IF (@rSourceTypeId = 2001)
	BEGIN 

	 DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint,
	 @lClassName nvarchar(100)


	 SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId,
	 @lClassName=CM.Title,@lCLassId=CM.Id
     FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM
	 ON A.BatchId = BM.Id 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
 WHERE A.Id = @rSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId



SELECT 
			DM.Title AS LearningType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'')  AS Teacher,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndTime,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' ELSE 'Completed' END) AS Status,
			ISNULL(@lClassName,'') AS Class,
			OL.LecturePath AS LecturePath,
			OL.LearningTypeId AS LearningTypeId,
			OL.IsDisplayMeetingId AS IsDisplayMeetingId,
			OL.MeetingId AS MeetingId,
			OL.MeetingPassword AS MeetingPassword,
			OL.IsCompleted AS IsCompleted,
			ISNULL(OL.Description,'')AS Description,
			ISNULL(OL.Title,'') AS Title,
			ISNULL(OL.IsMeetingStarted,'') AS IsMeetingStarted,
			OL.IsSubmitAssignment AS IsSubmitAssignment,
			OL.IsTakeTest AS IsTakeTest,
			OL.TestId AS TestId,
			OL.IsTrackAttendance AS IsTrackAttendance,
			OL.IsTrackAssignmentView AS IsTrackAssignmentView,
			OL.IsMeetingCreated AS IsMeetingCreated,
			--OL.MeetingProviderId As MeetingProviderId
			OL.AssignmentRemark,
			OL.BatchId,
			ISNULL(CONVERT(NVARCHAR,OL.AssignmentSubmissionEndDate),'') As SubmissionEndDate,
			ISNULL(OL.IsRecording,0) As IsRecording,
			OL.IsAssignment,
			OL.IsReference,
			OL.IsResource,
			OL.IsTrackAttendance
          FROM 
				sAcademic.tOnlineLearning OL
				
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				--Left JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
				--INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=CM.OrgId
				--INNER JOIN [sStudent].[tAcademic] A ON A.ClassId = OL.ClassId
				LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId 
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
				--LEFT JOIN (SELECT Id,Title FROM sSetup.tClassMaster WHERE ((Id = @rClassId ) OR (@rClassId=0))) CM ON CM.Id=OL.CLassId
				INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
				WHERE (
				( 
				(OLS.SourceTypeId = 2021 AND OLS.SourceId =@lOrgId) 
				OR
				(OLS.SourceTypeId = 2017 AND OLS.SourceId =@lDepartmentId) OR
				(OLS.SourceTypeId = 2016 AND OLS.SourceId =@lClassId) OR
				(OLS.SourceTypeId = 2005 AND OLS.SourceId =@lDivisionId) OR
				(OLS.SourceTypeId = 2003 AND OLS.SourceId =@lStudentId) OR
				(OLS.SourceTypeId = 2001 AND OLS.SourceId =@lAcademicId)
				 ))
				) D
				ON D.OnlineLearningId= OL.Id

            
            WHERE
				 OL.Id = @rId
				 --AND A.Id = @rSourceId
				

				ORDER BY OL.IsCompleted,OL.StartDate,OL.EndDate
		END
		
		IF(@rSourceTypeId = 95)
		BEGIN
		SELECT 
			DM.Title AS LearningType,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'')  AS Teacher,
			SM.Title AS SubjectName,
			TM.Title AS Topic,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndTime,
			(CASE WHEN OL.IsCompleted=0 THEN 'Pending' ELSE 'Completed' END) AS Status,
			ISNULL(CM.Title,'') AS Class,
			OL.LecturePath AS LecturePath,
			OL.LearningTypeId AS LearningTypeId,
			OL.IsDisplayMeetingId AS IsDisplayMeetingId,
			OL.MeetingId AS MeetingId,
			OL.MeetingPassword AS MeetingPassword,
			OL.IsCompleted AS IsCompleted,
			ISNULL(OL.Title,'') AS Title,
			ISNULL(OL.Description,'')AS Description,
			ISNULL(OL.IsMeetingStarted,'') AS IsMeetingStarted,
			CM.Id AS ClassId,
			OL.IsSubmitAssignment AS IsSubmitAssignment,
			OL.IsTakeTest AS IsTakeTest,
			OL.TestId AS TestId,
			OL.IsTrackAttendance AS IsTrackAttendance,
			OL.IsTrackAssignmentView AS IsTrackAssignmentView,
			OL.IsMeetingCreated AS IsMeetingCreated,
			--OL.MeetingProviderId As MeetingProviderId
			OL.AssignmentRemark,
			OL.SubjectId,
			OL.CoTeacherEmployeeId1,
			OL.CoTeacherEmployeeId2,
			OL.BatchId,
			ISNULL(OL.IsRecording,0) As IsRecording,
			OL.IsAssignment,
			OL.IsReference,
			OL.IsResource,
			OL.TeacherEmployeeId
		FROM 
				sAcademic.tOnlineLearning OL
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
				LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
				LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
				INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3

		WHERE
			 OL.Id = @rId
			 AND (OL.TeacherEmployeeId = @rSourceId OR OL.CoTeacherEmployeeId1=@rSourceId OR OL.CoTeacherEmployeeId2=@rSourceId)
			 --AND OL.TeacherEmployeeId = @rSourceId
			 
			
			ORDER BY OL.CreatedDateTime
			
			END
		
END
GO
PRINT N'Altering [sAccounting].[pVoucherListGet]...';


GO
 
ALTER PROCEDURE [sAccounting].[pVoucherListGet]

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

BEGIN 

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


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

BEGIN 
	
	IF(@rIsGivenAdmissionForm=1)
		SET @rIsGivenAdmissionForm = 1
  	IF(@rIsGivenAdmissionForm=2)
		SET @rIsGivenAdmissionForm =0
	 
	 
	 SET @rToDate = DATEADD(d,1,@rToDate)
	 --IF @rIsSearch = 1
		BEGIN
			SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName= sCommon.fSearchStringGet(@rLastName)
			SET @rHandledBy= sCommon.fSearchStringGet(@rHandledBy)
			--SET @rContactNo= sCommon.fSearchStringGet(@rContactNo)
		END
	
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rAdmissionInquiryIdText AS AdmissionInquiryIdText,
			 AI.Id
			,AI.ForBatchId
			,AI.ForClassId
			,AI.StatusId
			,ISNULL(SM.Id,0) AS InquiryStatusMasterId
			,ISNULL(AI.GenderId,0) AS GenderId
			,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
			,ISNULL(IMM.Title,'') AS InquiryMode
			,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		    ,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		    ,AI.OrgId
		    ,ISNULL(AI.Number,0) AS InquiryNumber
		    ,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		    ,OM.DisplayTitle AS OrgName
		    ,BM.Title AS ForBatch
			,ISNULL(CM.Title,'') AS ClassName	
			,AI.FirstName
			,AI.MiddleName
			,AI.LastName
			,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
			,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
			,ISNULL(AI.DateOfBirth,'') As DateOfBirth
			,ISNULL(GM.Title,'') As Gender			
			,AI.ContactNo
			,AI.ContactEmail			
			,AI.StreetOne
			,AI.StreetTwo
			,AI.StreetThree
			,AI.Country
			,AI.State
			,AI.City
			,AI.ZipCode
			,ISNULL(AI.Remark,'') AS Remark						
		    ,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
			,ISNULL(AI.MeritMarks,0) AS MeritMarks
			,ISNULL(AI.MeritGrade,'') AS MeritGrade
			,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
			,SM.Title as StatusName	
			--,cast(replace(FollowupDate,'/','-') as date) As FollowupDate
			,ISNULL(AI.FollowupDate,'') As FollowupDate
			,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
			,ISNULL(IRM.Title ,'') AS InquiryReference	
			,ISNULL(SCM.Title,'') AS AdmissionCategory		
			,ISNULL(AI.HandledBy,'') AS HandledBy
			,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
			,ISNULL(AI.StudentId,0) AS StudentId,
			ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
			ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
			ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
			CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
			--ISNULL(AI.IsGivenAdmissionForm,0) AS IsGivenAdmissionForm,
			ISNULL(SM.HighlightColor,'') AS HighlightColor,
			ISNULL(SA.PreviousStandard,'') As PreviousStandard,
			AI.AlternateContactNo,
			AI.AlternateContactEmail
			,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
			ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate
  FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
           --INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AI.StatusId AND StatusTypeId=104
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
			LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  --AND ((AI.StatusId=@rStatusId) OR (@rStatusId=0))
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (@rNumber=0))
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
	  
	  AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=0)OR (@rIsGivenAdmissionForm=-1))

	  AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN ISNULL(AI.IsTransportRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	  
	  AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN ISNULL(AI.IsHostelRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	 --AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=-1))
      --AND (AI.IsGivenAdmissionForm = CASE @rIsGivenAdmissionForm WHEN 0 THEN ISNULL(AI.IsGivenAdmissionForm,0) WHEN 2 THEN 1 WHEN 1 THEN 0 END)
	 AND ((AI.ContactNo = @rContactNo) OR (@rContactNo=''))
	 AND ((AI.HandledBy like @rHandledBy) OR (@rHandledBy=''))
	  --AND ((AI.IsTransportRequired=@rIsTransportRequired) OR (@rIsTransportRequired=0))	   
	    --AND ((AI.IsHostelRequired =@rIsHostelRequired) OR (@rIsHostelRequired=0))
	  Order by Case @rOrderBy When 1 then AI.MeritMarks END desc ,
			    Case @rOrderBy when 0 then AI.Number Else 
			    AI.Number END desc  
			    
END
GO
PRINT N'Altering [sAlert].[pAbsentStudentContinueGet]...';


GO

ALTER PROCEDURE [sAlert].[pAbsentStudentContinueGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 @rSubjectId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rIsPresent bit,
	 	 @rMailSubject nvarchar(500)='',
		 @rDays int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

CREATE TABLE #tmpData
(
AcademicId bigint,
Code nvarchar(20),
Name nvarchar(300),
MobileNo nvarchar(50),
EmailId nvarchar(50),
StudentContactNo nvarchar(50),
StudentEmail nvarchar(50),
FatherContactNo nvarchar(50),
FatherMail nvarchar(50),
MotherContactNo nvarchar(50),
MotherMail nvarchar(50),
MsgText nvarchar(max),
Subject nvarchar(max),
SourceId bigint,
SourceTypeId int,
OrgId int,
OrgGroupId int,
ReceiverSourceId bigint,
ReceiverSourceTypeId int,
Class nvarchar(100),
Division nvarchar(100),
AbsentDates date,
AbsentReason nvarchar(100),
PresentDates date,
WhatsAppContactNo nvarchar(20),
ConsecDates date
)

INSERT INTO #tmpData
Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SC.StudentEmail,'') AS StudentEmail,
			ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SC.FatherMail,'') AS FatherMail,
			ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SC.MotherMail,'') AS MotherMail,
			--CASE WHEN 0=0 THEN
			--replace (replace (
			--replace(replace(replace(@rTemplate,'[Name]',SC.Name),
			--'[Class]',SC.ClassName),
			--'[Division]',SC.DivisionName),
			--'[AbsentDates]',SR.AttendanceDate),
			--'[AbsentReason]',ISNULL(AR.Title,''))
			--ELSE
			--replace (
			--replace(replace(replace(@rTemplate,'[Name]',SC.Name),
			--'[Class]',SC.ClassName),
			--'[Division]',SC.DivisionName),
			--'[PresentDates]',SR.AttendanceDate)
			--END
			-- AS MsgText,
			'' AS MsgText,
			@rMailSubject AS Subject,
			SC.AcademicId AS SourceId,
			2001 AS SourceTypeId,
			SC.OrgId,
			SC.OrgGroupId,
			SC.AcademicId AS ReceiverSourceId,
			2001 AS ReceiverSourceTypeId,
			SC.ClassName AS Class,
			SC.DivisionName AS Division,
			SR.AttendanceDate AS AbsentDates,
			ISNULL(AR.Title,'') AS AbsentReason,
			SR.AttendanceDate AS PresentDates,
			SC.WhatsAppContactNo,
			 (
            select min(b.AttendanceDate) from sAttendance.tStudentRegister b where SR.AcademicId = b.AcademicId 
            and b.AttendanceDate >= SR.AttendanceDate
            and not exists ( 
                select 1 from sAttendance.tStudentRegister c where c.AcademicId = b.AcademicId and dateadd( dd, 1, b.AttendanceDate) = c.AttendanceDate  
            )
            ) ConsecDates

	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id
			
	WHERE
			((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
			AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND (SR.IsPresent = @rIsPresent)
		AND	SC.AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tStudentLeaveRequest WHERE LeaveFromDate = @rFromDate AND LeaveToDate=@rToDate)
		AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
   ORDER BY SR.AcademicId,SR.AttendanceDate asc
   --Select * from #tmpData ORDER BY AcademicId

--Select * from #tmpData

CREATE TABLE #tmp
(
AcademicId bigint ,
ConsecDates date ,
AbsentDays nvarchar(max)
)
INSERT INTO #tmp
SELECT AcademicId,ConsecDates,
isnull(STUFF((SELECT ',' + CONVERT(nvarchar,DATEPART(day,d.AbsentDates)) from #tmpData d  
WHERE d.AcademicId=a.AcademicId AND d.ConsecDates = a.ConsecDates FOR XML PATH('')), 1, 1, ''),'')
FROM #tmpData a

CREATE TABLE #Finaltmp
(
AcademicId bigint ,
ConsecDates date ,
AbsentDays nvarchar(max)
)
INSERT INTO #Finaltmp
Select * from #tmp GROUP BY AcademicId,ConsecDates,AbsentDays having COUNT(ConsecDates) >= @rDays
ORDER BY AcademicId,ConsecDates asc



ALTER TABLE #tmpData
DROP COLUMN AbsentDates,
 AbsentReason,
PresentDates;

--Select * from #Finaltmp
--Select * from #tmpData
Select Distinct
			tmp.AcademicId,
			tmp.Code,
			tmp.Name,
			tmp.MobileNo,	
			tmp.EmailId,
			tmp.StudentContactNo,
			tmp.StudentEmail,
			tmp.FatherContactNo,
			tmp.FatherMail,
			tmp.MotherContactNo,
			tmp.MotherMail,
			CASE WHEN 0=0 THEN
			
			replace(replace(replace(replace(@rTemplate,'[Name]',tmp.Name),
			'[Class]',tmp.Class),
			'[Division]',tmp.Division),
			'[AbsentDates]',isnull(STUFF((SELECT ',' + f.AbsentDays from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),''))
			--'[AbsentDates]',SR.AttendanceDate),
			--'[AbsentReason]',ISNULL(AR.Title,''))
			ELSE
			replace (replace(
			replace(replace(@rTemplate,'[Name]',tmp.Name),
			'[Class]',tmp.Class),
			'[Division]',tmp.Division),
			'[AbsentDates]',isnull(STUFF((SELECT ',' + f.AbsentDays from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),''))
			--'[PresentDates]',SR.AttendanceDate)
			END
			 AS MsgText,
			tmp.Subject,
			tmp.SourceId,
			tmp.SourceTypeId,
			tmp.OrgId,
			tmp.OrgGroupId,
			tmp.ReceiverSourceId,
			tmp.ReceiverSourceTypeId,
			tmp.Class,
			tmp.Division,
			--tmp.AbsentDates,
			--tmp.AbsentReason,
			--tmp.PresentDates,
			tmp.WhatsAppContactNo,
			--finaltmp.ConsecDates,
			--finaltmp.AbsentDays
			isnull(STUFF((SELECT ',' + f.AbsentDays from #Finaltmp f  
			WHERE f.AcademicId=tmp.AcademicId FOR XML PATH('')), 1, 1, ''),'')AS AbsentDays

	From 
		#tmpData tmp
	INNER JOIN #Finaltmp finaltmp ON tmp.AcademicId = finaltmp.AcademicId AND tmp.ConsecDates =finaltmp.ConsecDates
	
DROP TABLE #tmpData
DROP TABLE #tmp
DROP TABLE #Finaltmp
END
GO
PRINT N'Altering [sAlert].[pEmployeeBirthdayWishGet]...';


GO
 
 
ALTER PROCEDURE [sAlert].[pEmployeeBirthdayWishGet]
	 	 
	 	 @rDepartmentId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rDateOfBirth date
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			EC.EmployeeId AS AcademicId,
			EC.Code,
			EC.EmployeeName AS Name,
			EC.MobileNumber AS MobileNo,	
			EC.CompanyEmail AS EmailId,
			replace(replace(@rTemplate,'[Name]',EC.EmployeeName),'[SchoolName]',OM.Title)
			 AS Template,
			 OM.Title AS SchoolName,
			 EC.WhatsAppContactNo
		
		
	From 
		sHrm.vEmployeeCommunication EC
		INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
	WHERE
			((EC.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (EC.OrgId=@rOrgId)
		AND (DAY(EC.DateOfBirth) = DAY(@rDateOfBirth))
		AND (MONTH(EC.DateOfBirth) = MONTH(@rDateOfBirth))
		AND (EC.StatusId=7)
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryGet]...';


GO
ALTER PROCEDURE [sAssessment].[pMarkEntryGet]
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rExamDetailId int,
	 @rBatchId int,
	 @rIsWithPhoto bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

if(@rIsWithPhoto=1)
BEGIN
SELECT 
	
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,ISNULL(RD.Id,0) AS ResultDetailId
	,ISNULL(R.Id,0) AS ResultId  
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,CASE WHEN ISNULL(EM.IsMarksInDecimal,0) = 1 THEN ISNULL(RD.Obtain,0) ELSE ROUND(ISNULL(RD.Obtain,0),0) END  AS Obtain
	--,ISNULL(RD.Obtain,0) AS Obtain
	,ISNULL(RD.IsPresent,'true') as IsPresent
	,ED.Id AS ExamDetailId
	,ED.Maximum AS MaximumMark
	,ISNULL(EM.IsMarksInDecimal,0) AS IsMarkInDecimal
	,ISNULL(EM.IsNegativeMarks,0) AS IsNegativeMarks,
	ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
	ISNULL(ED.ExamTopic,'') as ExamTopic,
	0 AS PresentTotal,
	0 AS TotalCount
from sStudent.vStudentAcademic SA 
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
	LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
	LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicId and o.ClassSubjectId=V.ClassSubjectId

Where  (DM.Id=@rDivisionId OR @rDivisionId = 0)
	   AND (EM.ClassId = @rClassId OR @rClassId = 0)  
	   AND (ED.Id=@rExamDetailId OR @rExamDetailId = 0 )
	   AND (EM.Id=@rExamId OR @rExamId = 0)
	   AND SA.StatusId=1 AND SA.BatchId=@rBatchId
	   AND ((V.IsOptional = 1 AND    isnull(o.AcademicId,0) <> 0) OR (V.IsOptional = 0))	  
	Order By SA.RollNo
END
ELse
BEGIN
	SELECT 
	
	 EM.ClassId
	,DM.Id AS DivisionId
	,EM.Id AS ExamId
	,ED.ClassSubjectId AS ClassSubjectId
	,ISNULL(RD.Id,0) AS ResultDetailId
	,ISNULL(R.Id,0) AS ResultId  
	,SA.AcademicId
	,SA.Name AS StudentName
	,SA.Code 
	,SA.RollNo
	,CASE WHEN ISNULL(EM.IsMarksInDecimal,0) = 1 THEN ISNULL(RD.Obtain,0) ELSE ROUND(ISNULL(RD.Obtain,0),0) END  AS Obtain
	--,ISNULL(RD.Obtain,0) AS Obtain
	,ISNULL(RD.IsPresent,'true') as IsPresent
	,ED.Id AS ExamDetailId
	,ED.Maximum AS MaximumMark
	,ISNULL(EM.IsMarksInDecimal,0) AS IsMarkInDecimal
	,ISNULL(EM.IsNegativeMarks,0) AS IsNegativeMarks,
	CONVERT(VARBINARY(MAX), 0) AS  StudentPhoto,
	ISNULL(ED.ExamTopic,'') as ExamTopic,
	0 AS PresentTotal,
	0 AS TotalCount
from sStudent.vStudentAcademic SA 
	--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId
	INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
	INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  
	LEFT JOIN sAssessment.tResult R ON R.ExamId=EM.Id AND R.AcademicId=SA.AcademicId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id  
	LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
	LEFT JOIN sAssessment.tResultDetail RD ON R.Id=RD.ResultId AND RD.ExamDetailId=ED.Id
	LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicId and o.ClassSubjectId=V.ClassSubjectId

Where  (DM.Id=@rDivisionId OR @rDivisionId = 0)
	   AND (EM.ClassId = @rClassId OR @rClassId = 0)  
	   AND (ED.Id=@rExamDetailId OR @rExamDetailId = 0 )
	   AND (EM.Id=@rExamId OR @rExamId = 0)
	   AND SA.StatusId=1 AND SA.BatchId=@rBatchId
	   AND ((V.IsOptional = 1 AND    isnull(o.AcademicId,0) <> 0) OR (V.IsOptional = 0))	  
Order By SA.RollNo
END

END
GO
PRINT N'Altering [sAssessment].[pRptSubGradeSetDetail]...';


GO
ALTER PROCEDURE [sAssessment].[pRptSubGradeSetDetail]
	  @rExamId int,
	  @rDivisionId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 		
DECLARE @lGradeSetId int 
SELECT @lGradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId

CREATE TABLE #tmp
(
id int identity,
GradeCode nvarchar(50),
StudentCount int
)
INSERT INTO #tmp
SELECT 
		
		GSD.GradeCode AS GradeCode,
		(Select COUNT(distinct A.Id) from sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId AND R.ResultGrade = GSD.GradeCode
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			LEFT JOIN sAssessment.tGradeSetDetail GSD1 ON EM.GradeSetId=GSD1.GradeSetId AND ED.GradeSetId = GSD1.GradeSetId
			Where 
				EM.Id = @rExamId AND ED.GradeSetId = @lGradeSetId AND A.DivisionId = @rDivisionId AND GSD.GradeCode = GSD1.GradeCode
				AND StuM.StatusId =1
			)AS StudentCount
	FROM 
	
		sAssessment.tExamMaster EM
		INNER JOIN sAssessment.tGradeSetDetail GSD ON EM.GradeSetId=GSD.GradeSetId
		
	Where 
		EM.Id = @rExamId 
		ORDER BY GSD.Id

		Select id,GradeCode,StudentCount,
		(Select COUNT(id) from #tmp) AS GradeCount
		from #tmp
		--Select isnull(STUFF((SELECT ',' + GradeCode FROM #tmp
		--				   FOR XML PATH('')), 1, 1, ''),'')AS Grade
		--Select isnull(STUFF((SELECT ',' + CONVERT(varchar,StudentCount) FROM #tmp
		--FOR XML PATH('')), 1, 1, ''),'')AS Grade

		DROP TABLE #tmp
		
		--Select 0 as id,'' AS GradeCode,0 as StudentCount,0 AS GradeCount
END
GO
PRINT N'Altering [sAssessment].[pTypeWiseAssessmentConsolidatedDashboardGet]...';


GO

ALTER PROCEDURE [sAssessment].[pTypeWiseAssessmentConsolidatedDashboardGet]
	 
	@rOrgId int=0,
	@rTypeId int=0,
	@rCommonOrgGroupBatchId int=0,
	@rExamSubGroupId nvarchar(max)='',
	@rRangeId int=0,
	@rClassId int =0,
	@rDivisionId int =0,
	@rSubjectId int=0,
	@rEmployeeId bigint=0,
	@rIsCount bit=1
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
/******
	TypeId = 1 Class wise Count
	TypeId = 2 DiVision Wise Count
	TypeId = 3 Subject Wise Count
	TypeId = 4 Teacher Wise Count
	
	TypeId = 11 Class wise Detail's
	TypeId = 21 DiVision Wise Detail's
	TypeId = 31 Subject Wise Detail's
	TypeId = 41 Teacher Wise Detail's
******/
   
	CREATE TABLE #TblFinalRecord
			(
				Id int identity,
				FromPercentage DECIMAL(10,2),
				ToPercentage DECIMAL(10,2)
			) 
				--INSERT INTO #TblFinalRecord(FromPercentage,ToPercentage) VALUES (90.49,100),(80.49,90.49),(70.49,80.49),(60.49,70.49),(50.49,60.49),(40.49,50.49),(-1,40.49)	
				INSERT INTO #TblFinalRecord(FromPercentage,ToPercentage) VALUES (90.49,100),(75.49,90.49),(60.49,75.49),(45.49,60.49),(0,45.49)	
			DECLARE @lFromPercentage DECIMAL(10,2),@lToPercentage DECIMAL(10,2)
			 
	IF(@rTypeId=1)--TypeId = 1  is For Class Wise Count
		BEGIN
		  IF(@rIsCount = 1)
		  BEGIN
			SELECT CM.Id AS ClassId,CM.Title AS ClassName,
			COUNT(R90.R90) AS '> 90',
			COUNT(R80.R80) AS '> 75',
			COUNT(R70.R70) AS '> 60',
			COUNT(R60.R60) AS '> 45',
			--COUNT(R50.R50) AS '51-60',
			--COUNT(R40.R40) AS '41-50',
			COUNT(R30.R30) AS '< 45'
			FROM  sSetup.tClassMaster CM
					INNER JOIN sAssessment.tExamMaster EM ON CM.Id = EM.ClassId
					INNER JOIN sAssessment.tResult R ON  EM.Id = R.ExamId
					INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
					--LEFT JOIN sSetup.tClassMaster CM ON CM.Id = A.classId AND 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
				(SELECT R1.Id AS R90  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100			
					  )R90 ON R90.R90 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R80  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 75.49 AND R1.Percentage <= 90.49			
					  )R80 ON R80.R80 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R70  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 60.49 AND R1.Percentage <= 75.49			
					  )R70 ON R70.R70 = R.Id	
				   LEFT JOIN 
					  (SELECT R1.Id AS R60  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 45.49 AND R1.Percentage <= 60.49			
					  )R60 ON R60.R60 = R.Id
				  LEFT JOIN
					  (SELECT R1.Id AS R30  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 0 AND R1.Percentage <=45.49
					  )R30 ON R30.R30 = R.Id
	--				  (SELECT R1.Id AS R90  FROM sAssessment.tResult R1
	--WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100			
	--				  )R90 ON R90.R90 = R.Id
	--			 LEFT JOIN 
	--				  (SELECT R1.Id AS R80  FROM sAssessment.tResult R1
	--WHERE R1.Percentage > 80.49 AND R1.Percentage <= 90.49			
	--				  )R80 ON R80.R80 = R.Id
	--			 LEFT JOIN 
	--				  (SELECT R1.Id AS R70  FROM sAssessment.tResult R1
	--WHERE R1.Percentage > 70.49 AND R1.Percentage <= 80.49			
	--				  )R70 ON R70.R70 = R.Id	
	--			   LEFT JOIN 
	--				  (SELECT R1.Id AS R60  FROM sAssessment.tResult R1
	--WHERE R1.Percentage > 60.49 AND R1.Percentage <= 70.49			
	--				  )R60 ON R60.R60 = R.Id
	--			  LEFT JOIN 
	--				  (SELECT R1.Id AS R50  FROM sAssessment.tResult R1
	--WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49		
	--				  )R50 ON R50.R50 = R.Id
	--			 LEFT JOIN 
	--				  (SELECT R1.Id AS R40  FROM sAssessment.tResult R1
	--WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49
	--				  )R40 ON R40.R40 = R.Id
	--			 LEFT JOIN 
	--				  (SELECT R1.Id AS R30  FROM sAssessment.tResult R1
	--WHERE R1.Percentage <= 40.49
	--				  )R30 ON R30.R30 = R.Id
				   
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null) 
				--AND CM.Id = 110100003
				AND CM.OrgId = @rOrgId
				GROUP BY CM.Id,CM.Title
		  END
		  ELSE 
		  BEGIN
			SELECT CM.Id AS ClassId,CM.Title AS ClassName,
				   (COUNT(R90.R90) * 100 / COUNT(A.Id)) AS '> 90 Per',
				   (COUNT(R80.R80) * 100 / COUNT(A.Id)) AS '> 75 Per',
				   (COUNT(R70.R70) * 100 / COUNT(A.Id)) AS '> 60 Per',
				   (COUNT(R60.R60) * 100 / COUNT(A.Id)) AS '> 45 Per',
				   (COUNT(R30.R30) * 100 / COUNT(A.Id)) AS '< 45 Per'
			FROM  sSetup.tClassMaster CM
					INNER JOIN sAssessment.tExamMaster EM ON CM.Id = EM.ClassId
					INNER JOIN sAssessment.tResult R ON  EM.Id = R.ExamId
					INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
					--LEFT JOIN sSetup.tClassMaster CM ON CM.Id = A.classId AND 
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
				(SELECT R1.Id AS R90  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100			
					  )R90 ON R90.R90 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R80  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 75.49 AND R1.Percentage <= 90.49			
					  )R80 ON R80.R80 = R.Id
				 LEFT JOIN 
					  (SELECT R1.Id AS R70  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 60.49 AND R1.Percentage <= 75.49			
					  )R70 ON R70.R70 = R.Id	
				   LEFT JOIN 
					  (SELECT R1.Id AS R60  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 45.49 AND R1.Percentage <= 60.49			
					  )R60 ON R60.R60 = R.Id
				  LEFT JOIN
					  (SELECT R1.Id AS R30  FROM sAssessment.tResult R1
	WHERE R1.Percentage > 0 AND R1.Percentage <=45.49
	--R1.Percentage <= 0
					  )R30 ON R30.R30 = R.Id
				   
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null) 
				--AND CM.Id = 110100003
				AND CM.OrgId = @rOrgId
				GROUP BY CM.Id,CM.Title
		  END
		END
	ELSE IF (@rTypeId=2)--TypeId = 2 is For Division Wise Count
		BEGIN
		  IF(@rIsCount = 1)
		  BEGIN
			SELECT DM.Id AS DivisionId,DM.Code AS ClassDivisionName,
				--COUNT(R90.R90) AS '91-100',
				--COUNT(R80.R80) AS '81-90',
				--COUNT(R70.R70) AS '71-80',
				--COUNT(R60.R60) AS '61-70',
				--COUNT(R50.R50) AS '51-60',
				--COUNT(R40.R40) AS '41-50',
				--COUNT(R30.R30) AS 'Below-40'
				COUNT(R90.R90) AS '> 90',
				COUNT(R80.R80) AS '> 75',
				COUNT(R70.R70) AS '> 60',
				COUNT(R60.R60) AS '> 45',
				--COUNT(R50.R50) AS '51-60',
				--COUNT(R40.R40) AS '41-50',
				COUNT(R30.R30) AS '< 45'
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
					  (SELECT R1.Id AS R90,A1.DivisionId AS DivisionId   FROM sAssessment.tResult R1
					   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100
		        			  )R90 ON R90.R90 = R.Id AND DM.Id = R90.DivisionId	
		        		LEFT JOIN 
		        			  (SELECT R1.Id AS R80,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
		        			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 75.49 AND R1.Percentage <= 90.49
		        			  )R80 ON R80.R80 = R.Id AND DM.Id = R80.DivisionId	
		        		LEFT JOIN 
		        			  (SELECT R1.Id AS R70,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
		        			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 60.49 AND R1.Percentage <= 75.49
		        			  )R70 ON R70.R70 = R.Id AND DM.Id = R70.DivisionId		
		        		LEFT JOIN 
		        			  (SELECT R1.Id AS R60,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
		        			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 45.49 AND R1.Percentage <= 60.49
					  )R60 ON R60.R60 = R.Id AND DM.Id = R60.DivisionId	
				--	    LEFT JOIN 
				--			  (SELECT R1.Id AS R50,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				--			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49
				--			  )R50 ON R50.R50 = R.Id AND DM.Id = R50.DivisionId	
				--		LEFT JOIN 
				--			  (SELECT R1.Id AS R40,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				--			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49
				--			  )R40 ON R40.R40 = R.Id AND DM.Id = R40.DivisionId	
			LEFT JOIN 
				  (SELECT R1.Id AS R30,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	        WHERE R1.Percentage > 0 AND R1.Percentage <=45.49
			--R1.Percentage <= 0
				  )R30 ON R30.R30 = R.Id AND DM.Id = R30.DivisionId	
			   
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
				AND DM.OrgId = @rOrgId AND DM.IsObsolete = 0
				GROUP BY DM.Id,DM.Code,DM.OrderIndex
				ORDER BY DM.OrderIndex
		  END
		  ELSE
		  BEGIN
				SELECT DM.Id AS DivisionId,DM.Code AS ClassDivisionName,
				(COUNT(R90.R90) * 100 / COUNT(A.Id)) AS '> 90 Per',
				(COUNT(R80.R80) * 100 / COUNT(A.Id)) AS '> 75 Per',
				(COUNT(R70.R70) * 100 / COUNT(A.Id)) AS '> 60 Per',
				(COUNT(R60.R60) * 100 / COUNT(A.Id)) AS '> 45 Per',
				(COUNT(R30.R30) * 100 / COUNT(A.Id)) AS '< 45 Per'
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
					  (SELECT R1.Id AS R90,A1.DivisionId AS DivisionId   FROM sAssessment.tResult R1
					   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100
		        			  )R90 ON R90.R90 = R.Id AND DM.Id = R90.DivisionId	
		        		LEFT JOIN 
		        			  (SELECT R1.Id AS R80,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
		        			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 75.49 AND R1.Percentage <= 90.49
		        			  )R80 ON R80.R80 = R.Id AND DM.Id = R80.DivisionId	
		        		LEFT JOIN 
		        			  (SELECT R1.Id AS R70,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
		        			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 60.49 AND R1.Percentage <= 75.49
		        			  )R70 ON R70.R70 = R.Id AND DM.Id = R70.DivisionId		
		        		LEFT JOIN 
		        			  (SELECT R1.Id AS R60,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
		        			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
		        WHERE R1.Percentage > 45.49 AND R1.Percentage <= 60.49
					  )R60 ON R60.R60 = R.Id AND DM.Id = R60.DivisionId	
				--	    LEFT JOIN 
				--			  (SELECT R1.Id AS R50,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				--			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49
				--			  )R50 ON R50.R50 = R.Id AND DM.Id = R50.DivisionId	
				--		LEFT JOIN 
				--			  (SELECT R1.Id AS R40,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				--			   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49
				--			  )R40 ON R40.R40 = R.Id AND DM.Id = R40.DivisionId	
			LEFT JOIN 
				  (SELECT R1.Id AS R30,A1.DivisionId AS DivisionId  FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	        WHERE R1.Percentage > 0 AND R1.Percentage <=45.49
			--R1.Percentage <= 0
				  )R30 ON R30.R30 = R.Id AND DM.Id = R30.DivisionId	
			   
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
					AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
					AND DM.OrgId = @rOrgId AND DM.IsObsolete = 0
				GROUP BY DM.Id,DM.Code,DM.OrderIndex
				ORDER BY DM.OrderIndex
		  END
		END
	ELSE IF (@rTypeId=3)--TypeId = 3 is For Subject Wise Count
		BEGIN
		  IF(@rIsCount = 1)
			BEGIN
			 SELECT SM.Id AS SubjectId,SM.Title AS SubjectName,
				--COUNT(R90.R90) AS '91-100',
				--COUNT(R80.R80) AS '81-90',
				--COUNT(R70.R70) AS '71-80',
				--COUNT(R60.R60) AS '61-70',
				--COUNT(R50.R50) AS '51-60',
				--COUNT(R40.R40) AS '41-50',
				--COUNT(R30.R30) AS 'Below-40' 
				COUNT(R90.R90) AS '> 90',
				COUNT(R80.R80) AS '> 75',
				COUNT(R70.R70) AS '> 60',
				COUNT(R60.R60) AS '> 45',
				--COUNT(R50.R50) AS '51-60',
				--COUNT(R40.R40) AS '41-50',
				COUNT(R30.R30) AS '< 45'
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId AND CS.ClassId = A.classId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
				  (SELECT R.Id As R90,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
					INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
					INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
					INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
					LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
			   WHERE  RD.Obtain > 90.49 AND RD.Obtain <=100
	       			  )R90 ON R90.R90 = R.Id AND SM.Id = R90.SubjectId	AND DM.Id = R90.DivisionId
	       		  LEFT JOIN 
	       			  (SELECT R.Id As R80,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
	       				INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
	       				INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
	       				INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	       				INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
	       				LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
			   WHERE  RD.Obtain > 75.49 AND RD.Obtain <= 90.49 
	       			  )R80 ON R80.R80 = R.Id AND SM.Id = R80.SubjectId AND DM.Id = R80.DivisionId	
	       		 LEFT JOIN 
	       			  (SELECT R.Id As R70,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
	       				INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
	       				INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
	       				INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	       				INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
	       				LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
			   WHERE  RD.Obtain > 60.49 AND RD.Obtain <= 75.49 
				   ) R70 ON R70.R70 = R.Id AND SM.Id = R70.SubjectId	AND DM.Id = R70.DivisionId	
				 LEFT JOIN 
				  (SELECT R.Id As R60,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
					INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
					INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
					INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
					LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
			   WHERE  RD.Obtain > 45.49 AND RD.Obtain <= 60.49 
				   )R60 ON R60.R60 = R.Id AND SM.Id = R60.SubjectId	AND DM.Id = R60.DivisionId	
				--	  LEFT JOIN 
				--		  (SELECT R.Id As R50,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
				--			INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
				--			INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
				--			INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
				--			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
				--			LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
				--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				--WHERE  RD.Obtain > 50.49 AND RD.Obtain <= 60.49 
				--		   )R50 ON R50.R50 = R.Id AND SM.Id = R50.SubjectId	AND DM.Id = R50.DivisionId	
				--	 LEFT JOIN 
				--		  (SELECT R.Id As R40,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
				--			INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
				--			INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
				--			INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
				--			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
				--			LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
				--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				--WHERE  RD.Obtain > 40.49 AND RD.Obtain <= 50.49 
				--		   )R40 ON R40.R40 = R.Id AND SM.Id = R40.SubjectId	AND DM.Id = R40.DivisionId		
			 LEFT JOIN 
				  (SELECT R.Id As R30,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
					INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
					INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
					INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
					LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				   WHERE RD.Obtain > 0 AND RD.Obtain <=45.49
				   --RD.Obtain <= 0
				 )R30 ON R30.R30 = R.Id AND SM.Id = R30.SubjectId AND DM.Id = R30.DivisionId		
		   
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
					--AND CM.Id = 110100003
				AND SM.OrgId = @rOrgId AND DM.IsObsolete = 0 
				AND (DM.Id = @rDivisionId OR DM.ClassId = @rClassId)
			GROUP BY SM.Id,SM.title,SM.OrderIndex 
			ORDER BY SM.OrderIndex 
			END
			ELSE
			BEGIN
				SELECT SM.Id AS SubjectId,SM.Title AS SubjectName,
					(COUNT(R90.R90) * 100 / COUNT(A.Id)) AS '> 90 Per',
					(COUNT(R80.R80) * 100 / COUNT(A.Id)) AS '> 75 Per',
					(COUNT(R70.R70) * 100 / COUNT(A.Id)) AS '> 60 Per',
					(COUNT(R60.R60) * 100 / COUNT(A.Id)) AS '> 45 Per',
					(COUNT(R30.R30) * 100 / COUNT(A.Id)) AS '< 45 Per'
				FROM  sAssessment.tResult R 
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
					INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId AND CS.ClassId = A.classId
					INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
					LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN 
					  (SELECT R.Id As R90,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
						INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
						INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
						INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
						LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
						INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				   WHERE  RD.Obtain > 90.49 AND RD.Obtain <=100
	       				  )R90 ON R90.R90 = R.Id AND SM.Id = R90.SubjectId	AND DM.Id = R90.DivisionId
	       			  LEFT JOIN 
	       				  (SELECT R.Id As R80,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
	       					INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
	       					INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
	       					INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	       					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
	       					LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
	       					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				   WHERE  RD.Obtain > 75.49 AND RD.Obtain <= 90.49 
	       				  )R80 ON R80.R80 = R.Id AND SM.Id = R80.SubjectId AND DM.Id = R80.DivisionId	
	       			 LEFT JOIN 
	       				  (SELECT R.Id As R70,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
	       					INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
	       					INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
	       					INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	       					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
	       					LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
	       					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				   WHERE  RD.Obtain > 60.49 AND RD.Obtain <= 75.49 
					   ) R70 ON R70.R70 = R.Id AND SM.Id = R70.SubjectId	AND DM.Id = R70.DivisionId	
					 LEFT JOIN 
					  (SELECT R.Id As R60,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
						INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
						INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
						INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
						LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
						INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				   WHERE  RD.Obtain > 45.49 AND RD.Obtain <= 60.49 
					   )R60 ON R60.R60 = R.Id AND SM.Id = R60.SubjectId	AND DM.Id = R60.DivisionId	
					--	  LEFT JOIN 
					--		  (SELECT R.Id As R50,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
					--			INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
					--			INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
					--			INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
					--			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
					--			LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
					--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
					--WHERE  RD.Obtain > 50.49 AND RD.Obtain <= 60.49 
					--		   )R50 ON R50.R50 = R.Id AND SM.Id = R50.SubjectId	AND DM.Id = R50.DivisionId	
					--	 LEFT JOIN 
					--		  (SELECT R.Id As R40,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
					--			INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
					--			INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
					--			INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
					--			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
					--			LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
					--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
					--WHERE  RD.Obtain > 40.49 AND RD.Obtain <= 50.49 
					--		   )R40 ON R40.R40 = R.Id AND SM.Id = R40.SubjectId	AND DM.Id = R40.DivisionId		
				 LEFT JOIN 
					  (SELECT R.Id As R30,SM1.Id As SubjectId,A1.DivisionId As DivisionId FROM sAssessment.tResultDetail RD 
						INNER Join sAssessment.tResult R ON  RD.ResultId = R.Id
						INNER JOIN sStudent.tAcademic A1 ON R.AcademicId = A1.Id
						INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
						LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
						INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
					   WHERE RD.Obtain > 0 AND RD.Obtain <=45.49
					   --RD.Obtain <= 0
					 )R30 ON R30.R30 = R.Id AND SM.Id = R30.SubjectId AND DM.Id = R30.DivisionId		
		   
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
					AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
						--AND CM.Id = 110100003
					AND SM.OrgId = @rOrgId AND DM.IsObsolete = 0 
					AND (DM.Id = @rDivisionId OR DM.ClassId = @rClassId)
				GROUP BY SM.Id,SM.title,SM.OrderIndex 
				ORDER BY SM.OrderIndex 
			END
		END
		
	ELSE IF (@rTypeId=4)--TypeId = 4 is For Teacher Wise Count
		BEGIN
		 IF(@rIsCount = 1)
		  BEGIN
			SELECT ISNULL(DM.Id,'') AS DivisionId,ISNULL(DM.Code,'') AS ClassDivisionName,ISNULL(SM.Id,'') AS SubjectId,ISNULL(SM.Title,'') AS SubjectName,
				--COUNT(R90.R90) AS '91-100',
				--COUNT(R80.R80) AS '81-90',
				--COUNT(R70.R70) AS '71-80',
				--COUNT(R60.R60) AS '61-70',
				--COUNT(R50.R50) AS '51-60',
				--COUNT(R40.R40) AS '41-50',
				--COUNT(R30.R30) AS 'Below-40',
				COUNT(R90.R90) AS '> 90',
				COUNT(R80.R80) AS '> 75',
				COUNT(R70.R70) AS '> 60',
				COUNT(R60.R60) AS '> 45',
				--COUNT(R50.R50) AS '51-60',
				--COUNT(R40.R40) AS '41-50',
				COUNT(R30.R30) AS '< 45',
				EMP.EmployeeName,EMP.EmployeeId
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId	
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id		
				INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId --AND CS.ClassId = A.classId
				LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
				LEFT JOIN sSetup.tDivisionMaster DM ON  DM.ClassId = EM.ClassId
				INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId AND TS.DivisionId=DM.ID AND TS.EmployeeId = @rEmployeeId
				--INNER JOIN  sHrm.tEmployeeMaster EM ON EM.ID = TS.EmployeeId
				INNER JOIN sSetup.tBatchMaster BM ON  BM.Id = EM.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN (
				SELECT Id AS EmployeeId,FirstName+' '+ LastName AS EmployeeName FROM sHrm.tEmployeeMaster WHERE ISNULL(IsOtherUser,0) = 0
				) EMP ON EMP.EmployeeId = TS.EmployeeId 
			
				LEFT JOIN 
				(SELECT R1.Id AS R90,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
					INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
					-- INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
					INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
			WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100
	       			)R90 ON R90.R90 = R.Id AND SM.Id = R90.SubjectId	AND DM.Id = R90.DivisionId
	       			LEFT JOIN 
	       			(SELECT R1.Id AS R80,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
	       				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	       				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
	       				INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	       WHERE R1.Percentage > 75.49 AND R1.Percentage <= 90.49 
	       			)R80 ON R80.R80 = R.Id AND SM.Id = R80.SubjectId AND DM.Id = R80.DivisionId	
	       			LEFT JOIN 
	       			(SELECT R1.Id AS R70,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
	       				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	       				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
	       				INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	       WHERE R1.Percentage > 60.49 AND R1.Percentage <= 75.49 
	       			)R70 ON R70.R70 = R.Id AND SM.Id = R70.SubjectId	AND DM.Id = R70.DivisionId	
	       			LEFT JOIN 
	       			(SELECT R1.Id AS R60,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
	       				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	       				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
	       				INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	       WHERE R1.Percentage > 45.49 AND R1.Percentage <= 60.49 
				)R60 ON R60.R60 = R.Id AND SM.Id = R60.SubjectId	AND DM.Id = R60.DivisionId	
				--		LEFT JOIN 
				--		(SELECT R1.Id AS R50,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				--			INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--			--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				--			INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				--WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49 
				--		)R50 ON R50.R50 = R.Id AND SM.Id = R50.SubjectId	AND DM.Id = R50.DivisionId	
				--		LEFT JOIN 
				--		(SELECT R1.Id AS R40,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				--			INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--			--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				--			INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				--WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49 
				--		)R40 ON R40.R40 = R.Id AND SM.Id = R40.SubjectId	AND DM.Id = R40.DivisionId		
				LEFT JOIN 
				(SELECT R1.Id AS R30,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
					INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
					--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
					INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	      WHERE R1.Percentage > 0 AND R1.Percentage <=45.49
		  --R1.Percentage <= 0
			    )R30 ON R30.R30 = R.Id AND SM.Id = R30.SubjectId AND DM.Id = R30.DivisionId		
			WHERE COGBM.Id = @rCommonOrgGroupBatchId
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
				AND SM.OrgId = @rOrgId AND DM.IsObsolete = 0
			GROUP BY SM.Id,SM.title,EMP.EmployeeName,EMP.EmployeeId,DM.Code,DM.Id,SM.OrderIndex 
			ORDER BY SM.OrderIndex 
		 END
		  ELSE
		   BEGIN
			SELECT ISNULL(DM.Id,'') AS DivisionId,ISNULL(DM.Code,'') AS ClassDivisionName,ISNULL(SM.Id,'') AS SubjectId,ISNULL(SM.Title,'') AS SubjectName,
				(COUNT(R90.R90) * 100 / COUNT(A.Id)) AS '> 90 Per',
				(COUNT(R80.R80) * 100 / COUNT(A.Id)) AS '> 75 Per',
				(COUNT(R70.R70) * 100 / COUNT(A.Id)) AS '> 60 Per',
				(COUNT(R60.R60) * 100 / COUNT(A.Id)) AS '> 45 Per',
				(COUNT(R30.R30) * 100 / COUNT(A.Id)) AS '< 45 Per',
				EMP.EmployeeName,EMP.EmployeeId
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId	
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id		
				INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId --AND CS.ClassId = A.classId
				LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
				LEFT JOIN sSetup.tDivisionMaster DM ON  DM.ClassId = EM.ClassId
				INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId AND TS.DivisionId=DM.ID AND TS.EmployeeId = @rEmployeeId
				--INNER JOIN  sHrm.tEmployeeMaster EM ON EM.ID = TS.EmployeeId
				INNER JOIN sSetup.tBatchMaster BM ON  BM.Id = EM.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN (
				SELECT Id AS EmployeeId,FirstName+' '+ LastName AS EmployeeName FROM sHrm.tEmployeeMaster WHERE ISNULL(IsOtherUser,0) = 0
				)EMP ON EMP.EmployeeId = TS.EmployeeId 
			
				LEFT JOIN 
				(SELECT R1.Id AS R90,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
					INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
					-- INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
					INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
			WHERE R1.Percentage > 90.49 AND R1.Percentage <= 100
	       			)R90 ON R90.R90 = R.Id AND SM.Id = R90.SubjectId	AND DM.Id = R90.DivisionId
	       			LEFT JOIN 
	       			(SELECT R1.Id AS R80,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
	       				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	       				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
	       				INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	       WHERE R1.Percentage > 75.49 AND R1.Percentage <= 90.49 
	       			)R80 ON R80.R80 = R.Id AND SM.Id = R80.SubjectId AND DM.Id = R80.DivisionId	
	       			LEFT JOIN 
	       			(SELECT R1.Id AS R70,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
	       				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	       				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
	       				INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	       WHERE R1.Percentage > 60.49 AND R1.Percentage <= 75.49 
	       			)R70 ON R70.R70 = R.Id AND SM.Id = R70.SubjectId	AND DM.Id = R70.DivisionId	
	       			LEFT JOIN 
	       			(SELECT R1.Id AS R60,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
	       				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	       				--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
	       				INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
	       				INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	       WHERE R1.Percentage > 45.49 AND R1.Percentage <= 60.49 
				)R60 ON R60.R60 = R.Id AND SM.Id = R60.SubjectId	AND DM.Id = R60.DivisionId	
				--		LEFT JOIN 
				--		(SELECT R1.Id AS R50,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				--			INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--			--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				--			INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				--WHERE R1.Percentage > 50.49 AND R1.Percentage <= 60.49 
				--		)R50 ON R50.R50 = R.Id AND SM.Id = R50.SubjectId	AND DM.Id = R50.DivisionId	
				--		LEFT JOIN 
				--		(SELECT R1.Id AS R40,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				--			INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				--			--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				--			INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
				--			INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
				--WHERE R1.Percentage > 40.49 AND R1.Percentage <= 50.49 
				--		)R40 ON R40.R40 = R.Id AND SM.Id = R40.SubjectId	AND DM.Id = R40.DivisionId		
				LEFT JOIN 
				(SELECT R1.Id AS R30,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
					INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
					--INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
					INNER JOIN  sSetup.tClassSubject CS1 ON CS1.ClassId = A1.classId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	      WHERE R1.Percentage > 0 AND R1.Percentage <=45.49
		  --R1.Percentage <= 0
			    )R30 ON R30.R30 = R.Id AND SM.Id = R30.SubjectId AND DM.Id = R30.DivisionId		
			WHERE COGBM.Id = @rCommonOrgGroupBatchId
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
				AND SM.OrgId = @rOrgId AND DM.IsObsolete = 0
			GROUP BY SM.Id,SM.title,EMP.EmployeeName,EMP.EmployeeId,DM.Code,DM.Id,SM.OrderIndex 
			ORDER BY SM.OrderIndex 
		   END
		END
		
		
	ELSE IF(@rTypeId=11)--TypeId = 11  is For Class Wise Detail's
		BEGIN
		
				SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId
				SELECT CM.Id AS ClassId,CM.Title AS ClassName,STM.Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo--,COUNT(RAll.RAll) AS 'RAll'
				FROM  sAssessment.tResult R 
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
					INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
					INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
					LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
					LEFT JOIN sSetup.tClassMaster CM ON CM.Id = A.classId AND CM.Id = EM.ClassId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					LEFT JOIN 
					(SELECT R1.Id AS RAll  FROM sAssessment.tResult R1
	WHERE R1.Percentage > @lFromPercentage AND R1.Percentage <= @lToPercentage			
					)RAll ON RAll.RAll = R.Id
				WHERE COGBM.Id = @rCommonOrgGroupBatchId 
				AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
				--AND EM.ExamSubGroupId = @rExamSubGroupId
				AND CM.OrgId = @rOrgId AND ((CM.Id = @rClassId)OR(@rClassId=0))
				GROUP BY CM.Id,CM.Title,STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
				HAVING COUNT(RAll.RAll) >0

				DROP TABLE #TblFinalRecord
		END
	ELSE IF(@rTypeId=21) -- TypeId = 21  is For Division Wise Detail's
		BEGIN
		
		SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId
			SELECT DM.Id AS ClassId,DM.Code AS ClassName,STM.Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo
				FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
				(SELECT R1.Id AS RAll,A1.DivisionId AS DivisionId   FROM sAssessment.tResult R1
				INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
	WHERE R1.Percentage > @lFromPercentage AND R1.Percentage <= @lToPercentage
				--WHERE  R1.Percentage <= 40
				)RAll ON RAll.RAll = R.Id AND DM.Id = RAll.DivisionId	
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
			--AND EM.ExamSubGroupId = @rExamSubGroupId 
			 AND ((DM.Id = @rDivisionId)OR(@rDivisionId=0))
			AND DM.OrgId = @rOrgId
			GROUP BY DM.Id,DM.Code,STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
			HAVING COUNT(RAll.RAll) >0

			DROP TABLE #TblFinalRecord
		END
	ELSE IF(@rTypeId=31) -- TypeId = 31  is For Subject Wise Detail's
		BEGIN
			SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId
			SELECT SM.Id AS SubjectId,SM.Title AS SubjectName,STM.Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo
				FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
				INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
				INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId AND CS.ClassId = A.classId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId  AND BM.Id = EM.BatchId
				LEFT JOIN sSetup.tDivisionMaster DM ON DM.ClassId = A.classId AND DM.ClassId = EM.ClassId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN 
					(SELECT R1.Id AS RAll,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM 
					sAssessment.tResultDetail RD 
                	INNER Join sAssessment.tResult R1 ON  RD.ResultId = R1.Id
					INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
					INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
					LEFT JOIN  sSetup.tClassSubject CS1 ON  CS1.Id = ED.ClassSubjectId
					INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE RD.Obtain > @lFromPercentage AND RD.Obtain <= @lToPercentage
				)RAll ON RAll.RAll = R.Id AND SM.Id = RAll.SubjectId	AND DM.Id = RAll.DivisionId
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
			--AND EM.ExamSubGroupId = @rExamSubGroupId 
			 AND ((SM.Id = @rSubjectId)OR(@rSubjectId=0))
			 AND (DM.ClassId = @rClassId OR DM.Id = @rDivisionId)
			AND DM.OrgId = @rOrgId
			GROUP BY SM.Id,SM.title,STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
				HAVING COUNT(RAll.RAll) >0

			DROP TABLE #TblFinalRecord
		END
	ELSE IF(@rTypeId=41) -- TypeId = 41  is For Teacher Wise Detail's
		BEGIN
				 SELECT @lFromPercentage  = FromPercentage ,@lToPercentage = ToPercentage  FROM #TblFinalRecord WHERE Id = @rRangeId


			SELECT ISNULL(STM.Code,'')AS Code,STM.FirstName +' '+STM.LastName AS Name,ISNULL(SC.ParentContactNo,'') AS ParentContactNo
			--,EMP.EmployeeName,EMP.EmployeeId
			FROM  sAssessment.tResult R 
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
				INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id			
				INNER JOIN  sSetup.tClassSubject CS ON CS.ClassId=EM.ClassId AND CS.ClassId = A.classId
				LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
				INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = STM.Id
				LEFT JOIN sSetup.tDivisionMaster DM ON  DM.ClassId = EM.ClassId
				INNER JOIN sAcademic.tTeacherSubjectDivision TS ON TS.SubjectId=CS.SubjectId AND TS.DivisionId=DM.ID
				--INNER JOIN  sHrm.tEmployeeMaster EM ON EM.ID = TS.EmployeeId
				INNER JOIN sSetup.tBatchMaster BM ON  BM.Id = EM.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				LEFT JOIN (
				SELECT Id AS EmployeeId,FirstName+' '+ LastName AS EmployeeName FROM sHrm.tEmployeeMaster WHERE ISNULL(IsOtherUser,0) = 0
				)EMP ON EMP.EmployeeId = TS.EmployeeId 
				
				LEFT JOIN 
				  (SELECT R1.Id AS RAll,SM1.Id AS SubjectId,A1.DivisionId AS DivisionId FROM sAssessment.tResult R1
				   INNER JOIN sStudent.tAcademic A1 ON R1.AcademicId = A1.Id
				  -- INNER JOIN sAssessment.tExamMaster EM1 ON EM1.Id = R1.ExamId
				   INNER JOIN  sSetup.tClassSubject CS1 ON  CS1.ClassId = A1.classId
				   INNER JOIN sSetup.tSubjectMaster SM1 ON SM1.Id=CS1.SubjectId 
	WHERE R1.Percentage > @lFromPercentage AND R1.Percentage <= @lToPercentage
				  )RAll ON RAll.RAll = R.Id AND SM.Id = RAll.SubjectId	AND DM.Id = RAll.DivisionId
		 	
		   
			WHERE COGBM.Id = @rCommonOrgGroupBatchId 
			AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rExamSubGroupId,','))OR @rExamSubGroupId=Null)
			--AND EM.ExamSubGroupId = @rExamSubGroupId  
			--AND CM.Id = 110100003
				AND SM.OrgId = @rOrgId
				AND DM.Id = @rDivisionId AND SM.Id = @rSubjectId AND EMP.EmployeeId = @rEmployeeId
				GROUP BY STM.Code,STM.FirstName,STM.LastName,SC.ParentContactNo
			HAVING COUNT(RAll.RAll) >0

			DROP TABLE #TblFinalRecord
			
		END
	
END
GO
PRINT N'Altering [sAttendance].[pStudentAttendaceDashboardGet]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

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

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

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

--Organization wise Attendance

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

--PresentStudent Organization wise
		 (SELECT count(*) 
			FROM sAttendance.tStudentRegister SME 
			   INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			   INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
			   INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OME.Id and SME.IsPresent=1 AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
			) AS PresentStudent,

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

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

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

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

      END
   
ELSE IF @rTypeId=24     
      BEGIN

      (SELECT *FROM  (
           SELECT 
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DM.Code As DivisionCode,
              (SMD.Code)StudentID,
              AEL.Id AS SourceId,
              (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			  (SC.ParentContactNo) AS ContactNo
	   FROM sAttendance.tStudentRegister SMEL
			   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
			   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
			   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
			   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
			   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		WHERE OMEL.Id=@rOrgId AND
		      SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId  
		GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)

	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	 ) AS Tmp) 
		
          
      END   
   
ELSE IF @rTypeId=15
	   BEGIN	
		(SELECT *FROM(
              SELECT  
                  OGMEL.Id as OrgGroupId,
                  OGMEL.Title As OrgGroupTitle,
                  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
                  DM.Code As DivisionCode,
                  (SMD.Code)StudentID,
                  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				  (SC.ParentContactNo) AS ContactNo,
				  AEL.Id AS SourceId
		      FROM sAttendance.tStudentRegister SMEL
				   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
				   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			       INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
				   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				   Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			   WHERE OGMEL.Id=@rOrgGroupId AND
				   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
			   GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	    ) AS Tmp) 
	   END
	   
ELSE IF @rTypeId=25
	BEGIN	
	 (SELECT *FROM(
           SELECT  
                OGMEL.Id as OrgGroupId,
                OGMEL.Title As OrgGroupTitle,
                OMEL.Id As OrgId,
                (OMEL.Title) As OrgTitle,
                DM.Code As DivisionCode,
                (SMD.Code)StudentID,
                (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
				AEL.Id AS SourceId
			FROM sAttendance.tStudentRegister SMEL
				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		    WHERE OMEL.Id=@rOrgId AND
				  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
			GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	  ) AS Tmp) 

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

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

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

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

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


GO
 
ALTER PROCEDURE [sAttendance].[pStudentAttendaceDashboardNewGet]
	 
	 @rTypeId smallint,
	 @rFromDate date=NULL,
	 @rToDate date=NULL,
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDivisionId int=0,
	 @rClassId int =0,
	 @rGenderType int=0,
	 @rCommonOrgGroupBatchId int=0,
	 @rSyncDate int =0,
	 @rUserId Bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

				--@rUptoDate,
				@rCommonOrgGroupBatchId,GetDate()
				FROM sSetup.tOrgGroupMaster OGM 
				WHERE OGM.Id<>1 AND ISNULL(OGM.IsObsolete,0) = 0
				AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
	END

--Organization wise Attendance

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

--PresentStudent Organization wise
		 (SELECT count(*) 
			FROM sAttendance.tStudentRegister SME 
			   INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			   INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
			   INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OME.Id and SME.IsPresent=1 AND 
			--SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126) 
			((SME.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			((SME.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
			AND COGBM.Id=@rCommonOrgGroupBatchId
			AND SME.AttendanceTypeId = 1
			) AS PresentStudent,

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

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

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

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

      END
   
ELSE IF @rTypeId=24     
      BEGIN

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

	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	 ) AS Tmp) 
		
          
      END   
   
ELSE IF @rTypeId=15
	   BEGIN	
		(SELECT *FROM(
              SELECT  
                  OGMEL.Id as OrgGroupId,
                  OGMEL.Title As OrgGroupTitle,
                  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
                  DM.Code As DivisionCode,
                  (SMD.Code)StudentID,
                  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				  (SC.ParentContactNo) AS ContactNo,
				  AEL.Id AS SourceId
		      FROM sAttendance.tStudentRegister SMEL
				   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
				   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			       INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
				   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				   Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			   WHERE OGMEL.Id=@rOrgGroupId AND
				   --SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) 
				   	((SMEL.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
					((SMEL.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				   AND COGBM.Id=@rCommonOrgGroupBatchId
				   AND SMEL.AttendanceTypeId = 1
			   GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	    ) AS Tmp) 
	   END
	   
ELSE IF @rTypeId=25
	BEGIN	
	 (SELECT *FROM(
           SELECT  
                OGMEL.Id as OrgGroupId,
                OGMEL.Title As OrgGroupTitle,
                OMEL.Id As OrgId,
                (OMEL.Title) As OrgTitle,
                DM.Code As DivisionCode,
                (SMD.Code)StudentID,
                (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
				AEL.Id AS SourceId
			FROM sAttendance.tStudentRegister SMEL
				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		    WHERE OMEL.Id=@rOrgId AND
				  --SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) 
				  	((SMEL.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
					((SMEL.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				  AND COGBM.Id=@rCommonOrgGroupBatchId
				  AND SMEL.AttendanceTypeId = 1
			GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	  ) AS Tmp) 

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

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

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

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

  ELSE
    BEGIN

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


GO
 

ALTER PROCEDURE [sBiometric].[pEmployeeCheckInAdd]
	 
	 	@rEmployeeId bigint,
        @rAttendanceDate Datetime='', 
        @rCheckInTime Datetime='',
		@rCheckOutTime Datetime='',
		@rEmployeePhoto varbinary(max)=null,
		@rId int=0 
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	--IF(@rId = 0)	
	--BEGIN 
	IF EXISTS (SELECT 1 FROM sBiometric.tEmployeeCheckIn WHERE EmployeeId = @rEmployeeId AND CAST(AttendanceDate AS DATE) = CAST(@rAttendanceDate AS DATE))
	BEGIN 
		SELECT -1 AS RESULT
		RETURN
	END
	ELSE 
	BEGIN
	INSERT INTO sBiometric.tEmployeeCheckIn
		(
			
			EmployeeId,
			AttendanceDate,
			CheckInTime,
			EmployeePhoto
		)
	VALUES
		( 
			@rEmployeeId,
			@rAttendanceDate,
			@rCheckInTime,
			@rEmployeePhoto
		)
	 SELECT 1  As result
	
	END	 

--ELSE
--	 BEGIN
--	    UPDATE sBiometric.tEmployeeCheckIn
--	    SET 
--			EmployeePhoto=@rEmployeePhoto
	      
--	      WHERE EmployeeId = @rEmployeeId AND Id=@rId
--	     SELECT 11 AS Result
--	 END  	

 
END
GO
PRINT N'Altering [sCertificate].[pLeavingBulkGet]...';


GO

ALTER PROCEDURE [sCertificate].[pLeavingBulkGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rOrderBy int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.Code,
			SA.Name,
			ISNULL(L.Id,0) AS Id,
			ISNULL(L.LCNumber,0) AS LCNumber,
			ISNULL(L.LCDate,'') AS LCDate,
			ISNULL(L.LCRemark,'')AS LCRemark,
			ISNULL(L.LastExamName,'')AS LastExamName,
			ISNULL(L.LastExamResult,'')AS LastExamResult,
			ISNULL(L.RepeatDetail,'')AS RepeatDetail,
			--ISNULL(L.SubjectStudied,'')AS SubjectStudied,
			ISNULL(L.PromoteToClass,'')AS PromoteToClass,
			ISNULL(L.ExtraCurricularActivities,'')As ExtraCurricularActivities,
			ISNULL(L.NCCScoutDetail,'')AS NCCScoutDetail,
			ISNULL(L.TermsInInstitute,'')As TermsInInstitute,
			ISNULL(L.FeeDetail,'')AS FeeDetail,
			ISNULL(L.FeeConcessionDetail,'')AS FeeConcessionDetail,
			ISNULL(AD.TotalDaysAnnual,0)AS TotalDays,
			ISNULL(AD.PresentDaysAnnual,0)AS PresentDays,
			ISNULL(L.ProofOfDOB,'')AS ProofOfDOB,
			reverse(STUFF(reverse(isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title from sSetup.tSubjectMaster S  
						   INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
						   WHERE S.OrgId=@rOrgId AND CS.IsOptional=0 FOR XML PATH('')), 1, 1, '')),'') +',' +
			isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title FROM sAssessment.tOptionalSubject OS 
						   INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
						   INNER JOIN sSetup.tSubjectMaster S ON  S.Id = CS.SubjectId 
						   WHERE OS.AcademicId = SA.AcademicId FOR XML PATH('')), 1, 1, '')),'') 
						   ), 1, 1, ''))as SubjectStudied

			
			
  FROM 
			[sStudent].[vStudentAcademic]  SA 
			LEFT OUTER JOIN sCertificate.tLeaving L ON L.AcademicId=SA.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON SA.AcademicId=AD.AcademicId
  WHERE 
			(SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SA.BatchId=@rBatchId
			AND SA.OrgID=@rOrgId 
			AND L.Id IS NULL
			order by
			CASE @rOrderBy WHEN 2 THEN SA.Code END,
			CASE @rOrderBy WHEN 1 THEN SA.RollNo END,
			CASE @rOrderBy WHEN 0 THEN SA.RollNo END
END
GO
PRINT N'Altering [sCommunication].[pAssignedQueryListGet]...';


GO
 
 
ALTER PROCEDURE [sCommunication].[pAssignedQueryListGet]
	 
	 @rOrgGroupId smallint,
	 @rOrgGroupBatchId int,
	 @rSourceId bigint,
	 @rSourceTypeId smallint,
	 @rStatusId int,
	 @rFromDate datetime = NULL,
	 @rToDate datetime = NULL
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	SELECT 
			 Q.Id AS QueryId,
			 Q.Title AS QueryTitle,
			 Q.Remark AS QueryRemark,
			 SM.Id AS QueryStatusId,
			 SM.Title AS QueryStatus,
			 QCM.Title AS QueryCategoryTitle,
			 QCA.QueryCategoryId,
			 (CONVERT(VARCHAR(25),Q.CreatedDateTime, 100)) AS QueryCreatedDateTime,
			 (CASE WHEN U.SourceTypeId = 95 THEN 	'Employee'
			 WHEN U.SourceTypeId = 2003 THEN	'Student' END ) AS SourceType,
			 (CASE WHEN U.SourceTypeId = 95 THEN (SELECT EmployeeName FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId= U.SourceId )	 
			 WHEN U.SourceTypeId = 2003 THEN (SELECT Name FROM sStudent.vStudentAcademic WHERE StudentId= U.SourceId AND OrgGroupBatchId = @rOrgGroupBatchId)  END ) AS SourceName,
			  (CASE WHEN U.SourceTypeId = 95 THEN (SELECT DepartmentName FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId= U.SourceId )	 
			 WHEN U.SourceTypeId = 2003 THEN (SELECT ClassName +' - ' + DivisionName FROM sStudent.vStudentAcademic WHERE StudentId= U.SourceId AND OrgGroupBatchId = @rOrgGroupBatchId)  END ) AS ClasDivOrDept,
			 (CASE WHEN U.SourceTypeId = 95 THEN (SELECT OM.Title FROM sHrm.vEmployeeCommonDetail vECD INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vECD.OrgID WHERE vECD.EmployeeId= U.SourceId )	 
			 WHEN U.SourceTypeId = 2003 THEN (SELECT OrganizationName FROM sStudent.vStudentAcademic WHERE StudentId= U.SourceId AND OrgGroupBatchId = @rOrgGroupBatchId)  END ) AS OrgTitle,
			 ISNULL(Q.Number,0) AS QueryNumber
	FROM 
				sCommunication.tQueryCategoryAssignedTo QCA
			INNER JOIN sCommunication.tQuery Q ON Q.QueryCategoryId = QCA.QueryCategoryId AND (Q.StatusId=@rStatusId)
			INNER JOIN sSecurity.tUser U ON U.Id = Q.CreatedUserId
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id=QCA.QueryCategoryId AND (QCM.OrgGroupId = @rOrgGroupId)	
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = Q.StatusId
	WHERE 
			(QCA.SourceTypeId = @rSourceTypeId) 
			AND (QCA.SourceId = @rSourceId) 
			AND ((Q.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((Q.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	ORDER BY Q.CreatedDateTime Asc	
END
GO
PRINT N'Altering [sFee].[pAssignOptionalFeeAdd]...';


GO
 
ALTER PROCEDURE [sFee].[pAssignOptionalFeeAdd]
	 
		   @rFeeSetupId int,
           @rSourceTypeId int,
           @rSourceId bigint,
           @rBatchId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
IF NOT EXISTS(SELECT 1 FROM sFee.tFeeOptional WHERE FeeSetupId=@rFeeSetupId AND SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId AND BatchId=@rBatchId )	
BEGIN

	INSERT INTO sFee.tFeeOptional
		(
		   FeeSetupId,
		   SourceTypeId,
		   SourceId,
		   BatchId
		)
	VALUES
		(
			@rFeeSetupId,
			@rSourceTypeId,
			@rSourceId,
			@rBatchId
		)

		DECLARE @lOrgId NVARCHAR(10) = SUBSTRING(CAST(@rBatchId AS NVARCHAR(10)),1,4)

		EXEC sFee.pFeeProcessGenerateFeeOptionalAdd 0,@rFeeSetupId,@lOrgId,@rBatchId,0,0,3,@rSourceId,@rSourceTypeId

		SELECT 1 AS Result
		             
	END	 
	 ELSE
	 BEGIN

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


GO
 
/****** Object:  StoredProcedure [sSupport].[pClaimAdd]    Script Date: 08/27/2013 10:32:12 ******/

ALTER PROCEDURE [sFee].[pAssignOptionalFeeHeadAdd]
		  
           @rSourceTypeId int,
           @rSourceId bigint,
           @rBatchId int,
           @rClassId int,
           @rAdmissionCategoryId int,
           @rFeeHeadId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	 BEGIN TRANSACTION	
	 
	 IF(@rClassId=0)
	 BEGIN 
		SELECT @rClassId = ClassId FROM sStudent.vStudentAcademic SA WHERE AcademicId = @rSourceId
	 END 
	 
	DELETE FO FROM 
	
	SFee.tFeeOptional FO
	INNER JOIN sFee.tFeeSetup FS ON FO.FeeSetupId = FS.Id AND FO.BatchId = FS.BatchId
	INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
	INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id	 	 
		WHERE
	FHM.Id = @rFeeHeadId
	AND FS.BatchId = @rBatchId
	AND FS.ClassId = @rClassId
	AND FS.AdmissionCategoryId =@rAdmissionCategoryId 
	AND FS.IsOptional=1
	AND FO.SourceId = @rSourceId
	AND FO.SourceTypeId = @rSourceTypeId
	AND FO.BatchId  = @rBatchId
	 
	INSERT INTO sFee.tFeeOptional
		(
		   FeeSetupId,
		   SourceTypeId,
		   SourceId,
		   BatchId
		)
	 
			SELECT
				FS.Id,  
				@rSourceTypeId,
				@rSourceId,			 
				@rBatchId
			FROM 
				sFee.tFeeSetup FS
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id	 
				
	WHERE
		FHM.Id = @rFeeHeadId
		AND FS.BatchId = @rBatchId
		AND FS.ClassId = @rClassId
		AND FS.AdmissionCategoryId =@rAdmissionCategoryId 
		AND FS.IsOptional=1
	
	DECLARE @lOrgId NVARCHAR(10) = SUBSTRING(CAST(@rBatchId AS NVARCHAR(10)),1,4)
	 
	EXEC sFee.pFeeProcessGenerateFeeOptionalAdd @rFeeHeadId,0,@lOrgId,@rBatchId,@rClassId,@rAdmissionCategoryId,3,@rSourceId,@rSourceTypeId

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


GO
 

ALTER PROCEDURE [sFee].[pAssignOptionalFeeRemove]
	
	 @rFeeSetupId int,
	 @rCheck bit,
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
BEGIN TRY

	 BEGIN TRANSACTION	
	 
	 IF(@rCheck=1)
BEGIN 

If Exists(select FS.Id from sFee.tFeeAllocation FA INNER JOIN sFee.tFeeSetup FS ON FA.FeeSetupId=FS.Id 
  where FS.Id=@rFeeSetupId AND FA.SourceId=@rSourceId AND FA.SourceTypeId=@rSourceTypeId AND FS.BatchId=@rBatchId)
	    BEGIN
			select -50 as Result
			RETURN
		END 
else If Exists(select FS.Id from sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId=R.Id
	INNER JOIN sFee.tFeeSetup FS ON FS.Id=RD.FeeSetupId where FS.Id=@rFeeSetupId 
	AND R.SourceId=@rSourceId AND R.SourceTypeId=@rSourceTypeId AND FS.BatchId=@rBatchId)
	    BEGIN
			select -51 as Result
			RETURN
		END 
		select 0 as Result	
END	
ELSE
BEGIN
	 
 Delete From sFee.tFeeOptional where SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId AND BatchId=@rBatchId
  AND ((FeeSetupId=@rFeeSetupId)OR(@rFeeSetupId=0))

  DELETE FROM sFee.tFeeAllocationStudent WHERE AcademicId = @rSourceId AND FeeSetupId = @rFeeSetupId

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


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

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

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


GO
  
ALTER PROCEDURE [sFee].[pFeeConsolidateDashBoardGet]
		
	@rType nvarchar(100)='',
	@rCount int =0 ,
	@rDivisionId int  =0,
	@rClassId int  =0,
	@rOrgId int  =0,
	@rOrgGroupId int=0,
	@rOrgGroupBatchId int  =0,
	@rCollectionGroupId int =0,
	@rReceiptBookId int =0,
	@rDays int=0,
	@rCommonOrgGroupBatchId int=0,
	@rFromDate varchar(10)='',
	@rToDate varchar(10)='',
	@rMonth int =0,
	@rSyncDate int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

IF(@rType ='FeeStatusOrganization')
	BEGIN 
	IF(@rSyncDate =1)
		BEGIN
			DELETE  sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				
				CREATE TABLE #tempOrganizationSync(
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrgGroupName nvarchar(200),
				OrgGroupId int
				)
				INSERT INTO #tempOrganizationSync
					SELECT 
						SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
						O.Title AS OrgGroupName,
						O.Id AS OrgGroupId
					FROM 
						sStudent.vStudentAcademic SA
						INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.ID = SA.OrgId
						
					WHERE	
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  And ISNULL(O.IsObsolete,0) = 0
						  AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
					GROUP BY  o.Id,o.Title

					IF EXISTS (SELECT 1 FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId)
						BEGIN							
						IF(@rOrgGroupId !=0)
							INSERT INTO sFee.tTempOrgGroupFeeStatus
							SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
							ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganizationSync T
							SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
						END
					ELSE
						BEGIN						
						INSERT INTO sFee.tTempOrgGroupFeeStatus
							SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
							ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganizationSync T
							SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
						END
				
				DROP TABLE #tempOrganizationSync			
		END
	ELSE
		BEGIN

			IF  Exists(select 1 from sFee.tTempOrgGroupFeeStatus where CONVERT(date,UpdatedDateTime) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))) 
			BEGIN
	
				SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN
			DELETE  sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempOrganization(
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrgGroupName nvarchar(200),
				OrgGroupId int
				)
			INSERT INTO #tempOrganization
					SELECT 
						SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
						O.Title AS OrgGroupName,
						O.Id AS OrgGroupId
					FROM 
						sStudent.vStudentAcademic SA
						INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.ID = SA.OrgId
						
					WHERE	
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  And ISNULL(O.IsObsolete,0) = 0
						  AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
					GROUP BY  o.Id,o.Title

						
				IF EXISTS (SELECT 1 FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId)
					BEGIN
						
					IF(@rOrgGroupId !=0)
						INSERT INTO sFee.tTempOrgGroupFeeStatus
						SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganization  T
						SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					END
				ELSE
					BEGIN
					
					INSERT INTO sFee.tTempOrgGroupFeeStatus
						SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganization  T
						SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					END 
					
				DROP TABLE #tempOrganization
			END
		END
		
	
	END
ELSE IF(@rType = 'FeeStatusPaid&UnpaidDetilsClassWise')
	BEGIN 
	IF(@rCount = 1)
	BEGIN

	CREATE TABLE #tempPaidDetailsClassWise(
	OrgGroupId int,
	OrgGroupName nvarchar(50),
	ClassId int,
	ClassName nvarchar(50),
	PaidAmount DECIMAL(12,0),
	StudentCount int
	)
  
	INSERT INTO #tempPaidDetailsClassWise
	SELECT 
		 ISNULL(O.Id,0) AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 ISNULL(SA.ClassId,0)AS ClassId,
		 ISNULL(SA.ClassName,'') AS ClassName,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 COUNT(Distinct(SA.AcademicId)) as StudentCount
	FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
	WHERE
		(O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND
		((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0 AND FAS.PaidAmount > 0
	GROUP by O.Id,SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName
	 

		SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount,T.StudentCount
		FROM #tempPaidDetailsClassWise T
		WHERE T.PaidAmount > 0
			 
	DROP TABLE #tempPaidDetailsClassWise
 
	END
	ELSE IF(@rCount = 2)
	BEGIN

	CREATE TABLE #tempPendingDetailsClassWise(
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(40),
	ClassId int,
	ClassName nvarchar(50),
	PendingAmount DECIMAL(12,0) 
	)
 
	INSERT INTO #tempPendingDetailsClassWise
	SELECT 
		 ISNULL(SA.AcademicId,0) AS AcademicId,
		 ISNULL(O.Id,0) AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 ISNULL(SA.ClassId,0)AS ClassId,
		 ISNULL(SA.ClassName,'') AS ClassName,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
	FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
	WHERE
		(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0
	GROUP by O.Id,SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName,SA.AcademicId

		SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS UnPaidAmount,COUNT(T.PendingAmount)AS StudentCount
		FROM #tempPendingDetailsClassWise T
		WHERE T.PendingAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.ClassId,T.OrgGroupName
		HAVING ISNULL(SUM(T.PendingAmount),0) > 0
        ORDER BY T.ClassId
	 
	DROP TABLE #tempPendingDetailsClassWise
 
	END
	END
ELSE IF(@rType ='FeeStatusPaid&UnpaidDetils')
BEGIN 

	IF(@rCount = 1)
	BEGIN
		CREATE TABLE #tempPaidDetails(
			SourceId bigint,
			OrgGroupId int,
			ClassName nvarchar(50),
			DivisionId int,
			DivisionName nvarchar(50),
			Code nvarchar(20),
			Name nvarchar(200),
			ParentContactNo nvarchar(50),
			PaidAmount DECIMAL(12,0),
			ClassOrderIndex int,
			DivisionOrder int,
			RollNo int
		)
		INSERT INTO #tempPaidDetails
		SELECT 
				ISNULL(SA.AcademicId,0) AS SourceId,
				ISNULL(O.Id,0) AS OrgGroupId,
				ISNULL(SA.ClassName,'') AS ClassName,
				ISNULL(SA.DivisionId,0) AS DivisionId,
				ISNULL(SA.DivisionName,'') AS DivisionName,
				ISNULL(SA.Code,'') As Code,
				ISNULL(SA.Name,'') AS Name,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
				SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
				 SA.ClassOrderIndex,  
				 SA.DivisionOrder,
				 SA.RollNo 
			FROM 		
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
			    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
		 WHERE
				(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND((SA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				And ISNULL(O.IsObsolete,0) = 0
				AND FAS.PaidAmount > 0
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FAS.PaidAmount,0)) >0
		ORDER BY O.Id,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo

		SELECT T.SourceId, T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,T.DivisionId,
			T.ParentContactNo AS ParentContactNo,T.PaidAmount AS PaidAmount,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
		FROM #tempPaidDetails T
		WHERE T.PaidAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.Name,T.ParentContactNo,T.PaidAmount,T.Code,T.ClassOrderIndex,T.DivisionOrder,T.RollNo,T.DivisionId,T.SourceId
		HAVING T.PaidAmount > 0
		ORDER BY T.OrgGroupId,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
	END
	ELSE IF(@rCount = 2)
	BEGIN
		CREATE TABLE #tempPendingDetails(
			SourceId bigint,
			OrgGroupId int,
			ClassName nvarchar(50),
			DivisionId int,
			DivisionName nvarchar(50),
			Code nvarchar(20),
			Name nvarchar(200),
			ParentContactNo nvarchar(50),
			PendingAmount DECIMAL(12,0),
			ClassOrderIndex int,
			DivisionOrder int,
			RollNo int
		)
		INSERT INTO #tempPendingDetails
		SELECT 
				ISNULL(SA.AcademicId,0) AS SourceId,
				ISNULL(O.Id,0) AS OrgGroupId,
				ISNULL(SA.ClassName,'') AS ClassName,
				ISNULL(SA.DivisionId,0) AS DivisionId,
				ISNULL(SA.DivisionName,'') AS DivisionName,
				ISNULL(SA.Code,'') As Code,
				ISNULL(SA.Name,'') AS Name,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
				SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
				SA.ClassOrderIndex,  
				SA.DivisionOrder,
				SA.RollNo 
			FROM 		
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
			    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
		 WHERE
				(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND((SA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				And ISNULL(O.IsObsolete,0) = 0
				
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		ORDER BY O.Id,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo

		SELECT T.SourceId, T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,T.DivisionId,
			T.ParentContactNo AS ParentContactNo,T.PendingAmount AS UnPaidAmount,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
		FROM #tempPendingDetails T
		WHERE T.PendingAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.Name,T.ParentContactNo,T.PendingAmount,T.Code,T.ClassOrderIndex,T.DivisionOrder,T.RollNo,T.DivisionId,T.SourceId
		HAVING T.PendingAmount > 0
		ORDER BY T.OrgGroupId,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
	END
END

ELSE IF(@rType ='FeeStatusTotalHeadwiseAmount')
BEGIN 
	IF(@rSyncDate =1)
		BEGIN
		DELETE  sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempTotalPaidDetailsSync (
				FeeHeadId bigint,
				FeeHeadName nvarchar(200),
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				ReceiptBookId bigint,
				RecepitTitle nvarchar(100),
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrderIndex int
			)
			 
			INSERT INTO #tempTotalPaidDetailsSync
			SELECT 
				ISNULL(FHM.Id,0) AS FeeHeadId,
				ISNULL(FHM.code,'') AS FeeHeadName,
				ISNULL(CGM.Id,0) AS CollectionGroupId,
				ISNULL(CGM.Code,'') AS CollectionGroup,
				ISNULL(RBM.Id,'')  AS ReceiptBookId,
				ISNULL(RBM.Title,'')  AS ReceiptTitle,
				SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
				SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
				FHM.OrderIndex
			FROM 
				sStudent.tAcademic SA
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			 And ISNULL(O.IsObsolete,0) = 0
			GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Code,RBM.Title,RBM.Id,FHM.OrderIndex

			INSERT INTO sFee.tTempTotalPaidDetails
			SELECT @rOrgGroupId,T.FeeHeadId,ISNULL(T.FeeHeadName,'') AS FeeHeadName,T.CollectionGroupId,
						ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,
						T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
						ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
						T.OrderIndex,@rCommonOrgGroupBatchId,GETDATE() from #tempTotalPaidDetailsSync T
			GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId,T.OrderIndex
			ORDER BY T.OrderIndex

			SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))		

		--New Temp Table Create-------------
			CREATE TABLE #tempTotalStudentCountSync (
			AcademicId bigint,
			CollectionGroupId bigint,
			CollectionGroup nvarchar(200),
			RecepitTitle nvarchar(100),
			ReceiptBookId bigint,
			EndDate date,
			PaidAmount DECIMAL(12,0),
			PendingAmount DECIMAL(12,0)
			)
	
			--Test
	 
			INSERT INTO #tempTotalStudentCountSync
			SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
					INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					 ORDER BY ReceiptDate DESC) EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA
		        INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id 
				INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 And ISNULL(O.IsObsolete,0) = 0
			 AND COGBM.Id=@rCommonOrgGroupBatchId 
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	
			INSERT INTO sFee.tTempTotalStudentCount
			SELECT @rOrgGroupId,E.CollectionGroupId,E.CollectionGroup AS CollectionGroup,E.ReceiptBookId AS ReceiptId,E.ReceiptCollection AS ReceiptCollection,
					ISNULL(E.EndDate,'1900-01-01')AS EndDate,
					--E.EndDate AS EndDate,
					SUM(E.TotalStudentCount) AS TotalStudentCount,SUM(E.PaidStudentCount) AS PaidStudentCount,SUM(E.PendingStudentCount) AS PendingStudentCount,@rCommonOrgGroupBatchId,GETDATE() FROM (
			SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(T.CollectionGroup,'') As CollectionGroup,
				ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,T.CollectionGroupId AS CollectionGroupId,
				ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate from #tempTotalStudentCountSync T
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM #tempTotalStudentCountSync --CollectionGroupId,CollectionGroup,
						WHERE PendingAmount  = 0
						GROUP BY CollectionGroupId,ReceiptBookId
					) A ON A.CollectionGroupId = T.CollectionGroupId
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM #tempTotalStudentCountSync
						WHERE PendingAmount !=0
						GROUP BY CollectionGroupId,ReceiptBookId
					)B ON B.CollectionGroupId = T.CollectionGroupId 
					GROUP BY T.CollectionGroupId,T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
					)E
					GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate,E.CollectionGroupId
		
		 SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	


		-------------Create a New Temp Table For Pending date-----------------
			CREATE TABLE #tempPendingCountSync(
			AcademicId bigint,
			CollectionGroupId bigint,
			CollectionGroup nvarchar(200),
			RecepitTitle nvarchar(100),
			ReceiptBookId bigint,
			EndDate date,
			PaidAmount DECIMAL(12,0),
			PendingAmount DECIMAL(12,0)
			)
	 
			INSERT INTO #tempPendingCountSync
			SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
						(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id 
			
					INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
			
			WHERE  
					(LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
					AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
					And ISNULL(O.IsObsolete,0) = 0
			ORDER BY ReceiptDate DESC) EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 And ISNULL(O.IsObsolete,0) = 0
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate

			INSERT INTO sFee.tTempPendingCount
			SELECT @rOrgGroupId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,T.ReceiptBookId AS ReceiptId,
						T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount,@rCommonOrgGroupBatchId,GETDATE()
			FROM   #tempPendingCountSync T
			WHERE PendingAmount !=0
			 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()- @rDays) AND CONVERT(DATE,GETDATE())
			GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup

			SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	 
			DROP TABLE #tempTotalPaidDetailsSync
			DROP TABLE #tempTotalStudentCountSync
			DROP TABLE #tempPendingCountSync

		END
	ELSE
		BEGIN
		IF  Exists(select 1 from sFee.tTempTotalPaidDetails where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
			BEGIN
	
				SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN

			DELETE  sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			DELETE  sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			DELETE  sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempTotalPaidDetails (
				FeeHeadId bigint,
				FeeHeadName nvarchar(200),
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				ReceiptBookId bigint,
				RecepitTitle nvarchar(100),
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrderIndex int
				)
			
				INSERT INTO #tempTotalPaidDetails
				SELECT 
					ISNULL(FHM.Id,0) AS FeeHeadId,
					ISNULL(FHM.code,'') AS FeeHeadName,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Id,'')  AS ReceiptBookId,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
					FHM.OrderIndex
				FROM 
					sStudent.tAcademic SA
					INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
					INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				 And ISNULL(O.IsObsolete,0) = 0
				GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Code,RBM.Title,RBM.Id,FHM.OrderIndex

			INSERT INTO sFee.tTempTotalPaidDetails
				SELECT @rOrgGroupId,T.FeeHeadId,ISNULL(T.FeeHeadName,'') AS FeeHeadName,T.CollectionGroupId,
				ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
				ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
				ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
				T.OrderIndex,@rCommonOrgGroupBatchId,GETDATE()from #tempTotalPaidDetails T
				GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId,T.OrderIndex
				ORDER BY T.OrderIndex

			SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	

					--New Temp Table Create-------------
				CREATE TABLE #tempTotalStudentCount (
				AcademicId bigint,
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				RecepitTitle nvarchar(100),
				ReceiptBookId bigint,
				EndDate date,
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0)
				)
	
				--Test
	
				INSERT INTO #tempTotalStudentCount
				SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
					INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					 ORDER BY ReceiptDate DESC) EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
				FROM 
					sStudent.tAcademic SA
					INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id 
					INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				 And ISNULL(O.IsObsolete,0) = 0
				 AND COGBM.Id=@rCommonOrgGroupBatchId 
				GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	
			INSERT INTO sFee.tTempTotalStudentCount
			SELECT @rOrgGroupId,E.CollectionGroupId,E.CollectionGroup AS CollectionGroup,E.ReceiptBookId AS ReceiptId,E.ReceiptCollection AS ReceiptCollection,
					ISNULL(E.EndDate,'1900-01-01')AS EndDate,
					--E.EndDate AS EndDate,
					SUM(E.TotalStudentCount) AS TotalStudentCount,SUM(E.PaidStudentCount) AS PaidStudentCount,SUM(E.PendingStudentCount) AS PendingStudentCount,@rCommonOrgGroupBatchId,GETDATE() FROM (
			SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(T.CollectionGroup,'') As CollectionGroup,
				ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,T.CollectionGroupId AS CollectionGroupId,
				ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate from #tempTotalStudentCount T
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM #tempTotalStudentCount --CollectionGroupId,CollectionGroup,
						WHERE PendingAmount  = 0
						GROUP BY CollectionGroupId,ReceiptBookId
					) A ON A.CollectionGroupId = T.CollectionGroupId
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM #tempTotalStudentCount
						WHERE PendingAmount !=0
						GROUP BY CollectionGroupId,ReceiptBookId
					)B ON B.CollectionGroupId = T.CollectionGroupId 
					GROUP BY T.CollectionGroupId,T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
					)E
					GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate,E.CollectionGroupId
				 
				 SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

					-------------Create a New Temp Table For Pending date-----------------
				CREATE TABLE #tempPendingCount(
				AcademicId bigint,
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				RecepitTitle nvarchar(100),
				ReceiptBookId bigint,
				EndDate date,
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0)
				)
				
				INSERT INTO #tempPendingCount
				SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
						(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id 
					INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
			  WHERE  
					(LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
					AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
					And ISNULL(O.IsObsolete,0) = 0
			  ORDER BY ReceiptDate DESC) EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 And ISNULL(O.IsObsolete,0) = 0
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
		
		INSERT INTO sFee.tTempPendingCount
				SELECT @rOrgGroupId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,T.ReceiptBookId AS ReceiptId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount,@rCommonOrgGroupBatchId,GETDATE()
				FROM   #tempPendingCount T
				WHERE PendingAmount !=0
				 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()- @rDays) AND CONVERT(DATE,GETDATE())
				 GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup
		SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	
				DROP TABLE #tempTotalPaidDetails
				DROP TABLE #tempTotalStudentCount
				DROP TABLE #tempPendingCount
			END
		END
END

ELSE IF(@rType ='FeeStatusPaidSubPartAmount')
BEGIN 
	CREATE TABLE #tempPaidSubPart (
	OrgGroupId int,
	OrgGroupName nvarchar(50),
	ClassId bigint,
	ClassName nvarchar(50),
	--DivisionId bigint,
	--DivisionName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	ClassOrderIndex int,
	StudentCount int
	--,DivisionOrder int
	)
    
IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPaidSubPart
	SELECT 
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		 ISNULL(CGM.Id,0) AS CollectionGroupId,
		 ISNULL(CGM.Code,'') AS CollectionGroup,
		 ISNULL(RBM.Title,'')  AS ReceiptTitle,
		 ISNULL(RBM.Id,0) As ReceiptBookId,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		 SA.ClassOrderIndex,
		 COUNT(Distinct(FAS.AcademicId)) as StudentCount
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	    	
	WHERE
		(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
		And ISNULL(O.IsObsolete,0) = 0
		AND FAS.PaidAmount > 0
	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.ClassId,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	HAVING ISNULL(SUM(FAS.PaidAmount),0) > 0
	ORDER BY SA.ClassOrderIndex

		select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount, T.StudentCount AS StudentCount,
			ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex,
			'' as MonthName 
		from #tempPaidSubPart T
		 

	END 
	ELSE 
	BEGIN
	INSERT INTO #tempPaidSubPart
		
	SELECT 
		 SA.OrgId AS OrgGroupId,SA.OrganizationName As OrgGroupName,
		 SA.ClassId As ClassId,
		 SA.ClassName AS ClassName,
		 ISNULL(CGM.Id,0) AS CollectionGroupId,
		 ISNULL(CGM.Code,'') AS CollectionGroup,
		 ISNULL(RBM.Title,'')  AS ReceiptTitle,
		 ISNULL(RBM.Id,0) As ReceiptBookId,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		 SA.ClassOrderIndex,
		 COUNT(Distinct(FAS.AcademicId)) as StudentCount
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
		 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
		 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
		 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		 And ISNULL(O.IsObsolete,0) = 0
		 AND FAS.PaidAmount > 0
    GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.ClassId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	HAVING ISNULL(SUM(FAS.PaidAmount),0) > 0
	ORDER BY SA.ClassOrderIndex

	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount,T.StudentCount As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex,
		'' as MonthName 
		from #tempPaidSubPart T
	END
	
	DROP TABLE #tempPaidSubPart

END

ELSE IF(@rType ='FeeStatusPaidSubPartAmountMonthWise')
BEGIN 
	CREATE TABLE #tempPaidSubPartMonthWise (
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	MonthName nvarchar(15),
	)
   
    CREATE TABLE #tempPFSMonthWise (
       Id INT,
       Amount DECIMAL(12,0),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    
    INSERT INTO #tempPFSMonthWise	
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
	   (FS1.IsOptional=0)
	   --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate   
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))


     CREATE TABLE #tempPRMonthWise (
         PaidAmount DECIMAL(12,0),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPRMonthWise	
     SELECT 
		  ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 FROM
		  sFee.tReceipt R 
		  INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		  INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		  INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		  INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
		  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		  INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		  
		  INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		 
	WHERE		
		  (R.SourceTypeId = 2001)
		   AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		   AND (R.IsObsolete = 0) --AND BM.IsActive=1 
		   AND COGBM.Id=@rCommonOrgGroupBatchId 
		   And ISNULL(O.IsObsolete,0) = 0
		   --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
		   --AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
 

IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPaidSubPartMonthWise
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR.PaidAmount,0.00))AS PendingAmount,
		TPR.ReceiptDate		 
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN #tempPFSMonthWise TPFS ON TPFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=TPFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise TPR ON TPR.FeeSetupId = TPFS.Id AND SA.AcademicId = TPR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN sFee.tReceiptBookMaster RBM ON TPFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON TPFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=TPFS.FeeHeadId	    	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	And ISNULL(O.IsObsolete,0) = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.PaidAmount,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempPFSMonthWise1 (
       Id INT,
       Amount DECIMAL(12,0),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    INSERT INTO #tempPFSMonthWise1
    SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		 SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		 INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	     INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	     INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	     INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	     INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			 
		 INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		 --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		 AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		 And ISNULL(O.IsObsolete,0) = 0
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		 --AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		
	WHERE
				
		(FS1.IsOptional=1) AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
    
    CREATE TABLE #tempPRMonthWise1(
         PaidAmount DECIMAL(12,0),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPRMonthWise1
     SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		

	WHERE		
		(R.SourceTypeId = 2001)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		AND (R.IsObsolete = 0) 
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate  
   
	
	INSERT INTO #tempPaidSubPartMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,		
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR1.PaidAmount,0.00))AS PendingAmount,
		TPR1.ReceiptDate
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPFSMonthWise1 TPFS1 ON TPFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TPFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise1 TPR1 ON TPR1.FeeSetupId = TPFS1.Id AND SA.AcademicId = TPR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TPFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TPFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TPFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	And ISNULL(O.IsObsolete,0) = 0
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR1.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount,COUNT(T.AcademicId) As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END
	
	DROP TABLE #tempPaidSubPartMonthWise
	DROP TABLE #tempPFSMonthWise
	DROP TABLE #tempPRMonthWise
	DROP TABLE #tempPFSMonthWise1
	DROP TABLE #tempPRMonthWise1
	
END

ELSE IF(@rType ='FeeStatusPendingSubPartAmount')
BEGIN 
CREATE TABLE #tempPendingSubPart(
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(50),
	ClassId bigint ,
	ClassName nvarchar(50),
	--DivisionId bigint,
	--DivisionName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	ClassOrderIndex int
	--,DivisionOrder int
	)

IF(@rCollectionGroupId = 0)
	BEGIN

	INSERT INTO #tempPendingSubPart
    SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId  AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex
	FROM 
		sStudent.vStudentAcademic SA 
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
		(FS.IsOptional=0)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) 
		And ISNULL(O.IsObsolete,0) = 0
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId = 0))
	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassId,SA.ClassName,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	
	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,COUNT(T.AcademicId)AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex from #tempPendingSubPart T
		WHERE T.PendingAmount >0
     group by T.OrgGroupId,T.OrgGroupName,T.ClassName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex
		ORDER BY T.ClassOrderIndex
		
    DROP TABLE #tempPendingSubPart
		
	END 
	ELSE 
	BEGIN
	
	INSERT INTO #tempPendingSubPart
	SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex  
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
		(FS.IsOptional=0)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) 
		And ISNULL(O.IsObsolete,0) = 0
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId = 0))
	 GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	
	SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex from #tempPendingSubPart T
	WHERE T.PendingAmount >0
	GROUP BY T.OrgGroupId,T.ClassName,T.OrgGroupName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex
	--HAVING ISNULL(SUM(T.PendingAmount),0) > 0
	ORDER BY T.ClassOrderIndex	
		
   
	   DROP TABLE #tempPendingSubPart
		
	END
	END

ELSE IF(@rType ='FeeStatusPendingSubPartDetails')
BEGIN 
CREATE TABLE #tempPendingSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
)

IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPendingSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And ISNULL(O.IsObsolete,0) = 0
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
		select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
			ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPendingSubPartDetails T
		WHERE T.PendingAmount >0
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempPendingSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 And ISNULL(O.IsObsolete,0) = 0
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

		select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPendingSubPartDetails T
		WHERE T.PendingAmount >0
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.RollNo
		
		 
	END
	
	DROP TABLE #tempPendingSubPartDetails
	 
END	
	
ELSE IF(@rType ='FeeStatusTotalSubPartAmount')
BEGIN 
CREATE TABLE #tempTotalSubPart (
AcademicId bigint,
OrgGroupId int,
OrgGroupName nvarchar(50),
ClassId bigint,
ClassName nvarchar(50),
--DivisionId bigint,
--DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
ClassOrderIndex int
--,DivisionOrder int
)

IF(@rCollectionGroupId = 0)
	BEGIN

	INSERT INTO #tempTotalSubPart
	SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		SA.OrgId AS OrgGroupId,
		SA.OrganizationName AS OrgGroupName,
		SA.ClassId AS ClassId,
		SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE 
		   ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId=0))

	GROUP by SA.OrgId,SA.OrganizationName, SA.ClassId,SA.ClassName--,SA.DivisionName
		,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex--,SA.DivisionOrder
	

	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from #tempTotalSubPart T
	group by T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName,T.CollectionGroupId,T.ReceiptBookId
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		
	END 
	ELSE 
	BEGIN
	
	INSERT INTO #tempTotalSubPart
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		  SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex--,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE 
		   ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId=0))

	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassId,SA.ClassName--,SA.DivisionName
		,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex--,SA.DivisionOrder

		 
	SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from #tempTotalSubPart T
	GROUP BY T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName--,T.ClassOrderIndex,T.DivisionOrder
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		--ORDER BY T.ClassOrderIndex,T.DivisionOrder
		
	END
	
	DROP TABLE #tempTotalSubPart
	
  END	
ELSE IF(@rType ='FeeStatusTotalSubPartDetails')
BEGIN 
CREATE TABLE #tempTotalSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
)

 
IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempTotalSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND  ISNULL(CGM.Id,0)=0
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 And ISNULL(O.IsObsolete,0) = 0
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempTotalSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
	ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempTotalSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And ISNULL(O.IsObsolete,0) = 0
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempTotalSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId--,T.ClassOrderIndex,T.DivisionOrder 
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
	ORDER BY T.RollNo
		
	 
	END
	
	DROP TABLE #tempTotalSubPartDetails
	
END
  
ELSE IF(@rType ='FeeStatusPaidSubPartDetails')
BEGIN 
CREATE TABLE #tempPaidSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
)

 
IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPaidSubPartDetails
	SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND  ISNULL(CGM.Id,0)=0
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And ISNULL(O.IsObsolete,0) = 0
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
	HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
	ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempPaidSubPartDetails
	SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 And ISNULL(O.IsObsolete,0) = 0
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetails T
		
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
		
	END
	
	DROP TABLE #tempPaidSubPartDetails
END

ELSE IF(@rType ='FeeStatusPaidSubPartDetailsMonthWise')
BEGIN 
CREATE TABLE #tempPaidSubPartDetailsMonthWise(
AcademicId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
)

CREATE TABLE #tempDFSMonthWise(
     Id INT,
     Amount DECIMAL(12,0),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

)

INSERT INTO #tempDFSMonthWise
	 SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And ISNULL(O.IsObsolete,0) = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
	   (FS1.IsOptional=1) --AND BM.IsActive=1 
	   AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And ISNULL(O.IsObsolete,0) = 0
	   --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
	    --AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
	    --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
		


CREATE TABLE #tempDRMonthWise(
       PaidAmount DECIMAL(12,0),
	   FeeSetupId INT,
	   SourceId BIGINT,
	   ReceiptDate DATE
)
INSERT INTO #tempDRMonthWise
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
		,R.ReceiptDate
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
	WHERE		
		(R.SourceTypeId = 2001) 
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And ISNULL(O.IsObsolete,0) = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate     
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate



IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPaidSubPartDetailsMonthWise
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise TDFS ON TDFS.AcademicId=SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDRMonthWise TDR ON TDR.FeeSetupId = TDFS.Id AND SA.AcademicId = TDR.SourceId
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	AND((DATEPART(M, TDR.ReceiptDate)  =@rMonth)OR(@rMonth=0))
	And ISNULL(O.IsObsolete,0) = 0
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetailsMonthWise T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempDFSMonthWise1(
     Id INT,
     Amount DECIMAL(12,0),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT  

    )
    
    INSERT INTO #tempDFSMonthWise1
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And ISNULL(O.IsObsolete,0) = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	
CREATE TABLE #tempDRMonthWise1(
       PaidAmount DECIMAL(12,0),
	   FeeSetupId INT,
	   SourceId BIGINT,
	   ReceiptDate DATE
)
INSERT INTO #tempDRMonthWise1
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId,
		R.ReceiptDate
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		And ISNULL(O.IsObsolete,0) = 0
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
	
	
	
	insert into #tempPaidSubPartDetailsMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR1.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise1 TDFS1 ON TDFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDRMonthWise TDR1 ON TDR1.FeeSetupId = TDFS1.Id AND SA.AcademicId = TDR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND((DATEPART(M, TDR1.ReceiptDate)  =@rMonth)OR(@rMonth=0))
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	And ISNULL(O.IsObsolete,0) = 0
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetailsMonthWise T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName
		--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
		
		DROP TABLE #tempDFSMonthWise1
	DROP TABLE #tempDRMonthWise1
	END
	
	DROP TABLE #tempPaidSubPartDetailsMonthWise
	DROP TABLE #tempDFSMonthWise
	DROP TABLE #tempDRMonthWise
	
	
	
END

ELSE IF(@rType='ReceiptOrganization')
  BEGIN
	IF(@rSyncDate =1)
		BEGIN
				DELETE  sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				CREATE TABLE #tempReceiptOrganizationSync(
				OrgGroupId int,
				OrgGroupName nvarchar(500),
				ReceiptId bigint,
				TotalReceiptAmount DECIMAL(12,0),
				IsObsolete bit
				)
				INSERT INTO #tempReceiptOrganizationSync
				SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,R.Id AS ReceiptCount,R.ReceiptAmount,R.IsObsolete
				FROM  sFee.tReceipt R
				INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
				WHERE R.SourceTypeId = 2001
				AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND (COGBM.Id=@rCommonOrgGroupBatchId )
				And ISNULL(O.IsObsolete,0) = 0 
				AND (R.ReceiptDate between @rFromDate and @rToDate)    
			
			INSERT INTO sFee.tTempReceiptOrganization
				SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate() FROM #tempReceiptOrganizationSync T  
				LEFT JOIN (
				SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganizationSync WHERE IsObsolete = 1
				GROUP BY OrgGroupId,OrgGroupName
				) A ON A.OrgGroupId=t.OrgGroupId
				WHERE IsObsolete = 0
				GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
				ORDER BY OrgGroupId
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				
				DROP TABLE #tempReceiptOrganizationSync
		END 
	ELSE
		BEGIN
			IF  Exists(select 1 from sFee.tTempReceiptOrganization where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND CONVERT(date,ReceiptDate) =@rFromDate AND CONVERT(date,ReceiptDate) =@rToDate )
			BEGIN
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
	ELSE
			BEGIN 
			DELETE  sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				CREATE TABLE #tempReceiptOrganization(
				OrgGroupId int,
				OrgGroupName nvarchar(500),
				ReceiptId bigint,
				TotalReceiptAmount DECIMAL(12,0),
				IsObsolete bit
				)
				INSERT INTO #tempReceiptOrganization
				SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,R.Id AS ReceiptCount,R.TotalReceiptAmount,R.IsObsolete
				FROM  sFee.tReceipt R
				INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
				WHERE R.SourceTypeId = 2001
				AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND (COGBM.Id=@rCommonOrgGroupBatchId ) 
				AND (R.ReceiptDate between @rFromDate and @rToDate)    
			
				INSERT INTO sFee.tTempReceiptOrganization
				SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate() FROM #tempReceiptOrganization T  
				LEFT JOIN (
				SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganization WHERE IsObsolete = 1
				GROUP BY OrgGroupId,OrgGroupName
				) A ON A.OrgGroupId=t.OrgGroupId
				WHERE IsObsolete = 0
				GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
				ORDER BY OrgGroupId
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DROP TABLE #tempReceiptOrganization
			END
		END
  END
ELSE IF(@rType='ReceiptBookCollectionGroup')
  BEGIN
	CREATE TABLE #tempReceiptBookCollection (
	RecepitTitle nvarchar(200),
	--CollectionTitle nvarchar(200),
	ReceiptCount int,
	ReceiptAmount DECIMAL(12,0),
	ReceiptId bigint,
	--CollectionGroupId bigint,
	IsObsolete bit
)

INSERT INTO #tempReceiptBookCollection
 SELECT ISNULL(RBM.Title,'')  AS RecepitTitle ,
			--ISNULL(CGM.Code,'') AS CollectionTitle,
			ISNULL(COUNT(DISTINCT R.Id),0) AS ReceiptCount,CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
			ISNULL(RBM.Id,0) AS ReceiptId,
			--ISNULL(CGM.Id,0) AS CollectionGroupId,
			R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					
			INNER JOIN  sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id 			
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId 
			AND FS.AdmissionCategoryId=SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			
			--LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id 
			--AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND (R.IsObsolete = 1) 
			--AND(BM.IsActive =1) 
			AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))AND R.ReceiptDate between @rFromDate and @rToDate 
			And ISNULL(O.IsObsolete,0) = 0   
			GROUP BY RBM.Title,RBM.Id,R.ReceiptBookId,R.IsObsolete,R.Id,R.ReceiptAmount
			
			--SELECT  TRC.RecepitTitle +'-'+ TRC.CollectionTitle AS ReceictCollection,TRC.ReceiptId AS ReceiptId,TRC.CollectionGroupId AS CollectionGroupId,ISNULL(COUNT(TRC.ReceiptCount),0) AS ReceiptCount,SUM(ReceiptAmount) AS ReceiptAmount ,
			--ISNULL(A.CancelReceiptCount,0)AS CancelAmount FROM #tempReceiptBookCollection TRC 
			--LEFT JOIN (
			--SELECT ReceiptId,CollectionGroupId,SUM(ReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptBookCollection WHERE IsObsolete = 1
			--GROUP BY ReceiptId,CollectionGroupId
			--) A ON A.ReceiptId=TRC.ReceiptId AND A.CollectionGroupId=TRC.CollectionGroupId
			
			--WHERE IsObsolete = 0
			--GROUP BY TRC.RecepitTitle,TRC.CollectionTitle,A.ReceiptId,A.CancelReceiptCount,TRC.ReceiptId,TRC.CollectionGroupId,TRC.ReceiptCount 

			SELECT  TRC.RecepitTitle AS ReceictCollection,TRC.ReceiptId AS ReceiptId,0 AS CollectionGroupId,ISNULL(COUNT(TRC.ReceiptCount),0) AS ReceiptCount,SUM(ReceiptAmount) AS ReceiptAmount ,
			ISNULL(A.CancelReceiptCount,0)AS CancelAmount FROM #tempReceiptBookCollection TRC 
			LEFT JOIN (
			SELECT ReceiptId,SUM(ReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptBookCollection WHERE IsObsolete = 1
			GROUP BY ReceiptId
			) A ON A.ReceiptId=TRC.ReceiptId
			
			WHERE IsObsolete = 0
			GROUP BY TRC.RecepitTitle,A.ReceiptId,A.CancelReceiptCount,TRC.ReceiptId,TRC.ReceiptCount 
		DROP TABLE #tempReceiptBookCollection
  END
ELSE IF(@rType='ReceiptBookCollectionGroupDetail')
  BEGIN
  CREATE TABLE #tempReceiptBookCollectionDetail(
  SourceId bigint,
Code nvarchar(200),
Name nvarchar(200),
ReceiptNumber bigint,
ReceiptAmount DECIMAL(12,0),
ReceiptId bigint,
IsObsolete bit
)
  
	INSERT INTO #tempReceiptBookCollectionDetail
 SELECT ISNULL(SA.Id,0) AS SourceId,SM.Code AS Code,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) As Name,R.ReceiptNumber AS ReceiptNumber,CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,R.Id AS ReceiptId,R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId=SM.Id	
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.AdmissionCategoryId =  SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND (R.IsObsolete = 0) 
			--AND(BM.IsActive =1) 
			And ISNULL(O.IsObsolete,0) = 0			
			AND COGBM.Id=@rCommonOrgGroupBatchId AND R.ReceiptDate between @rFromDate and @rToDate     
			GROUP BY SA.Id,SM.Code,R.ReceiptNumber,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId), R.ReceiptBookId,R.Id,R.IsObsolete,R.ReceiptAmount 
			--ORDER BY 
	 
  SELECT *  FROM #tempReceiptBookCollectionDetail ORDER BY ReceiptNumber
  
  DROP TABLE #tempReceiptBookCollectionDetail
  END
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


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

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


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

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

	INSERT INTO sFee.tFeeSetup
		(
		   Id,
           ClassId,
           AdmissionCategoryId,
           BatchId,
           FeeId,
           IsOptional,
           IsVariable,
           Amount,
           StartDate,
           EndDate,
           ReceiptBookId,
           CreatedUserId,
           CreatedDateTime,
           IsServiceTax,
           CollectionGroupId,
           FeeDuration,
           LevelAmount
        )
	VALUES
		(
			@lNextNumber,
			@rClassId,
			@rAdmissionCategoryId,
            @rBatchId,
            @rFeeId,
            @rIsOptional,
            @rIsVariable,
            @rAmount,
            @rStartDate,
            @rEndDate,
            @rReceiptBookId,
            @rCreatedUserId,
			sCommon.fGetDate(),
			@rIsServiceTax,
			@rCollectionGroupId,
			@rFeeDuration,
			@rLevelAmount
		)

		SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tFeeSetup
	    SET
			 --ClassId=@rClassId,
			 --AdmissionCategoryId=@rAdmissionCategoryId,
    --         BatchId=@rBatchId,
             IsOptional=@rIsOptional,
             IsVariable=@rIsVariable,
             Amount=@rAmount,
             StartDate=@rStartDate,
             EndDate=@rEndDate,
             ReceiptBookId=@rReceiptBookId,
             UpdatedUserId=@rUpdatedUserId,
			 UpdatedDateTime=sCommon.fGetDate(),
			 IsServiceTax=@rIsServiceTax,
			 CollectionGroupId=@rCollectionGroupId,
			 FeeDuration=@rFeeDuration,
			 LevelAmount=@rLevelAmount
	      WHERE (Id = @rId)
	       --AND (FeeId=@rFeeId) 

	      SELECT 11 AS Result   
	 END  
	
	If Not Exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGRoupId)
	BEGIN
		Insert INto sSystem.tPortalSync 
		(
			OrgGRoupId,
			FeeChange
		)
		Values
		(
			@rOrgGRoupId,
			1
		)
	END
	Else
	BEGIN
		Update sSystem.tPortalSync 
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
		
	END

	EXEC [sFee].[pFeeProcessGenerate] @rOrgId,@rBatchId,@rClassId,NULL,NULL,@rCreatedUserId

	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sFee].[pReceiptAdd]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
DECLARE @lIsCreated INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml

BEGIN
	BEGIN TRY
	
	 SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId

	 DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 339 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	 IF @lConfigValue = ''
		SET @lConfigValue = 'ReceiptBookWise'
	 
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@rId = 0)--ID Condition Added by dhruv for issue no.0013266	
		BEGIN
			IF(@lConfigValue='ReceiptBookWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			ELSE IF(@lConfigValue='PayTypeWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
		END
		ELSE
		BEGIN
			IF(@lConfigValue='ReceiptBookWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId AND Id != @rId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			ELSE IF(@lConfigValue='PayTypeWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId AND Id != @rId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
		END 
	END
	ELSE
	BEGIN
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId,@rPayTypeId,@lConfigValue)
		Print @rReceiptNumber
	END	
EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rIsCreated = @lIsCreated OUTPUT
 	IF(@lIsCreated = 1)
 		BEGIN
			SELECT -501 AS Result
			RETURN
		END
 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

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

--IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
--			BEGIN
--				SELECT -102 AS Result
--				RETURN	
--			END

		--Added By Dhruv
			IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		--Added By Dhruv

	INSERT INTO sFee.tReceipt
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptNumber,
		   ReceiptDate,
		   ReceiptAmount,
		   TotalReceiptAmount,
		   DiscountAmount,
		   PayTypeId,
		   ChequeNo,
		   BankName,
		   ReceiptBookId,
		   Remark,
		   IsObsolete,
		   BatchId,
		   CreatedUserId,
		   CreatedDateTime,
		   OrgGroupBatchId,
		   ChequeDate,
		   FeeInvoiceId,
		   CollectionGroupId,
		   DepositedLedgerId,
		   PaymentTransactionId,
		   ReceiptPrintGroupId,
		   IsDiscountCoupon  ---Added By Dhruv for Issue . 0011150
        )
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
		    @rReceiptNumber,
		    @rReceiptDate,
		    @rReceiptAmount,
		    @rTotalReceiptAmount,
		    @rDiscountAmount,
		    @rPayTypeId,
		    @rChequeNo,
		    @rBankName,
		    @rReceiptBookId,
		    @rRemark,
		    @rIsObsolete,
		    @rBatchId,
		    @rCreatedUserId,
		    sCommon.fGetDate(),
		    @rOrgGroupBatchId,
		    @rChequeDate,
		    @rFeeInvoiceId,
		    @rCollectionGroupId,
		    @rDepositedLedgerId,
		    @rPaymentTransactionId,
			@rReceiptPrintGroupId,
			@rIsDiscountCoupon
		)
		
		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		
	FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
		IF (@rCharge > 0)
		BEGIN
		EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
		END
	
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) FROM sFee.tReceiptBookMaster where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
		EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
		END

		EXEC [sFee].[pFeeProcessGeneratePaidFeeAdd] @rOrgId,@rBatchId,@rSourceId,@lNextNumber,@rCreatedUserId
 END 
	ELSE
	IF EXISTS(SELECT 1 FROM sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND Id = @rId)
	BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
	SELECT @rId AS RESULT
	END 
	ELSE
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END

		BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptNumber = @rReceiptNumber,
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
	SELECT @rId AS RESULT
	END 
	END
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pRptFeePendingAllBatchGet]...';


GO
 
 
ALTER PROCEDURE [sFee].[pRptFeePendingAllBatchGet]
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rUptoDate date='',
		@rBatchId int='',
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)='',	
		@rBuilder2 nvarchar(max)='',
		@rIsDetail bit=0,
		@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) = '',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId  int=0,
		@rOrgGroupId int = 0,
		@rOrgIds nvarchar(max) = '',
		@rReportType int=1,    
	    @rClassStatusId int=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	
	DECLARE @p as TempPendingFee

	IF(@rReportType=1)
	BEGIN
	
		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,
	    RT.Pickup  AS Pickup,
		RT.DRoppoint As DRoppoint,
		SC.PresentContactNo
			
  FROM 
  
			 sStudent.vStudentAcademic SA
			 Left join [sStudent].[tStudentCommunication] SC ON SC.studentId=SA.studentId
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode
			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 
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			    AND ((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 ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA1.Code=@rCode) OR (@rCode=''))
				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 = FS1.ClassId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
		        AND ((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 ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA1.Code=@rCode) OR (@rCode=''))
		) 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)
			WHERE	
				(CAST(LEFT(SA1.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (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))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA1.Code=@rCode) OR (@rCode=''))
				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,B.Title As Pickup,B1.Title As DRoppoint 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))
	Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
    LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
 ) RT
    ON RT.SourceId = SA.StudentId 
    AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
    AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			(CAST(LEFT(SA.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
		   AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			    )
		   AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		   AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 	   
			Order by SA.RollNo
 
		SELECT
			@rBuilder1 AS Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			OrgId,			 
			ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			ReceiptOrderIndex,
			BatchId,
			BatchName,
		    Pickup,
			DRoppoint,
			PresentContactNo
			
			FROM @p 
			
			GROUP By 
			OrgId,AcademicId,ReceiptBookId,DivisionId,BatchId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,OrgName,ReceiptOrderIndex,BatchName,Pickup,DRoppoint,PresentContactNo
			ORDER BY AcademicId Desc
	END
	ELSE
	BEGIN
	
	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(FAS.FeeAmount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0) AS PendingAmount,
		--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(FAS.Remark,'') AS Remark,
		FS.ReceiptBookId,
		--FS.FeeName,
		FM.Title AS FeeName, 
		FM.Code AS FeeCode,
		--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,
	    RT.Pickup  AS Pickup,
		RT.DRoppoint As DRoppoint,
		SC.PresentContactNo
			
  FROM	 sStudent.vStudentAcademic SA
        INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sStudent.tStudentCommunication SC	ON SC.StudentId = SA.StudentId 
		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,B.Title As Pickup,B1.Title As DRoppoint 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))
	    Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
        LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
        ) RT
        ON RT.SourceId = SA.StudentId 
        AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
        AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	    WHERE	
			(CAST(LEFT(SA.OrgGroupBatchId, 4) AS int) = @rOrgGroupId OR @rOrgGroupId=0)
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			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 ISNULL(FAS.ToPayAmount,0) !=0
		   AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			    )
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		   AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		   AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 	  
			Order by SA.RollNo

			
				SELECT
			@rBuilder1 AS Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			OrgId,			 
			ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,
			RollNo, 
			Name,
			Code,
			ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			ReceiptOrderIndex,
			BatchId,
			BatchName,
		    Pickup,
			DRoppoint,
			PresentContactNo
			
			FROM @p 
			
			GROUP By 
			OrgId,AcademicId,ReceiptBookId,DivisionId,BatchId,
			ClassDivision,RollNo, Name,Code,ReceiptBookTitle,OrgName,ReceiptOrderIndex,BatchName,Pickup,DRoppoint,PresentContactNo
			ORDER BY AcademicId
	END
END
GO
PRINT N'Altering [sFee].[pRptFeePendingDetailListAsOnDateOtherGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptFeePendingDetailListAsOnDateOtherGet]
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rIsReceiptBookGroup bit=0,
		@rFeeHeadId nvarchar(max) = '',
	    @rIsDisplayOrgGroup bit=0,
	    @rFeeId nvarchar(max) = '',
	    @rFilterId int=0,
	    @rOrgIds nvarchar(max) = '',
		@rReportType int=1,
		@rClassStatusId int=0    
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
IF(@rReportType=1)
BEGIN
print '1'
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeName,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	FS.ReceiptBookId
			 END) AS ReceiptBookId,	
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.Title,'')
			 END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.OrderIndex,0)
			 END) AS ReceiptOrderIndex,	 
		--FS.ReceiptBookId,
		--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			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=FS1.ClassId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))				
				AND (R.ReceiptDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		  LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	
			 SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)	
			AND (SA.classstatusid = @rClassStatusId OR @rClassStatusId=0)		
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)			
			 AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     ) 	
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')	
			Order by SA.RollNo
END
ELSE
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0)AS PendingAmount,
		--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,
		FM.Title AS FeeName, 
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	FS.ReceiptBookId
			 END) AS ReceiptBookId,	
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.Title,'')
			 END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.OrderIndex,0)
			 END) AS ReceiptOrderIndex,	 
		--FS.ReceiptBookId,
		--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo
  FROM sStudent.vStudentAcademic SA  
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId	
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FAS.FeeSetupId AND FA.SourceId=SA.AcademicId 		
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	
			 SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)			
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND (SA.classstatusid = @rClassStatusId OR @rClassStatusId=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 ISNULL(FAS.ToPayAmount,0) !=0
			 AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     ) 	
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')	
			Order by SA.RollNo
END
 
END
GO
PRINT N'Altering [sFee].[pRptFeePendingDetailListGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptFeePendingDetailListGet]  

	@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) = '',  
	@rIsDetail bit=0,  
	@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) = '',  
	@rIsReceiptBookGroup bit=0,  
	@rFeeHeadId nvarchar(max) = '',  
	@rIsDisplayOrgGroup bit=0,  
	@rFeeId nvarchar(max) = '',  
	@rFilterId int=0,  
	@rOrgIds  nvarchar(max) = '',  
	@rPayDate date='',  
	@rCollectionGroupId int =0,  
	@rCastCategoryId int = 0,
	@rReportType int=0,
	@rClassStatusId int=0 ,
	@rCollectionGrupId nvarchar(max) ='' 
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 
	
	CREATE TABLE #TempIsOptional
	(
		FeeId int,  
		Id int,  
		IsOptional bit,  
		IsVariable bit,  
		Amount decimal(12,2),  
		StartDate date,  
		EndDate date,  
		BatchId int,  
		ReceiptBookId int,  
		AcademicId bigint,  
		FeeName nvarchar(100),  
		FeeHeadId int,
		CollectionGroupId int,
		CollectionGroup nvarchar(max)
	)
	
	INSERT INTO #TempIsOptional
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup      
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId   
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id      
			AND 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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE   
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))      
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=0)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')  

	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.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup       
		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.tAcademic SA1 ON SA1.Id=FO.SourceId   
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId  
			
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId 
		WHERE  
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=1)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')  
	 
	CREATE TABLE #TempReceipt
	(
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint  
	)
	
	INSERT INTO #TempReceipt
	SELECT   
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId  
	FROM  
		sFee.tReceipt R   
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId  
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId     
		AND (SA1.ClassId=@rClassId OR @rClassId=0)   
		AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
		AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)  
	WHERE    
		(R.SourceTypeId = 2001)  
		AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
		AND (R.IsObsolete = 0)   
		AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))  
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)  
		AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016  
		-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))  
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
		AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	GROUP BY FeeSetupId,R.SourceId  
	
	CREATE TABLE #TempAssignRoute
	(
		SourceId bigint  
	)
	
	INSERT INTO #TempAssignRoute
	SELECT 
		AT.SourceId 
	FROM 
		sTransport.tAssignRoute AT   
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
	
	IF(@rReportType=1)
	BEGIN	   
		SELECT   
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,  
		@rIsDetail AS IsDetail,  
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		SA.AcademicId,  
		SA.RollNo,  
		SA.Name,  
		SA.Code,  
		SA.ClassId,  
		SA.DivisionId,  
		SA.ClassName,  
		SA.DivisionName,  
		SA.DivisionOrder,  
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		FS.Id AS FeeSetupId,  
		ISNULL(FS.IsVariable,0)AS IsVariable,  
		ISNULL(FS.Amount,0)AS Amount,  
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,  
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,  
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,  
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,  
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,  
		ISNULL(R.PaidAmount,0) AS PaidAmount,  
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,  
		ISNULL(FA.Remark,'') AS Remark,  
		FS.FeeName,  
		FHM.Id AS FeeHeadId,  
		FHM.Title AS FeeHeadName,  
		FHM.OrderIndex AS FeeHeadOrderIndex,  
		SA.OrgId,  
		O.Title AS OrgName,  
		O.OrderIndex AS OrgOrderIndex,  
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0  
		WHEN @rIsReceiptBookGroup = 1 THEN FS.ReceiptBookId  
		END) AS ReceiptBookId,   
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'  
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.Title,'')  
		END) AS ReceiptBookTitle,  
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0  
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.OrderIndex,0)  
		END) AS ReceiptOrderIndex,    
		--FS.ReceiptBookId,  
		ISNULL(RBM.FullTitle,'') AS ReceiptBookFullTitle,
		ISNULL(RBM.Address1,'') AS RecieptBookAddress1,
		IsNULL(RBM.Address2,'') As RecieptBookAddress2,
		IsNULL(RBM.Remark1,'') As Remark1,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
		SA.OrgGroupBatchId,  
		SA.DepartmentId,  
		SA.DepartmentName,  
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,  
		ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark,  
		@rPayDate AS PayDate ,  
		ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId,  
		ISNULL(CCM.Title,'') AS CastCategoryName,  
		ISNULL(CCM.OrderIndex,'') AS CastCategoryOrderIndex,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate  ,
		FS.CollectionGroupId,
		FS.CollectionGroup,
		SA.BatchName 
	FROM   
		sStudent.vStudentAcademic SA  
		INNER JOIN #TempIsOptional FS ON FS.AcademicId=SA.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA  
		ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId  
		LEFT JOIN #TempReceipt R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId  
		INNER JOIN sSetup.tOrganizationMaster O ON   
		SA.OrgId = O.Id  
		INNER JOIN sFee.tReceiptBookMaster RBM   
		ON FS.ReceiptBookId=RBM.Id  
		LEFT JOIN sStudent.tStudentCommunication SC   
		ON SC.StudentId = SA.StudentId  
		LEFT JOIN sStudent.tStudentOther SO   
		ON SO.StudentId = SA.StudentId  
		LEFT JOIN sCommon.tCastCategoryMaster CCM   
		ON CCM.Id = SO.CastCategoryId    
		INNER JOIN sFee.tFeeHeadMaster FHM  
		ON FHM.Id = FS.FeeHeadId
		
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
		LEFT JOIN #TempAssignRoute RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
	WHERE   
		SA.OrgGroupBatchId = @rOrgGroupBatchId  
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
		AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
		AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		AND ((SA.Code=@rCode) OR (@rCode=''))  
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)     
		AND (  
				(@rFilterId = 0) -- All  
				OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
				OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
				OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')       
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0)) 
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  
	Order by SA.RollNo  
	END
	ELSE
	BEGIN
	SELECT   
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,  
		@rIsDetail AS IsDetail,  
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		SA.AcademicId,  
		SA.RollNo,  
		SA.Name,  
		SA.Code,  
		SA.ClassId,  
		SA.DivisionId,  
		SA.ClassName,  
		SA.DivisionName,  
		SA.DivisionOrder,  
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		FS.Id AS FeeSetupId,  
		ISNULL(FS.IsVariable,0)AS IsVariable,  
		ISNULL(FS.Amount,0)AS Amount,  
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,  
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,  
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,  
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,  
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,  
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0.00) PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,  
		--FS.FeeName,  
		FM.Title AS FeeName,  
		FHM.Id AS FeeHeadId,  
		FHM.Title AS FeeHeadName,  
		FHM.OrderIndex AS FeeHeadOrderIndex,  
		SA.OrgId,  
		O.Title AS OrgName,  
		O.OrderIndex AS OrgOrderIndex,  
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0  
		WHEN @rIsReceiptBookGroup = 1 THEN FS.ReceiptBookId  
		END) AS ReceiptBookId,   
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'  
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.Title,'')  
		END) AS ReceiptBookTitle,  
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0  
		WHEN @rIsReceiptBookGroup = 1 THEN ISNULL(RBM.OrderIndex,0)  
		END) AS ReceiptOrderIndex,    
		ISNULL(FS.ReceiptBookId,'0') As ReceiptBookId,  
		ISNULL(RBM.FullTitle,'') AS ReceiptBookFullTitle,
		ISNULL(RBM.Address1,'') AS RecieptBookAddress1,
		IsNULL(RBM.Address2,'') As RecieptBookAddress2,
		IsNULL(RBM.Remark1,'') As Remark1,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
		SA.OrgGroupBatchId,  
		SA.DepartmentId,  
		SA.DepartmentName,  
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,  
		ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark,  
		@rPayDate AS PayDate ,  
		ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId,  
		ISNULL(CCM.Title,'') AS CastCategoryName,  
		ISNULL(CCM.OrderIndex,'') AS CastCategoryOrderIndex,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		SA.BatchName    
	FROM   
		sStudent.vStudentAcademic SA		
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId	
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FAS.FeeSetupId AND FA.SourceId=SA.AcademicId  
		LEFT JOIN sStudent.tStudentCommunication SC	ON SC.StudentId = SA.StudentId  
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId  
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id 
		AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
	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 ISNULL(FAS.ToPayAmount,0.00) !=0
		AND (  
				(@rFilterId = 0) -- All  
				OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
				OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
				OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')       
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0))   
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')  
	Order by SA.RollNo  
	END
	
	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
	DROP TABLE #TempAssignRoute

	--SELECT   
	--	'' AS Builder1,  
	--	'' AS Builder2,  
	--	0 AS IsDetail,  
	--	0 As IsFilter,  
	--	0 As IsHeader,  
	--	0 AS IsDisplayOrgGroup,  
	--	1104000002505 AS AcademicId,  
	--	0 AS RollNo,  
	--	'' AS Name,  
	--	'' AS Code,  
	--	0 AS ClassId,  
	--	0 AS DivisionId,  
	--	'' AS ClassName,  
	--	'' AS DivisionName,  
	--	0 AS DivisionOrder,  
	--	'' AS ClassDivision,  
	--	0 AS FeeSetupId,  
	--	0 AS IsVariable,  
	--	0.00 AS Amount,  
	--	'2001-01-30' AS StartDate,  
	--	'2001-01-30' AS EndDate,  
	--	0.00 AS FAAmount,  
	--	0.00 AS DiscountAmount,  
	--	0.00 AS AdditionalAmount,  
	--	0.00 AS PaidAmount,
	--	0.00 PendingAmount,
	--	'' AS Remark,  
	--	'' AS FeeName,  
	--	0 AS FeeHeadId,  
	--	'' AS FeeHeadName,  
	--	0 AS FeeHeadOrderIndex,  
	--	0 AS OrgId,  
	--	'' AS OrgName,  
	--	0 AS OrgOrderIndex,  
	--	0 AS ReceiptBookId,   
	--	'' AS ReceiptBookTitle,  
	--	0 AS ReceiptOrderIndex,    
	--	0 As ReceiptBookId,  
	--	'' AS ReceiptBookFullTitle,
	--	'' AS RecieptBookAddress1,
	--	'' As RecieptBookAddress2,
	--	'' As Remark1,
	--	0 AS ReceiptOrderIndex,  
	--	0 AS OrgGoupBatchId,  
	--	0 AS DepartmentId,  
	--	'' AS DepartmentName,  
	--	'' AS ParentContactNo,  
	--	'' AS ReferenceRemark,  
	--	'2001-01-30' AS PayDate ,  
	--	0 AS CastCategoryId,  
	--	'' AS CastCategoryName,  
	--	0 AS CastCategoryOrderIndex,
	--	'' AS ReportTemplate,
	--0 As CollectionGroupId,
	--'' AS CollectionGroup,
	--'' AS BatchName

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


GO
 
 
ALTER PROCEDURE [sFee].[pRptFeePendingDetailListOtherGet]
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rIsReceiptBookGroup bit=0,
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '',
		@rReportType int=1,
		@rClassStatusId int=0 
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
IF(@rReportType=1)
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeId,
		FS.FeeName,
		FS.FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	FS.ReceiptBookId
			 END) AS ReceiptBookId,	
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.Title,'')
			 END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.OrderIndex,0)
			 END) AS ReceiptOrderIndex,	 
		--FS.ReceiptBookId,
		--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.Id AS AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
			AND 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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    BM.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (R.ReceiptDate <= @rUptoDate)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeHeadMaster FHM
			ON FHM.Id = FS.FeeHeadId	
	 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	
			 SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
				AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))	
			Order by SA.RollNo
END
ELSE
BEGIN
SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0)AS PendingAmount,
		--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(FAS.Remark,'') AS Remark,
		FS.FeeId,
		--FS.FeeName,
		FM.Title AS FeeName, 
		--FS.FeeOrderIndex,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	FS.ReceiptBookId
			 END) AS ReceiptBookId,	
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.Title,'')
			 END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.OrderIndex,0)
			 END) AS ReceiptOrderIndex,	 
		--FS.ReceiptBookId,
		--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo
  FROM  sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId	
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId		
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	
			 SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			--AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND ISNULL(FAS.ToPayAmount,0) !=0
			AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 	
			Order by SA.RollNo
END 
END
GO
PRINT N'Altering [sFee].[pRptFeePendingWithFeeNameGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptFeePendingWithFeeNameGet]
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rIsReceiptBookGroup bit=0	,
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '' ,
		@rReportType int=1,
		@rClassStatusId int=0       
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	IF(@rReportType=1)

		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,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		''
			
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			     (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode
			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 = FS1.ClassId 
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
		       (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  )
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
			LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.StudentId = SA.StudentId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		
	WHERE	
			(SA.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			  AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))    
			Order by SA.RollNo

	SELECT
			@rBuilder1 as Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookId
			 END) AS ReceiptBookId,	
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookTitle
			 END) AS ReceiptBookTitle,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptOrderIndex
			 END) AS ReceiptOrderIndex,	 
			
			OrgId,			 
			--ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,RollNo, Name,Code,
			--ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			Pickup AS ParentContactNo,
			DRoppoint AS StudentContactNo
			--ReceiptOrderIndex
			FROM @p 
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,
			ClassDivision,RollNo, Name,Code,
			ReceiptBookTitle,OrgName,ReceiptOrderIndex,Pickup,DRoppoint
			ORDER BY AcademicId

END

	ELSE
		BEGIN

	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(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0) AS PendingAmount,
		--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(FAS.Remark,'') AS Remark,
		FS.ReceiptBookId,
		--FS.FeeName,
		--FS.FeeCode,
		FM.Title AS FeeName, 
		FM.Code AS 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,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		''	
  FROM  sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		--LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=SF.FeeSetupId AND FA.SourceId=SA.AcademicId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId 
		
	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 ISNULL(FAS.ToPayAmount,0) !=0
			AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))    
			Order by SA.RollNo

	SELECT
			@rBuilder1 as Builder1,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookId
			 END) AS ReceiptBookId,	
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptBookTitle
			 END) AS ReceiptBookTitle,
			(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ReceiptOrderIndex
			 END) AS ReceiptOrderIndex,	 
			
			OrgId,			 
			--ReceiptBookId,
			AcademicId,
			DivisionId,
			ClassDivision,RollNo, Name,Code,
			--ReceiptBookTitle,
			OrgName,
			SUM(PendingAmount) AS PendingAmount, 
			[sFee].[fPendingFeeNamesGet](AcademicId,ReceiptBookId,	@p) AS PendingFeeName,
			Pickup AS ParentContactNo,
			DRoppoint AS StudentContactNo
			--ReceiptOrderIndex
			FROM @p 
			GROUP By ReceiptBookId,OrgId,AcademicId,DivisionId,
			ClassDivision,RollNo, Name,Code,
			ReceiptBookTitle,OrgName,ReceiptOrderIndex,Pickup,DRoppoint	
			ORDER BY AcademicId

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


GO
 
ALTER PROCEDURE [sFee].[pRptFeeReceiptListGet]  
  @rReportId int=0,  
  @rReceiptBookId int=0,  
  @rAdmissionCategoryId int=0,  
  @rClassId int=0,  
  @rDivisionId int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rFromReceiptNo int=0,  
  @rToReceiptNo int=0,  
  @rBatchId int,  
  @rUserId bigint=0,  
  @rBuilder1 nvarchar(max)=0,  
  @rBuilder2 nvarchar(max)=0,  
  @rIsDetail bit=0,  
  @rIsCancel bit=0,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int=0,  
  @rPaytypeId int=0,  
  @rCommonBatch nvarchar(100)='',  
  @rDepartmentId int=0,  
  @rFromRollNo int=0,  
     @rToRollNo int=0,  
     @rCode nvarchar(20),  
     @rIsFilter bit=0,  
     @rIsHeader bit=0,  
     @rCreatedUserName nvarchar(100)='',  
     @rFeeHeadId nvarchar(max) = '',  
     @rIsDisplayOrgGroup bit=0,  
     @rIsDiscount bit = 0,  
     @rFeeId nvarchar(max) = '',  
     @rFilterId int=0,  
     @rCustomGroupId smallint = 0,  
     @rOrgGroupId int=0,  
     @rFeeStatusId int=0,  
     @rFromChequeDate date='',      
  @rToChequeDate date='',      
     @rBankName nvarchar(100)='',  
     @rOrgIds nvarchar(max) = '',  
     @rBankNames nvarchar(max) = '',  
  
  @rFromChequeClearDate Date = '',  
  @rToChequeClearDate Date = '' ,
  @rClassStatusId int=0 ,
  @rPayTypeIds nvarchar(max) = '',
  @rUserAcessUserId bigint = 0
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   
  BEGIN      
  SET @rBankName = sCommon.fSearchStringGet(@rBankName)      
    END   
  IF(@rReportId=10138 OR @rReportId=20547 OR @rReportId=20456)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate,
		   ISNULL(SO.GenderId,0) AS GenderId   
		  FROM   
		   sFee.tReceipt R  
		  --INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  --INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  --INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
    
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
		  LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId

		  --According UserAccess
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =SA.OrgId
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND OM.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  

		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  
		  --According UserAccess
		  INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013 AND RBM.IsObsolete=0 AND UA.UserId =@rUserAcessUserId 


		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  AND (  
		  (@rFilterId = 0) -- All  
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
			AND ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')     
  
		 ORDER BY R.ReceiptNumber
	END
	ELSE
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate   
		  FROM   
		   sFee.tReceipt R  
		  --INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  --INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  --INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
    
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  AND (  
		  (@rFilterId = 0) -- All  
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
			AND ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')     
  
		 ORDER BY R.ReceiptNumber  
	END
 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END
GO
PRINT N'Altering [sFee].[pRptFeeStatusCollectionGroupWiseGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptFeeStatusCollectionGroupWiseGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rExemptionTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rFeeGroupId int=0,
		@rCollectionGroupId int = 0,
		@rClassStatusId int=0 --,
		--@rOrgIds nvarchar(max) = '' 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

CREATE TABLE #TempIsOptional
	(
		FeeId int,  
		Id int,  
		IsOptional bit,  
		IsVariable bit,  
		Amount decimal(12,2),  
		StartDate date,  
		EndDate date,  
		BatchId int,  
		ReceiptBookId int,  
		AcademicId bigint,  
		FeeName nvarchar(100),  
		FeeHeadId int,
		CollectionGroupId int,
		CollectionGroup nvarchar(max)
	)
	
	INSERT INTO #TempIsOptional
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup      
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId   
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id      
			AND 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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE   
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))      
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=0)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGroupId,','))OR @rCollectionGroupId='')  

	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.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup       
		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.tAcademic SA1 ON SA1.Id=FO.SourceId   
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId  
			
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId 
		WHERE  
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=1)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGroupId,','))OR @rCollectionGroupId='')  

	CREATE TABLE #TempReceipt
	(
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint  
	)
	
	INSERT INTO #TempReceipt
	SELECT   
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId  
	FROM  
		sFee.tReceipt R   
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId  
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId     
		AND (SA1.ClassId=@rClassId OR @rClassId=0)   
		AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
		AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)  
	WHERE    
		(R.SourceTypeId = 2001)  
		AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
		AND (R.IsObsolete = 0)   
		AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))  
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)  
		AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016  
		-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))  
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
	GROUP BY FeeSetupId,R.SourceId  

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		@rFeeGroupId As FeeGroup,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(CGM.OrderIndex,0) AS CollectionGroupOrderIndex,		
		CASE WHEN ROW_NUMBER() OVER (PARTITION BY SA.ClassId  ORDER BY SA.ClassId ) =1 THEN (SELECT COUNT(1) FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId WHERE A.ClassId= SA.ClassId AND A.BatchId = SA.BatchId  AND A.OrgId = SA.OrgId AND BM.OrgGroupBatchId = SA.OrgGroupBatchId GROUP BY ClassId) ELSE 0 END AS StudentCount,
		--CASE WHEN ROW_NUMBER() OVER (PARTITION BY SA.AcademicId  ORDER BY SA.AcademicId) =1 THEN (CASE WHEN (SUM(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) THEN 1 ELSE 0 END) ELSE 0 END AS PendingAmount

		( SELECT SUM(T.PaidCount) FROM 
		(SELECT 
			COUNT(DISTINCT(S1.Id)) AS PaidCount FROM sStudent.tAcademic S1
			INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=S1.Id  
		 INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
		INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS.ReceiptBookId=RBM1.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		GROUP BY S1.Id
		HAVING SUM(ISNULL(FAS.ToPayAmount,0.00)) = 0 
		) T )			
			AS PaidCount,
		( SELECT SUM(T.PendingCount) FROM 
		(SELECT 
			COUNT(DISTINCT(S1.Id)) AS PendingCount FROM sStudent.tAcademic S1
			INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=S1.Id  
		 INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
		INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS.ReceiptBookId=RBM1.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		GROUP BY S1.Id
		HAVING SUM(ISNULL(FAS.ToPayAmount,0.00)) > 0 
		) T )			
			AS PendingCount

		--( SELECT SUM(T.PaidCount) FROM (SELECT 
		--	COUNT(DISTINCT(S1.AcademicId)) AS PaidCount FROM sStudent.vStudentAcademic S1
		--	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,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		--		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))			
		--		WHERE 
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--			AND (FS1.IsOptional=0)
		--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))			 
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--			UNION ALL
				
		--		SELECT 
		--			FS1.FeeId,
		--			FS1.Id,
		--			ISNULL(FS1.IsOptional,0)AS IsOptional,
		--			ISNULL(FS1.IsVariable,0)AS IsVariable,
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--			FS1.BatchId,
		--			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		--			SA1.AcademicId,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--	INNER JOIN sFee.tFeeOptional FO
		--		ON FO.FeeSetupId=FS1.Id 
		--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--	INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		--	AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
		--	AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--WHERE
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--		AND (FS1.IsOptional=1)
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))							
		--	) FS ON FS.AcademicId=S1.AcademicId
		--	LEFT JOIN sFee.tFeeAllocation FA
		--		ON FA.FeeSetupId=FS.Id AND FA.SourceId=S1.AcademicId
		--	LEFT JOIN
		--	(
		--		SELECT 
		--				ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--		FROM
		--				sFee.tReceipt R 
		--			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
		--			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
		--			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
		--		WHERE		
		--			(R.SourceTypeId = 2001)
		--		AND (R.IsObsolete = 0) 
		--		AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		--		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND (R.ReceiptDate <= @rUptoDate)
		--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--				GROUP BY FeeSetupId,R.SourceId
		
		--	) R ON R.FeeSetupId = FS.Id AND S1.AcademicId = R.SourceId
		--	INNER JOIN sFee.tReceiptBookMaster RBM1
		--		ON FS.ReceiptBookId=RBM.Id
		--	LEFT JOIN sFee.tCollectionGroupMaster CGM1
		--		ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--	WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--	GROUP BY S1.AcademicId
		--HAVING SUM(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 
		--) T )			
		--	AS PaidCount,

		--	( SELECT SUM(T.PendingCount) FROM (SELECT 
		--	COUNT(DISTINCT(S1.AcademicId)) AS PendingCount FROM sStudent.vStudentAcademic S1
		--	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,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		--		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))			
		--		WHERE 
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--			AND (FS1.IsOptional=0)
		--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))			 
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--			UNION ALL
				
		--		SELECT 
		--			FS1.FeeId,
		--			FS1.Id,
		--			ISNULL(FS1.IsOptional,0)AS IsOptional,
		--			ISNULL(FS1.IsVariable,0)AS IsVariable,
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--			FS1.BatchId,
		--			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		--			SA1.AcademicId,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--	INNER JOIN sFee.tFeeOptional FO
		--		ON FO.FeeSetupId=FS1.Id 
		--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--	INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		--	AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
		--	AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--WHERE
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--		AND (FS1.IsOptional=1)
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))							
		--	) FS ON FS.AcademicId=S1.AcademicId
		--	LEFT JOIN sFee.tFeeAllocation FA
		--		ON FA.FeeSetupId=FS.Id AND FA.SourceId=S1.AcademicId
		--	LEFT JOIN
		--	(
		--		SELECT 
		--				ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--		FROM
		--				sFee.tReceipt R 
		--			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
		--			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
		--			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
		--		WHERE		
		--			(R.SourceTypeId = 2001)
		--		AND (R.IsObsolete = 0) 
		--		AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		--		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND (R.ReceiptDate <= @rUptoDate)
		--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--				GROUP BY FeeSetupId,R.SourceId
		
		--	) R ON R.FeeSetupId = FS.Id AND S1.AcademicId = R.SourceId
		--	INNER JOIN sFee.tReceiptBookMaster RBM1
		--		ON FS.ReceiptBookId=RBM.Id
		--	LEFT JOIN sFee.tCollectionGroupMaster CGM1
		--		ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--	WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--	GROUP BY S1.AcademicId
		--HAVING SUM(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 
		--) T )			
		--	AS PendingCount



  FROM 
  
			 sStudent.vStudentAcademic SA
		 INNER JOIN #TempIsOptional FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #TempReceipt R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM
			ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND	((CGM.Id=@rCollectionGroupId) OR (@rCollectionGroupId=0))   
		 AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )	
				 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
    --AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			     
			Order by SA.RollNo
			

	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
				

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


GO
 
ALTER PROCEDURE [sFee].[pRptFeeStatusNegativeGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0    
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.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(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0.00) AS PendingAmount,
		ISNULL(FAS.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FM.Title AS FeeName,
		SA.OrgId,
		SA.BatchId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex
		--,
		
			
  FROM 
  
			 sStudent.vStudentAcademic SA
		 INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		 INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
		 INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FAS.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	AND ((FS.EndDate <= @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(FAS.ToPayAmount,0.00) < 0
	 AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     ) 	
   AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
   AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))			     	
			Order by SA.Code,SA.RollNo
	
END
GO
PRINT N'Altering [sFee].[pRptPendingFeeMonthwiseGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptPendingFeeMonthwiseGet]
	 
		@rReportId int=0,
		@rReceiptBookId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rUptoDate date='',
		@rFromReceiptNo int=0,
		@rToReceiptNo int=0,
		@rBatchId int,
		@rUserId bigint=0,
		@rBuilder1 nvarchar(max)=0,
		@rBuilder2 nvarchar(max)=0,
		@rIsDetail bit=0,
		@rIsCancel bit=0,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int=0,
		@rPaytypeId int=0,
		@rCommonBatch nvarchar(100)='',
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20),
	    @rIsFilter bit=0,
	    @rIsHeader bit=0,
	    @rCreatedUserName nvarchar(100)='',
	    @rFeeHeadId nvarchar(max) = '',
	    @rIsDisplayOrgGroup bit=0,
	    @rFeeId nvarchar(max) = '',
	    @rFilterId int=0,
	    @rPayDate date='',--,
	    --@rOrgIds nvarchar(max) = ''
	    @rReportType int=1,
		@rClassStatusId int=0
	
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	
DECLARE @lStartMonth AS INT

SELECT @lStartMonth = MONTH(BM.FromDate) FROM sSetup.tBatchMaster BM WHERE BM.Id=@rBatchId

DECLARE @lMonth1 AS INT
DECLARE @lMonth2 AS INT
DECLARE @lMonth3 AS INT
DECLARE @lMonth4 AS INT
DECLARE @lMonth5 AS INT
DECLARE @lMonth6 AS INT
DECLARE @lMonth7 AS INT
DECLARE @lMonth8 AS INT
DECLARE @lMonth9 AS INT
DECLARE @lMonth10 AS INT
DECLARE @lMonth11 AS INT
DECLARE @lMonth12 AS INT

IF (@lStartMonth = 1)
BEGIN
	SET @lMonth1 = 1
	SET @lMonth2 = 2
	SET @lMonth3 = 3
	SET @lMonth4 = 4
	SET @lMonth5 = 5
	SET @lMonth6 = 6
	SET @lMonth7 = 7
	SET @lMonth8 = 8
	SET @lMonth9 = 9
	SET @lMonth10 = 10
	SET @lMonth11 = 11
	SET @lMonth12 = 12
END

ELSE IF (@lStartMonth = 2)
BEGIN
	SET @lMonth1 = 2
	SET @lMonth2 = 3
	SET @lMonth3 = 4
	SET @lMonth4 = 5
	SET @lMonth5 = 6
	SET @lMonth6 = 7
	SET @lMonth7 = 8
	SET @lMonth8 = 9
	SET @lMonth9 = 10
	SET @lMonth10 = 11
	SET @lMonth11 = 12
	SET @lMonth12 = 1
END

ELSE IF (@lStartMonth = 3)
BEGIN
	SET @lMonth1 = 3
	SET @lMonth2 = 4
	SET @lMonth3 = 5
	SET @lMonth4 = 6
	SET @lMonth5 = 7
	SET @lMonth6 = 8
	SET @lMonth7 = 9
	SET @lMonth8 = 10
	SET @lMonth9 = 11
	SET @lMonth10 = 12
	SET @lMonth11 = 1
	SET @lMonth12 = 2
END

ELSE IF (@lStartMonth = 4)
BEGIN
	SET @lMonth1 = 4
	SET @lMonth2 = 5
	SET @lMonth3 = 6
	SET @lMonth4 = 7
	SET @lMonth5 = 8
	SET @lMonth6 = 9
	SET @lMonth7 = 10
	SET @lMonth8 = 11
	SET @lMonth9 = 12
	SET @lMonth10 = 1
	SET @lMonth11 = 2
	SET @lMonth12 = 3
END

ELSE IF (@lStartMonth = 5)
BEGIN
	SET @lMonth1 = 5
	SET @lMonth2 = 6
	SET @lMonth3 = 7
	SET @lMonth4 = 8
	SET @lMonth5 = 9
	SET @lMonth6 = 10
	SET @lMonth7 = 11
	SET @lMonth8 = 12
	SET @lMonth9 = 1
	SET @lMonth10 = 2
	SET @lMonth11 = 3
	SET @lMonth12 = 4
END

ELSE IF (@lStartMonth = 6)
BEGIN
	SET @lMonth1 = 6
	SET @lMonth2 = 7
	SET @lMonth3 = 8
	SET @lMonth4 = 9
	SET @lMonth5 = 10
	SET @lMonth6 = 11
	SET @lMonth7 = 12
	SET @lMonth8 = 1
	SET @lMonth9 = 2
	SET @lMonth10 = 3
	SET @lMonth11 = 4
	SET @lMonth12 = 5
END

ELSE IF (@lStartMonth = 7)
BEGIN
	SET @lMonth1 = 7
	SET @lMonth2 = 8
	SET @lMonth3 = 9
	SET @lMonth4 = 10
	SET @lMonth5 = 11
	SET @lMonth6 = 12
	SET @lMonth7 = 1
	SET @lMonth8 = 2
	SET @lMonth9 = 3
	SET @lMonth10 = 4
	SET @lMonth11 = 5
	SET @lMonth12 = 6
END

ELSE IF (@lStartMonth = 8)
BEGIN
	SET @lMonth1 = 8
	SET @lMonth2 = 9
	SET @lMonth3 = 10
	SET @lMonth4 = 11
	SET @lMonth5 = 12
	SET @lMonth6 = 1
	SET @lMonth7 = 2
	SET @lMonth8 = 3
	SET @lMonth9 = 4
	SET @lMonth10 = 5
	SET @lMonth11 = 6
	SET @lMonth12 = 7
END

ELSE IF (@lStartMonth = 9)
BEGIN
	SET @lMonth1 = 9
	SET @lMonth2 = 10
	SET @lMonth3 = 11
	SET @lMonth4 = 12
	SET @lMonth5 = 1
	SET @lMonth6 = 2
	SET @lMonth7 = 3
	SET @lMonth8 = 4
	SET @lMonth9 = 5
	SET @lMonth10 = 6
	SET @lMonth11 = 7
	SET @lMonth12 = 8
END

ELSE IF (@lStartMonth = 10)
BEGIN
	SET @lMonth1 = 10
	SET @lMonth2 = 11
	SET @lMonth3 = 12
	SET @lMonth4 = 1
	SET @lMonth5 = 2
	SET @lMonth6 = 3
	SET @lMonth7 = 4
	SET @lMonth8 = 5
	SET @lMonth9 = 6
	SET @lMonth10 = 7
	SET @lMonth11 = 8
	SET @lMonth12 = 9
END

ELSE IF (@lStartMonth = 11)
BEGIN
	SET @lMonth1 = 11
	SET @lMonth2 = 12
	SET @lMonth3 = 1
	SET @lMonth4 = 2
	SET @lMonth5 = 3
	SET @lMonth6 = 4
	SET @lMonth7 = 5
	SET @lMonth8 = 6
	SET @lMonth9 = 7
	SET @lMonth10 = 8
	SET @lMonth11 = 9
	SET @lMonth12 = 10
END

ELSE IF (@lStartMonth = 12)
BEGIN
	SET @lMonth1 = 12
	SET @lMonth2 = 1
	SET @lMonth3 = 2
	SET @lMonth4 = 3
	SET @lMonth5 = 4
	SET @lMonth6 = 5
	SET @lMonth7 = 6
	SET @lMonth8 = 7
	SET @lMonth9 = 8
	SET @lMonth10 = 9
	SET @lMonth11 = 10
	SET @lMonth12 = 11
END

BEGIN


	CREATE TABLE #TempStudentPendingFee
	(
		[AcademicId] bigint NULL
	)

	IF(@rReportType=1)
		BEGIN    
	
			INSERT INTO #TempStudentPendingFee 
	SELECT 
	 	DISTINCT SA.AcademicId
    FROM 
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@rClassId) OR (@rClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=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 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=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))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			
		(SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (ISNULL(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.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))   

			SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.ClassId,
		SA.DivisionId,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.Code,
		SA.Name,
		SA.AdmissionCategoryId,

		[sCommon].[fGetMonthName](@lMonth1) AS Month1,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth1,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail1,

		[sCommon].[fGetMonthName](@lMonth2) AS Month2,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth2,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail2,

		[sCommon].[fGetMonthName](@lMonth3) AS Month3,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth3,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail3,

		[sCommon].[fGetMonthName](@lMonth4) AS Month4,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth4,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail4,

		[sCommon].[fGetMonthName](@lMonth5) AS Month5,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth5,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail5,

		[sCommon].[fGetMonthName](@lMonth6) AS Month6,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth6,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail6,

		[sCommon].[fGetMonthName](@lMonth7) AS Month7,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth7,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail7,

		[sCommon].[fGetMonthName](@lMonth8) AS Month8,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth8,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail8,

		[sCommon].[fGetMonthName](@lMonth9) AS Month9,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth9,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail9,

		[sCommon].[fGetMonthName](@lMonth10) AS Month10,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth10,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail10,

		[sCommon].[fGetMonthName](@lMonth11) AS Month11,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth11,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail11,

		[sCommon].[fGetMonthName](@lMonth12) AS Month12,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth12,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail12,
		
		@rPayDate AS PayDate
	
		
  FROM 
		  sStudent.vStudentAcademic SA
		  INNER JOIN #TempStudentPendingFee T ON T.AcademicId = SA.AcademicId
		   LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		  WHERE 
		(SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
				 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))   
		END
	ELSE
		BEGIN
		INSERT INTO #TempStudentPendingFee 
		SELECT 	DISTINCT SA.AcademicId  FROM  sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId AND FS.BatchId =SA.BatchId  AND FS.AdmissionCategoryId=SA.AdmissionCategoryId AND SA.ClassId=FS.ClassId
		WHERE (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		--AND (ISNULL(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 ISNULL(FAS.ToPayAmount,0) !=0
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND ((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))

		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.ClassId,
		SA.DivisionId,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		SA.RollNo,
		SA.Code,
		SA.Name,
		SA.AdmissionCategoryId,

		[sCommon].[fGetMonthName](@lMonth1) AS Month1,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth1,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail1,

		[sCommon].[fGetMonthName](@lMonth2) AS Month2,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth2,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail2,

		[sCommon].[fGetMonthName](@lMonth3) AS Month3,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth3,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail3,

		[sCommon].[fGetMonthName](@lMonth4) AS Month4,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth4,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail4,

		[sCommon].[fGetMonthName](@lMonth5) AS Month5,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth5,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail5,

		[sCommon].[fGetMonthName](@lMonth6) AS Month6,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth6,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail6,

		[sCommon].[fGetMonthName](@lMonth7) AS Month7,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth7,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail7,

		[sCommon].[fGetMonthName](@lMonth8) AS Month8,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth8,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail8,

		[sCommon].[fGetMonthName](@lMonth9) AS Month9,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth9,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail9,

		[sCommon].[fGetMonthName](@lMonth10) AS Month10,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth10,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail10,

		[sCommon].[fGetMonthName](@lMonth11) AS Month11,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth11,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail11,

		[sCommon].[fGetMonthName](@lMonth12) AS Month12,
		[sFee].[fPendingFeeAmountGet] (SA.AcademicId ,@rBatchId,@rOrgId,@rOrgGroupBatchId,@lMonth12,@rUptoDate,@rReceiptBookId,@rFeeId) AS Detail12,
		
		@rPayDate AS PayDate
	
		
  FROM 
		  sStudent.vStudentAcademic SA
		  INNER JOIN #TempStudentPendingFee T ON T.AcademicId = SA.AcademicId
		   LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		  WHERE 
		(SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
				 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))   
		END

END
		DROP TABLE #TempStudentPendingFee
END
GO
PRINT N'Altering [sFee].[pRptSummaryFeeStatusGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptSummaryFeeStatusGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	--@rFromRollNo int,
 --   @rToRollNo int,
   -- @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	
	  @rCollectionGroupId int =0 ,    
	  @rIsReceiptBook bit=0,
	  @rIsOrganization bit=0,
	  @rIsDepartment bit=0,
	  @rIsClass bit=0,
	  @rIsDivision bit=0,
	    @rReportType int=0,
		  @rClassStatusId int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

IF(@rReportType=1)
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		--SA.AcademicId,
		--SA.RollNo,
		--SA.Name,
		--SA.Code,
		
		
		SA.DivisionOrder AS DivisionOrderIndex,
		
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		
		ISNULL(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.FeeName,
		
	
	
	
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		@rFeeGroupId As FeeGroup,
		SA.OrgGroupBatchId AS BatchId,
		SA.BatchName AS BatchName,
		
		
          @rIsReceiptBook AS IsReceiptBook,
		  @rIsOrganization AS IsOrganization,
		  @rIsDepartment AS IsDepartment,
		  @rIsClass AS IsClass,
		  @rIsDivision AS IsDivision,
		 
		
		 -- Receipt Book
		 ISNULL(FS.ReceiptBookId,'0') As ReceiptBookId,  
		 ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		 ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex ,
		  -- Receipt Book
         
          -- Org
		  SA.OrgId,  
		  O.Title AS OrgName,  
		  O.OrderIndex AS OrgOrderIndex, 
		  -- Org
		  
		   -- Department
		 SA.DepartmentId,
		 SA.DepartmentName,
		  -- Department
		  
		  -- Class
		  SA.ClassId,  
		  SA.ClassName,  
		  SA.ClassOrderIndex ,  
		  -- Class
		  
		   --Division 
		  SA.DivisionId,  
		  SA.DivisionName, 
		  --Division
		  
		  --Amount
		  
		  ISNULL(R.PaidAmount,0) AS PaidAmount
		  --Amount
  
  FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
		AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		WHERE
			((FS1.ClassId=@rClassId) OR (@rClassId=0))
			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
			AND (FS1.IsOptional=1)
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
					sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
				INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				--AND (R.ReceiptDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
				AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		 --INNER JOIN sSetup.tDepartmentMaster DM  ON SA.DepartmentId=DM.Id  
		 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
		WHERE	
		((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
		AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
		--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		--AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		--AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
		AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )	
	AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
	AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
	AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	AND (tSA.AdmissionDate <= @rUptoDate)
	AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	Order by SA.RollNo 
	--GROUP BY 
	--FS.Id,ISNULL(FS.IsVariable,0),ISNULL(FS.Amount,0),ISNULL(FS.StartDate,'1900-01-01'),ISNULL(FS.EndDate,'1900-01-01'),ISNULL(FA.VariableAmount,0.00),ISNULL(FA.DiscountAmount,0.00),ISNULL(FA.AdditionalAmount,0.00),ISNULL(FA.NotApplicableAmount,0.00),ISNULL(FA.Remark,''),FS.FeeName,ExemptionTypeId,	SA.ExemptionTypeId,
	--	ISNULL(ETM.Title,''),
	--	FHM.Id,
	--	FHM.Title,
	--	FHM.OrderIndex,
		
	--	SA.OrgGroupBatchId,
	--	SA.BatchName,
	--FS.ReceiptBookId,RBM.Title,RBM.OrderIndex,RBM.OrderIndex,SA.OrgId,O.Title,O.OrderIndex,SA.DepartmentId,SA.DepartmentName,
 --   SA.ClassId,SA.ClassName,SA.ClassOrderIndex,SA.DivisionId,SA.DivisionName,SA.DivisionOrder,ISNULL(R.PaidAmount,0)
    
	
	
	 
	--Order by SA.RollNo
	
				
--	UNION ALL
	
--	SELECT 
--		R.Id AS ReceiptId,
--		0 AS ClassId,
--		--SA.ClassName,
--		0 AS DivisionId,
--		--SA.DivisionName,
--		EM.DepartmentId,
--		EM.DepartmentName AS ClassDept,
--		0 AS RollNo,
--		EM.Code,
--		EM.EmployeeName,
--		PTM.Title AS PayType,
--		R.ReceiptAmount
			
--  FROM 
--			sFee.tReceipt R
--		INNER JOIN sCommon.tSourceTypeMaster STM
--			ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95
--		INNER JOIN sHrm.vExtEmployeeMaster EM
--			ON EM.EmployeeId=R.SourceId
--		INNER JOIN sFinanceCommon.tPayTypeMaster PTM
--			ON PTM.Id=R.PayTypeId
			
--WHERE 
--		((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
--	AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
--	AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
--	AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
--	AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
--	AND (R.BatchId = @rBatchId)
END
ELSE
BEGIN
SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,		
		SA.DivisionOrder AS DivisionOrderIndex,		
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FM.Title AS FeeName,	
		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(FAS.VariableAmount,0.00)AS FAAmount,
		ISNULL(FAS.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FAS.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FAS.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0.00)AS PendingAmount,		
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		@rFeeGroupId As FeeGroup,
		SA.OrgGroupBatchId AS BatchId,
		SA.BatchName AS BatchName,		
		
          @rIsReceiptBook AS IsReceiptBook,
		  @rIsOrganization AS IsOrganization,
		  @rIsDepartment AS IsDepartment,
		  @rIsClass AS IsClass,
		  @rIsDivision AS IsDivision,	 
		
		 -- Receipt Book
		 ISNULL(FS.ReceiptBookId,'0') As ReceiptBookId,  
		 ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		 ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex ,
		  -- Receipt Book
         
          -- Org
		  SA.OrgId,  
		  O.Title AS OrgName,  
		  O.OrderIndex AS OrgOrderIndex, 	
		  
		   -- Department
		 SA.DepartmentId,
		 SA.DepartmentName,	
		  -- Class
		  SA.ClassId,  
		  SA.ClassName,  
		  SA.ClassOrderIndex , 
		  		 
		   --Division 
		  SA.DivisionId,  
		  SA.DivisionName 
		
  FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId	
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id		
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
		LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = 0) OR (0 = 0))  AND ((AR.OrgGroupBatchId = 0) OR (0 = 0)) 
        LEFT JOIN
		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = 0) OR (0 = 0))) RT
		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = 0) OR (0 = 0)) 
		WHERE	
		((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FAS.DiscountAmount,0) > 0))
		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
		AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
		AND (SA.StatusId=@rStatusId OR @rStatusId=0)		
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
		AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )	
	AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
	AND ((FS.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
	AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	AND (tSA.AdmissionDate <= @rUptoDate)
	AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	Order by SA.RollNo 
END
END
GO
PRINT N'Altering [sHrm].[pEmployeeDataUpdateGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pEmployeeDataUpdateGet]
	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rIsBlank bit,
	 @rStatusId int,
	 @rDepartmentId int,
	 @rGroupId int,
	 @rTypeId int,
	 @rGradeId int 
	  
	 --@rOrderBy int
	 
AS
SET NOCOUNT ON

BEGIN

		 DECLARE @lDataTypeId nvarchar(1)
		 IF(@rSubCategory = 'EmployeeBusinessHead')
		 BEGIN
			SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field='OrganizationHeadManager'
		 END
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		
		IF(@rSubCategory = 'MaritalStatus' OR @rSubCategory = 'Gender' OR @rSubCategory = 'Religion' OR @rSubCategory = 'BloodGroup'
		   OR @rSubCategory = 'OrganizationDepartment' OR @rSubCategory = 'EmployeeType' OR @rSubCategory = 'EmployeeBusinessHead'
			OR @rSubCategory = 'EmployeeGroup' OR @rSubCategory = 'EmployeeGrade' OR @rSubCategory = 'EmployeeDesignation'
			 OR @rSubCategory='Payroll' OR @rSubCategory='PayrollGroup'
			  OR @rSubCategory='OrgGroupDepartment'  OR @rSubCategory='EmployeeManager' OR @rSubCategory='CustomTag'
			 )
		BEGIN
			SET @rSubCategory = @rSubCategory + 'Id'
		END
		
		 ELSE IF ( @rSubCategory = 'CasteCategory')
			BEGIN 
		 		SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') + 'Id'
		 END
		 ELSE IF(@rSubCategory = 'NotEmployee')
		 BEGIN
		 SET @rSubCategory = Replace(@rSubCategory,'NotEmployee','IsOtherUser')
		 END

		
		 Declare @Sql nvarchar(max)
		 print @lDataTypeId
		 SET @Sql =  CASE @rCategoryId					  
					 WHEN 1 THEN -- EmployeeCommunication
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EC.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EC.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EC.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EC.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EC.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.EmployeeId 
							Where  ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15)) 
							
							+ 'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EC.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EC.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EC.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EC.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'
					 WHEN 2 THEN -- Other
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(EP.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(EP.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(EP.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(EP.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(EP.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId=EM.EmployeeId  
							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(EP.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(EP.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(EP.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(EP.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'
							
					WHEN 3 THEN -- JobDetail
					
					CASE WHEN  @rSubCategory ='EmployeeManagerId' then 
						
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
						CASE WHEN '+@lDataTypeId+'=1 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),'''')
						WHEN '+@lDataTypeId+'=2 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0'')
						WHEN '+@lDataTypeId+'=3 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''False'')
						WHEN '+@lDataTypeId+'=4 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN ISNULL((SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0'')
						END AS SubCategory 
							FROM 
							sHrm.vExtEmployeeMaster EM
							INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.EmployeeId  
							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL((SELECT CODE FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0),'''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL((SELECT CODE FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL((SELECT CODE FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL((SELECT CODE FROM sHrm.vExtEmployeeMaster WHERE EmployeeId=EJD.EmployeeManagerId AND ISNULL(IsOtherUser,0) = 0 ),''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'

							else

								'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
								CASE WHEN '+@lDataTypeId+'=1 THEN ISNULL(EJD.'+@rSubCategory+','''')
								WHEN '+@lDataTypeId+'=2 THEN ISNULL(EJD.'+@rSubCategory+',''0'')
								WHEN '+@lDataTypeId+'=3 THEN ISNULL(EJD.'+@rSubCategory+',''False'')
								WHEN '+@lDataTypeId+'=4 THEN ISNULL(EJD.'+@rSubCategory+',''0001/01/01'')
								WHEN '+@lDataTypeId+'=5 THEN ISNULL(EJD.'+@rSubCategory+',''0'')
								END AS SubCategory 
								FROM 
								sHrm.vExtEmployeeMaster EM
								INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.EmployeeId  
								Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
								+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
								AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
								AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
								AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
								AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
								AND 
									('+CAST(@rIsBlank AS nvarchar(1))+'=0 
									OR ('+@lDataTypeId+'=1 AND ISNULL(EJD.'+@rSubCategory+','''')='''')
									OR ('+@lDataTypeId+'=2 AND ISNULL(EJD.'+@rSubCategory+',''0'')=''0'')
									OR ('+@lDataTypeId+'=3 AND ISNULL(EJD.'+@rSubCategory+',''False'')=''False'')
									OR ('+@lDataTypeId+'=4 AND ISNULL(EJD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
								) ORDER BY EM.Number'
							end
					 
					WHEN 4 THEN --General
						
						CASE WHEN  @rSubCategory ='CustomTagId' then 

							'Select  EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,STUFF( (SELECT DISTINCT '','' + CTM.Title FROM sHrm.tEmployeeCustomTag ECT INNER JOIN sHrm.tCustomTagMaster CTM ON ECT.CustomTagId=CTM.Id 
							WHERE ECT.EmployeeId = EM.EmployeeId FOR XML PATH ('''')), 1, 1, '''')  AS SubCategory
							
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeeCustomTag ECT ON ECT.EmployeeId=EM.EmployeeId  
							LEFT JOIN sHrm.tCustomTagMaster CTM ON ECT.CustomTagId=CTM.Id

							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(ECT.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(ECT.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(ECT.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(ECT.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							GROUP BY EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,EM.Number ORDER BY EM.Number'
						else

						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
					    CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(HEM.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(HEM.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(HEM.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(HEM.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(HEM.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							INNER JOIN sHrm.tEmployeeMaster HEM ON HEM.Id=EM.EmployeeId  
							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(HEM.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(HEM.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(HEM.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(HEM.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'
				   
					     end
					
					WHEN 5 THEN --Statutory
						'Select EM.Id,EM.EmployeeId,EM.Code,EM.EmployeeName,EM.LastName,EM.EmployeeGroup,EM.DepartmentName,
					    CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(ESO.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(ESO.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(ESO.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(ESO.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(ESO.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sHrm.vExtEmployeeMaster EM
							LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId  
							Where ISNULL(EM.IsOtherUser,0) = 0 AND EM.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (EM.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (EM.DepartmentId='+ CAST(@rDepartmentId AS nvarchar(15)) +' OR '+CAST(@rDepartmentId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGroupId='+ CAST(@rGroupId AS nvarchar(15)) +' OR '+CAST(@rGroupId AS nvarchar(15))+'=0)
							AND (EM.EmployeeGradeId='+ CAST(@rGradeId AS nvarchar(15)) +' OR '+CAST(@rGradeId AS nvarchar(15))+'=0)
							AND (EM.EmployeeTypeId='+ CAST(@rTypeId AS nvarchar(15)) +' OR '+CAST(@rTypeId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(ESO.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(ESO.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(ESO.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(ESO.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							) ORDER BY EM.Number'
				   
					END
		print @Sql    
	    
	   EXECUTE  sp_executesql @Sql
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeProfileGet]...';


GO
 
 
ALTER PROCEDURE [sHrm].[pRptEmployeeProfileGet]
(

		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rPayrollId int,
		@rPayrollGroupId int,
		@rPayrollYearId int,
    	@rEmployeeId bigint,
		@rEmployeeCode nvarchar(200),
		@rEmployeeName nvarchar(200),
	    @rOrderByField nvarchar(20)='',
		@rOrgId int = 0,
		@rDepartmentId int = 0,
		@rStatusId int = 0
)
AS
SET NOCOUNT ON

BEGIN
		SELECT 
				@rOrderByField AS OrderByField,
				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,
				EM.EmployeeId AS EmployeeId,
				tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS Name,
				DM.Id AS DepartmentId,
				DM.Title AS DepartmentName,
				CONVERT(date,EJD.DateOfJoining) AS DateOfJoining,
				EM.Code AS Code,
				CONVERT(date,EJD.DateOfleaving) AS DateOfleaving,
				EDM.Title AS Designation,
				EPD.Qualification,
				EM.GenderTitle,
				CONVERT(date,EPD.DateOfBirth) AS DateOfBirth,
				EPD.UIDNumber,
				EC.PersonalEmail AS Email,
				ESO.BankName,
				ESO.AccountNumber,
				ESO.EPFNumber,
				ESO.PanNumber,
				EC.MobileNumber,
				ISNULL(DATEDIFF(YY,EJD.DateOfJoining,EJD.DateOfleaving),'')AS EXPYEAR,
				ISNULL(DATEDIFF(MM,EJD.DateOfJoining,EJD.DateOfleaving),'') AS EXPMONTH,
				EM.FirstName,
				EM.LastName,
				tEM.Number
		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.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
			INNER JOIN  sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.EmployeeId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EM.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
			INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		WHERE 
				(EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			AND((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			 AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			 AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
			 AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
			 AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			 AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
			 AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			 AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		END
GO
PRINT N'Altering [siTax].[pForm16IncomeTaxSlabDetailGet]...';


GO
 
 
ALTER PROCEDURE [siTax].[pForm16IncomeTaxSlabDetailGet]   
@rEmployeeId bigint,
@rAssesmentYearId bigint,
@rOrgGroupId int,
@rGrossAmount DECIMAL(18,2),
@rTaxDeducatedatsourceus192 DECIMAL(18,2)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	DECLARE @GenderId INT
	DECLARE @DateOfBirth DATE
	DECLARE @Age INT
	DECLARE @TaxPercentage DECIMAL(18,2) 
	DECLARE @TaxExeption DECIMAL(18,2)
	DECLARE @AmountFROM DECIMAL(18,2) 
	DECLARE @AmountTo DECIMAL(18,2)
	DECLARE @Count INT =0
	DECLARE @Counter INT =0
	DECLARE @TaxAmount DECIMAL(18,2)=0
	DECLARE @EducationCess DECIMAL(18,2)=0
	DECLARE @TaxPayable DECIMAL(18,2)=0
	DECLARE @ReliefUnderSection89 DECIMAL(18,2)=0
	DECLARE @TaxPayable2 DECIMAL(18,2)=0
	DECLARE @TaxSeductedAtSource192 DECIMAL(18,2)=0
	DECLARE @Balance DECIMAL(18,2)=0
	DECLARE @TaxCalculation DECIMAL(18,2)=0


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

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

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

	

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

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

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


			SELECT @TaxSeductedAtSource192=ISNULL(SUM(Amount),0) 
			FROM [siTax].[tIncomeTaxChallan] 
			WHERE 
			IsObsolete=0 
			AND AssesmentYearId=@rAssesmentYearId 
			AND EmployeeId=@rEmployeeId 
			AND OrgGroupId=@rOrgGroupId 
	

			
			SET @TaxSeductedAtSource192=@TaxSeductedAtSource192+@rTaxDeducatedatsourceus192
			
			IF(@rGrossAmount <= @AmountTo)
			BEGIN
			 
			 IF(@TaxAmount > @ReliefUnderSection89)
			 BEGIN
				SET @Balance=@TaxAmount-@ReliefUnderSection89
			 END
			 ELSE
			 BEGIN
				 SET @ReliefUnderSection89 = @TaxAmount
				 SET @Balance=@TaxAmount-@ReliefUnderSection89
			 END

			END
			ELSE 
			BEGIN
				SET @Balance = @TaxAmount
			END

 			IF @Balance < 0
			BEGIN			
			SET @Balance = 0
			END
			
			SET @EducationCess =(@Balance*4)/100
			SET @TaxPayable=@Balance
	
			--SET @TaxPayable2 =CASE WHEN @TaxPayable>@ReliefUnderSection89 AND @TaxAmount <= 350000  THEN  @TaxPayable-@ReliefUnderSection89 ELSE 0 END 
			SET @TaxPayable2 =@Balance+@EducationCess
			SET @Balance=@TaxPayable2-@TaxSeductedAtSource192

			print  @TaxPayable2
			print  @TaxSeductedAtSource192
			 
		END

	SELECT ISNULL(@TaxAmount,0) AS TaxAmount
	,ISNULL(@EducationCess,0) AS EducationCess3
	,ISNULL(@TaxPayable,0) AS TaxPayable
	,ISNULL(@ReliefUnderSection89,0) AS ReliefUnderSection89
	, ISNULL(@TaxPayable2,0) AS TaxPayable2
	,ISNULL(@TaxSeductedAtSource192,0) AS TaxSeductedAtSource192
	,ISNULL(@Balance,0) AS Balance
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeePaybillDetail]...';


GO
 

ALTER PROCEDURE [sPayroll].[pRptEmployeePaybillDetail]
	
	 @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,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rStatusId int = 0
	  
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		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,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		MM.Title AS MonthName,
		ISNULL(PPE.WorkingDays,0) AS WorkingDays,
		(ISNULL(PPE.WorkingDays,0) - ISNULL(PPE.Lwp,0)) AS PresentDays,
		--ISNULL(PPE.Lwp,0) AS AbsentDays,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
		tEM.FirstName,
		tEm.LastName,
		ISNULL(ESO.AccountHolderName,'')AS AccountHolderName,
		tEM.Number
		
	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 
	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 ((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 ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptEmployeePFDetail]...';


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

BEGIN 


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

	SELECT 
		@rOrderByField AS OrderByField,
		@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(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
	   (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID 
		--WHERE PS.PayrollId = @rPayrollId 
		--AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    PPE.TotalEarning,
	    EM.FirstName,
		EM.LastName,
		tEM.Number
	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
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId 
		--AND AT.ForMonth =PP.SalaryMonth AND AT.ForYear =PP.SalaryYear
		AND AT.ForMonth=PP.SalaryMonth AND AT.ForYear =PP.SalaryYear
		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 ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)	
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 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 ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))		
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
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,
	 @rOrderByField nvarchar(20)='',
	 @rMonths nvarchar(50)='',
	 @rOrgId int = 0,
	 @rStatusId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)

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

	SELECT
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		EM.EmployeeDesignation,
		EM.EmployeeGrade,
		ESO.EPFNumber,
		ESO.PanNumber,
		PPE.TotalEarning,		
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		PE.Amount As PPEAmount,
		P.Title AS PayElementTitle,
		P.ID AS PayElementId,
		P.PayElementTypeId,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber, 
		MM.Title AS MonthName,
		P.Title AS PayElementName,
		P.Code AS PayElementCode,
		(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.WorkingDays,@lMonthDay) else 0 END) AS WorkingDays,
		--ISNULL(EWD.WorkingDays,@lMonthDay) AS WorkingDays,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.Lwp else 0 END) AS Lwp,
		(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.PaidLeave,0) else 0 END) AS PaidLeave,
		P.SortOrder,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		PPE.GrossBasic,
		P.PayElementDefaultId,
		ISNULL(EPD.Qualification,'') AS Qualification,
		EJD.DateOfJoining AS DateOfAppointment,
		ISNULL(ESO.PayScale,'') AS PayScale,
		EPD.DateOfBirth,
		ISNULL(ROG.SelectableField,'') AS SelectableField,
		RGO.SchoolRequiredSignature ,
		RGO.SchoolRemark1,
		ISNULL(ESO.BasicPay,0) AS BasicPay,
		DAY(DATEADD(DD,-1,DATEADD(mm, DATEDIFF(mm, 0, CONVERT(DATE,CONVERT(nvarchar,PP.SalaryMonth) +'/01/'+CONVERT(nvarchar,PP.SalaryYear)) ) + 1, 0))) AS MonthDay,
		ESO.UAN,
		EPD.GenderId,
		ISNULL(PPR.Remark,'') AS PayProcessEmployeeRemark,
		tEM.FirstName,
		tEm.LastName,
		EM.DateOfJoining,
		OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
		ISNULL(REPLACE(REPLACE(
		(SELECT STUFF(
		(
		  SELECT  ' ' + Leave FROM -- create comma separated values
			(
					Select '<br>'+('<b>'+ LTM.Code +'</b>' +' - '+ CAST(SUM(CAST(L.NoOfLeave AS FLOAT)) AS varchar(50)) ) + '</br>'AS Leave 
					from 
					sHrm.tLeaveTypeMaster LTM  
					INNER JOIN sHrm.tLeave L ON  EM.EmployeeId = L.EmployeeId 
					INNER JOIN sCommon.tStatusMaster SM ON SM.Id=L.StatusId
					Where EM.EmployeeId=EM.EmployeeId AND LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0 
					AND LTM.Id = L.LeaveTypeId AND SM.Id=550
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					GROUP BY LTM.Code
					)AS T FOR XML PATH('')
		)
		,1,1,'')),'&lt;','<'),'&gt;','>')
		,'') AS LeaveCount,
		tEM.Number
		
	FROM 
	sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	LEFT JOIN sCommon.tReportOrgGroup ROG ON ROG.OrgGroupId=PY.OrgGroupId AND (ROG.ReportId = @rReportId OR @rReportId = 0) 
	LEFT JOIN sCommon.tReportRemarkGroupOrg RGO ON RGO.OrgId = tEM.OrgID AND RGO.ReportRemarkGroupId =  4
	LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
	AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
	left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	
	--LEFT JOIN sHrm.tEmployeeWorkingDays EWD ON tEM.Id = EWD.EmployeeId AND PP.SalaryMonth=EWD.ForMonth AND PP.SalaryYear=EWD.ForYear
where 
      (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND (P.IsObsolete=0)
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptMonthlyPFStatement]...';


GO
 
 

ALTER PROCEDURE [sPayroll].[pRptMonthlyPFStatement]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 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))
	 

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

	SELECT
		@rOrderByField AS OrderByField, 
		@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,
		ISNULL(PPE.TotalEarning,0) AS TotalEarning,
		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(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
	    (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND PGM.Id=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroup,
		EM.FirstName,
		EM.LastName,
		tEM.Number
	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		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
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForMonth=@rForMonth AND AT.ForYear =@rForYear
		--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) 
		AND PFPro.EmployeePfAmount!=0
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
		AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptMonthlyProfessoionTaxSummary]...';


GO
 
 
 
ALTER PROCEDURE [sPayroll].[pRptMonthlyProfessoionTaxSummary]
	
		@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,
		@rOrgId int = 0,
		@rStatusId int = 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))
		
 
		SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
		SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)

		SELECT
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2, 
			PTR.Id,
			PTR.Tax,
			ISNULL(A.NomberOfEmployee,0) AS NumberOfEmployee
		FROM 
			sPayroll.tProfessionalTaxRange PTR
		LEFT JOIN 
		(	
		SELECT 
			PTR.Id, COUNT(EM.EmployeeId) AS NomberOfEmployee ,PE.Amount
		FROM 
			sPayroll.tProfessionalTaxRange PTR
			INNER JOIN sPayroll.tPayProcess PP ON PP.PayrollYearId = PTR.PayrollYearId
			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 PayElementDefaultId = 57 
			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
		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 ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
			AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
			AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
			AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		GROUP BY 
			PTR.Id,EM.EmployeeId,PE.Amount
		) A ON A.Id = PTR.Id AND PTR.Tax = A.Amount
		WHERE PTR.PayrollYearId = @rPayrollYearId
		GROUP BY PTR.Id,PTR.Tax,A.NomberOfEmployee
		ORDER BY PTR.Tax
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)='',
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rIsDetail bit = 0,
	 @rStatusId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	
	DECLARE @lBasicPayElementId int
	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 
	@rOrderByField AS OrderByField,
	@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,
	EM.FirstName,
	EM.LastName,
	tEM.Number,
	OM.Id AS OrganizationId,
	OM.Title AS OrganizationTitle,
	OM.Code AS OrganizationCode,
	OM.OrderIndex AS OrganizationOrderIndex,
	@rIsDetail AS IsDetail

	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
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = tEM.OrgId
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='')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
END
GO
PRINT N'Altering [sPayroll].[pRptPaysheetDetail]...';


GO
 
 
 
ALTER PROCEDURE [sPayroll].[pRptPaysheetDetail]
	
	 @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,
	 @rOrgId int,
	 @rOrderByField nvarchar(20)='',
	 @rStatusId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
DECLARE @lOrgGroupId int = 0
DECLARE @lCurrencyCode nvarchar(20) = ''
    SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
	SELECT
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@lCurrencyCode AS CurrencyCode,
		@rForYear AS Foryear,
		(Select DateName( month , DateAdd( month ,@rForMonth, 0 ) - 1 )) AS ForMonth,
		(SELECT Title FROM sSetup.tOrganizationMaster  WHERE Id= EM.OrgId ) AS OrgName,
		(SELECT OG.Title FROM sSetup.tOrgGroupMaster OG INNER JOIN sSetup.tOrganizationMaster OM  ON OG.Id=OM.OrgGroupId WHERE OM.Id=EM.OrgId) AS TrustName,
		(SELECT SmallAddress1 FROM sSetup.tOrganizationMaster WHERE Id= EM.OrgId ) AS ReportAddress1,
		(SELECT SmallAddress2 FROM sSetup.tOrganizationMaster WHERE Id= EM.OrgId ) AS ReportAddress2,
	    (SELECT EM1.FirstName+' '+EM1.MiddleName+' ' +EM1.LastName From  sHrm.tEmployeeMaster EM1
			INNER JOIN sHrm.tEmployeeJobDetail EJ ON EM1.Id=EJ.EmployeeId
			INNER JOIN sHrm.tEmployeeDesignationMaster ED ON ED.Id=EJ.EmployeeDesignationId
			Where EJ.OrgId=EM.OrgID AND ED.Code='PRINCIPAL' AND  ISNULL(EM.IsOtherUser,0) = 0)AS HeadMasterName,
		
		10000 AS SalaryGrant,
		10000 AS RecoveryAdj,
		10000 AS GrossAmount,
		10000 AS TutionFees	,						
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=1 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS BasicPay,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=8 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS GradePay,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=2 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS DA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=4 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS HRA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=3 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS CLA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=18 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS TA,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=17 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS Differenc,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP 
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=56 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS PF,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS PT,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS TrSoc,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS NtrSoc,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=54 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS LIC,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=57 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS RD,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=52 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS IncomeTax,
			
		(SELECT sum(PE.Amount) FROM sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
			INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
			WHERE P.PayElementDefaultId=52 and PayrollId=@rPayrollId
			GROUP BY PE.PayElementId,P.code) AS Other,
			1 AS HM,
			1 AS AHM,
			1 AS Sup,
			1 AS TG,
			1 AS TUG,
			1 AS SplTr,
			1 AS OS,
			1 AS HC,
			1 AS SrCl,
			1 AS JrCl,
			1 AS Libr,
			1 AS LAs,
			1 AS LAt,
			1 AS Naik,
			1 AS Peon,
			1 AS SS,
			EM.FirstName,
		    EM.LastName,
			EM.OrgID
				
			
			
	FROM 
	sHrm.tEmployeeMaster EM
    INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.EmployeeId = EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId AND EM.IsObsolete = 0 
	INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id AND ODM.IsObsolete = 0
	WHERE ((EM.OrgID = @rOrgId) OR (@rOrgId = 0))
	AND (ODM.Id = @rDepartmentId OR @rDepartmentId = 0)
	AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptPFChallanDetailGet]...';


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

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

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

	SELECT 
		@rOrderByField AS OrderByField,
		@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(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
		(SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    --ISNULL(ESO.UAN,'') AS UAN,
	   -- PPE.TotalEarning,
	    OOD.PFEstablishmentCode,
	    OM.DisplayTitle AS OrganizationName,
	    OM.StreetOne + ' ' + OM.StreetTwo + ' ' + OM.StreetThree AS OrgAddress,
		OM.CityName AS OrgCity,
		OM.StateName AS OrgState,
		OM.CountryName AS OrgCountry,
		OM.ZipCode AS OrgZipCode,
		OM.HomePage AS OrgHomePage,
		OM.PhoneNo AS OrgPhoneNo,
		OM.RegistrationDetail AS OrgRegistrationDetail,
	    EM.FirstName,
		EM.LastName
		
	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
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForMonth=@rForMonth AND AT.ForYear =@rForYear
		INNER JOIN sSetup.tOrganizationOtherDetail OOD ON OOD.OrgId = EM.OrgID 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = OOD.OrgId
		--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) 
		--AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
  --      AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		--) 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) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
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,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

	SELECT 
		@rOrderByField AS OrderByField,
		@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(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
	   (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    PPE.TotalEarning,
	    EM.FirstName,
		EM.LastName,
		tEM.Number
	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
		--INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForMonth=@rForMonth AND AT.ForYear =@rForYear
		--INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = 0) OR (0 = 0))  AND ((AT.ForYear = 0) OR (0 = 0)) 
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = @rForMonth) OR (@rForMonth = 0))  AND ((AT.ForYear = @rForYear) OR (@rForYear = 0)) 
		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) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 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) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
END
GO
PRINT N'Altering [sPayroll].[pRptPFECRFormat]...';


GO
 

 
 
ALTER 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,
	 @rOrgGroupId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 0
	 
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))	

DECLARE @lIsActivateUniqueId bit = 0
DECLARE @lIsECRIsLWP nvarchar(10)

SELECT @lIsECRIsLWP = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 259 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

IF (@lIsECRIsLWP = '') OR (@lIsECRIsLWP = 'False')
	SET @lIsActivateUniqueId = 0
ELSE
	SET @lIsActivateUniqueId = 1

BEGIN  

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
	SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)
-- For report
	SELECT 
		@rOrderByField AS OrderByField,
		@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,
	    (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    CASE WHEN @lIsActivateUniqueId = 1 THEN ROUND(1+PPE.Lwp,0)-1 ELSE 0 END AS NCPDays,
	    ISNULL(A.TotalEarning,0) AS TotalEarning,
	    EM.FirstName,
		EM.LastName,
		tEM.Number
	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) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 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) 
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
--	For Notepad report
	
	SELECT 
		ISNULL(ESO.UAN,'') AS UAN,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		--ISNULL(cast(replace(A.TotalEarning, '.','') as integer),0) AS TotalEarning,
		ISNULL(CONVERT(DECIMAL(12,0),A.TotalEarning),0) AS TotalEarning,
		CASE WHEN ISNULL(PFS.PfSalaryLimit,0) > (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		THEN 
		--(SELECT ISNULL(SUM(cast(replace(PPE.Amount, '.','') as integer)),0) FROM sPayroll.tPayProcessElement PPE 
		(SELECT ISNULL(SUM(CONVERT(DECIMAL(12,0),PPE.Amount)),0) FROM sPayroll.tPayProcessElement PPE
		INNER JOIN sPayroll.tPayElement P ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId 
		IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		--ELSE ISNULL(cast(replace(PFS.PfSalaryLimit, '.','') as integer),0)  END AS PfSalaryLimit1,
		ELSE ISNULL(CONVERT(DECIMAL(12,0),PFS.PfSalaryLimit),0)  END AS PfSalaryLimit1,
		CASE WHEN ISNULL(PFS.PfSalaryLimit,0) > (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  THEN 
		--(SELECT ISNULL(SUM(cast(replace(PPE.Amount, '.','') as integer)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
		(SELECT ISNULL(SUM(CONVERT(DECIMAL(12,0),PPE.Amount)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		--ELSE ISNULL(cast(replace(PFS.PfSalaryLimit, '.','') as integer),0)  END AS PfSalaryLimit2,
		ELSE ISNULL(CONVERT(DECIMAL(12,0),PFS.PfSalaryLimit),0)  END AS PfSalaryLimit2,
		CASE WHEN ISNULL(PFS.PfSalaryLimit,0) > (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		)  
		--THEN (SELECT ISNULL(SUM(cast(replace(PPE.Amount, '.','') as integer)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P
		THEN (SELECT ISNULL(SUM(CONVERT(DECIMAL(12,0),PPE.Amount)),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		--)  ELSE ISNULL(cast(replace(PFS.PfSalaryLimit, '.','') as integer),0)  END AS PfSalaryLimit3,
		)  ELSE ISNULL(CONVERT(DECIMAL(12,0),PFS.PfSalaryLimit),0)  END AS PfSalaryLimit3,
		--ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit1,
		--ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit2,
		--ISNULL(PFS.PfSalaryLimit,0) AS PfSalaryLimit3,
		--ISNULL(cast(replace(PFPro.EmployeePfAmount, '.','') as integer),0) AS EmployeePfAmount,
		ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployeePfAmount),0) AS EmployeePfAmount,
		--ISNULL(cast(replace(PFPro.EmployerFpsAmount, '.','') as integer),0) AS EmployerFpsAmount,
		ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployerFpsAmount),0) AS EmployerFpsAmount,
		--ISNULL(cast(replace(PFPro.EmployeePfAmount, '.','') as integer),0) - ISNULL(cast(replace(PFPro.EmployerFpsAmount, '.','') as integer),0) AS EPFEPS,
		ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployeePfAmount),0) - ISNULL(CONVERT(DECIMAL(12,0),PFPro.EmployerFpsAmount),0) AS EPFEPS,
		--CASE WHEN @lIsActivateUniqueId = 1 THEN cast(replace(ROUND(1+PPE.Lwp,0)-1, '.','') as integer) ELSE 0 END AS NCPDays,
		CASE WHEN @lIsActivateUniqueId = 1 THEN Convert(DECIMAL(12,0),(1+PPE.Lwp)-1,0) ELSE 0 END 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) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 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) 		
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
END
GO
PRINT N'Altering [sRecruitment].[pCandidateDetailExportGet]...';


GO
 
ALTER PROCEDURE [sRecruitment].[pCandidateDetailExportGet]
(
		@rOrgGroupID smallint, 
		@rVacancyId int=0,		
		@rCandidateNumber int=0, 
		@rFirstName nvarchar(100), 
		@rLastName nvarchar(100),
		@rRecruitmentStatusId smallint,
		@rFromDate date=null,
		@rToDate date=null 
		
	
 )
AS
SET NOCOUNT ON

BEGIN
 
 		--SET @rCandidateNumber = ISNULL( sCommon.fSearchStringGet(@rCandidateNumber),0)
		SET @rFirstname = ISNULL( sCommon.fSearchStringGet(@rFirstname),'')
		SET @rLastName = ISNULL( sCommon.fSearchStringGet(@rLastName),'')
		
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				--RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				--RSL.RecruitmentStatusId AS RecruitmentStatusId
				CM.RecruitmentStatusId,
				GM.Title AS Gender,
				ISNULL(MS.Title,'') AS MaritalStatus,
				ISNULL(RM.Title,'') AS Religion,
				ISNULL(CCM.Title,'') AS CastCategory,
				ISNULL(CM.FamilyCast,'') AS FamilyCast,
				ISNULL(CM.Qualification,'')AS Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				CM.LastDrawnSalary,
				CM.ExpectedSalary,
				ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
				ISNULL([PresentStreetOne],'') AS PresentStreetOne,
				ISNULL([PresentStreetTwo],'') AS PresentStreetTwo,
				ISNULL([PresentStreetThree],'') AS PresentStreetThree,
				ISNULL([PresentCountry],'') AS PresentCountry,
				ISNULL([PresentState],'') AS PresentState,
				ISNULL([PresentCity],'') AS PresentCity,
				ISNULL([PresentZipCode],'') AS PresentZipCode,
				ISNULL([PresentContactNo],'') AS PresentContactNo,
				ISNULL([PermanentStreetOne],'') AS PermanentStreetOne,
				ISNULL([PermanentStreetTwo],'') AS PermanentStreetTwo,
				ISNULL([PermanentStreetThree],'') AS PermanentStreetThree,
				ISNULL([PermanentCountry],'') AS PermanentCountry,
				ISNULL([PermanentState],'') AS PermanentState,
				ISNULL([PermanentCity],'') AS PermanentCity,
				ISNULL([PermanentZipCode],'') AS PermanentZipCode,
				ISNULL([PermanentContactNo],'') AS PermanentContactNo,
				CM.CreatedDateTime
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			--LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId		
			--LEFT JOIN sRecruitment.tRecruitmentStatusLog  RSL  ON RSL.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			
			INNER JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id		
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id = CM.MaritalStatusId	
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId
			LEFT JOIN sRecruitment.tCandidateCommunications CC ON CC.CandidateId = CM.Id

		WHERE 
		--RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
		--		AND
				((CM.CandidateNumber=@rCandidateNumber ) OR (@rCandidateNumber = 0))
			AND ((CM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((CM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((VM.Id = @rVacancyId) OR (@rVacancyId = 0))	
			AND ((CM.RecruitmentStatusId = @rRecruitmentStatusId) OR (@rRecruitmentStatusId = 0))	
			AND CM.OrgGroupID = @rOrgGroupID
			AND ((CONVERT(date,CM.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,CM.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
			ORDER BY CM.CandidateNumber
END
GO
PRINT N'Altering [sSecurity].[pAppPermissionGet]...';


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

	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard 
			20097, -- View Query
			30249, -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786, --Online Learning 
			30787, --Online learning Student View
			30815, --Consolidate - Fee Status
			30813, --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930   -- Consolidate - Admission Inquiry Summary
			)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard
			20097, -- View Query
			30249,  -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786 , --Online Learning 
			30787,  --Online learning Student View
			30815,  --Consolidate - Fee Status
			30813,  --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930  -- Consolidate - Admission Inquiry Summary
			) 
		) TP 
		GROUP BY TP.TaskId
	END
END
GO
PRINT N'Altering [sStudent].[pXMLStudentImportAdd]...';


GO
 
ALTER PROCEDURE [sStudent].[pXMLStudentImportAdd]
	
	@rStudentImpXml [nvarchar](max),
	@rToOrgId int,
	@rToBatchId int,
	@rToClassId int,
	@rToDivisionId int,
	@rAdmissionDate date,
	@rCreatedUserId bigint,
	@rIsStudentOldCodeWithOrgId bit=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStudentImpXml
BEGIN

	
	DECLARE @lCount INT
	DECLARE @lNextNumber BIGINT 
	Declare @lExistCode nvarchar(max)
	DECLARE @MaxCode AS bigint
	
 
 
	IF EXISTS(SELECT SM.Code
	from
	(
			SELECT StudentId FROM
			OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			WITH (
					StudentId bigint)	
	)E
	INNER JOIN sStudent.tStudentMaster SM ON SM.ReferenceSourceId=E.StudentId AND SM.OrgId=@rToOrgId	
	)
	BEGIN
		SELECT @lExistCode  = COALESCE(@lExistCode ,'') + 'Old : '+ CONVERT(VARCHAR(15),E.Code) +' - ' + 'New : '+  SM.Code + ' , ' 
		from
		(
				SELECT StudentId,Code FROM
				OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
				WITH (
						StudentId bigint,
						Code nvarchar(20)
						)
		)E
		INNER JOIN sStudent.tStudentMaster SM ON SM.ReferenceSourceId=E.StudentId AND SM.OrgId=@rToOrgId	
		SELECT @lExistCode
		RETURN
	END
	
	--BEGIN TRY
	--BEGIN TRANSACTION

	EXECUTE sCommon.pTableRowIdGet @rToOrgId, 'sStudent.tStudentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	SELECT @MaxCode = MAX(Number) FROM sStudent.tStudentMaster WHERE OrgId = @rToOrgId
	--SET @MaxCode = ISNULL(@MaxCode,0) + 1
	
	IF(@rIsStudentOldCodeWithOrgId = 0)
	BEGIN
	SELECT 
			@lNextNumber + ROW_NUMBER() OVER(ORDER BY E.StudentId)AS NewStudentId,
			E.StudentId,
			ISNULL(@MaxCode,0) + ROW_NUMBER() OVER(ORDER BY E.StudentId) AS Code,			
			AdmissionCategoryId
	INTO 
			sStudent.tTempStudentId
	from
	(
			SELECT StudentId,AdmissionCategoryId,Code FROM
			OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			WITH (
					StudentId bigint,
					AdmissionCategoryId int,
					Code nvarchar(20)
					)	
	)E
	END
	ELSE IF (@rIsStudentOldCodeWithOrgId = 1)
	BEGIN
	SELECT 
			@lNextNumber + ROW_NUMBER() OVER(ORDER BY E.StudentId)AS NewStudentId,
			E.StudentId,
			CONVERT(NVARCHAR(4),LEFT(E.StudentId,4)) + E.Code AS Code,
			AdmissionCategoryId
	INTO 
			sStudent.tTempStudentId
	from
	(
			SELECT StudentId,AdmissionCategoryId,Code FROM
			OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			WITH (
					StudentId bigint,
					AdmissionCategoryId int,
					Code nvarchar(20)
					)	
	)E
	END

	SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
				 WITH ( Id int )
	SET @lNextNumber  = @lCount + @lNextNumber 
	
	EXECUTE sCommon.pTableRowIdModify @rToOrgId, @rTableTitle = 'sStudent.tStudentMaster', @rCurrentNumber = @lNextNumber 
		 print 'Academic'
	--Insert Into Student Master
	INSERT INTO sStudent.tStudentMaster
	(
			Id,
			Code,
			Number,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			StatusId,
			RecordStatusId,
			CreatedUserId,
			CreatedDateTime,
			ReferenceSourceId,
			AdmissionCategoryId,
			RegistrationNumber,
			IsBlackList,
			BlackListReason,
			SUId
		
	)
	SELECT 
			TS.NewStudentId,
			TS.Code,
			CASE WHEN ISNUMERIC(TS.Code) <> 0 THEN TS.Code ELSE TS.NewStudentId END,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			@rToOrgId,
			1,
			502,
			@rCreatedUserId,
			sCommon.fGetDate(),
			TS.StudentId,
			SM.AdmissionCategoryId,
			SM.RegistrationNumber,
			SM.IsBlackList,
			SM.BlackListReason,
			SM.SUId
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentMaster SM ON SM.ID=TS.StudentId
		
	--Insert Into Academic
		
	EXECUTE sCommon.pTableRowIdGet @rToOrgId, 'sStudent.tAcademic', 0, 1, 1,@outNextNumber = @lNextNumber output
 print 'Academic'
	INSERT INTO sStudent.tAcademic
	(
			Id,
			StudentId,
			ClassId,
			BatchId,
			DivisionId,
			RollNo,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			AdmissionCategoryId,
			ClassStatusId
	)
	SELECT
			@lNextNumber+ ROW_NUMBER() OVER(ORDER BY StudentId),
			NewStudentId,
			@rToClassId,
			@rToBatchId,
			@rToDivisionId,
			0,
			@rToOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			AdmissionCategoryId,
			1
	FROM 
			sStudent.tTempStudentId

print 'Academic1'		
	SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			 WITH ( Id int )
	SET @lNextNumber  = @lCount + @lNextNumber 
	
	EXECUTE sCommon.pTableRowIdModify @rToOrgId, @rTableTitle = 'sStudent.tAcademic', @rCurrentNumber = @lNextNumber 
	
	--Insert Into Student Other
	INSERT INTO sStudent.tStudentOther
	(
		   [StudentId]
		  ,[UIDNumber]
		  ,[DateOfBirth]
		  ,[BirthDateInWord]
		  ,[TransportModeId]
		  ,[GenderId]
		  ,[BloodGroupId]
		  ,[BirthPlace]
		  ,[BirthTaluka]
		  ,[BirthDistrict]
		  ,[FamilyCast]
		  ,[FamilySubCast]
		  ,[CastCategoryId]
		  ,[ReligionId]
		  ,[HouseId]
		  ,[MotherTongueId]
		  ,[NationalityId]
		  ,[Hobby]		   
		  ,[CreatedUserId]
		  ,[CreatedDateTime]
		  ,ReferenceRemark
		  ,AdhaarNumber
		  ,MotherTongue
		  ,QuotaId
		  ,BirthState
		  ,BirthCountry
	)
	SELECT 
		   TS.NewStudentId
		  ,SO.[UIDNumber]
		  ,SO.[DateOfBirth]
		  ,SO.[BirthDateInWord]
		  ,SO.[TransportModeId]
		  ,SO.[GenderId]
		  ,SO.[BloodGroupId]
		  ,SO.[BirthPlace]
		  ,SO.[BirthTaluka]
		  ,SO.[BirthDistrict]
		  ,SO.[FamilyCast]
		  ,SO.[FamilySubCast]
		  ,SO.[CastCategoryId]
		  ,SO.ReligionId		   
		  ,NULL
		  ,so.MotherTongueId
		  ,So.NationalityId		 
		  ,SO.[Hobby] 
		  ,@rCreatedUserId
		  ,sCommon.fGetDate()
		  ,ReferenceRemark
		  ,AdhaarNumber
		  ,MotherTongue
		  ,QuotaId
		  ,BirthState
		  ,BirthCountry
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=TS.StudentId
	
	--Insert Into Student Admission
	INSERT INTO sStudent.tStudentAdmission
	(
		   [StudentId]
		  ,[PreviousStudentId]
		  ,[AdmissionStandardId]
		  ,[AdmissionDate]
		  ,[AdmissionYear]
		  ,[BatchId]
		  ,[CreatedUserId]
		  ,[CreatedDateTime]
		  ,PreviousSchool
	)
	SELECT 
		   TS.NewStudentId
		  ,TS.StudentId
		  ,@rToClassId
		  ,@rAdmissionDate
		  ,YEAR(GETDATE())
		  ,@rToBatchId
		  ,@rCreatedUserId
		  ,sCommon.fGetDate()
		  ,PreviousSchool
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId=TS.StudentId
	
	
INSERT INTO [sStudent].[tStudentCommunication]
           ([StudentId]
           ,[PresentStreetOne]
           ,[PresentStreetTwo]
           ,[PresentStreetThree]
           ,[PresentCountry]
           ,[PresentState]
           ,[PresentCity]
           ,[PresentZipCode]
           ,[PresentContactNo]
           ,[PermanentStreetOne]
           ,[PermanentStreetTwo]
           ,[PermanentStreetThree]
           ,[PermanentCountry]
           ,[PermanentState]
           ,[PermanentCity]
           ,[PermanentZipCode]
           ,[PermanentContactNo]
           ,[EmergencyStreetOne]
           ,[EmergencyStreetTwo]
           ,[EmergencyStreetThree]
           ,[EmergencyCountry]
           ,[EmergencyState]
           ,[EmergencyCity]
           ,[EmergencyZipCode]
           ,[EmergencyContactNo]
           ,[ParentContactNo]
           ,[ParentEmail]
           ,[StudentContactNo]
           ,[StudentEmail]
           ,[CreatedUserId]
           ,[CreatedDateTime]  
		   ,PresentDistanceFromSchool)
		
 
 SELECT 
			TS.NewStudentId
           ,[PresentStreetOne]
           ,[PresentStreetTwo]
           ,[PresentStreetThree]
           ,[PresentCountry]
           ,[PresentState]
           ,[PresentCity]
           ,[PresentZipCode]
           ,[PresentContactNo]
           ,[PermanentStreetOne]
           ,[PermanentStreetTwo]
           ,[PermanentStreetThree]
           ,[PermanentCountry]
           ,[PermanentState]
           ,[PermanentCity]
           ,[PermanentZipCode]
           ,[PermanentContactNo]
           ,[EmergencyStreetOne]
           ,[EmergencyStreetTwo]
           ,[EmergencyStreetThree]
           ,[EmergencyCountry]
           ,[EmergencyState]
           ,[EmergencyCity]
           ,[EmergencyZipCode]
           ,[EmergencyContactNo]
           ,[ParentContactNo]
           ,[ParentEmail]
           ,[StudentContactNo]
           ,[StudentEmail]
           ,@rCreatedUserId
           ,sCommon.fGetDate()
		   ,PresentDistanceFromSchool
        
	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN [sStudent].[tStudentCommunication] SA ON SA.StudentId=TS.StudentId          
	
	
	
	INSERT INTO  [sStudent].[tStudentFamily]
           ([StudentId]
           ,[FatherName]
           ,[FatherDateOfBirth]
           ,[FatherOccupation]
           ,[FatherQualification]
           ,[FatherContactNo]
           ,[FatherMail]
           ,[FatherOfficeAddress]
           ,[FatherIncome]
           ,[MotherName]
           ,[MotherDateOfBirth]
           ,[MotherOccupation]
           ,[MotherQualification]
           ,[MotherContactNo]
           ,[MotherMail]
           ,[MotherOfficeAddress]
           ,[MotherIncome]
           ,[RelationshipName]
           ,[RelativeName]
           ,[RelativeDateOfBirth]
           ,[RelativeOccupation]
           ,[RelativeQualification]
           ,[RelativeContactNo]
           ,[RelativeMail]
           ,[RelativeOfficeAddress]
           ,[RelativeIncome]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,[MarriageAnniversaryDate]
		   ,LiveWithId
		   ,IsFatherExStudent
		   ,FatherPassOutYear
		   ,IsMotherExStudent
		   ,MotherPassOutYear
		   ,IsRelativeExStudent
		   ,RelativePassOutYear)
     SELECT    
			TS.NewStudentId
           ,[FatherName]
           ,[FatherDateOfBirth]
           ,[FatherOccupation]
           ,[FatherQualification]
           ,[FatherContactNo]
           ,[FatherMail]
           ,[FatherOfficeAddress]
           ,[FatherIncome]
           ,[MotherName]
           ,[MotherDateOfBirth]
           ,[MotherOccupation]
           ,[MotherQualification]
           ,[MotherContactNo]
           ,[MotherMail]
           ,[MotherOfficeAddress]
           ,[MotherIncome]
           ,[RelationshipName]
           ,[RelativeName]
           ,[RelativeDateOfBirth]
           ,[RelativeOccupation]
           ,[RelativeQualification]
           ,[RelativeContactNo]
           ,[RelativeMail]
           ,[RelativeOfficeAddress]
           ,[RelativeIncome]
           ,@rCreatedUserId
           ,sCommon.fGetDate()
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,[MarriageAnniversaryDate]
		   ,LiveWithId
		   ,IsFatherExStudent
		   ,FatherPassOutYear
		   ,IsMotherExStudent
		   ,MotherPassOutYear
		   ,IsRelativeExStudent
		   ,RelativePassOutYear
   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentFamily SA ON SA.StudentId=TS.StudentId    


INSERT INTO  [sStudent].[tStudentHealth]
           ([StudentId]
           ,[IdentificationMark1]
           ,[IdentificationMark2]
           ,[IsPysicalDeformity]
           ,[PysicalDeformityRemark]
           ,[IsMajorIllness]
           ,[MajorIllnessRemark]
           ,[IsAllergy]
           ,[AllergyRemark]
           ,[IsPastHistory]
           ,[PastHistoryRemark]
           ,[FamilyDoctorName]
           ,[FamilyDoctorContactNo]
           ,[UpdatedUserId]
           ,[UpdatedDateTime])
SELECT

			TS.NewStudentId
           ,[IdentificationMark1]
           ,[IdentificationMark2]
           ,[IsPysicalDeformity]
           ,[PysicalDeformityRemark]
           ,[IsMajorIllness]
           ,[MajorIllnessRemark]
           ,[IsAllergy]
           ,[AllergyRemark]
           ,[IsPastHistory]
           ,[PastHistoryRemark]
           ,[FamilyDoctorName]
           ,[FamilyDoctorContactNo]
           ,@rCreatedUserId
           ,sCommon.fGetDate()

   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentHealth SA ON SA.StudentId=TS.StudentId 
		
		
		INSERT INTO  [sStudent].[tStudentImages]
           ([StudentId]
           ,[StudentPhoto]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,[UpdatedDateTime])
           
           SELECT           
            TS.NewStudentId
           ,[StudentPhoto]
           ,[FatherPhoto]
           ,[MotherPhoto]
           ,[RelativePhoto]
           ,sCommon.fGetDate()
         	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentImages SA ON SA.StudentId=TS.StudentId    
		
		
		
		INSERT INTO [sStudent].[tStudentAdditional]
           (StudentId,
			BankAccountNumber,
			BankName,
			BankBranch,
			BankIFSCCode,
			Class9BoardRegistrationNumber,
			Class11BoardRegistrationNumber,
			PassportNumber,
			PassportType,
			PassportCountryCode,
			PassportIssueDate,
			PassportExpiryDate
           )
           
           SELECT           
            TS.NewStudentId,
            BankAccountNumber,
            BankName,
			BankBranch,
			BankIFSCCode,
			Class9BoardRegistrationNumber,
			Class11BoardRegistrationNumber,
			PassportNumber,
			PassportType,
			PassportCountryCode,
			PassportIssueDate,
			PassportExpiryDate
         	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentAdditional SA ON SA.StudentId=TS.StudentId        
	    

		---Studen Sibling Detail-
			
		INSERT INTO [sStudent].[tStudentSibling]
           (StudentId,
			SiblingName1,
			SiblingInstitue1,
			SiblingClass1,
			SiblingAge1,
			SiblingRelation1,
			SiblingName2,
			SiblingInstitue2,
			SiblingClass2,
			SiblingAge2,
			SiblingRelation2,
			SiblingName3,
			SiblingInstitue3,
			SiblingClass3,
			SiblingAge3,
			SiblingRelation3

           )
           
           SELECT           
            TS.NewStudentId,
            SiblingName1,
			SiblingInstitue1,
			SiblingClass1,
			SiblingAge1,
			SiblingRelation1,
			SiblingName2,
			SiblingInstitue2,
			SiblingClass2,
			SiblingAge2,
			SiblingRelation2,
			SiblingName3,
			SiblingInstitue3,
			SiblingClass3,
			SiblingAge3,
			SiblingRelation3
         	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN [sStudent].[tStudentSibling] SA ON SA.StudentId=TS.StudentId        

		INSERT INTO  [sStudent].[tCollegeDetail]
            (StudentId,
			AdmissionNumber,
			IsTransfer,
			TransferFrom,
			PassingYear,
			IsTFWS,
			IsCertificateHolder,
			CertificateName,
			SSCBoard,
			SSCSchool,
			SSCPassingYear,
			SSCObtainMarks,
			SSCOutOfMarks,
			SSCPercentage,
			SSCMathMarks,
			SSCMathOutOfMarks,
			HSCBoard,
			HSCSchool,
			HSCPassingYear,
			HSCObtainMarks,
			HSCOutOfMarks,
			HSCPercentage,
			HSCPhysicsMarks,
			HSCPhysicsOutOfMarks,
			HSCChemistryMarks,
			HSCChemistryOutOfMarks,
			HSCMathMarks,
			HSCMathOutOfMarks,
			HSCBiologyMarks,
			HSCBiologyOutOfMarks,
			PCMMarks,
			PCBMarks,
			JEERollNo,
			JEEMeritNo,
			JEEMeritMarks,
			JEEOutOfMarks,
			DiplomaBoard,
			DiplomaCollege,
			DiplomaPassingYear,
			DiplomaObtainMarks,
			DiplomaOutOfMarks,
			DiplomaPercentage,
			ApplicationNo,
			AdmissionRound,
			MaritalStatusId
)
SELECT

			TS.NewStudentId,
            AdmissionNumber,
			IsTransfer,
			TransferFrom,
			PassingYear,
			IsTFWS,
			IsCertificateHolder,
			CertificateName,
			SSCBoard,
			SSCSchool,
			SSCPassingYear,
			SSCObtainMarks,
			SSCOutOfMarks,
			SSCPercentage,
			SSCMathMarks,
			SSCMathOutOfMarks,
			HSCBoard,
			HSCSchool,
			HSCPassingYear,
			HSCObtainMarks,
			HSCOutOfMarks,
			HSCPercentage,
			HSCPhysicsMarks,
			HSCPhysicsOutOfMarks,
			HSCChemistryMarks,
			HSCChemistryOutOfMarks,
			HSCMathMarks,
			HSCMathOutOfMarks,
			HSCBiologyMarks,
			HSCBiologyOutOfMarks,
			PCMMarks,
			PCBMarks,
			JEERollNo,
			JEEMeritNo,
			JEEMeritMarks,
			JEEOutOfMarks,
			DiplomaBoard,
			DiplomaCollege,
			DiplomaPassingYear,
			DiplomaObtainMarks,
			DiplomaOutOfMarks,
			DiplomaPercentage,
			ApplicationNo,
			AdmissionRound,
			MaritalStatusId

   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tCollegeDetail SA ON SA.StudentId=TS.StudentId 

		-- -Student Custom Tag-
		INSERT INTO [sStudent].[tStudentCustomTag]
           (StudentId,CustomTagId
           )
SELECT

			TS.NewStudentId,CustomTagId
       
   	FROM
			sStudent.tTempStudentId TS	
		INNER JOIN sStudent.tStudentCustomTag SA ON SA.StudentId=TS.StudentId 
		

	    -- for update hostel 
	    -- Start
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tAssignRoom A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tAssignRoomAsset A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tAttendanceRegister A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tChangeRoom A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sHostel.tHostelAdmission A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tHostelDepositAdd A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tHostelDepositAdjustment A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tHostelDepositRefund A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.StudentId = T.NewStudentId 
		--FROM sHostel.tStudentGatePass A JOIN sStudent.tTempStudentId T ON A.StudentId = T.StudentId
		
		--UPDATE A SET A.WhomToMeetSourceId = T.NewStudentId 
		--FROM sHostel.tVisitorGatePass A JOIN sStudent.tTempStudentId T ON A.WhomToMeetSourceId = T.StudentId AND WhomToMeetSourceTypeId = 2003
		-- End
		
		
		-- for update transport
		-- Start
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sTransport.tAssignRoute A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		--UPDATE A SET A.SourceId = T.NewStudentId 
		--FROM sTransport.tAttendanceRegister A JOIN sStudent.tTempStudentId T ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		-- End
		
		-- for update Library
		-- Start
		UPDATE A SET A.ReaderSourceId = T.NewStudentId 
		FROM sLibrary.tBookLog A JOIN sStudent.tTempStudentId T ON A.ReaderSourceId = T.StudentId AND A.ReaderSourceTypeId = 2003
		
		UPDATE A SET A.SourceId = T.NewStudentId 
		FROM sLibrary.tLibraryAttendance A JOIN sStudent.tTempStudentId T 
		ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		-- End
		
		-- for update Canteen
		-- Start
		UPDATE A SET A.SourceId = T.NewStudentId 
		FROM sCanteen.tCanteenIssue A JOIN sStudent.tTempStudentId T 
		ON A.SourceId = T.StudentId AND A.SourceTypeId = 2003
		
		-- End
	
	DROP TABLE sStudent.tTempStudentId
	
    SELECT 1 AS Result
	
	--COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT Error_message()
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
PRINT N'Creating [sFee].[pFeeAsNotApplicableAdd]...';


GO
 
CREATE PROCEDURE [sFee].[pFeeAsNotApplicableAdd]
	 	 
		@rClassId int=0,
		@rBatchId int=0,	 
		@rOrgId int=0,
		@rOrgGroupBatchId int=0,
		--@rStatusId int=0, 
	 --   @rCode nvarchar(20)='',
	    @rStudentId bigint,
		@rAdmissionDate date
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
		DECLARE @rAcademicId bigint 
		Select @rAcademicId = Id From [sStudent].[tAcademic] WHERE StudentId = @rStudentId AND BatchId = @rBatchId
		CREATE TABLE #TempFeeUpdate
		(
			AcademicId bigint,
			FeeSetupId int,
			PendingAmount Decimal(12,2)
		)
		INSERT INTO #TempFeeUpdate
		Select 
		SA.AcademicId,
		FS.Id,
		ISNULL(FS.Amount,0)AS PendingAmount
		from sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeSetup FS ON SA.ClassId=FS.ClassId AND FS.BatchId = SA.BatchId AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
		Where SA.ClassId = @rClassId AND SA.BatchId = @rBatchId AND FS.EndDate < @rAdmissionDate
		--AND Month(FS.EndDate) < Month(@rAdmissionDate) AND Year(FS.EndDate) <= Year(@rAdmissionDate) 
		AND SA.AcademicId = @rAcademicId
		AND SA.OrgId = @rOrgId AND SA.OrgGroupBatchId  = @rOrgGroupBatchId
		
	SELECT * FROM #TempFeeUpdate
	MERGE sFee.tFeeAllocation FA
	USING #TempFeeUpdate TU
	ON FA.FeeSetupId = TU.FeeSetupId AND FA.SourceTypeId = 2001 AND FA.SourceId = TU.AcademicId

	
	WHEN NOT MATCHED BY TARGET THEN
	  INSERT (SourceTypeId, SourceId, FeeSetupId,VariableAmount,DiscountAmount,AdditionalAmount,NotApplicableAmount,Remark,ReferenceTypeId,ReferenceSourceId,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,NotApplicableRemark)
	  VALUES (2001, TU.AcademicId,TU.FeeSetupId,0,0,0,TU.PendingAmount,'',0,0,0,sCommon.fGetDate(),0,sCommon.fGetDate(),'Updated NA Amount');
DROP TABLE	#TempFeeUpdate

SELECT 1 AS Result
 
END
GO
PRINT N'Creating [sFee].[pFeeProcessGenerateFeeAllocationAdd]...';


GO
 
--@rOrgId = 9911@lBatchId=991100101,@rAcademicId = 9911000000366,@rReceiptId=,@rCreatedUserId=
CREATE PROCEDURE [sFee].[pFeeProcessGenerateFeeAllocationAdd]

		@rXmlDoc nvarchar(MAX),
		@rOrgId int,
		@rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	DECLARE @lInterrorCode INT,
			@intDoc INT
	--BEGIN TRY
	
	BEGIN TRANSACTION	
	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

	SELECT
			ROW_NUMBER() OVER (ORDER BY SourceId) as RowNumberFeeAllocation,
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			NotApplicableAmount,
			AdditionalAmount,
			Remark
	INTO #TmpFeeAllocation		 
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId',
		VariableAmount decimal(12,2) '@VariableAmount',
		DiscountAmount decimal(12,2) '@DiscountAmount',
		NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
		AdditionalAmount decimal(12,2) '@AdditionalAmount',
		Remark nvarchar(200) '@Remark'
	) 

	DECLARE @RowCountFeeAllocation BIGINT=0
	SELECT @RowCountFeeAllocation = COUNT(RowNumberFeeAllocation) FROM #TmpFeeAllocation

	WHILE (@RowCountFeeAllocation!=0)
	BEGIN	
		DECLARE @lSourceId bigint,@lSourceTypeId int,@lFeeSetupId int,@lVariableAmount decimal(12,2),@lDiscountAmount decimal(12,2),@lNotApplicableAmount decimal(12,2)
		DECLARE @lAdditionalAmount decimal(12,2),@lRemark nvarchar(200),@lBatchId bigint

		SELECT @lSourceId = SourceId,@lSourceTypeId = SourceTypeId,@lFeeSetupId = FeeSetupId,
			   @lVariableAmount = VariableAmount,@lDiscountAmount = DiscountAmount,
			   @lNotApplicableAmount = NotApplicableAmount,@lAdditionalAmount = AdditionalAmount,
			   @lRemark = Remark
	    FROM #TmpFeeAllocation 
		WHERE RowNumberFeeAllocation = @RowCountFeeAllocation

		SELECT @lBatchId = BatchId FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId

		IF EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS INNER JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId INNER JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId AND FS.ClassId = A.ClassId WHERE FAS.AcademicId = @lSourceId AND A.OrgId=@rOrgId AND A.BatchId=@lBatchId)
		BEGIN
		    
				DECLARE @lFeeAmount decimal(12,2),@lPaidAmount decimal(12,2),@lToPayAmount decimal(12,2)

				SELECT @lFeeAmount = Amount FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId
				SELECT @lPaidAmount = PaidAmount FROM sFee.tFeeAllocationStudent WHERE AcademicId = @lSourceId AND FeeSetupId = @lFeeSetupId
				 
				SET @lToPayAmount = (@lFeeAmount+@lVariableAmount+@lAdditionalAmount)-(@lNotApplicableAmount+@lDiscountAmount+@lPaidAmount)
				 
				UPDATE [sFee].[tFeeAllocationStudent] 
				SET 
				    FeeAmount = @lFeeAmount,
					VariableAmount = @lVariableAmount,
					DiscountAmount = @lDiscountAmount,
					NotApplicableAmount = @lNotApplicableAmount,
					AdditionalAmount = @lAdditionalAmount,
					ToPayAmount = @lToPayAmount,
					Remark = @lRemark,
					UpdatedUserId = @rCreatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				WHERE 
					AcademicId = @lSourceId
					AND FeeSetupId = @lFeeSetupId
		END
		ELSE
		BEGIN
				SELECT RowNumFeeSetup,Id AS FeeSetupId,Amount AS FeeAmount,IsOptional,IsVariable 
				INTO  #tempFeeSetup 
				FROM
				(SELECT ROW_NUMBER() OVER (ORDER BY FS.id) RowNumFeeSetup,FS.Id,FS.Amount,FS.IsOptional,FS.IsVariable FROM sFee.tFeeSetup FS
				INNER JOIN sStudent.tAcademic A ON FS.ClassId = A.ClassId AND FS.AdmissionCategoryId = A.AdmissionCategoryId
				WHERE FS.BatchId=@lBatchId  AND A.Id= @lSourceId
				AND FS.FeeId IN (SELECT Id FROM sFee.tFeeMaster WHERE IsObsolete=0) AND 
				FS.ReceiptBookId IN (SELECT Id FROM sFee.tReceiptBookMaster WHERE IsObsolete=0)
				) AS tFeeSetup
		  
		  
				DECLARE @RowFeesetup BIGINT=0
				SELECT @RowFeesetup = COUNT(RowNumFeeSetup) FROM #tempFeeSetup

				WHILE (@RowFeesetup!=0)
				BEGIN
					DECLARE @FPFeeSetupId BIGINT=0
					DECLARE @FeeAmount DECIMAL(12,2)=0.00			
					DECLARE @IsOptional Bit=0
					DECLARE @IsVariable Bit=0					
					SELECT @IsOptional=IsOptional,@IsVariable=IsVariable,@FPFeeSetupId=FeeSetupId,@FeeAmount=ISNULL(FeeAmount,0) FROM #tempFeeSetup WHERE RowNumFeeSetup=@RowFeesetup

					DECLARE @ToPayAmount DECIMAL(12,2)=0.00
					DECLARE @FPPaidAmount DECIMAL(12,2)=0.00
					DECLARE @VariableAmount DECIMAL(12,2)=0.00
					DECLARE @DiscountAmount DECIMAL(12,2)=0.00
					DECLARE @AdditionalAmount DECIMAL(12,2)=0.00
					DECLARE @NotApplicableAmount DECIMAL(12,2)=0.00
					DECLARE @Remark NVARCHAR(400)=''

					SELECT @FPPaidAmount=ISNULL(SUM(RD.Amount),0) FROM sFee.tReceipt  R
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id AND R.IsObsolete = 0
					WHERE R.SourceId=@lSourceId AND RD.FeeSetupId=@FPFeeSetupId 
					GROUP BY R.sourceid,RD.feesetupid

					IF(@IsOptional=1 AND @IsVariable=1)
					BEGIN
				
						SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')						
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@lSourceId AND FA.feesetupid=@FPFeeSetupId
				
						IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END											
						 
					END
			
					IF(@IsOptional=1 AND @IsVariable=0)
					BEGIN

						SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@lSourceId AND FA.feesetupid=@FPFeeSetupId

						IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END							

					END

					IF(@IsOptional=0 AND @IsVariable=1)
					BEGIN
				
						SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@lSourceId AND FA.feesetupid=@FPFeeSetupId
				
						IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END				

					END

					IF(@IsOptional=0 AND @IsVariable=0)
					BEGIN
				
						SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@lSourceId AND FA.feesetupid=@FPFeeSetupId
				
						IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END			

					END

					SET @ToPayAmount=(@FeeAmount+@VariableAmount+@AdditionalAmount)-(@NotApplicableAmount+@DiscountAmount+@FPPaidAmount)

					IF(@IsOptional=0)
					BEGIN
						IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.AcademicId=@lSourceId AND FAS.FeeSetupId=@FPFeeSetupId)
						BEGIN
						 
							INSERT INTO [sFee].[tFeeAllocationStudent]
									([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
									,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
							VALUES
								(@lSourceId,@FPFeeSetupId,@FeeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@ToPayAmount
								,@FPPaidAmount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
						END
					END

					IF EXISTS (SELECT 1 FROM [sFee].[tFeeOptional] WHERE FeeSetupId=@lFeeSetupId AND SourceId=@lSourceId AND BatchId=@lBatchId AND (@IsOptional=1))
					BEGIN
						IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@lSourceId AND FAS.feesetupid=@FPFeeSetupId)
						BEGIN
						
							INSERT INTO [sFee].[tFeeAllocationStudent]
									([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
									,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
							VALUES
								(@lSourceId,@FPFeeSetupId,@FeeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@ToPayAmount
								,@FPPaidAmount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())
						END 
					END 
					SET @RowFeesetup=@RowFeesetup-1
				END

				DROP TABLE #tempFeeSetup
		END
		SET @RowCountFeeAllocation=@RowCountFeeAllocation-1
	END
	 
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
END
GO
PRINT N'Creating [sFee].[pFeeProcessGenerateFeeOptionalAdd]...';


GO
  
--@rOrgId = 9911@lBatchId=991100101,@rAcademicId = 9911000000366,@rReceiptId=,@rCreatedUserId=
CREATE PROCEDURE [sFee].[pFeeProcessGenerateFeeOptionalAdd]
		
		@rFeeHeadId bigint = 0,
		@rFeeSetupId bigint = 0,
		@rOrgId int,
		@rBatchId int,
		@rClassId bigint = 0,
		@rAdmissionCategoryId bigint = 0,
		@rCreatedUserId bigint,
		@rSourceId bigint,
		@rSourceTypeId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRANSACTION

	IF (@rFeeSetupId != 0 AND @rFeeHeadId = 0)
	BEGIN
		IF EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS INNER JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId INNER JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId AND FS.ClassId = A.ClassId WHERE FAS.AcademicId = @rSourceId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId)
		BEGIN
		
		IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS INNER JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId INNER JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId AND FS.ClassId = A.ClassId WHERE FAS.AcademicId = @rSourceId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND FeeSetupId = @rFeeSetupId)
		BEGIN
			DECLARE @feesetupid BIGINT=0
			DECLARE @feeAmount DECIMAL(12,2)=0.00			
			DECLARE @IsOptional Bit=0
			DECLARE @IsVariable Bit=0					
			SELECT @IsOptional=isoptional,@IsVariable=isvariable,@feesetupid=Id,@feeAmount=ISNULL(Amount,0) FROM sFee.tFeeSetup WHERE Id = @rFeeSetupId
		
			DECLARE @toPayamount DECIMAL(12,2)=0.00
			DECLARE @paidAmount DECIMAL(12,2)=0.00
			DECLARE @VariableAmount DECIMAL(12,2)=0.00
			DECLARE @DiscountAmount DECIMAL(12,2)=0.00
			DECLARE @AdditionalAmount DECIMAL(12,2)=0.00
			DECLARE @NotApplicableAmount DECIMAL(12,2)=0.00
			DECLARE @Remark NVARCHAR(400)=''


			SELECT @paidAmount=ISNULL(SUM(RD.amount),0) FROM sFee.treceipt  R
			JOIN sFee.tReceiptDetail RD ON RD.receiptid = R.id AND R.IsObsolete = 0
			WHERE R.sourceid=@rSourceId AND RD.feesetupid=@feesetupid 
			GROUP BY R.sourceid,RD.feesetupid
						
			IF(@IsOptional=1 AND @IsVariable=1)
			BEGIN
				SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
				,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')						
				FROM [sFee].[tFeeAllocation] AS FA					  			
				WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@feesetupid
				
				IF(@VariableAmount>0)BEGIN SET @feeAmount=0 END											
			END
			
			IF(@IsOptional=1 AND @IsVariable=0)
			BEGIN

				SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
				,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
				FROM [sFee].[tFeeAllocation] AS FA					  			
				WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@feesetupid

				IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END							
			END

			IF(@IsOptional=0 AND @IsVariable=1)
			BEGIN
				
				SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
				,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
				FROM [sFee].[tFeeAllocation] AS FA					  			
				WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@feesetupid
				
				IF(@VariableAmount>0)BEGIN SET @feeAmount=0 END				
			END

			IF(@IsOptional=0 AND @IsVariable=0)
			BEGIN
				
				SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
				,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
				FROM [sFee].[tFeeAllocation] AS FA					  			
				WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@feesetupid
				
				IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END			
			END

			SET @toPayamount=(@feeAmount+@VariableAmount+@AdditionalAmount)-(@NotApplicableAmount+@DiscountAmount+@paidamount)
			
			IF EXISTS (SELECT 1 FROM [sFee].[tFeeOptional] WHERE FeeSetupId=@feesetupid AND SourceId=@rSourceId AND BatchId=@rBatchId AND (@IsOptional=1))
				BEGIN
				IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@rSourceId AND FAS.feesetupid=@feesetupid)
				BEGIN
					INSERT INTO [sFee].[tFeeAllocationStudent]
							([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
							,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
					VALUES
						(@rSourceId,@feesetupid,@feeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@toPayamount
						,@paidamount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
				END
			END
		END
		
	END
	END
	ELSE IF(@rFeeHeadId != 0 AND @rFeeSetupId = 0)
	BEGIN
	    
		IF EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS INNER JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId INNER JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId AND FS.ClassId = A.ClassId WHERE FAS.AcademicId = @rSourceId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId)
		BEGIN

			SELECT
				ROW_NUMBER() OVER (ORDER BY FS.Id) as ROWId,
				FS.Id as FeeSetupId
			INTO #TempFeeSetup
			FROM 
				sFee.tFeeSetup FS
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id	 
			WHERE
				FHM.Id = @rFeeHeadId
				AND FS.BatchId = @rBatchId
				AND FS.ClassId = @rClassId
				AND FS.AdmissionCategoryId =@rAdmissionCategoryId 
				AND FS.IsOptional=1
		     
			 
			 DECLARE @Counter int

			 SELECT @Counter = COUNT(ROWId) FROM #TempFeeSetup

			 WHILE (@Counter != 0)
			 BEGIN
				
				DECLARE @lFeeSetupId bigint
				
				SELECT @lFeeSetupId = FeeSetupId FROM #TempFeeSetup WHERE ROWId = @Counter
				 
				IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS INNER JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId INNER JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId AND FS.ClassId = A.ClassId WHERE FAS.AcademicId = @rSourceId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND FeeSetupId = @lFeeSetupId)
				BEGIN
					DECLARE @fhfeesetupid BIGINT=0
					DECLARE @fhfeeAmount DECIMAL(12,2)=0.00			
					DECLARE @fhIsOptional Bit=0
					DECLARE @fhIsVariable Bit=0					
					SELECT @fhIsOptional=isoptional,@fhIsVariable=isvariable,@fhfeesetupid=Id,@fhfeeAmount=ISNULL(Amount,0) FROM sFee.tFeeSetup WHERE Id = @lFeeSetupId
		
					DECLARE @fhtoPayamount DECIMAL(12,2)=0.00
					DECLARE @fhpaidAmount DECIMAL(12,2)=0.00
					DECLARE @fhVariableAmount DECIMAL(12,2)=0.00
					DECLARE @fhDiscountAmount DECIMAL(12,2)=0.00
					DECLARE @fhAdditionalAmount DECIMAL(12,2)=0.00
					DECLARE @fhNotApplicableAmount DECIMAL(12,2)=0.00
					DECLARE @fhRemark NVARCHAR(400)=''


					SELECT @fhpaidAmount=ISNULL(SUM(RD.amount),0) FROM sFee.treceipt  R
					JOIN sFee.tReceiptDetail RD ON RD.receiptid = R.id AND R.IsObsolete = 0
					WHERE R.sourceid=@rSourceId AND RD.feesetupid=@fhfeesetupid 
					GROUP BY R.sourceid,RD.feesetupid
						
					IF(@fhIsOptional=1 AND @fhIsVariable=1)
					BEGIN
						SELECT @fhVariableAmount=ISNULL(FA.[VariableAmount],0),@fhDiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@fhAdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@fhNotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@fhRemark=ISNULL(FA.Remark,'')						
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@fhfeesetupid
				
						IF(@fhVariableAmount>0)BEGIN SET @fhfeeAmount=0 END											
					END
			
					IF(@fhIsOptional=1 AND @fhIsVariable=0)
					BEGIN

						SELECT @fhVariableAmount=ISNULL(FA.[VariableAmount],0),@fhDiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@fhAdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@fhNotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@fhRemark=ISNULL(FA.Remark,'')
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@fhfeesetupid

						IF(@fhVariableAmount>0)BEGIN SET @fhVariableAmount=0 END							
					END

					IF(@fhIsOptional=0 AND @fhIsVariable=1)
					BEGIN
				
						SELECT @fhVariableAmount=ISNULL(FA.[VariableAmount],0),@fhDiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@fhAdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@fhNotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@fhRemark=ISNULL(FA.Remark,'')
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@fhfeesetupid
				
						IF(@fhVariableAmount>0)BEGIN SET @fhfeeAmount=0 END				
					END

					IF(@fhIsOptional=0 AND @fhIsVariable=0)
					BEGIN
				
						SELECT @fhVariableAmount=ISNULL(FA.[VariableAmount],0),@fhDiscountAmount=ISNULL(FA.[DiscountAmount],0)
						,@fhAdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@fhNotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@fhRemark=ISNULL(FA.Remark,'')
						FROM [sFee].[tFeeAllocation] AS FA					  			
						WHERE FA.sourceid=@rSourceId AND FA.feesetupid=@fhfeesetupid
				
						IF(@fhVariableAmount>0)BEGIN SET @fhVariableAmount=0 END			
					END

					SET @fhtoPayamount=(@fhfeeAmount+@fhVariableAmount+@fhAdditionalAmount)-(@fhNotApplicableAmount+@fhDiscountAmount+@fhpaidAmount)
					 
					IF EXISTS (SELECT 1 FROM [sFee].[tFeeOptional] WHERE FeeSetupId=@fhfeesetupid AND SourceId=@rSourceId AND BatchId=@rBatchId AND (@fhIsOptional=1))
						BEGIN
						 
						IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@rSourceId AND FAS.feesetupid=@fhfeesetupid)
						BEGIN
							INSERT INTO [sFee].[tFeeAllocationStudent]
									([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
									,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
							VALUES
								(@rSourceId,@fhfeesetupid,@fhfeeAmount,@fhVariableAmount,@fhDiscountAmount,@fhAdditionalAmount,@fhNotApplicableAmount,@fhtoPayamount
								,@fhpaidAmount,@fhRemark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
						END
					END
				END
				SET @Counter = @Counter - 1
			 END

		END
	END
	COMMIT TRANSACTION
END
GO
PRINT N'Creating [sFee].[pFeeProcessGeneratePaidFeeAdd]...';


GO
--@rOrgId = 9911@rBatchId=991100101,@rAcademicId = 9911000000366,@rReceiptId=,@rCreatedUserId=
CREATE PROCEDURE [sFee].[pFeeProcessGeneratePaidFeeAdd]
		@rOrgId int,
		@rBatchId int,
	    @rAcademicId bigint,
		@rReceiptId bigint,
		@rCreatedUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS INNER JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId INNER JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId AND FS.ClassId = A.ClassId WHERE FAS.AcademicId = @rAcademicId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId)
	BEGIN
		  SELECT ROW_NUMBER() OVER (ORDER BY FS.Id) as RowNumberFeeSetup,FS.Id AS FeeSetupId,PaidAmount AS PaidAmount,ToPayAmount AS PendingAmount 
		  INTO  #temptFeeSetup 
		  FROM [sFee].[tFeeAllocationStudent] FAS
		  INNER JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId 
		  INNER JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId 
		  AND FS.ClassId = A.ClassId
		  WHERE FAS.AcademicId = @rAcademicId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId

		  DECLARE @rowcountFeesetup BIGINT=0
		  SELECT @rowcountFeesetup = COUNT(RowNumberFeeSetup) FROM #temptFeeSetup

		  WHILE (@rowcountFeesetup!=0)
		  BEGIN	
				DECLARE @FeeSetupId BIGINT=0
				DECLARE @PaidAmount DECIMAL(12,2) = 0.00
				DECLARE @PendingAmount DECIMAL(12,2) = 0.00
				DECLARE @ReceiptPaidAmount DECIMAL(12,2) = 0.00

				SELECT @FeeSetupId=FeeSetupId,@PaidAmount=PaidAmount,@PendingAmount=PendingAmount FROM #temptFeeSetup WHERE RowNumberFeeSetup=@rowcountFeesetup

				SELECT @ReceiptPaidAmount = Amount FROM sFee.tReceiptDetail RD INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId WHERE ReceiptId = @rReceiptId AND FeeSetupId = @FeeSetupId AND R.SourceId = @rAcademicId

				SET @PaidAmount = @PaidAmount + @ReceiptPaidAmount
				SET @PendingAmount = @PendingAmount - @ReceiptPaidAmount

				UPDATE [sFee].[tFeeAllocationStudent] 
				SET 
					ToPayAmount = @PendingAmount,
					PaidAmount = @PaidAmount,
					UpdatedUserId = @rCreatedUserId,
					UpdatedDateTime = sCommon.fGetDate()
				WHERE 
					AcademicId = @rAcademicId
					AND FeeSetupId = @FeeSetupId

				SET @rowcountFeesetup=@rowcountFeesetup-1
		  END

		  DROP TABLE #temptFeeSetup
	END
	ELSE 
	BEGIN
		  SELECT RowNumFeeSetup,Id AS FeeSetupId,Amount AS FeeAmount,IsOptional,IsVariable 
		  INTO  #tempFeeSetup 
		  FROM
		  (SELECT ROW_NUMBER() OVER (ORDER BY FS.id) RowNumFeeSetup,FS.Id,FS.Amount,FS.IsOptional,FS.IsVariable FROM sFee.tFeeSetup FS
		  INNER JOIN sStudent.tAcademic A ON FS.ClassId = A.ClassId AND FS.AdmissionCategoryId = A.AdmissionCategoryId
		  WHERE FS.BatchId=@rBatchId  AND A.Id= @rAcademicId
		  AND FS.FeeId IN (SELECT Id FROM sFee.tFeeMaster WHERE IsObsolete=0) AND 
		  FS.ReceiptBookId IN (SELECT Id FROM sFee.tReceiptBookMaster WHERE IsObsolete=0)
		  ) AS tFeeSetup
		  
		  
		  DECLARE @RowFeesetup BIGINT=0
		  SELECT @RowFeesetup = COUNT(RowNumFeeSetup) FROM #tempFeeSetup

		  WHILE (@RowFeesetup!=0)
		  BEGIN
				DECLARE @FPFeeSetupId BIGINT=0
				DECLARE @FeeAmount DECIMAL(12,2)=0.00			
				DECLARE @IsOptional Bit=0
				DECLARE @IsVariable Bit=0					
				SELECT @IsOptional=IsOptional,@IsVariable=IsVariable,@FPFeeSetupId=FeeSetupId,@FeeAmount=ISNULL(FeeAmount,0) FROM #tempFeeSetup WHERE RowNumFeeSetup=@RowFeesetup

				DECLARE @ToPayAmount DECIMAL(12,2)=0.00
				DECLARE @FPPaidAmount DECIMAL(12,2)=0.00
				DECLARE @VariableAmount DECIMAL(12,2)=0.00
				DECLARE @DiscountAmount DECIMAL(12,2)=0.00
				DECLARE @AdditionalAmount DECIMAL(12,2)=0.00
				DECLARE @NotApplicableAmount DECIMAL(12,2)=0.00
				DECLARE @Remark NVARCHAR(400)=''

				SELECT @FPPaidAmount=ISNULL(SUM(RD.Amount),0) FROM sFee.tReceipt  R
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id AND R.IsObsolete = 0
				WHERE R.SourceId=@rAcademicId AND RD.FeeSetupId=@FPFeeSetupId 
				GROUP BY R.sourceid,RD.feesetupid

				IF(@IsOptional=1 AND @IsVariable=1)
				BEGIN
				
					SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
					,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')						
					FROM [sFee].[tFeeAllocation] AS FA					  			
					WHERE FA.sourceid=@rAcademicId AND FA.feesetupid=@FPFeeSetupId
				
					IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END											
						 
				END
			
				IF(@IsOptional=1 AND @IsVariable=0)
				BEGIN

					SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
					,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
					FROM [sFee].[tFeeAllocation] AS FA					  			
					WHERE FA.sourceid=@rAcademicId AND FA.feesetupid=@FPFeeSetupId

					IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END							

				END

				IF(@IsOptional=0 AND @IsVariable=1)
				BEGIN
				
					SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
					,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
					FROM [sFee].[tFeeAllocation] AS FA					  			
					WHERE FA.sourceid=@rAcademicId AND FA.feesetupid=@FPFeeSetupId
				
					IF(@VariableAmount>0)BEGIN SET @FeeAmount=0 END				

				END

				IF(@IsOptional=0 AND @IsVariable=0)
				BEGIN
				
					SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
					,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
					FROM [sFee].[tFeeAllocation] AS FA					  			
					WHERE FA.sourceid=@rAcademicId AND FA.feesetupid=@FPFeeSetupId
				
					IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END			

				END

				SET @ToPayAmount=(@FeeAmount+@VariableAmount+@AdditionalAmount)-(@NotApplicableAmount+@DiscountAmount+@FPPaidAmount)

				IF(@IsOptional=0)
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.AcademicId=@rAcademicId AND FAS.FeeSetupId=@FPFeeSetupId)
					BEGIN
						 
						INSERT INTO [sFee].[tFeeAllocationStudent]
								([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
								,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
						VALUES
							(@rAcademicId,@FPFeeSetupId,@FeeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@ToPayAmount
							,@FPPaidAmount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
					END
				END

				IF EXISTS (SELECT 1 FROM [sFee].[tFeeOptional] WHERE FeeSetupId=@feesetupid AND SourceId=@rAcademicId AND BatchId=@rBatchId AND (@IsOptional=1))
				BEGIN
					IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@rAcademicId AND FAS.feesetupid=@FPFeeSetupId)
					BEGIN
						
						INSERT INTO [sFee].[tFeeAllocationStudent]
								([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
								,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
						VALUES
							(@rAcademicId,@FPFeeSetupId,@FeeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@ToPayAmount
							,@FPPaidAmount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())
					END 
				END 
			 SET @RowFeesetup=@RowFeesetup-1
		  END

		  DROP TABLE #tempFeeSetup
	END

END
GO
PRINT N'Creating [sFee].[pRptFeeStatusCollectionGroupWiseGet_Old]...';


GO
 
CREATE PROCEDURE [sFee].[pRptFeeStatusCollectionGroupWiseGet_Old]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rExemptionTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rFeeGroupId int=0,
		@rCollectionGroupId int = 0,
		@rClassStatusId int=0 --,
		--@rOrgIds nvarchar(max) = '' 
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

CREATE TABLE #TempIsOptional
	(
		FeeId int,  
		Id int,  
		IsOptional bit,  
		IsVariable bit,  
		Amount decimal(12,2),  
		StartDate date,  
		EndDate date,  
		BatchId int,  
		ReceiptBookId int,  
		AcademicId bigint,  
		FeeName nvarchar(100),  
		FeeHeadId int,
		CollectionGroupId int,
		CollectionGroup nvarchar(max)
	)
	
	INSERT INTO #TempIsOptional
		SELECT   
			FS1.FeeId,  
			FS1.Id,  
			ISNULL(FS1.IsOptional,0)AS IsOptional,  
			ISNULL(FS1.IsVariable,0)AS IsVariable,  
			ISNULL(FS1.Amount,0)AS Amount,  
			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
			FS1.BatchId,  
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
			SA1.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup      
		FROM 
			sFee.tFeeSetup FS1  
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId   
			INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id      
			AND 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 sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE   
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))      
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=0)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGroupId,','))OR @rCollectionGroupId='')  

	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.Id AS AcademicId,  
			FM.Title AS FeeName,  
			FM.FeeHeadId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup       
		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.tAcademic SA1 ON SA1.Id=FO.SourceId   
			AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId  
			
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.OrgGroupBatchId = @rOrgGroupBatchId 
		WHERE  
			BM.OrgGroupBatchId = @rOrgGroupBatchId  
			AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))  
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))  
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=1)  
			AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))  
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))      
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
			AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGroupId,','))OR @rCollectionGroupId='')  

	CREATE TABLE #TempReceipt
	(
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint  
	)
	
	INSERT INTO #TempReceipt
	SELECT   
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId  
	FROM  
		sFee.tReceipt R   
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId  
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId     
		AND (SA1.ClassId=@rClassId OR @rClassId=0)   
		AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
		AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)  
	WHERE    
		(R.SourceTypeId = 2001)  
		AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))  
		AND (R.IsObsolete = 0)   
		AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))  
		AND (R.OrgGroupBatchId = @rOrgGroupBatchId)  
		AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016  
		-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))  
		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))  
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
	GROUP BY FeeSetupId,R.SourceId  

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		@rFeeGroupId As FeeGroup,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(CGM.OrderIndex,0) AS CollectionGroupOrderIndex,		
		CASE WHEN ROW_NUMBER() OVER (PARTITION BY SA.ClassId  ORDER BY SA.ClassId ) =1 THEN (SELECT COUNT(1) FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId WHERE A.ClassId= SA.ClassId AND A.BatchId = SA.BatchId  AND A.OrgId = SA.OrgId AND BM.OrgGroupBatchId = SA.OrgGroupBatchId GROUP BY ClassId) ELSE 0 END AS StudentCount,
		--CASE WHEN ROW_NUMBER() OVER (PARTITION BY SA.AcademicId  ORDER BY SA.AcademicId) =1 THEN (CASE WHEN (SUM(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) THEN 1 ELSE 0 END) ELSE 0 END AS PendingAmount

		( SELECT SUM(T.PaidCount) FROM 
		(SELECT 
			COUNT(DISTINCT(S1.AcademicId)) AS PaidCount FROM sStudent.vStudentAcademic S1
			INNER JOIN #TempIsOptional FS1 ON FS1.AcademicId=S1.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA1  ON FA1.FeeSetupId=FS1.Id AND FA1.SourceId=S1.AcademicId  
		LEFT JOIN #TempReceipt R1 ON R1.FeeSetupId = FS1.Id AND S1.AcademicId = R1.SourceId
		INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS1.ReceiptBookId=RBM1.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS1.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		GROUP BY S1.AcademicId
		HAVING SUM(ISNULL(FS1.Amount,0.00)+ISNULL(FA1.VariableAmount,0.00)+ISNULL(FA1.AdditionalAmount,0.00) -ISNULL(FA1.DiscountAmount,0.00)-ISNULL(FA1.NotApplicableAmount,0.00)-ISNULL(R1.PaidAmount,0.00)) = 0 
		) T )			
			AS PaidCount,
		( SELECT SUM(T.PendingCount) FROM 
		(SELECT 
			COUNT(DISTINCT(S1.AcademicId)) AS PendingCount FROM sStudent.vStudentAcademic S1
			INNER JOIN #TempIsOptional FS1 ON FS1.AcademicId=S1.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA1  ON FA1.FeeSetupId=FS1.Id AND FA1.SourceId=S1.AcademicId  
		LEFT JOIN #TempReceipt R1 ON R1.FeeSetupId = FS1.Id AND S1.AcademicId = R1.SourceId
		INNER JOIN sFee.tReceiptBookMaster RBM1 ON FS1.ReceiptBookId=RBM1.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM1 ON FS1.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		GROUP BY S1.AcademicId
		HAVING SUM(ISNULL(FS1.Amount,0.00)+ISNULL(FA1.VariableAmount,0.00)+ISNULL(FA1.AdditionalAmount,0.00) -ISNULL(FA1.DiscountAmount,0.00)-ISNULL(FA1.NotApplicableAmount,0.00)-ISNULL(R1.PaidAmount,0.00)) > 0 
		) T )			
			AS PendingCount

		--( SELECT SUM(T.PaidCount) FROM (SELECT 
		--	COUNT(DISTINCT(S1.AcademicId)) AS PaidCount FROM sStudent.vStudentAcademic S1
		--	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,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		--		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))			
		--		WHERE 
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--			AND (FS1.IsOptional=0)
		--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))			 
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--			UNION ALL
				
		--		SELECT 
		--			FS1.FeeId,
		--			FS1.Id,
		--			ISNULL(FS1.IsOptional,0)AS IsOptional,
		--			ISNULL(FS1.IsVariable,0)AS IsVariable,
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--			FS1.BatchId,
		--			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		--			SA1.AcademicId,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--	INNER JOIN sFee.tFeeOptional FO
		--		ON FO.FeeSetupId=FS1.Id 
		--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--	INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		--	AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
		--	AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--WHERE
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--		AND (FS1.IsOptional=1)
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))							
		--	) FS ON FS.AcademicId=S1.AcademicId
		--	LEFT JOIN sFee.tFeeAllocation FA
		--		ON FA.FeeSetupId=FS.Id AND FA.SourceId=S1.AcademicId
		--	LEFT JOIN
		--	(
		--		SELECT 
		--				ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--		FROM
		--				sFee.tReceipt R 
		--			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
		--			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
		--			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
		--		WHERE		
		--			(R.SourceTypeId = 2001)
		--		AND (R.IsObsolete = 0) 
		--		AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		--		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND (R.ReceiptDate <= @rUptoDate)
		--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--				GROUP BY FeeSetupId,R.SourceId
		
		--	) R ON R.FeeSetupId = FS.Id AND S1.AcademicId = R.SourceId
		--	INNER JOIN sFee.tReceiptBookMaster RBM1
		--		ON FS.ReceiptBookId=RBM.Id
		--	LEFT JOIN sFee.tCollectionGroupMaster CGM1
		--		ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--	WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--	GROUP BY S1.AcademicId
		--HAVING SUM(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 
		--) T )			
		--	AS PaidCount,

		--	( SELECT SUM(T.PendingCount) FROM (SELECT 
		--	COUNT(DISTINCT(S1.AcademicId)) AS PendingCount FROM sStudent.vStudentAcademic S1
		--	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,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
		--		AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))			
		--		WHERE 
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--			AND (FS1.IsOptional=0)
		--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))			 
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--			UNION ALL
				
		--		SELECT 
		--			FS1.FeeId,
		--			FS1.Id,
		--			ISNULL(FS1.IsOptional,0)AS IsOptional,
		--			ISNULL(FS1.IsVariable,0)AS IsVariable,
		--			ISNULL(FS1.Amount,0)AS Amount,
		--			ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
		--			ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
		--			FS1.BatchId,
		--			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		--			SA1.AcademicId,				 
		--			FS1.CollectionGroupId
		--		FROM sFee.tFeeSetup FS1
		--	INNER JOIN sFee.tFeeOptional FO
		--		ON FO.FeeSetupId=FS1.Id 
		--	--INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		--	INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		--	AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		--		AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
		--	AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--WHERE
		--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
		--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		--		AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
		--		AND (FS1.IsOptional=1)
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))							
		--	) FS ON FS.AcademicId=S1.AcademicId
		--	LEFT JOIN sFee.tFeeAllocation FA
		--		ON FA.FeeSetupId=FS.Id AND FA.SourceId=S1.AcademicId
		--	LEFT JOIN
		--	(
		--		SELECT 
		--				ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		--		FROM
		--				sFee.tReceipt R 
		--			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		--			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
		--			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
		--			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
		--		WHERE		
		--			(R.SourceTypeId = 2001)
		--		AND (R.IsObsolete = 0) 
		--		AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
		--		AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
		--		AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
		--		AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		--		AND (R.ReceiptDate <= @rUptoDate)
		--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit('',','))OR ''='')
		--			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		--				GROUP BY FeeSetupId,R.SourceId
		
		--	) R ON R.FeeSetupId = FS.Id AND S1.AcademicId = R.SourceId
		--	INNER JOIN sFee.tReceiptBookMaster RBM1
		--		ON FS.ReceiptBookId=RBM.Id
		--	LEFT JOIN sFee.tCollectionGroupMaster CGM1
		--		ON FS.CollectionGroupId=CGM1.Id AND RBM1.Id = CGM1.ReceiptBookId AND CGM1.OrgGroupBatchId = @rOrgGroupBatchId
		--	WHERE (CGM1.Id = CGM.Id OR ISNULL(CGM.Id,0) = 0) AND RBM1.Id = RBM.Id AND S1.ClassId = SA.ClassId
		--	GROUP BY S1.AcademicId
		--HAVING SUM(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 
		--) T )			
		--	AS PendingCount



  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
					sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (R.ReceiptDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM
			ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
        LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND	((CGM.Id=@rCollectionGroupId) OR (@rCollectionGroupId=0))   
		 AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )	
				 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
    --AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			     
			Order by SA.RollNo
			

	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
				

END
GO
PRINT N'Creating [sSecurity].[pScreenGroupDataListGet]...';


GO
 
CREATE PROCEDURE [sSecurity].[pScreenGroupDataListGet]

	@rUserId [bigint]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lOrgGroupId bigint , @lConfigValue nvarchar(10) = ''

IF EXISTS (SELECT OM.OrgGroupId FROM sSecurity.tUser U INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId WHERE U.Id = @rUserId)
BEGIN
	SELECT @lOrgGroupId = OM.OrgGroupId FROM sSecurity.tUser U INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId WHERE U.Id = @rUserId
		
	SELECT @lConfigValue = ISNULL(CS.ItemValue,'False') FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id=CS.Configurationid AND CS.SourceId= @lOrgGroupId AND CS.SourceTypeId=2010 WHERE CM.Id = 327

		IF(@lConfigValue = 'True')
		BEGIN
		     IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@lOrgGroupId)
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T.ModuleId AND MP.OrgGroupId=@lOrgGroupId
					WHERE (P.Permission & 2) =2 AND P.OrgGroupId = @lOrgGroupId AND T.IsObsolete = 0 AND P.UserId=@rUserId
					AND T.Id IN (20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,
					30228,20693,20692,20241,20563,20561,30249,20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,
					139,20175,20176,141,142,20158, 30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962)
				END
			ELSE
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					WHERE (P.Permission & 2) =2 AND U.IsObsolete=0 AND T.IsObsolete = 0 AND U.UserId=@rUserId
					AND T.Id IN (20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,
					30228,20693,20692,20241,20563,20561,30249,20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,
					139,20175,20176,141,142,20158, 30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962)
				END
		END
		ELSE
		BEGIN
			  IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@lOrgGroupId)
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T.ModuleId AND MP.OrgGroupId=@lOrgGroupId
					WHERE (P.Permission & 2) =2 AND P.OrgGroupId = @lOrgGroupId AND T.IsObsolete = 0 AND P.UserId=@rUserId
				END
			  ELSE
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					WHERE (P.Permission & 2) =2 AND U.IsObsolete=0 AND T.IsObsolete = 0 AND U.UserId=@rUserId
				END
		END
END

END
GO
PRINT N'Creating [sSetup].[pHistoryTransfer]...';


GO
 
alter PROCEDURE [sSetup].[pHistoryTransfer]
	 @rType smallint = 0,
	 @rDate date = ''
	 	 	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN
BEGIN TRY
		BEGIN TRANSACTION 
	IF(@rType = 1) -- Copy To History Table
	BEGIN

	INSERT INTO [sAlert].[tAlertLogHistory] SELECT * FROM [sAlert].[tAlertLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tAlertLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAlert].[tNotificationLogHistory] SELECT * FROM [sAlert].[tNotificationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tNotificationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAlert].[tWhatsAppLogHistory] SELECT * FROM [sAlert].[tWhatsAppLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tWhatsAppLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAudit].[tActivityLogHistory] SELECT * FROM [sAudit].[tActivityLog] WHERE CAST(AuditDate AS DATE) < @rDate
	DELETE FROM [sAudit].[tActivityLog] WHERE CAST(AuditDate AS DATE) < @rDate

	--INSERT INTO [sAudit].[tOperationLogHistory] SELECT * FROM [sAudit].[tOperationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sAudit].[tOperationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	--INSERT INTO [sHrm].[tLeaveBalanceLogHistory] SELECT * FROM [sHrm].[tLeaveBalanceLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sHrm].[tLeaveBalanceLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	--INSERT INTO [sLibrary].[tBookLogHistory] SELECT * FROM [sLibrary].[tBookLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sLibrary].[tBookLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	--INSERT INTO [sRecruitment].[tRecruitmentStatusLogHistory] SELECT * FROM [sRecruitment].[tRecruitmentStatusLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sRecruitment].[tRecruitmentStatusLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sSecurity].[tUserLogHistory] SELECT * FROM [sSecurity].[tUserLog] WHERE CAST(LoggedInDateTime AS DATE) < @rDate
	DELETE FROM [sSecurity].[tUserLog] WHERE CAST(LoggedInDateTime AS DATE) < @rDate

	INSERT INTO [sSystem].[tBackupLogHistory] SELECT * FROM [sSystem].[tBackupLog] WHERE CAST(BackupDateTime AS DATE) < @rDate
	DELETE FROM [sSystem].[tBackupLog] WHERE CAST(BackupDateTime AS DATE) < @rDate

	INSERT INTO [sAcademic].[tClassworkViewHistory] SELECT * FROM [sAcademic].[tClassworkView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sAcademic].[tClassworkView] WHERE CAST(ViewByDateTime AS DATE) < @rDate

	INSERT INTO [sAcademic].[tOnlineLearningViewHistory] (OnlineLearningId,AcademicId,IsViewReference,IsViewAssignment,IsViewResource,ViewByUserId,LastViewByDateTime,AssignmentTeacherRemark) SELECT OnlineLearningId,AcademicId,IsViewReference,IsViewAssignment,IsViewResource,ViewByUserId,LastViewByDateTime,AssignmentTeacherRemark FROM [sAcademic].[tOnlineLearningView] WHERE CAST(LastViewByDateTime AS DATE) < @rDate
	DELETE FROM [sAcademic].[tOnlineLearningView] WHERE CAST(LastViewByDateTime AS DATE) < @rDate

	INSERT INTO  [sCommunication].[tAssignmentViewHistory] SELECT * FROM [sCommunication].[tAssignmentView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sCommunication].[tAssignmentView] WHERE CAST(ViewByDateTime AS DATE) < @rDate

	INSERT INTO  [sCommunication].[tCircularViewHistory] SELECT * FROM [sCommunication].[tCircularView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sCommunication].[tCircularView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	END
	ELSE IF(@rType = 2) -- Delete From Exception Table
	BEGIN 
		DELETE FROM [sSystem].[tExceptionLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	END
	COMMIT TRANSACTION			 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION		
	END CATCH	
END
GO

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


INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('21.09.16',210916,'BEGIN','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO 
 
GO
PRINT N'Dropping [sAttendance].[tStudentRegister].[UK_tStudentRegister]...';


GO
DROP INDEX [UK_tStudentRegister]
    ON [sAttendance].[tStudentRegister];


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


GO
ALTER TABLE [sAlert].[tEventTemplate] DROP COLUMN [WhatsAppNamespace];


GO
ALTER TABLE [sAlert].[tEventTemplate]
    ADD [WhatsAppTemplateLanguage] NVARCHAR (10) NULL;


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


GO
ALTER TABLE [sAlert].[tWhatsAppConfiguration]
    ADD [WhatsAppNamespace] NVARCHAR (100) NULL;


GO
PRINT N'Altering [sFrontOffice].[tEmployeeGatePass]...';


GO
Update [sFrontOffice].[tEmployeeGatePass] Set ReturnGatePassTime = '00:00:00.0000000' Where ReturnGatePassTime is null

ALTER TABLE [sFrontOffice].[tEmployeeGatePass] ALTER COLUMN [ReturnGatePassTime] TIME (7) NOT NULL;


GO
ALTER TABLE [sFrontOffice].[tEmployeeGatePass]
    ADD [AssignEmployeeId] BIGINT   NULL,
        [StatusId]         SMALLINT NULL;


GO
PRINT N'Altering [sRecruitment].[tCandidateMaster]...';


GO
ALTER TABLE [sRecruitment].[tCandidateMaster]
    ADD [ReferenceId] SMALLINT       NULL,
        [MainSubject] NVARCHAR (100) NULL,
        [OrgId]       INT            NULL;


GO
PRINT N'Creating [sHrm].[tLeavePeriod]...';


GO
CREATE TABLE [sHrm].[tLeavePeriod] (
    [OrgId]         SMALLINT NOT NULL,
    [LeavePeriodId] INT      NOT NULL
);


GO
PRINT N'Creating [sRecruitment].[tAssignOrganization]...';


GO
CREATE TABLE [sRecruitment].[tAssignOrganization] (
    [OrgId]     INT    NOT NULL,
    [VacancyId] BIGINT NOT NULL
);


GO
PRINT N'Creating [sAttendance].[tStudentRegister].[UK_tStudentRegister]...';


GO
CREATE NONCLUSTERED INDEX [UK_tStudentRegister]
    ON [sAttendance].[tStudentRegister]([AcademicId] ASC, [AttendanceTypeId] ASC, [SubjectId] ASC, [AttendanceGroupId] ASC, [AbsentReasonId] ASC, [AttendanceTagId] ASC, [EmployeeId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


GO

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


GO





 
ALTER VIEW [sStudent].[vStudentAcademic]   
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,
	   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	  Convert(Nvarchar(20),A.RollNo) + '-' + SM.FirstName+' '+SM.LastName AS RollNoName,	  
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,	  
	  SM.RecordStatusId,	  
	  DM.InchargeEmployeeId, 
	  BM.OrgGroupBatchId,	  
	  ISNULL(A.AdmissionCategoryId,0) AS AdmissionCategoryId,
	  --SM.AdmissionCategoryId,
	  DM.OrderIndex DivisionOrder,
	  BM.IsActive AS IsActiveBatch,
	  BM.Title AS BatchName,
	  ISNULL(DeptM.Id,0) AS DepartmentId,
	  ISNULL(DeptM.Title,'') AS DepartmentName,
	  SM.IsBlackList,
	  SM.BlackListReason,
	  CM.OrderIndex AS ClassOrderIndex,
	  ISNULL(A.ExemptionTypeId,0) AS ExemptionTypeId,
	  ISNULL(OM.DisplayTitle,'')  AS OrganizationName,
	  OM.StreetOne,
	  OM.StreetTwo,
	  OM.StreetThree,
	  OM.ZipCode,
	  ISNULL(SM.SUId,'') AS SUId ,
	  ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
	  ISNULL(OM.ReportOrgTitle,'') AS ReportOrgTitle,
	  ISNULL(A.FeeStructureId,0) AS FeeStructureId,
	  SM.ReferenceSourceId ,
	  SM.StudentGroupId,
	  SM.StudentOtherGroupId,
	  A.BatchStatusId,
	  A.ClassStatusId,
	  STM1.Title AS ClassStatusName,
	  ISNULL(SO.GenderId,0) AS GenderId
	  
  FROM 
	sStudent.tAcademic A
	
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId
	INNER JOIN sSetup.tDepartmentMaster DeptM
		ON DeptM.Id=CM.DepartmentId
	INNER JOIN sSetup.tOrganizationMaster OM 
	    ON A.OrgId = OM.Id
	INNER JOIN sStudent.tStatusMaster STM1
		ON STM1.Id=A.ClassStatusId
	LEFT JOIN sStudent.tStudentOther SO 
		ON SO.StudentId=SM.Id
 


GO

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


GO
 
 
ALTER PROCEDURE [dbo].[pEmployeeMasterGet]
@rOrgId int = 0,
 @rBuilder1 nvarchar(max)='',
 @rBuilder2 nvarchar(max)='',
 @rEmployeeStatusId int=0,
 @rEmployeeId bigint = 0
AS

BEGIN
	IF EXISTS (SELECT EM.PunchId FROM sHrm.tEmployeeMaster EM INNER JOIN sBiometric.BioDetailMapping BM ON BM.EmpID = EM.Id WHERE EM.PunchId is null)
	BEGIN
	UPDATE EM
	SET
		PunchId = BM.EmpPunchID
	FROM
	    sHrm.tEmployeeMaster EM
		INNER JOIN sBiometric.BioDetailMapping AS BM
		ON BM.EmpID = EM.Id
		WHERE PunchId is null
	END
	
	select *,isnull(FirstName,'') +' '+ isnull(MiddleName,'') as 'FullName'
 from sHrm.tEmployeeMaster
	where 1=1
	AND (Id = @rEmployeeId OR @rEmployeeId = 0)
	and PunchId is not null
	and OrgID = @rOrgId
	AND (StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0) 
	AND ISNULL(IsOtherUser,0) = 0	
END
GO
PRINT N'Altering [sAcademic].[pClassworkHomeworkQueueGet]...';


GO


ALTER PROCEDURE [sAcademic].[pClassworkHomeworkQueueGet]

	 @rId bigint=0,	 
	 @rSubjectId int=0,
	 @rClassId int=0,
	 @rEmployeeId bigint=0,
	 @rDivisionid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rOrgId int=0,
     --@rBatchId int
     @rOrgGroupBatchId int=0,
    @rUserId bigint =0,
	@rStatusId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


DECLARE @rSourceId bigint
DECLARE @rSourceTypeId int

set @rSourceId = ( SELECT SourceId FROM sSecurity.tUser where Id=@rUserId)
set @rSourceTypeId = ( SELECT ISNULL(SourceTypeId,0) FROM sSecurity.tUser where Id=@rUserId)


BEGIN 


	--if(@rId = 0)
		--BEGIN

			if(@rSourceTypeId = 95)
				BEGIN

				CREATE TABLE #TempData
				( 
					Id bigint,
					EmployeeId bigint,
					ClassId int,
					DivisionId int,
					SubjectId int,
					ClassWorkDate Date,
					Classwork nvarchar(max),
					Homework nvarchar(1000),
					ClassworkStatusId int,
					HomeWorkStatusId int,
					HomeWorkEndDate date,
					CreatedDateTime datetime,
					BatchId bigint,
					Batch nvarchar(100),
					SubjectName nvarchar(100),
					TeacherName nvarchar(200),
					ClassName nvarchar(100),
					DivisionName nvarchar(100),
					OrgId int,
					Organization nvarchar(200),
					UniqueId nvarchar(500),
					StatusId int,
					SubjectCordinatorEmployeeId bigint,
					Status nvarchar(200),
					IsSubmitHomework bit
				)
				INSERT INTO #TempData  
					SELECT 
					AC.Id,
					AC.EmployeeId,
					AC.ClassId,
					AC.DivisionId,
					AC.SubjectId,
					AC.ClassWorkDate,
					AC.Classwork,
					AC.Homework,
					ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
					ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
					--AC.HomeWorkEndDate,
					ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
					AC.CreatedDateTime,
					AC.BatchId,
					BM.Title AS Batch,
					ISNULL(vTSD.SubjectName,'') as SubjectName,
					ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
					ISNULL(vTSD.ClassTitle,'') AS ClassName,
					ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
					BM.OrgId,
					OM.DisplayTitle AS Organization,
					REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
					ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
					CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
					ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
			FROM 
					sAcademic.tClasswork AC
					INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
					INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
					--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
					INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
					INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
					INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
			WHERE 
					--((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
					((AC.Id = @rId) OR (@rId = 0))
					AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
					AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
					AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
					AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
					AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
					--AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
					--AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
					AND (OGBM.Id = @rOrgGroupBatchId) 
					AND ((U.UserId = @rUserId)OR(@rUserId=0))
					AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
					AND ((ISNULL(vTSD.SubjectCordinatorEmployeeId,0) = @rSourceId) or (@rSourceId=0))
					AND ISNULL(EM.IsOtherUser,0) = 0 
			order by 
					AC.HomeWorkEndDate DESC
						
				if (EXISTS (select 1 from #TempData))
				BEGIN
				
					Select * FROM #TempData tmp
					WHERE (tmp.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
					AND (tmp.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
				END
				ELSE
				BEGIN
					SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
			CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
			AND ((ISNULL(vTSD.EmployeeId,0) = @rSourceId) or (@rSourceId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
				END

									
				DROP TABLE #TempData
				END

			ELSE IF (@rUserId = 0)
			BEGIN
			SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,

			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
			CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
			--INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			--INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			--AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
			END

			ELSE
				BEGIN
					SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,

			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.StatusId,549) AS StatusId,vTSD.SubjectCordinatorEmployeeId,
			CASE WHEN ISNULL(AC.StatusId,549) = 549 then 'Pending' WHEN AC.StatusId=550 then 'Approve' ELSE  'Reject' END  AS Status,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			--INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id 
			--INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ((ISNULL(AC.StatusId,549) = @rStatusId) OR (@rStatusId=0)) 
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
				END

		--END 
	--ELSE
	--	BEGIN
	--	SELECT 
	--		AC.Id,
	--		AC.EmployeeId,
	--		AC.ClassId,
	--		AC.DivisionId,
	--		AC.SubjectId,
	--		AC.ClassWorkDate,
	--		AC.Classwork,
	--		AC.Homework,
	--		ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
	--		ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
	--		--AC.HomeWorkEndDate,
	--		ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
	--		AC.CreatedDateTime,
	--		AC.BatchId,
	--		BM.Title AS Batch,
	--	    ISNULL(vTSD.SubjectName,'') as SubjectName,
	--	    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
	--	    ISNULL(vTSD.ClassTitle,'') AS ClassName,
	--	    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
	--	    BM.OrgId,
	--	    OM.DisplayTitle AS Organization,
	--	    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId
			
	--FROM 
	--		sAcademic.tClasswork AC
	--		INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
	--		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
	--		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
	--		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
	--		INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
	--		INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
	--		INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
	--		INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	--WHERE 
	--        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
	--		((AC.Id = @rId) OR (@rId = 0))
	--		AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
	--		AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
	--		AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
	--		AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
	--		AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
	--		AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
	--		AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
	--		AND (OGBM.Id = @rOrgGroupBatchId) 
	--		AND ((U.UserId = @rUserId)OR(@rUserId=0))
	--		GROUP BY AC.Id,
	--		AC.EmployeeId,
	--		AC.ClassId,
	--		AC.DivisionId,
	--		AC.SubjectId,
	--		AC.ClassWorkDate,
	--		AC.Classwork,
	--		AC.Homework,
	--		ClassworkStatusId,
	--		HomeWorkStatusId,
	--		--AC.HomeWorkEndDate,
	--		AC.HomeWorkEndDate,
	--		AC.CreatedDateTime,
	--		AC.BatchId,
	--		BM.Title,
	--	  vTSD.SubjectName,
	--	    EM.FirstName,  EM.LastName,
	--	    vTSD.ClassTitle,
	--	   vTSD.DivisionTitle,
	--	    BM.OrgId,
	--	    OM.DisplayTitle,
	--	     AC.ClassWorkDate, AC.DivisionId,AC.SubjectId
	--order by 
	--		AC.HomeWorkEndDate DESC
	--	END
	
END
GO
PRINT N'Altering [sAdmission].[pAdmissionAndInquiryConsolidateDashBoardGet]...';


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

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

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

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

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

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

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

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

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

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

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

		END
-- For Admission TypeId=1
ELSE IF(@rType='StatusClassWise')
		BEGIN
		
			SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(AF.Id),0) AS StatusCount ,CM.OrderIndex 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


				DECLARE @lSQLString nvarchar(max)=''

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

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

						print @lSQLString

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

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

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

						print @lSQLString1

						execute(@lSQLString1)
				END
			END

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

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


				DECLARE @lSQLStduentList nvarchar(max)=''

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

					--print @lSQLStduentList

					execute(@lSQLStduentList)

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

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

					print @lSQLStduentList1

						execute(@lSQLStduentList1)
			END
		END

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

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


				DECLARE @lSQLString3 nvarchar(max)=''

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

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

						print @lSQLString3

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

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

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

						print @lSQLString4

						execute(@lSQLString4)
				END
			END

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

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


				DECLARE @lSQLStduentList3 nvarchar(max)=''

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

					--print @lSQLStduentList

					execute(@lSQLStduentList3)

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

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

					print @lSQLStduentList4

						execute(@lSQLStduentList4)
			END
		END
	END
END
GO
PRINT N'Altering [sAdmission].[pRptAdmissionFormReceiptGet]...';


GO


ALTER PROCEDURE [sAdmission].[pRptAdmissionFormReceiptGet]
	 	 
	 	 @rAdmissionFormReceiptId bigint,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rFeeName nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT 
			AF.FirstName +' '+AF.LastName AS StudentName,
			--AF.MiddleName AS FatherName,
			AFFD.FatherName AS FatherName,
			AFFD.MotherName AS MotherName,
			AF.StreetOne+', '+AF.StreetTwo+', '+AF.StreetThree+', '+AF.City+', '+AF.State+', '+AF.Country+' - '+AF.ZipCode AS StudentAddress,
			AF.ContactNo AS MobileNo,
			AF.FormNo,
			AFR.ReceiptNumber,
			AFR.ReceiptDate,
			CM.Title AS ClassName,
			BM.Title AS BatchName,
			AFR.ReceiptAmount,
			@rFeeName AS FeeName,
			PTM.Title AS PayTypeName
	FROM 
		sAdmission.tAdmissionForm AF
		LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFFD ON AFFD.AdmissionFormId = AF.Id
		INNER JOIN sAdmission.tAdmissionFormReceipt AFR ON AF.Id = AFR.SourceId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId 
		INNER JOIN sOp.tPayTypeMaster PTM ON PTM.Id = AFR.PayTypeId 
	WHERE
		AFR.Id = @rAdmissionFormReceiptId
		AND AF.BatchId = @rBatchId
		AND AF.OrgId = @rOrgId
END
GO
PRINT N'Altering [sAlert].[pCheckEventTemplateGet]...';


GO
 
 
 
ALTER PROCEDURE [sAlert].[pCheckEventTemplateGet]

	@rOrgId smallint,
	@rEventId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
			AlertModeId,
			ISNULL(IsAutoSend,'false') AS IsAutoSend,
			Template,
			MailSubject,
			ISNULL(DefaultAlertTo,'') AS DefaultAlertTo,
			EMailCC,
			EMailBCC,
			ISNULL(WhatsAppTemplate,'') AS WhatsAppTemplate,
			ISNULL(WhatsAppTemplateLanguage,'') AS WhatsAppTemplateLanguage
	FROM 
			sAlert.tEventTemplate
	WHERE	
			EventId=@rEventId
			AND OrgId=@rOrgId
	ORDER BY AlertModeId
END
GO
PRINT N'Altering [sAlert].[pEventTemplateAdd]...';


GO
 
ALTER PROCEDURE [sAlert].[pEventTemplateAdd]
	 
	
	@rEventTemplateDetailXml [nvarchar](max),
	--@rAcademicId bigint,
	@rAlertModeId int,
	@rOrgId int
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rEventTemplateDetailXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN	
	 DELETE FROM sAlert.tEventTemplate
				 WHERE AlertModeId =@rAlertModeId  AND OrgId=@rOrgId
	
 
	 INSERT INTO sAlert.tEventTemplate
		(
			OrgId,
			EventId,
			MailSubject,
			Template,
			AlertModeId,
			IsAutoSend,
			DefaultAlertTo,
			SMSTemplateID,
			EMailCC,
			EMailBCC,
			WhatsAppTemplate,
			WhatsAppTemplateLanguage
			)
		SELECT
		
			OrgId,
			EventId,
			MailSubject,
			Template,
			AlertModeId,
			IsAutoSend,
			DefaultAlertTo,
			SMSTemplateID,
			EMailCC,
			EMailBCC,
			WhatsAppTemplate,
			WhatsAppTemplateLanguage
			
		FROM OPENXML (@loDoc, '/Table/EventTemplateDetail', 1)
		WITH ( 
				OrgId int,
				EventId bigint,
				AlertModeId int,
				MailSubject nvarchar(100),
				Template nvarchar(max),
				IsAutoSend bit,
				DefaultAlertTo nvarchar(500),
				SMSTemplateID nvarchar(100),
				EMailCC nvarchar(500),
				EMailBCC nvarchar(500),
				WhatsAppTemplate nvarchar(100),
				WhatsAppTemplateLanguage nvarchar(100)
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAlert].[pEventTemplateListGet]...';


GO
 
 
 
ALTER PROCEDURE [sAlert].[pEventTemplateListGet]

	@rAlertModeId int,
	@rOrgGroupId smallint,
	@rOrgId int,
	@rIsAutoSend bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	SELECT 
			EM.Title AS EventName,
			ISNULL(ET.Template,ISNULL(EM.Template,'')) AS TemplateName,
			EM.Id,
			ISNULL(ET.AlertModeId,0) AS AlertModeId,
			ISNULL(IsAutoSend,0) AS IsAutoSend,
			EM.Fields AS FieldName,
			MM.Title AS ModuleName,
			MM.Id AS ModuleId,
			ISNULL(ET.MailSubject,ISNULL(EM.MailSubject,'')) AS MailSubject,
			ISNULL(EM.IsAllowAutoSend,0) AS IsAllowAutoSend,
			ISNULL(ET.DefaultAlertTo,'') AS DefaultAlertTo,
			ISNULL(EM.IsAssignDefaultAlert,0) AS IsAssignDefaultAlert,
			ISNULL(ET.SMSTemplateID,'')AS SMSTemplateID,
			ISNULL(ET.EMailCC,'') AS EMailCC,
			ISNULL(ET.EMailBCC,'') AS EMailBCC,
			ISNULL(ET.WhatsAppTemplate,'') AS WhatsAppTemplate,
			ISNULL(ET.WhatsAppTemplateLanguage,'') AS WhatsAppTemplateLanguage
	FROM 
			 sAlert.tEventMaster EM
			 INNER JOIN sCommon.tModuleMaster MM ON MM.Id=EM.ModuleId
			 LEFT JOIN sAlert.tEventTemplate ET ON ET.EventId=EM.Id AND ET.OrgId=@rOrgId
			 AND ((ET.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			 INNER JOIN sSecurity.tModulePermission MP ON MP.OrgGroupId=@rOrgGroupId AND MP.ModuleId=EM.ModuleId 
			 --AND MP.ModuleId!=162
	WHERE	
			(EM.IsObsolete=0)
			ORDER BY ModuleName
			
END
GO
PRINT N'Altering [sAlert].[pWhatsAppConfigurationAdd]...';


GO
 
 
ALTER PROCEDURE [sAlert].[pWhatsAppConfigurationAdd]
	
	@rOrgId smallint,
	@rWhatsAppURL nvarchar(1000),	
	@rAdminUsername nvarchar(50),
	@rAdminPassword nvarchar(50),			
	@rOrgGroupId smallint,
	@rIsAllOrg bit,	
	@rRegisteredContactNo nvarchar(20),
	@rWhatsAppNamespace nvarchar(100) = ''	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 IF(@rIsAllOrg=1)
	 BEGIN
		DECLARE @lCount INT
		CREATE TABLE #tTable  
		(
			Id bigint identity,
			OrgId smallint
		)
		INSERT INTO #tTable
		(
			OrgId
		)
		SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId
		
		SELECT @lCount =  COUNT(Id) FROM #tTable
		WHILE @lCount > 0 
		BEGIN
			SELECT @rOrgId=OrgId FROM #tTable WHERE Id = @lCount
			IF NOT EXISTS(SELECT OrgId FROM sAlert.tWhatsAppConfiguration WHERE OrgId=@rOrgId)
BEGIN

	INSERT INTO sAlert.tWhatsAppConfiguration
		(
			OrgId,
			WhatsAppURL,			
			AdminUsername,
			AdminPassword,
			RegisteredContactNo,
			WhatsAppNamespace			
		)
	VALUES
		(
			@rOrgId,
			@rWhatsAppURL,
			@rAdminUsername,
			@rAdminPassword,			
			@rRegisteredContactNo,
			@rWhatsAppNamespace
		)
		             
	END	 
	 ELSE
	 BEGIN
	    UPDATE  sAlert.tWhatsAppConfiguration
	    SET
			WhatsAppURL=@rWhatsAppURL,
			AdminUsername=@rAdminUsername,
			AdminPassword=@rAdminPassword,
			RegisteredContactNo=@rRegisteredContactNo,
			WhatsAppNamespace=@rWhatsAppNamespace     
	      WHERE OrgId = @rOrgId 	   
	 END  
		SELECT @rOrgId AS Result
			SET @lCount = @lCount - 1
		END
	 END
	 ELSE
	 BEGIN
	 
 IF NOT EXISTS(SELECT OrgId FROM sAlert.tWhatsAppConfiguration WHERE OrgId=@rOrgId)
BEGIN

	INSERT INTO sAlert.tWhatsAppConfiguration
		(
			OrgId,
			WhatsAppURL,			
			AdminUsername,
			AdminPassword,
			RegisteredContactNo,
			WhatsAppNamespace	
		)
	VALUES
		(
			@rOrgId,
			@rWhatsAppURL,
			@rAdminUsername,
			@rAdminPassword,			
			@rRegisteredContactNo,
			@rWhatsAppNamespace	
		)
		             
	END	 
	 ELSE
	 BEGIN
	    UPDATE  sAlert.tWhatsAppConfiguration
	    SET
			WhatsAppURL=@rWhatsAppURL,
			AdminUsername=@rAdminUsername,
			AdminPassword=@rAdminPassword,
			RegisteredContactNo=@rRegisteredContactNo,
			WhatsAppNamespace=@rWhatsAppNamespace  	      
	      WHERE OrgId = @rOrgId 	   
	 END  
		SELECT @rOrgId AS Result
	END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAlert].[pWhatsAppConfigurationGet]...';


GO
 
 
ALTER PROCEDURE [sAlert].[pWhatsAppConfigurationGet]
	 
	 @rOrgId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	SELECT
			WC.WhatsAppURL,
			WC.AdminUsername,
			WC.AdminPassword,
			WC.RegisteredContactNo,
			WC.Token,
			ISNULL(WC.WhatsAppNamespace,'') AS 	WhatsAppNamespace
	FROM
			sAlert.tWhatsAppConfiguration WC
	WHERE 
			WC.OrgId=@rOrgId
END
GO
PRINT N'Altering [sAssessment].[pCSEXamIndicatorGet]...';


GO
ALTER PROCEDURE [sAssessment].[pCSEXamIndicatorGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rCCECSGroupId int,
	  @rBatchId int,
	  @rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
--BEGIN TRY
	DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX),@query2  AS NVARCHAR(MAX),@query3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT  ',' + QUOTENAME(CM.Title) FROM sAssessment.tCCECSGroupMaster CGM
					INNER JOIN sAssessment.tCCECSMaster CM ON CM.CCECAGroupId=CGM.Id
					INNER JOIN sAssessment.tCCECSClass CC ON CC.CCECSGroupId=CGM.Id AND CC.BatchID=@rBatchId
					INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= CM.Id AND CL.ClassID= @rClassId
					AND CC.ClassId = @rClassId AND CGM.OrgId = @rOrgId AND CGM.Id=@rCCECSGroupId AND CL.BatchID=@rBatchId
					AND ((CM.Id=@rCCECSId) OR (@rCCECSId=0))
					Order by CM.OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
	SET @query = 'Select AcademicId,RollNo,Code As Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Code,SA.Name,AM.Title,	 ISNULL(AIS.IndicatorIds,'''') AS Term1Indicator
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1 AND CA.BatchID='+convert(nvarchar,@rBatchID)+'
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	 INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id AND CL.ClassID='+ CONVERT(nvarchar,@rClassId)+' ANd CL.BatchId='+convert(nvarchar,@rBatchID)+'
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id AND AIS.ExamId= ' + Convert(nvarchar,@rExamId) + ' AND (AIS.CCECSId = ' + convert(nvarchar,@rCCECSId) + ' OR ' + convert(nvarchar,@rCCECSId) + ' = 0 ) 
	WHERE SA.ClassId=' + CONVERT(nvarchar,@rClassId) + ' 
	And SA.DivisionId = ' + CONVERT(nvarchar,@rDivisionID) + '	
	And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + '	
	And AM.CCECAGroupId= ' + CONVERT(nvarchar,@rCCECSGroupId) + '
	 
	) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'
	print @query
EXECUTE(@query)
--END TRY
--BEGIN CATCH
--	SELECT -1 AS RESULT
--END CATCH
END
GO
PRINT N'Altering [sAssessment].[pMarkEntryMasterUpdate]...';


GO

ALTER PROCEDURE [sAssessment].[pMarkEntryMasterUpdate]	 
           
       @rExamId int,
       @rDivisionId int,
       @rBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
	 --Get Siddhi Krupa Configuration Value
	 DECLARE @lConfigValue bit, @lOrgId int
	 DECLARE @lSiddhiKrupaApplicable bit
	 SELECT @lSiddhiKrupaApplicable = ISNULL(IsApplySiddhiKrupa,0) From sAssessment.tExamMaster Where Id = @rExamId
	 
	 SELECT @lOrgId = OM.Id From sSetup.tBatchMaster BM
					  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
					  Where BM.Id = @rBatchId
 	 
 	 SELECT @lConfigValue = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM
						    LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId AND SourceTypeId = 1016 AND SourceId = @lOrgId
						    WHERE CS.ConfigurationId = 278 
	 
	 --DECLARE @lMinimum int, @lObtain int, @lSiddhiMark int, @lKrupaMark int
	 --SELECT @lMinimum = ED.Minimum, @lObtain= RD.Obtain, @lSiddhiMark = RD.GraceMark, @lKrupaMark = RD.KrupaMark
		--			    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 sSetup.tDivisionMaster DM ON DM.ClassId = EM.ClassId
		--			    WHERE EM.Id = @rExamId AND EM.BatchId = @rBatchId AND DM.Id = @rDivisionId
	 --End Here
	 
	 DECLARE @lIsExcludeAbsentTotal bit,@lIsAllExamPassRequired bit, @lIsFailPercentageZero bit
	 
	 SELECT @lIsExcludeAbsentTotal = IsExcludeAbsentTotal,@lIsAllExamPassRequired=IsAllExamPassRequired FROM sAssessment.tExamMaster EM
	 WHERE EM.Id = @rExamId AND BatchId = @rBatchId
	 
	 SELECT @lIsFailPercentageZero = IsRemovePercentageForFail FROM sAssessment.tExamMaster EM WHERE EM.Id = @rExamId AND BatchId = @rBatchId
	 
		   UPDATE RD SET	SubjectGrade='',
							SubjectGradePoint=0,
							Percentile=0.00 
							--Remark=''
			FROM sAssessment.tResultDetail RD  
			INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id 
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = R.AcademicId AND R.ExamId = @rExamId AND SA.DivisionId=@rDivisionId 
			
			UPDATE R SET	TotalMarks=0,
							TotalObtain=0,
							ResultStatus='',
							ResultGrade='',
							ResultGradePoint = 0,
							RankNumber =0,
							Percentage = 0.00,
							Percentile =0.00
							--resultRemark=''			
			FROM sAssessment.tResult R 
			INNER JOIN sStudent.vStudentAcademic  SA ON SA.AcademicId=R.AcademicId AND ExamId = @rExamId AND DivisionId=@rDivisionId 
	 
	 DECLARE @lIsMarksInDecimal bit,@lDecimalFormat nvarchar(10)
	 select @lDecimalFormat = DecimalFormat from sAssessment.tExamMaster where Id =@rExamId
	select @lIsMarksInDecimal = IsMarksInDecimal from sAssessment.tExamMaster where Id= @rExamId
	
	IF @lIsExcludeAbsentTotal = 0
	BEGIN  
	UPDATE sAssessment.tResult SET TotalMarks= A.Maximum, 
					TotalObtain=A.Obtain,
	Percentage = (A.Obtain/A.Maximum)*100
	FROM 
	(SELECT
		CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
				Round(SUM(Obtain) ,1)
			WHEN ( @lIsMarksInDecimal= 1 AND @lDecimalFormat='0.00' ) THEN
				ROUND(ROUND(SUM(Obtain),2),2) 	
			ELSE			  
				ROUND(ROUND(SUM(Obtain),2) ,0) 
			END  AS Obtain,
		  
		  --round(SUM(Obtain),0) AS Obtain,
		  SUM(Maximum) AS Maximum,R.Id 
		  FROM sAssessment.tResultDetail RD
		  INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId --AND RD.IsPresent =1
		  INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
		  INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id AND ED.Id=RD.ExamDetailId
		  INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = EM.ClassId AND R.AcademicId=SA.AcademicId AND EM.BatchId=SA.BatchId
		  WHERE (R.ExamId = @rExamId OR @rExamId = 0) AND (SA.DivisionId=@rDivisionId or @rDivisionId=0) AND  ED.IsIncludeInTotal=1
		  AND EM.BatchId = @rBatchId AND SA.BatchId = @rBatchId
		  GROUP BY R.Id ) AS A 	
		  WHERE (ExamId = @rExamId OR @rExamId = 0) AND A.Id=sAssessment.tResult.Id
	END
	ELSE
	BEGIN
	
	UPDATE sAssessment.tResult SET TotalMarks= A.Maximum, 
	TotalObtain=A.Obtain,
	Percentage = (A.Obtain/A.Maximum)*100
	FROM 
	(SELECT  
		CASE WHEN  (@lIsMarksInDecimal = 1 AND @lDecimalFormat='0.0') THEN
				Round(Round(SUM(Obtain) ,1) ,1)
			WHEN ( @lIsMarksInDecimal= 1 AND @lDecimalFormat='0.00' ) THEN
				Round(ROUND(SUM(Obtain),2) ,2) 
			ELSE			  
				Round(ROUND(SUM(Obtain),2),0) 
			END  AS Obtain,
		--round(SUM(Obtain),0) AS Obtain,
		SUM(Maximum) AS Maximum,R.Id 
	FROM sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId AND RD.IsPresent = 1
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId=EM.Id AND ED.Id=RD.ExamDetailId
	INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = EM.ClassId AND R.AcademicId=SA.AcademicId AND EM.BatchId=SA.BatchId
	WHERE (R.ExamId = @rExamId OR @rExamId = 0) AND (SA.DivisionId=@rDivisionId or @rDivisionId=0) AND  ED.IsIncludeInTotal=1
	AND EM.BatchId = @rBatchId AND SA.BatchId = @rBatchId
	GROUP BY R.Id ) AS A 	
	WHERE (ExamId = @rExamId OR @rExamId = 0) AND A.Id=sAssessment.tResult.Id
	
	END
	--- Update Result Status	
	

	
	UPDATE R
	SET ResultStatus='' 
	FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A
	ON R.AcademicId = A.Id
	WHERE R.ExamId = @rExamId 
	AND A.DivisionId = @rDivisionId
	AND A.BatchId = @rBatchId
	
	
	--UPDATE R
	--SET ResultStatus='FAIL' 
	--FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
	--INNER JOIN
	--(
	--SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
	--INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
	--INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
	--INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
	--AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
	--AND A.BatchId = @rBatchId
	--INNER JOIN sAssessment.tOptionalSubject OS ON OS.ClassSubjectId = ED.ClassSubjectId AND OS.AcademicId = R.AcademicId
	--WHERE
	---- ClassSubjectId
	----NOT IN (SELECT ClassSubjectId FROM sAssessment.tOptionalSubject WHERE AcademicId=A.Id) 
	----AND 
	--RD.Obtain < Minimum
	-- ) D ON R.Id = D.Id	
	--WHERE R.ExamId = @rExamId	 
	--AND A.DivisionId = @rDivisionId 
	--AND A.BatchId = @rBatchId	

	
	--UPDATE R
	--SET ResultStatus='PASS' 
	--FROM sAssessment.tResult R INNER JOIN sStudent.tAcademic A
	--ON R.AcademicId = A.Id
	--WHERE R.ExamId = @rExamId 
	--AND R.ResultStatus = ''
	--AND A.DivisionId = @rDivisionId 
	--AND A.BatchId = @rBatchId
	
	
	--	UPDATE sAssessment.tResult SET ResultStatus='' 
	--WHERE ExamId = @rExamId
	--AND AcademicId IN (SELECT Id FROM sStudent.tAcademic WHERE
	--DivisionId = @rDivisionId AND BatchId = @rBatchId)
	
	IF @lIsExcludeAbsentTotal = 0
	BEGIN
		UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
		SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
		INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
		INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
		INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
		AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
		AND A.BatchId = @rBatchId	
		WHERE 
		--ClassSubjectId
		--NOT IN (SELECT ClassSubjectId FROM sAssessment.tOptionalSubject WHERE AcademicId=A.Id) 
		--AND 
		RD.Obtain < Minimum
		)
		
	END
	ELSE
	BEGIN
		UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
		SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
		INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
		INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
		INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
		AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
		AND A.BatchId = @rBatchId
		AND RD.IsPresent = 1
		WHERE
		 RD.Obtain < Minimum	
		)		
	END
	
	IF @lIsAllExamPassRequired = 1
	BEGIN
		UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ExamId = @rExamId AND  AcademicId 
		IN (	
		SELECT DISTINCT R.AcademicId FROM sAssessment.tResult R
		INNER JOIN sStudent.tAcademic A ON A.Id = R.AcademicId
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId = R.ExamId AND EC.ExamId = @rExamId
		WHERE A.BatchId = @rBatchId AND A.DivisionId = @rDivisionId AND R.ResultStatus = 'FAIL')
		
		IF @lConfigValue = 1 AND @lSiddhiKrupaApplicable = 1
		BEGIN
			UPDATE sAssessment.tResult SET ResultStatus='PASS' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			AND R.ResultStatus ='FAIL'
			WHERE RD.Obtain + RD.GraceMark + RD.KrupaMark >= Minimum AND RD.GraceMark > 0 --AND RD.KrupaMark > 0
			)
		
			UPDATE sAssessment.tResult SET ResultStatus='PROMOTED' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			AND R.ResultStatus ='PASS'
			WHERE RD.KrupaMark > 0
			)
			
			UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			--AND R.ResultStatus ='FAIL'
			WHERE RD.Obtain + RD.GraceMark + RD.KrupaMark < Minimum 
			)
			
		END		
	END
	
	
	UPDATE sAssessment.tResult SET ResultStatus='PASS' 
	WHERE ExamId = @rExamId AND ResultStatus <> 'FAIL'
	AND AcademicId IN (SELECT Id FROM sStudent.tAcademic WHERE
	DivisionId = @rDivisionId AND BatchId = @rBatchId)
	
	

	IF @lConfigValue = 1 AND @lSiddhiKrupaApplicable = 1
	BEGIN
		BEGIN
		    UPDATE sAssessment.tResult SET ResultStatus='PASS' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			AND R.ResultStatus ='FAIL'
			WHERE RD.Obtain + RD.GraceMark + RD.KrupaMark >= Minimum --AND RD.GraceMark > 0 --AND RD.KrupaMark > 0
			)
		
			UPDATE sAssessment.tResult SET ResultStatus='PROMOTED' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			AND R.ResultStatus ='PASS'
			WHERE RD.KrupaMark > 0
			)
			
			UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			--AND R.ResultStatus ='FAIL'
			WHERE RD.Obtain + RD.GraceMark + RD.KrupaMark < Minimum 
			)
			
			
		END	
	END
	
	IF @lIsFailPercentageZero =  1
	BEGIN
		UPDATE RT SET RT.Percentage=0 FROM sAssessment.tResult RT
		INNER JOIN sStudent.tAcademic SA ON SA.Id = RT.AcademicId
		AND RT.ExamId = @rExamId AND SA.DivisionId = @rDivisionId AND SA.BatchId = @rBatchId
		AND RT.ResultStatus='FAIL'

		IF @lConfigValue = 1 AND @lSiddhiKrupaApplicable = 1
		BEGIN
			UPDATE sAssessment.tResult SET ResultStatus='PASS' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			AND R.ResultStatus ='FAIL'
			WHERE RD.Obtain + RD.GraceMark + RD.KrupaMark >= Minimum --AND RD.GraceMark > 0 --AND RD.KrupaMark > 0
			)
		
			UPDATE sAssessment.tResult SET ResultStatus='PROMOTED' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			AND R.ResultStatus ='PASS'
			WHERE RD.KrupaMark > 0
			)
			
			UPDATE sAssessment.tResult SET ResultStatus='FAIL' WHERE ID IN (
			SELECT DISTINCT R.ID FROM sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
			INNER JOIN sAssessment.tResult R ON R.Id =RD.ResultId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id 
			AND R.ExamId = @rExamId AND A.DivisionId =@rDivisionId 	
			AND A.BatchId = @rBatchId	
			--AND R.ResultStatus ='FAIL'
			WHERE RD.Obtain + RD.GraceMark + RD.KrupaMark < Minimum 
			)
			
		END
	END
	
	
	SELECT 1 AS RESULT 
	
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pRptProgressCardGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptProgressCardGet]	 	 
	 @rClassId int,
	 @rBatchId int,
	 @rDivisionId int,	 
	 @rClassSubjectIdStr nvarchar(max),
	 @rExamGroupIdStr nvarchar(max),
	 @rFromDate Date='',
	 @rToDate Date='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

 --Select * from dbo.TempTableForProgress
	--SELECT 
	--	'' AS ACADEMICID,
	--	'' AS ExamDate,
	--	0 AS Maximum,
	--	0 AS Obtain,
	--	0 AS Percentage,
	--	'' AS ExamTopic,
	--	'' AS SubjectName,
	--	'' AS ExamGroup,
	--	'' AS StudentPhoto,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	'' AS StudentName,
	--	'' AS RollNo,
	--    '' AS IsMarksInDecimal,
	--	'' AS Year,
	--	'' AS MonthFrom,
	--	'' AS MonthTo,
	--	'' AS Code,
	--	'' AS EXAMNAME,
	--	'' AS ResultStatus

		

	CREATE TABLE #tempProgressCard
	(
		Id int Identity,
		AcademicId Bigint,
		ClassSubjectId bigint,
		ExamDate Date,
		Obtain Decimal(6,2),
		Maximum Decimal(6,2),
		Percentage Decimal(6,2),
		ExamId int
		
	)
 
 DECLARE @query  AS NVARCHAR(MAX)
 set @query = 'INSERT INTO #tempProgressCard 
 SELECT	R.AcademicId,ED.ClassSubjectId,ED.ExamDate ,SUM(RD.Obtain) AS Obtain,SUM(ED.Maximum) AS Maximum,
 (SUM(RD.Obtain)/SUM(ED.Maximum))*100 AS PERCENTAGE,ED.ExamId
FROM sAssessment.tExamMaster EM INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id
INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id AND ED.Id = RD.ExamDetailId
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = ESGM.ExamGroupId
INNER JOIN sStudent.tAcademic AM ON AM.Id = R.AcademicId
WHERE RD.ISPRESENT = 1 AND EM.ClassId =' + CONVERT(NVARCHAR,@rClassId) + '
 

AND AM.DivisionId = ' + CONVERT(NVARCHAR(500),@rDivisionId) + '
AND EGM.Id IN (' + CONVERT(NVARCHAR(500),@rExamGroupIdStr) + ')
AND ED.ClassSubjectId IN (' + CONVERT(NVARCHAR(500),@rClassSubjectIdStr) + ')
AND ED.EXAMDATE >= ''' + CONVERT(NVARCHAR,@rFromDate) +
''' AND ED.EXAMDATE <= ''' + CONVERT(NVARCHAR,@rToDate) +
''' AND ((AM.RollNo >= '''+ CONVERT(NVARCHAR(10),@rFromRollNo)+''') OR (' + CONVERT(NVARCHAR(10),@rFromRollNo)+'='''+ CONVERT(NVARCHAR(10),0) + ''')) 
AND ((AM.RollNo <= '''+ CONVERT(NVARCHAR(10),@rToRollNo) + ''' ) OR (' + CONVERT(NVARCHAR(10),@rToRollNo)+'='''+ CONVERT(NVARCHAR(10),0) + ''')) 
GROUP BY R.AcademicId,ED.ClassSubjectId,ED.ExamDate,ED.ExamId'
 --print @query
execute(@query)

-- To maintain Group Footer length add in report row	
--select 1, '.' + replicate('`', 600)  + '.'   font size 1

SELECT
T.AcademicId,
T.ExamDate,
T.Maximum,T.Obtain,T.Percentage,
CASE WHEN ED.ExamTopic = '0' THEN '' ELSE ED.ExamTopic  END AS ExamTopic,
CS.SubjectName AS SubjectName,
EGM.Title AS ExamGroup,
SF.StudentPhoto as StudentPhoto , 
SF.ClassName,
SF.DivisionName,
SF.Name AS StudentName,SF.RollNo, 
EM.IsMarksInDecimal,
SF.Code,
sCommon.fGetMonthName(DatePart(MM,@rFromDate)) AS MonthFrom,
sCommon.fGetMonthName(DatePart(MM,@rToDate)) AS MonthTo,
BM.Title AS Year,
ISNULL(ESGM.Title,'') AS EXAMNAME ,
(Select ResultStatus FROM sAssessment.tResult Where AcademicId = T.AcademicId AND  ExamId = EC.ExamId)AS ResultStatus



FROM #tempProgressCard T 
INNER JOIN sAssessment.tExamMaster EM on EM.Id=T.ExamId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = T.ExamId AND EM.Id=ED.ExamId AND T.ExamDate = ED.ExamDate
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = ESGM.ExamGroupId
INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id
INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = ED.ClassSubjectId AND CS.ClassSubjectId=T.ClassSubjectId 
INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId	= T.AcademicId AND SF.StatusId=1
INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SF.BatchId
Order By SF.RollNo,CS.OrderIndex,T.ExamDate Desc



DROP TABLE #tempProgressCard

END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGet]
	 
	 @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=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rFromObtain decimal(5,2)=0,
	 @rToObtain decimal(5,2)=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	
	 --,@rcolumn_visible bit
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam
 IF(@rOrgGroupBatchId=0)
	SELECT @rOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id=@rBatchId  
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

Select @GradeStringHtml = GradeStringHtml from sAssessment.tGradeSetMaster where Id =@GradeSetId
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(1000),
		Remark3 nvarchar(1000),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays smallint,
		PresentDays smallint,
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 smallint,
		PresentDays1 smallint,
		TotalDays2 smallint,
		PresentDays2 Smallint,
		TotalDays3 smallint,
		PresentDays3 smallint,
		TotalDays4 smallint,
		PresentDays4 smallint,
		TotalDays5 smallint,
		PresentDays5 smallint,
		TotalDays6 smallint,
		PresentDays6 smallint,
		TotalDays7 smallint,
		PresentDays7 smallint, 
		TotalDays8 smallint,
		PresentDays8 smallint,
		TotalDays9 smallint,
		PresentDays9 smallint,
		TotalDays10 smallint,
		PresentDays10 smallint,
		TotalDays11 smallint,
		PresentDays11 smallint,
		TotalDays12 smallint,
		PresentDays12 smallint,
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 smallint,
		SR_PresentDaysTerm2 smallint,
		SR_TotalDaysTerm1 smallint,
		SR_TotalDaysTerm2 smallint,
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max)
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	
	ExamCode,
	
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	Batch,
	ClassTeacherName,
	FirstName,
	LastName,
	IsDisplayMonthlyAttendance,
	MarksheetHeaderA4,
	IsImageHeader,
	MyGoal,
	AreaOfInterest,
	Responsibility,
	MyInterestHobby,
	MyStrength,
	Achievements, 
	
	DentalHygiene,
	VisionLeft,
	VisionRight,
	IsDetail,
	SubjectGroupId,
	SubjectGroupTitle,
	SubjectGroupCode,
	DecimalFormat,
	SubjectRemark,
	GraceMark,
	KrupaMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText,
    IsShowWithDetail,
    IsPresent,
    GradeTitle,
	
	SubjectHighestDivisionGrade,
	SubjectHighestDivisionMark,
	
	AchievementsTerm1,
	AchievementsTerm2,
	GeneralRemarkTerm1,
	GeneralRemarkTerm2,
	ResultRemark1Term1,
	ResultRemark2Term1,
	ResultRemark1Term2,
	ResultRemark2Term2,
	SR_HeightTerm1,
	SR_WeightTerm1,
	SR_HeightTerm2,
	SR_WeightTerm2,
	SR_PresentDaysTerm1,
	SR_PresentDaysTerm2,
	SR_TotalDaysTerm1,
	SR_TotalDaysTerm2,
	HouseName,
	HouseId,
	AdhaarNumber,
	UIdNumber,
	FatherContactNo ,
	MotherContactNo ,
	FatherMail ,
	MotherMail ,
	Gender,
	CoordinatorEmployeeSign,
	StudentAddress
		
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		Convert(nvarchar(50),@rClassId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		ISNULL(R.ResultStatus,'') AS ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		ISNULL(R.Percentage,0) As Percentage,
		R.RankNumber,
		ISNULL(R.ResultGrade,'') AS ResultGrade,


		EM.IsMarksInDecimal,
		
				
		1,
		--RD.Obtain,
		R.Percentile,
		--SM.Title AS ClassSubject,
		RD.Id AS ResultDetailId,
		R.Id AS ResultId,

		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,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
		SI.StudentPhoto
		ELSE NULL END)AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.TotalDays,
		SR.PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		ISNULL(ESGM.Code,'') AS ExamCode,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		 
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		--(CASE EM.IsDisplayImageHeader WHEN 1 THEN
		--	OI.CertificateHeaderA4 
		--	ELSE NULL END)AS  MarksheetHeaderA4,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		@rIsDetail AS IsDetail,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark,
		RD.GraceMark,
		RD.KrupaMark,
		@GradeStringHtml,
		SR.ResultRemark3,
		EM.IsDisplayTotalMark,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		
		'' AS AchievementsTerm1,
		'' AS AchievementsTerm2,
		'' AS GeneralRemarkTerm1,
		'' AS GeneralRemarkTerm2,
		'' AS ResultRemark1Term1,
		'' AS ResultRemark2Term1, 
		'' AS ResultRemark1Term2,
		'' AS ResultRemark2Term2,
		SR.StudentHeight AS SR_HeightTerm1,
		SR.StudentWeight AS SR_WeightTerm1,
		SR.StudentHeight AS SR_HeightTerm2,
		SR.StudentWeight AS SR_WeightTerm2,
		SR.PresentDays AS SR_PresentDaysTerm1,
	    SR.PresentDays AS SR_PresentDaysTerm2,
	    SR.TotalDays AS SR_TotalDaysTerm1,
	    SR.TotalDays AS SR_TotalDaysTerm2,
	    HM.Title As HouseName,HM.Id as HouseId,
	    ISNULL(SO.AdhaarNumber,'') As AdhaarNumber,
	    ISNULL(SO.UIdNumber,'') As UIdNumber,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END)AS Gender,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		(SC.PresentStreetOne +' '+ SC.PresentStreetTwo +' '+ SC.PresentStreetThree +' '+ SC.PresentCity +' '+ SC.PermanentState) AS StudentAddress
				
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 sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	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
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	Left JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	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
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.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 = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=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 ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=0))
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		AND  ISNULL(EMP.IsOtherUser,0) = 0
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	Order By ED.DisplayOrder

 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--print ('tempcombine')
	--SELECT * FROM #tempcombineExam
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--SET @lCount1 = @lCount+1
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.Obtain,0),
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 				
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 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 sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
--print(@query)
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.ExamSubGroupDisplayTitle,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 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 sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code,
					AchievementsTerm1 = SR.Achievements,
					GeneralRemarkTerm1 = SR.GeneralRemark,
					ResultRemark1Term1 = SR.ResultRemark1,
					ResultRemark2Term1 = SR.ResultRemark2,
					SR_HeightTerm1 = SR.StudentHeight,
					SR_WeightTerm1 = SR.StudentWeight,
					SR_PresentDaysTerm1 = SR.PresentDays,
					SR_TotalDaysTerm1 = SR.TotalDays
					
					From
					 
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		 	
						
		execute(@query)
		
					select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum,
					AchievementsTerm2 = SR.Achievements,
					GeneralRemarkTerm2 = SR.GeneralRemark,
					ResultRemark1Term2 = SR.ResultRemark1,
					ResultRemark2Term2 = SR.ResultRemark2,
					SR_HeightTerm2 = SR.StudentHeight,
					SR_WeightTerm2 = SR.StudentWeight,
					SR_PresentDaysTerm2 = SR.PresentDays,
					SR_TotalDaysTerm2 = SR.TotalDays
									 
					 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
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 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 sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
	--SELECT * FROM #TempAllExam	
	drop table #tempcombineExam
	Drop table #TempAllExam
	
	--Select
	--	'' As Builder1,
	--	'' As Builder2,
	--    '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
	--	'' As IsDisplayMonthlyAttendanceText,
	--    '' AS ClassIdText,
	--	0 As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	0 As TotalMark ,
	--	0 As TotalObtain,
	--	0 As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
 --       '' As IsMarksInDecimal,
 --             0 As column_visible,

 --             0 As Percentile ,

 --            0 As ResultDetailId, 
 --            0 As ResultId,

	--	'' As Remark1 ,
	--	'' As Remark2 ,
	--	'' As Remark3 ,
	--	'' As DisplayTitle ,		
	--	0 As IsRankNo , 
	--	0 As IsGrade ,
	--	0 As IsPercentile ,
	--	0 As IsPercentage ,
	--	0 As IsSubjectPercentile ,
	--	0 As IsProcessResult ,
	--	0 As IsNegativeMarks ,
	--	0 As IsIncludeCoScholastic ,
	--	0 As IsOnPrePrinted ,
	--	0 As IsDisplayPhoto ,
	--	0 As IsDisplayBirthDate ,
	--	0 As IsLockForEdit ,
	--	0 As IsDisplaySchoolName ,			
	--	0 As IsDisplayAttendance ,
	--	0 As IsDisplayHeightWeight ,
	--	0 As IsResultStatus ,
	--	'' As FooterAdjustmentText ,
	--	'' As DetailAdjustmentText ,
	--	0 As FooterAdjustment ,
	--	0 As DetailAdjustment ,
	--	'' As ResultRemark ,
	--	'' As DateOfBirth ,
	--	0 As HeightTerm1 ,
	--	0 As WeightTerm1 ,
	--	0 As HeightTerm2,
	--	0 As WeightTerm2 ,
	--	0 As HeightAnnual ,
	--	0 As WeightAnnual ,
	--	0 As PresentDaysTerm1,
	--	0 As PresentDaysTerm2 ,
	--	0 As PresentDaysAnnual ,
	--	0 As TotalDaysTerm1 ,
	--	0 As TotalDaysTerm2 ,
	--	0 As TotalDaysAnnual ,
	--	0 As TermScopeId ,		 
	--	0x As StudentPhoto ,
	--	'' As GradeString,
	--	0 As IsDisplayGradeString ,		 
	--	0 As IsDisplayInMarksheet ,
	--	0 As IsShowSubjectGrade ,
	--	0 As IsIncludeInTotal ,
	--	0 As ClassSubjectID ,
	--	0 As SubjectId ,
	--	--Maximum decimal(5,2),
	--	0 As SubjectOrderIndex ,
	--	'' As SubjectGrade ,
	--	'' As SubjectName ,
	--	'' As SubjectCode ,	
	--	0 As SubjectMinimum ,		
	--	0 As SubjectMaximum ,
	--	0 As SubjectObtain ,
	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,

	--	0 As TotalDays ,
	--	0 As PresentDays ,
	--	0 As StudentHeight,
	--	0 As StudentWeight ,
	--	'' As ExamSeatNo ,
	--    0 As ExamId ,

 --       '' AS ExamCode,

	--	0 As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	0 As IsShowSubjectMark , 
	--	0 As IsOptionalSubject ,
	--	0 As CoScholasticScopeId ,
	--	0 As IsDisplayPrincipalSign ,
	--	0 As IsDisplayTeacherSign ,
	--	0x As EmployeeSign,
 --            '' As Batch,
 --            '' As ClassTeacherName,
 --      '' AS FirstName,
 --      '' AS LastName,
 --            0 As IsDisplayMonthlyAttendance,
	--	0x As MarksheetHeaderA4 ,
	--	0 As IsImageHeader ,
 --            '' As    MyGoal,
 --       '' As  AreaOfInterest,
 --       '' As Responsibility,
 --       '' As MyInterestHobby,
 --       '' As MyStrength,
 --       '' As Achievements,

	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
 --             0 As IsDetail,
 --             0 AS   SubjectGroupId,
 --             ''   AS SubjectGroupTitle,
 --        '' AS SubjectGroupCode,
 --        '' AS DecimalFormat,
 --        '' AS SubjectRemark,
 --               0 As GraceMark,
 --               0 As KrupaMark,
 --                '' As GradeStringHtml,
 --          '' As ResultRemark3,
 --         0 As IsDisplayTotalMark,
 --         ''  As ContactNo,
	--	'' As PresentAddress ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
 --       '' As ImprovementArea,
 --       '' As ProgressArea,
 --       '' As GeneralRemark,
 --              '' As MyActivity,
 --        ''  As ClassTeacherRemark,

 --        '' As HouseRemark,
	--	  '' As BloodGroup ,
 --         '' As BatchIdText,
 --                0 As IsShowWithDetail,
 --                0 As IsPresent,
 --                ''  As GradeTitle,

 --         '' As SubjectHighestDivisionGrade,
 --                 0  As SubjectHighestDivisionMark,

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign			
-- SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
 
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Altering [sAttendance].[pAttendanceSummaryDashboard]...';


GO

ALTER  PROCEDURE [sAttendance].[pAttendanceSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rAttendanceDate date ='',
	@rClassId int=0,
	@rDepartmentId int =0,
	@rDivisionId int=0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'AttendanceList')
		BEGIN
			SELECT COUNT(SR.AcademicId)
					,ISNULL((SELECT COUNT(SR.AcademicId)
						FROM sStudent.vStudentAcademic SA 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId	 
							 AND SR.AttendanceDate = @rAttendanceDate WHERE SR.IsPresent=1 AND ((SA.OrgId=@rOrgId)OR(@rOrgId=0))
							 AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS PresentCount,
					ISNULL((SELECT COUNT(SR.AcademicId)
					FROM sStudent.vStudentAcademic SA 
						INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId AND SR.AttendanceDate = @rAttendanceDate
						INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId	 
						  WHERE SR.IsPresent=0 AND  ((CM.Id =@rClassId)OR(@rClassId=0)) AND ((SA.OrgId=@rOrgId)OR(@rOrgId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0)) ),0) AS AbsentCount,
				ISNULL((SELECT COUNT(SR.AcademicId)
				FROM sStudent.vStudentAcademic SA 
				INNER JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=SA.AcademicId  AND SLR.LeaveFromDate = @rAttendanceDate AND  SLR.LeaveToDate = @rAttendanceDate
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId	 
				WHERE ((CM.Id =@rClassId)OR(@rClassId=0)) AND ((SA.OrgId=@rOrgId)OR(@rOrgId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS LeaveCount
				FROM sStudent.vStudentAcademic SA 
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId  AND SR.AttendanceDate = @rAttendanceDate
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
			WHERE ((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
		END
	ELSE IF(@rType = 'ClassWiseAttendance')
		BEGIN 
			SELECT CM.Id,CM.Title,ISNULL(T.PresentCount,0) AS PresentCount ,ISNULL(T1.AbsentCount,0) As AbsentCount,CM.OrderIndex
				FROM sSetup.tClassMaster CM
						LEFT JOIN sStudent.vStudentAcademic SA  ON CM.Id = SA.ClassId	
						LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId  AND SR.AttendanceDate = @rAttendanceDate
						LEFT JOIN 
							(SELECT COUNT(SA.AcademicId) AS PresentCount,SA.ClassId FROM sStudent.vStudentAcademic SA 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
							WHERE SR.IsPresent=1 AND  AttendanceDate = @rAttendanceDate
							GROUP BY SA.ClassId 
						)T ON T.ClassId = SA.ClassId
						
						LEFT JOIN 
							(SELECT COUNT(SA.AcademicId) AS AbsentCount,SA.ClassId FROM sStudent.vStudentAcademic SA 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
							WHERE SR.IsPresent=0 AND  AttendanceDate = @rAttendanceDate
							GROUP BY SA.ClassId 
						)T1 ON T1.ClassId = SA.ClassId 
						--AND T.ClassId = T1.ClassId
			WHERE ((CM.OrgId=@rOrgId)OR (@rOrgId=0))
			AND ((CM.Id =@rClassId)OR(@rClassId=0))
			AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
				GROUP BY CM.Title, CM.Id,T.PresentCount,T1.AbsentCount,CM.OrderIndex
				ORDER BY CM.OrderIndex
		END
	
	ELSE 
		BEGIN 
		
			SELECT CM.Id,(CM.Title +' - '+ DM.Title) AS  Title ,ISNULL(T.PresentCount,0) AS PresentCount ,ISNULL(T1.AbsentCount,0) As AbsentCount,CM.OrderIndex
				FROM sSetup.tClassMaster CM
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id 
						LEFT JOIN sStudent.vStudentAcademic SA  ON CM.Id = SA.ClassId AND DM.Id = SA.DivisionId
						LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId  AND SR.AttendanceDate = @rAttendanceDate
						LEFT JOIN 
							(SELECT COUNT(SA.AcademicId) AS PresentCount,SA.ClassId,SA.DivisionId FROM sStudent.vStudentAcademic SA 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id AND DM.Id = SA.DivisionId
							WHERE SR.IsPresent=1 AND  AttendanceDate = @rAttendanceDate
							GROUP BY SA.ClassId,SA.DivisionId
						)T ON T.ClassId = SA.ClassId AND T.DivisionId = SA.DivisionId
						
						LEFT JOIN 
							(SELECT COUNT(SA.AcademicId) AS AbsentCount,SA.ClassId,SA.DivisionId FROM sStudent.vStudentAcademic SA 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id AND DM.Id = SA.DivisionId
							WHERE SR.IsPresent=0 AND  AttendanceDate = @rAttendanceDate
							GROUP BY SA.ClassId,SA.DivisionId
						)T1 ON T1.ClassId = SA.ClassId AND T1.DivisionId = SA.DivisionId
						--AND T.ClassId = T1.ClassId
			WHERE ((CM.OrgId=@rOrgId)OR (@rOrgId=0))
			AND ((CM.Id =@rClassId)OR(@rClassId=0))
			AND ((DM.Id =@rDivisionId)OR(@rDivisionId=0))
			AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
				GROUP BY CM.Title, CM.Id,T.PresentCount,T1.AbsentCount,CM.OrderIndex,DM.Title
				ORDER BY CM.OrderIndex
		END
END
GO
PRINT N'Altering [sAttendance].[pRptAttendanceSubjectwiseStatusGet]...';


GO
 
ALTER PROCEDURE [sAttendance].[pRptAttendanceSubjectwiseStatusGet]
	 	 	  
		 @rBuilder1 nvarchar(max)='',
	     @rBuilder2 nvarchar(max)='', 
		 @rOrgId smallint,
		 @rBatchId int,
		 @rClassId int,
		 @rDivisionId int,
		 @rSubjectId int,
		 @rFromDate date,
		 @rToDate date,
		 @rStudentCode nvarchar(20),
		 @rReportId int,
		 @rDepartmentId int,
		 @rSubject nvarchar(MAX)='',
		 @rStatusID int=0,
		 @rFromPercentage int=0,
		 @rToPercentage int=100
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rToDate = DATEADD (d,1,@rToDate)
 
SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.AcademicId,
		SA.RollNo,		
		SA.Code,
		SA.Name,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		R.SubjectId,
		R.Code AS SubjectCode,
		R.Title AS SubjectName,
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND (SR.IsPresent = 1)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalPresentCount,
		
		ISNULL((SELECT COUNT(1) FROM sAttendance.tStudentRegister SR WHERE SR.AcademicId = SA.ACademicID 
		AND SR.SubjectId = R.SubjectId		
		AND((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		AND (SR.IsPresent = 0)
		AND SR.AttendanceTypeId = 5
		Group BY SR.AcademicId,SR.SubjectId),0) AS TotalAbsentCount,
		
		@rFromPercentage as FromPercentage,
		@rToPercentage as ToPercentage

		FROM sStudent.vStudentAcademic SA INNER JOIN
	(
	SELECT DISTINCT SR.SubjectId,SM.Code,SM.Title,SA.AcademicId FROM
		sAttendance.tStudentRegister SR INNER JOIN 
		sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId 
	WHERE
		((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND (SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		----AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
		--AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
		--AND (SR.IsPresent = 1)
		AND SR.AttendanceTypeId = 5
		AND (ISNULL(SR.SubjectId,0) IN (SELECT cast(item as nvarchar(20)) FROM  sCommon.fnSplit(@rSubject,',')) OR (@rSubject=''))
		)
			 R
		ON SA.AcademicId = R.AcademicId
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((SA.StatusId  =@rStatusID) OR (@rStatusID=0))
	 
		




	--Select 
	--	@rBuilder1 AS Builder1,
	--	@rBuilder2 AS Builder2,
	--	SA.AcademicId,
	--	SA.Name,
	--	SA.Code,
	--	SA.RollNo,
		
	--	--SA.TotalCount,
	--	--SA.PresentCount,
	--	--SA.AbsentDays,
	--	--SA.AbsentCount,
	--	ISNULL(SM.Id,0) AS SubjectId,
	--	ISNULL(SM.Code,'') AS SubjectCode,
	--	ISNULL(SM.Title,'') AS SubjectName	
	--From 
	--sStudent.vStudentAcademic SA INNER JOIN 
	--(SELECT DISTINCT SR.SubjectId,SR.AcademicId FROM
	--sAttendance.tStudentRegister SR ) R ON R.AcademicId = SA.AcademicId
	
	-- ON SA.AcademicId=SR.AcademicId
	--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId
	--WHERE
	--	((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
	--	AND (SA.OrgId=@rOrgId)
	--	AND	(SA.BatchId = @rBatchId) 
	--	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	--	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	--	----AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
	--	AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	--	AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--	AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
	--	AND (SR.IsPresent = 1)
	--	AND SR.AttendanceTypeId = 5
	--	--AND (SA.StatusId != 3)
	
	
	
END
GO
PRINT N'Altering [sAttendance].[pStudentAttendaceDashboardGet]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

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

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

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

--Organization wise Attendance

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

--PresentStudent Organization wise
		 (SELECT count(*) 
			FROM sAttendance.tStudentRegister SME 
			   INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			   INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
			   INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OME.Id and SME.IsPresent=1 AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
			) AS PresentStudent,

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

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

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

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

      END
   
ELSE IF @rTypeId=24     
      BEGIN

      (SELECT *FROM  (
           SELECT 
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DM.Code As DivisionCode,
              (SMD.Code)StudentID,
              AEL.Id AS SourceId,
              (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			  (SC.ParentContactNo) AS ContactNo
	   FROM sAttendance.tStudentRegister SMEL
			   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
			   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
			   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
			   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
			   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		WHERE OMEL.Id=@rOrgId AND
		      SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId  
		GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)

	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	 ) AS Tmp) 
		
          
      END   
   
ELSE IF @rTypeId=15
	   BEGIN	
		(SELECT *FROM(
              SELECT  
                  OGMEL.Id as OrgGroupId,
                  OGMEL.Title As OrgGroupTitle,
                  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
                  DM.Code As DivisionCode,
                  (SMD.Code)StudentID,
                  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				  (SC.ParentContactNo) AS ContactNo,
				  AEL.Id AS SourceId
		      FROM sAttendance.tStudentRegister SMEL
				   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
				   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			       INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
				   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				   Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			   WHERE OGMEL.Id=@rOrgGroupId AND
				   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
			   GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	    ) AS Tmp) 
	   END
	   
ELSE IF @rTypeId=25
	BEGIN	
	 (SELECT *FROM(
           SELECT  
                OGMEL.Id as OrgGroupId,
                OGMEL.Title As OrgGroupTitle,
                OMEL.Id As OrgId,
                (OMEL.Title) As OrgTitle,
                DM.Code As DivisionCode,
                (SMD.Code)StudentID,
                (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
				AEL.Id AS SourceId
			FROM sAttendance.tStudentRegister SMEL
				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		    WHERE OMEL.Id=@rOrgId AND
				  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
			GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	  ) AS Tmp) 

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

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

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

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

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


GO
 
ALTER PROCEDURE [sAttendance].[pStudentAttendaceDashboardNewGet]
	 
	 @rTypeId smallint,
	 @rFromDate date=NULL,
	 @rToDate date=NULL,
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDivisionId int=0,
	 @rClassId int =0,
	 @rGenderType int=0,
	 @rCommonOrgGroupBatchId int=0,
	 @rSyncDate int =0,
	 @rUserId Bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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

				--@rUptoDate,
				@rCommonOrgGroupBatchId,GetDate()
				FROM sSetup.tOrgGroupMaster OGM 
				WHERE OGM.Id<>1 AND ISNULL(OGM.IsObsolete,0) = 0
				AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
	END

--Organization wise Attendance

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

--PresentStudent Organization wise
		 (SELECT count(*) 
			FROM sAttendance.tStudentRegister SME 
			   INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			   INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
			   INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OME.Id and SME.IsPresent=1 AND 
			--SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126) 
			((SME.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
			((SME.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
			AND COGBM.Id=@rCommonOrgGroupBatchId
			AND SME.AttendanceTypeId = 1
			) AS PresentStudent,

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

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

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

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

      END
   
ELSE IF @rTypeId=24     
      BEGIN

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

	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	 ) AS Tmp) 
		
          
      END   
   
ELSE IF @rTypeId=15
	   BEGIN	
		(SELECT *FROM(
              SELECT  
                  OGMEL.Id as OrgGroupId,
                  OGMEL.Title As OrgGroupTitle,
                  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
                  DM.Code As DivisionCode,
                  (SMD.Code)StudentID,
                  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				  (SC.ParentContactNo) AS ContactNo,
				  AEL.Id AS SourceId
		      FROM sAttendance.tStudentRegister SMEL
				   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
				   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			       INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
				   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				   Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			   WHERE OGMEL.Id=@rOrgGroupId AND
				   --SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) 
				   	((SMEL.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
					((SMEL.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				   AND COGBM.Id=@rCommonOrgGroupBatchId
				   AND SMEL.AttendanceTypeId = 1
			   GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	    ) AS Tmp) 
	   END
	   
ELSE IF @rTypeId=25
	BEGIN	
	 (SELECT *FROM(
           SELECT  
                OGMEL.Id as OrgGroupId,
                OGMEL.Title As OrgGroupTitle,
                OMEL.Id As OrgId,
                (OMEL.Title) As OrgTitle,
                DM.Code As DivisionCode,
                (SMD.Code)StudentID,
                (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
				AEL.Id AS SourceId
			FROM sAttendance.tStudentRegister SMEL
				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		    WHERE OMEL.Id=@rOrgId AND
				  --SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) 
				  	((SMEL.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = '')) AND
					((SMEL.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				  AND COGBM.Id=@rCommonOrgGroupBatchId
				  AND SMEL.AttendanceTypeId = 1
			GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	  ) AS Tmp) 

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

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

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

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

  ELSE
    BEGIN

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


GO

ALTER PROCEDURE [sAudit].[pActivityLogGet]
	@rOrgGroupId int,
	@rOrgId int,
	@rUserName nvarchar(100),
	@rScreenName nvarchar(100),
	@rActivity nvarchar(500),
	@rFromDate date,
	@rToDate date,
	@rOSTypeId tinyint=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rScreenName = sCommon.fSearchStringGet(@rScreenName)
SET @rActivity = sCommon.fSearchStringGet(@rActivity)
SET @rToDate = DATEADD(day,1,@rToDate)
       SELECT 
            AL.OrgGroupId,
            AL.OrgId,
            OM.Title AS OrganizationName,
            AL.UserId,
			U.DisplayTitle AS UserName,
			U.LoginTitle,
			U.SessionId,
			S.Title AS ScreenName,
			AL.AuditDate,
			(CASE WHEN AL.ScreenId=126
				  THEN AL.Activity		
			      WHEN AL.ScreenId=20878
				  THEN AL.Activity		
				  WHEN AL.ScreenId=30179
				  THEN AL.Activity
				  WHEN AL.ScreenId=20196
				  THEN AL.Activity
				  WHEN AL.ScreenId=30788
				  THEN AL.Activity
				  WHEN AL.ScreenId=30780
				  THEN AL.Activity
				  WHEN AL.ScreenId=30790
				  THEN AL.Activity
			 ELSE SUBSTRING(AL.Activity, CHARINDEX(' ', AL.Activity)+1, LEN(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1))  END)AS  Activity,			
			ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
			ISNULL(AL.RecordDetail,'') AS RecordDetail,
			ISNULL(OS.Title,'') AS OSType
			
       FROM 
		   sAudit.tActivityLog AL
		   INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
		   INNER JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId
		   LEFT JOIN sAlert.tOSType OS ON OS.Id = AL.OSTypeId
       WHERE
		   AL.OrgGroupId = @rOrgGroupId
		   AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
		   AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
		   AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
		   AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))
		   AND (AL.AuditDate >= @rFromDate)
		   AND (AL.AuditDate <= @rToDate)
		   AND ((AL.OSTypeId = @rOSTypeId) OR (@rOSTypeId=0))
       ORDER BY 
			AL.AuditDate DESC
END
GO
PRINT N'Altering [sBiometric].[pAbsentReportGet]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pAbsentReportGet]        
 @rFromDate Date,        
 @rToDate Date,        
 @rStatus nvarchar(10) = 'A',        
 @rOrgGroupId int =0,        
 @rBuilder1 nvarchar(max)='',        
 @rBuilder2 nvarchar(max)='',        
 @rOrgId int = 0,
 @rEmployeeStatusId int=0,
 @rEmployeeId bigint = 0
           
WITH EXECUTE AS CALLER        
AS        
SET NOCOUNT ON        
BEGIN         
  Select         
 @rBuilder1 AS Builder1,        
    @rBuilder2 AS Builder2,         
 Em.code,    
 P.AtdDate,    
 DM.[DisplayTitle],    
 EM.FirstName + ' ' + Em.MiddleName + ' ' + EM.LastName as EmployeeName,    
 isnull([Status],'A') as Status from sBiometric.tProcess P     
 inner join sHrm.tEmployeeMaster EM  on  P.Sourceid = Em.id    
 inner join [sHrm].[tEmployeeJobDetail] EJD on EM.id= EJD.EmployeeID      
 INNER JOIN [sSetup].[tDepartmentMaster] DM ON EJD.OrganizationDepartmentId = DM.id --AND P.SourceTypeId = 3       
 Where p.Status = 'A'
 AND (EM.Id = @rEmployeeId OR @rEmployeeId = 0)         
   AND ((P.AtdDate >= @rFromDate) OR (@rFromDate = ''))         
   AND ((P.AtdDate <= @rToDate) OR (@rToDate = '')) 
   AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)       
   AND ISNULL(EM.IsOtherUser,0) = 0     
END
GO
PRINT N'Altering [sBiometric].[pBiometricDailyReportGet]...';


GO
 
ALTER PROCEDURE [sBiometric].[pBiometricDailyReportGet]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 0,	
	 @rStatus nvarchar(max) = '',
	 @rEmployeeStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
DECLARE  @rToDate Date
SET @rToDate = @rFromDate

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 
AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
AND ISNULL(EM.IsOtherUser,0) = 0 

DECLARE @lCount int
DECLARE @lCount1 int
Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lMonth as nvarchar(3)
DECLARE @lYear as nvarchar(4)

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)
		Select @lMonth = RIGHT('00' + CAST(DATEPART(MM,@lDate) AS varchar(2)), 2)
		Select @lYear  = RIGHT('0000' + CAST(DATEPART(yyyy,@lDate) AS varchar(4)), 4)
		
		set @lQuery = 'INSERT INTO #TempMonthTrans
						SELECT Distinct ' + convert(nvarchar(15),@lEmployeeId) + ',''' + convert(nvarchar(15),@lDate) + ''',
						substring(DATENAME( dw, ''' + convert(nvarchar(15),@lDate) + '''),1,3) AS DN1,
											 

											 CASE When [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', ' + convert(nvarchar(10),@lYear) + ',' + convert(nvarchar(10),@lMonth) + ',' + convert(nvarchar(15),@lDay)+',
											 ' + convert(nvarchar(15),@lBatchId) + ',' + Convert(nvarchar(10),@rOrganizationDepartmentId) + ',' + convert(nvarchar(10),@rOrgId) + ') <> ''-'' then 
											 [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', ' + convert(nvarchar(10),@lYear) + ',' + convert(nvarchar(10),@lMonth) + ',' + convert(nvarchar(15),@lDay)+',
											 ' + convert(nvarchar(15),@lBatchId) + ',' + Convert(nvarchar(10),@rOrganizationDepartmentId) + ',' + convert(nvarchar(10),@rOrgId) + ') 
											 else D'+convert(nvarchar(15),@lDay)+' end AS 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)'
						--print @lQuery
			execute (@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1	
	END
	
	
	--Select * from #TempMonthTrans
	--return
	

	SET @strQuery = 'select Day(T.Attn_Date), T.*,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	
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 
	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 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 PresentStatus IN ' + @rStatus + ' AND (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0) Order By T.Attn_Date,T.EmployeeId'
	--WHERE (PresentStatus IN '+ '''' + @rStatus + '''' + ' OR (PresentStatus like ''%L%'')) Order By T.Attn_Date,T.EmployeeId' 


	--WHERE 1=1 and (ED.EmployeeGradeId in (' + convert(nvarchar(100),@rGRadeId) + ') OR (' + convert(nvarchar(100),@rGRadeId) + ') = 0) )' 
	
	
	print (@strQuery)
	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 TotEarly,
	--'' 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

	--CASE 
	--					When [sHrm].[fWeekHOffGetBio](' + 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) + ') in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
	--					When [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',' + CONVERT(nvarchar(13),@rOrganizationDepartmentId) + ',' + convert(nvarchar(15),@rOrgId) + ') Not in (''-'',''XX'') 
	--					Then [sHrm].[fWeekHOffGetBio](' + 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
GO
PRINT N'Altering [sBiometric].[pBiometricReportData]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pBiometricReportData]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int,
	@rDeptId int,
	@rForYear int=0,
	@rForMonth int=0,
	@rIsFirstIn bit=0,
	@rIsLastOut bit=0,
	@rIsOT bit=0,
	@rIsLateBy	bit=0,
	@rIsEarlyBy bit=0,
	@rIsDuration  bit=0,
	@rEmployeeStatusId int=0,
	@rEmployeeId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

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

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

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

		case when @Days >= 29 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,29,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D29,
		case when @Days >= 30 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,30,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D30,
		case when @Days >= 31 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,31,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D31,


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


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 @lEmpDepartmentID 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))

truncate table #TempMonthTrans

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,@lEmpDepartmentID = OrganizationDepartmentId  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)

		DECLARE @weekoffstatus nvarchar(20)

		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@rEmployeeId , @rForYear ,@rForMonth ,@rDay ,@rBatchId ,@rDepartmentId ,@rOrgId , @rBiometricStatus )
		SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(@lDate)  ,Month(@lDate), @lDay, @lBatchId,@lEmpDepartmentID,@rOrgId)		
		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(''' + convert(nvarchar(15),@lDate) + 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) + ')


		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 ''' +@weekoffstatus +''' in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
						When ''' +@weekoffstatus +''' Not in (''-'',''XX'') 
						Then ''' +@weekoffstatus +''' 
						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 
						INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId AND (ED.OrganizationDepartmentId ='''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+'''= 0 )
						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 (ISNULL(T1.SourceTypeId,95) = 95 OR T1.SourceTypeId = 0)'				
						
		Execute(@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1			
	END

	--SELECT * FROM #TempMonthTrans
	
	SET @strQuery = 'select  Day(T.Attn_Date), T.*,isnull(A.TotAbsent,0) AS TotAbsent,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,isnull(TotEarly,0) AS TotEarly,
	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 AND ISNULL(EMP.IsOtherUser,0) = 0 
	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'',''PW'',''PH'') 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 IN (''W'',''PW'',''PHW'') group by EmployeeId) 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  (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0) AND (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 TotEarly,
	--'' 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 [sBiometric].[pEmployeeCheckInGet]...';


GO
 

ALTER PROCEDURE [sBiometric].[pEmployeeCheckInGet]
	 
	 @rOrgId int,
	 @rEmployeeId bigint=0,
	 @rFromDate date = '',
	 @rToDate date = ''
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 Select 
		U.LoginTitle,B.EmployeePhoto ,EMp.FirstName+' ' +ISNULL(EMp.MiddleName,'')+' '+emp.LastName AS Name,B.CheckInTime,Emp.Id As EmployeeID ,B.CheckOutTime,B.Id,emp.Code
	 from sSecurity.tUser 
	 U INNER JOIN sHrm.tEmployeeMaster EMP ON  EMP.Id=U.SourceId
	 INNER JOIN sBiometric.tEmployeeCheckIn B ON B.EmployeeID=EMP.Id
	 WHere U.SourceTypeId =95 AND U.OrgId=@rORgId 
	 AND ((B.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0)) AND  ISNULL(EMP.IsOtherUser,0) = 0 
	 AND ((CAST(B.AttendanceDate AS DATE) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 AND ((CAST(B.AttendanceDate AS DATE) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	
END
GO
PRINT N'Altering [sBiometric].[pLateINRegisterGet]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pLateINRegisterGet]  
 @rFromDate Date,  
 @rToDate Date,  
 @rOrgGroupId int =0,  
 @rBuilder1 nvarchar(max)='',  
 @rBuilder2 nvarchar(max)='',  
 @rOrgId int = 0,
 @rEmployeeStatusId int=0,
 @rEmployeeId bigint = 0    
     
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
  Select   
   @rBuilder1 AS Builder1,@rBuilder2 AS Builder2,  
   Em.code,P.AtdDate,EM.DepartmentName,EM.EmployeeName,p.[Status] as [Status],P.CheckInTime,  
   Sh.PunchId , SFM.ShiftName as shiftName,p.LateComeTime  
   from sBiometric.tProcess P   
  INNER JOIN sHrm.vExtEmployeeMaster EM ON P.SourceId= EM.EmployeeId --AND P.SourceTypeId = 3  
  left join sHrm.tEmployeeMaster SH on SH.Id =  p.SourceId  
  left join sBiometric.tShiftMaster SFM on SFM.Id = SH.ShiftId  
  Where   
   (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
  AND ((P.AtdDate >= @rFromDate) OR (@rFromDate = ''))   
   AND ((P.AtdDate <= @rToDate) OR (@rToDate = ''))  
   and p.LateComeTime != '00:00'  and p.LateComeTime != ''
   AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)   
END
GO
PRINT N'Altering [sBiometric].[pMonthlyStatusUpdate]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pMonthlyStatusUpdate]
    
    @rAttndanceDate date,
    @rIsDelete bit=0,
    @rOrgGroupId int=0,
    @rBatchId int=0,
    @rOrgId int=0,
    @rUserId bigint=0
    
AS
SET NOCOUNT ON
BEGIN

	IF OBJECT_ID('tempdb..#TempLateCountEntry') IS NOT NULL
		DROP TABLE #TempLateCountEntry
	
	IF(@rIsDelete = 0)
	BEGIN
		IF EXISTS(SELECT 1 FROM sBiometric.tMonthlyStatusUpdate WHERE CONVERT(date,AttndanceDate) = CONVERT(date,@rAttndanceDate) AND Left(EmployeeID,4) =@rOrgId)
		BEGIN
			SELECT -201 AS RESULT 
			RETURN
		END
	END
	--ELSE
	--BEGIN
	--	IF NOT EXISTS(SELECT 1 FROM sBiometric.tMonthlyStatusUpdate WHERE AttndanceDate=@rAttndanceDate)
	--	BEGIN
	--		SELECT -102 AS RESULT
	--		RETURN
	--	END
	--END

	BEGIN TRY
	BEGIN TRANSACTION
	
	IF(@rIsDelete = 0)
	BEGIN
		Declare @Days int 
		DECLARE @rMonth int
		DECLARE @rYear int
		Set @rMonth = MONTH(@rAttndanceDate)
		Set @rYear = Year(@rAttndanceDate)
		select @Days=sCommon.fGetDaysInMonth(@rMonth,@rYear)
		
		INSERT INTO 
		sBiometric.tMonthlyStatusUpdate 
		SELECT            			            
	 Attn_Dt, Mt.EmployeeId, CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,1,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,1,BM.Id,0,BM.OrgId) Else Mt.D01 End D01,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,2,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,2,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D02 End D02,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,3,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,3,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D03 End D03,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,4,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,4,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D04 End D04,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,5,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,5,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D05 End D05,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,6,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,6,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else Mt.D06 End D06,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,7,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,7,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D07 End D07,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,8,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,8,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D08 End D08,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,9,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,9,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D09 End D09,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,10,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,10,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D10 End D10,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,11,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,11,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D11 End D11,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,12,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,12,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D12 End D12,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,13,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,13,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D13 End D13,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,14,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,14,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D14 End D14,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,15,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,15,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D15 End D15,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,16,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,16,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D16 End D16,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,17,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,17,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D17 End D17,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,18,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,18,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D18 End D18,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,19,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,19,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D19 End D19,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,20,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,20,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D20 End D20,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,21,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,21,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D21 End D21,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,22,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,22,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D22 End D22,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,23,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,23,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D23 End D23,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,24,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,24,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D24 End D24,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,25,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,25,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D25 End D25,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,26,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,26,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D26 End D26,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,27,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,27,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D27 End D27,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,28,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,28,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D28 End D28,
	 CAse when @Days >= 29 AND [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,29,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,29,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D29 End D29,
	 CAse when @Days >= 30 AND [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,30,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,30,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D30 End D30,
	 CAse when @Days >= 31 AND [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,31,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,31,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D31 End D31, 
	 D01_IN, D02_IN, D03_IN, D04_IN, D05_IN, D06_IN, D07_IN, D08_IN, D09_IN, D10_IN, D11_IN, D12_IN, D13_IN, D14_IN, D15_IN, D16_IN, D17_IN, D18_IN, D19_IN, D20_IN, D21_IN, D22_IN, 
			D23_IN, D24_IN, D25_IN, D26_IN, D27_IN, D28_IN, D29_IN, D30_IN, D31_IN, D01_OUT, D02_OUT, D03_OUT, D04_OUT, D05_OUT, D06_OUT, D07_OUT, D08_OUT, D09_OUT, D10_OUT, D11_OUT, 
			D12_OUT, D13_OUT, D14_OUT, D15_OUT, D16_OUT, D17_OUT, D18_OUT, D19_OUT, D20_OUT, D21_OUT, D22_OUT, D23_OUT, D24_OUT, D25_OUT, D26_OUT, D27_OUT, D28_OUT, D29_OUT, 
			D30_OUT, D31_OUT, Tot_Attn, Tot_Abs, Tot_WeekOFF, Tot_Holiday, Tot_HD, Tot_Leave
		FROM sBiometric.tMonthTrans Mt  LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Mt.EmployeeId 
		inner join sSetup.tBatchMaster BM ON BM.OrgId = ED.OrgId AND BM.IsActive = 1  AND ED.OrgId = @rOrgId
		WHERE CONVERT(date,Attn_Dt) = CONVERT(date,@rAttndanceDate) --AND Mt.EmployeeId = 9931000000051
		
	-- Leave Entry
	DECLARE @lIsErrorCaseAsAnAbsent bit=0	
	DECLARE @lErrorCaseAsAnAbsent nvarchar(50)
	
	SELECT @lErrorCaseAsAnAbsent = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 254 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	IF (@lErrorCaseAsAnAbsent IS NULL) OR (@lErrorCaseAsAnAbsent = 'False')
	SET @lIsErrorCaseAsAnAbsent = 0
	ELSE
	SET @lIsErrorCaseAsAnAbsent = 1	 
	
	DECLARE @lIsErrorCaseLeaveEntryDirectly bit=0	
	DECLARE @lErrorCaseLeaveEntryDirectly nvarchar(50)
	
	SELECT @lIsErrorCaseLeaveEntryDirectly = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 255 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	IF (@lIsErrorCaseLeaveEntryDirectly IS NULL) OR (@lIsErrorCaseLeaveEntryDirectly = 'False')
	SET @lErrorCaseLeaveEntryDirectly = 0
	ELSE
	SET @lErrorCaseLeaveEntryDirectly = 1	
	
	DECLARE @lIsAbsentAsLWP bit=0	
	DECLARE @lAbsentAsLWP nvarchar(50)
	
	SELECT @lAbsentAsLWP = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 258 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	IF (@lAbsentAsLWP IS NULL) OR (@lAbsentAsLWP = 'False')
	SET @lIsAbsentAsLWP = 0
	ELSE
	SET @lIsAbsentAsLWP = 1
	
	
	DECLARE @lErrorCaseLeaveDeduction nvarchar(50)
	SELECT @lErrorCaseLeaveDeduction = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 306 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	
	IF(@lIsErrorCaseLeaveEntryDirectly=1)
	BEGIN 		
		DECLARE @rFromDate date
		DECLARE @rToDate date
		
		SET @rFromDate = @rAttndanceDate		
		SET @rToDate = CONVERT(date, (CONVERT(nvarchar(4),YEAR(@rAttndanceDate)) +'-'+CONVERT(nvarchar(2),MONTH(@rAttndanceDate)) +'-'+ CONVERT(nvarchar(2),@Days)))
		
		CREATE TABLE #TempMonthlyStatusUpdate
		(
		Id int Identity,
		EmployeeId bigint,	
		AttendanceDate Date,
		PresentStatus nvarchar(50)
		)

		INSERT INTO #TempMonthlyStatusUpdate

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 01) as datetime),D01 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 02) as datetime),D02 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 03) as datetime),D03 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 04) as datetime),D04 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 05) as datetime),D05 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 06) as datetime),D06 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 07) as datetime),D07 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 08) as datetime),D08 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 09) as datetime),D09 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 10) as datetime),D10 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 11) as datetime),D11 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 12) as datetime),D12 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 13) as datetime),D13 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 14) as datetime),D14 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 15) as datetime),D15 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 16) as datetime),D16 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 17) as datetime),D17 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 18) as datetime),D18 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 19) as datetime),D19 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 20) as datetime),D20 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 21) as datetime),D21 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 22) as datetime),D22 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 23) as datetime),D23 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 24) as datetime),D24 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 25) as datetime),D25 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 26) as datetime),D26 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 27) as datetime),D27 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 28) as datetime),D28 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
		BEGIN
		INSERT INTO #TempMonthlyStatusUpdate
		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 29) as datetime),D29 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID
		END

		IF Month(@rFromDate) <> 2
		BEGIN
		INSERT INTO #TempMonthlyStatusUpdate
		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 30) as datetime),D30 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID
		END

		IF Month(@rFromDate) NOT IN (2,4,6,9,11)
		BEGIN
		INSERT INTO #TempMonthlyStatusUpdate
		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 31) as datetime),D31 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID
		END
		
		DECLARE @lCount int = 0
		SELECT @lCount = COUNT(Id) FROM #TempMonthlyStatusUpdate				
	 --- 3 Late Count means Add 1 Leave START HERE

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

		SELECT ROW_NUMBER() OVER(ORDER BY EMPLOYEEID ASC) AS RowNumber,EMPLOYEEID,ATTN_DT,count_late INTO #TempLateCountEntry FROM sBiometric.tMonthTrans 
		where EMPLOYEEID IN(SELECT EMPLOYEEID FROM  #TempMonthlyStatusUpdate WHERE MONTH(AttendanceDate)=@rMonth AND YEAR(AttendanceDate)=@rYear  GROUP BY EMPLOYEEID)
		AND MONTH(ATTN_DT)=@rMonth AND YEAR(ATTN_DT)=@rYear
		
		DECLARE @lMonthTransCount int=0		
		SELECT @lMonthTransCount = COUNT(RowNumber) FROM #TempLateCountEntry

		WHILE (@lMonthTransCount > 0)
		BEGIN 
			DECLARE @lLateCount int = 0
			DECLARE @rEmployeeId bigint = 0
			DECLARE @lAttnDt date
			DECLARE @rLeaveTypeId int = 0
			DECLARE @rTotalLeave int = 0
			DECLARE @FromDt date
			DECLARE @ToDt date
			DECLARE @lNextNumber bigint			

			IF(@lLateCountLeaveType IS NOT NULL)
				BEGIN
					SELECT @rEmployeeId=ISNULL(EmployeeId,0) FROM #TempLateCountEntry WHERE RowNumber = @lMonthTransCount 

					DECLARE @lIsErrorCaseAsAnAbsentEmployeeWise_ForLate nvarchar(100)
					DECLARE @lIsAbsentAsLWPEmployeeWise_ForLate nvarchar(100)

					SELECT @lIsErrorCaseAsAnAbsentEmployeeWise_ForLate = Value FROM sBiometric.tEmployeeConfiguration WHERE EmployeeId = @rEmployeeId AND EmployeeConfigurationMasterId = 2
					SELECT @lIsAbsentAsLWPEmployeeWise_ForLate = Value FROM sBiometric.tEmployeeConfiguration WHERE EmployeeId = @rEmployeeId AND EmployeeConfigurationMasterId = 1

					IF (@lIsErrorCaseAsAnAbsentEmployeeWise_ForLate IS NULL)
						SET @lIsErrorCaseAsAnAbsentEmployeeWise_ForLate = @lErrorCaseAsAnAbsent
					IF (@lIsAbsentAsLWPEmployeeWise_ForLate IS NULL)
						SET @lIsAbsentAsLWPEmployeeWise_ForLate = @lAbsentAsLWP
					

					IF(@lIsErrorCaseAsAnAbsentEmployeeWise_ForLate = 'True' OR @lIsAbsentAsLWPEmployeeWise_ForLate = 'True')
					BEGIN
					set @lLateCount= (SELECT ISNULL([sBiometric].[fEmployeeLateCountGet](@rEmployeeId, @rMonth,@rYear),0) AS LateCount)

					IF(@lLateCount >= 3)
					BEGIN
						SELECT @rLeaveTypeId=ISNULL(Id,0) FROM  sHrm.tLeaveTypeMaster WHERE OrgId = @rOrgId AND Code=@lLateCountLeaveType

						SET @rTotalLeave = (SELECT (@lLateCount/3) AS RESULT ) 

						IF(@rLeaveTypeId!=0)
							BEGIN
							SET @lAttnDt = GETDATE()
							
							SET @ToDt =  CONVERT(date, (CONVERT(nvarchar(4),@rYear) +'-'+CONVERT(nvarchar(2),@rMonth) +'-'+ CONVERT(nvarchar(2),@Days)))

							SET @FromDt = (select DATEADD(D,(-@rTotalLeave)+1 ,@ToDt))

							IF NOT EXISTS(SELECT 1 FROM sHrm.tLeave WHERE EmployeeId = @rEmployeeId AND OrgId = @rOrgId AND BatchId = @rBatchId AND StatusId=550 and LeaveReason='Late Coming' AND ReportDate=@ToDt)

								BEGIN
								 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tLeave', 0, 1, 1,@outNextNumber = @lNextNumber output
							 
								INSERT INTO [sHrm].[tLeave]([Id],[EmployeeId],[ReportDate],[FromDate],[ToDate],[LeavePeriodId],[LeaveTypeId],[LeaveReason],NoOfLeave,BatchId,[OrgId],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime],[StatusId],[FromTime],[ToTime])
								 VALUES (@lNextNumber,@rEmployeeId,@ToDt,@FromDt,@ToDt ,1,@rLeaveTypeId,'Late Coming',@rTotalLeave,@rBatchId,@rOrgId,@rUserId,sCommon.fGetDate(),@rUserId,sCommon.fGetDate(),550,NULL,NULL)	

								--EXEC [sHrm].[pLeaveAdd] 0,@rEmployeeId,@ToDt,@FromDt,@ToDt ,1,@rLeaveTypeId,'Late Coming',@rTotalLeave,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL
								END
							END
					END
			END
		END

			SET @lMonthTransCount = @lMonthTransCount -1
		END
	--- END HERE
		
		WHILE (@lCount > 0)
		BEGIN		
			 DECLARE @lEmployeeId bigint = 0
			 DECLARE @lAttendanceDate date
			 DECLARE @lPresentStatus nvarchar(50) = ''
			 DECLARE @lLeaveTypeId int = 0
			 			 
				SELECT @lEmployeeId=ISNULL(EmployeeId,0),@lAttendanceDate=AttendanceDate,@lPresentStatus=PresentStatus FROM #TempMonthlyStatusUpdate WHERE Id = @lCount AND PresentStatus='E'
					IF(@lEmployeeId!=0)
					BEGIN
						DECLARE @lIsErrorCaseAsAnAbsentEmployeeWise nvarchar(100)	= @lErrorCaseAsAnAbsent					

					SELECT @lIsErrorCaseAsAnAbsentEmployeeWise = Value FROM sBiometric.tEmployeeConfiguration WHERE EmployeeId = @lEmployeeId AND EmployeeConfigurationMasterId = 2
					

					IF (@lIsErrorCaseAsAnAbsentEmployeeWise IS NULL)
						SET @lIsErrorCaseAsAnAbsentEmployeeWise = @lErrorCaseAsAnAbsent
					
					--print(@lIsErrorCaseAsAnAbsentEmployeeWise)

					IF(@lIsErrorCaseAsAnAbsentEmployeeWise = 'True')
					BEGIN

						SELECT @lLeaveTypeId=ISNULL(Id,0) FROM  sHrm.tLeaveTypeMaster WHERE OrgId = @rOrgId AND IsLWP=1
						
						IF(@lLeaveTypeId!=0)
						BEGIN
							IF(@lErrorCaseLeaveDeduction='0' OR @lErrorCaseLeaveDeduction='1')
								EXEC [sHrm].[pLeaveAdd] 0,@lEmployeeId,@lAttendanceDate,@lAttendanceDate,@lAttendanceDate ,1,@lLeaveTypeId,'Error Case',1,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL
							ELSE IF(@lErrorCaseLeaveDeduction='0.50')
								EXEC [sHrm].[pLeaveAdd] 0,@lEmployeeId,@lAttendanceDate,@lAttendanceDate,@lAttendanceDate ,1,@lLeaveTypeId,'Error Case',0.50,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL
						END	
					END
			 END
			 			 
				SELECT @lEmployeeId=ISNULL(EmployeeId,0),@lAttendanceDate=AttendanceDate,@lPresentStatus=PresentStatus FROM #TempMonthlyStatusUpdate WHERE Id = @lCount AND (PresentStatus='A' OR PresentStatus = 'HD')
					IF(@lEmployeeId!=0)
					BEGIN					
					DECLARE @lIsAbsentAsLWPEmployeeWise nvarchar(100) = @lAbsentAsLWP
					SELECT @lIsAbsentAsLWPEmployeeWise = Value FROM sBiometric.tEmployeeConfiguration WHERE EmployeeId = @lEmployeeId AND EmployeeConfigurationMasterId = 1
					IF (@lIsAbsentAsLWPEmployeeWise IS NULL)BEGIN					
						SET @lIsAbsentAsLWPEmployeeWise = @lAbsentAsLWP 
						END
										
					IF(@lIsAbsentAsLWPEmployeeWise = 'True')					
					SELECT @lLeaveTypeId=ISNULL(Id,0) FROM  sHrm.tLeaveTypeMaster WHERE OrgId = @rOrgId AND IsLWP=1
					IF(@lLeaveTypeId!=0)
					BEGIN										
						IF(@lPresentStatus = 'HD') BEGIN 
						EXEC [sHrm].[pLeaveAdd] 0,@lEmployeeId,@lAttendanceDate,@lAttendanceDate,@lAttendanceDate ,2,@lLeaveTypeId,'Error Case(Half Day)',0.50,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL 
						END
						ELSE BEGIN
						EXEC [sHrm].[pLeaveAdd] 0,@lEmployeeId,@lAttendanceDate,@lAttendanceDate,@lAttendanceDate ,1,@lLeaveTypeId,'Error Case(Full Day)',1,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL
						END
				END
			 END
			 
			 SET @lCount = @lCount -1
		END
	END
	END
	ELSE
	BEGIN
		DELETE FROM sBiometric.tMonthlyStatusUpdate WHERE CONVERT(date,AttndanceDate) = CONVERT(date,@rAttndanceDate)
		AND Left(EmployeeID,4)=@rOrgId
	END
	
	SELECT 1 AS RESULT	
	   
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Altering [sBiometric].[pRptDateWiseTimeSheetSummary]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pRptDateWiseTimeSheetSummary]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rToDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 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',
	 @rEmployeeStatusId int=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 
INNER 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 
AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)
AND ISNULL(EM.IsOtherUser,0) = 0 


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 @lEmpDepartmentID 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,Leave nvarchar(100),DayNumber nvarchar(8),PresentStatus nvarchar(25),
		FirstIn nvarchar(20),LastOut nvarchar(20),OverTime nvarchar(20),LateBy nvarchar(20),Duration nvarchar(20),EarlyBy nvarchar(20))

truncate table #TempMonthTrans

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,@lEmpDepartmentID = OrganizationDepartmentId  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)

		DECLARE @weekoffstatus nvarchar(20)

		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@rEmployeeId , @rForYear ,@rForMonth ,@rDay ,@rBatchId ,@rDepartmentId ,@rOrgId , @rBiometricStatus )
		SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(@lDate)  ,Month(@lDate), @lDay, @lBatchId,@lEmpDepartmentID,@rOrgId)		
		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(''' + convert(nvarchar(15),@lDate) + 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) + ')

		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 ''' +@weekoffstatus +''' in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
						When ''' +@weekoffstatus +''' Not in (''-'',''XX'') 
						Then ''' +@weekoffstatus +''' 
						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 
						INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId AND (ED.OrganizationDepartmentId ='''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+'''= 0 )
						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 (ISNULL(T1.SourceTypeId,95) = 95 OR T1.SourceTypeId = 0)'				
						
		Execute(@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1			
	END
	--Select * from #TempMonthTrans
	
	UPDATE tmp 
	SET PresentStatus='A'
	FROM  #TempMonthTrans tmp
	INNER JOIN sHrm.tLeave L ON tmp.EmployeeId=L.EmployeeId
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE L.StatusId = 550 AND L.EmployeeId = tmp.EmployeeId AND CAST(Attn_Date AS DATE) BETWEEN L.FromDate AND L.ToDate

	UPDATE tmp 
	SET Leave=LTM.Code + '/' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
	FROM  #TempMonthTrans tmp
	INNER JOIN sHrm.tLeave L ON tmp.EmployeeId=L.EmployeeId
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE L.StatusId = 550 AND L.EmployeeId = tmp.EmployeeId AND CAST(Attn_Date AS DATE) BETWEEN L.FromDate AND L.ToDate


	--Select * from #TempMonthTrans

	SET @strQuery = 'select  Day(T.Attn_Date), T.*,isnull(A.TotAbsent,0) AS TotAbsent,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,isnull(TotEarly,0) AS TotEarly,
	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 AND ISNULL(EMP.IsOtherUser,0) = 0 
	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'',''PW'',''PH'') 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 IN (''W'',''PW'',''PHW'') group by EmployeeId) 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 (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0) AND (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 Leave,
	--'' 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 TotEarly,
	--'' 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 [sBiometric].[pRptEmployeeCheckInGet]...';


GO
 
ALTER PROCEDURE [sBiometric].[pRptEmployeeCheckInGet]    
      
   @rOrgId int ,    
   @rBuilder1 nvarchar(max)='',    
   @rBuilder2 nvarchar(max)='',    
   @rdate date='',
   @rEmployeeStatusId int=0,
   @rEmployeeId bigint = 0    
       
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
BEGIN     
  Select     
   convert(binary,null,0) as EmployeePhoto ,    
   EMp.FirstName+' ' +EMp.MiddleName+' '+emp.LastName AS Name,    
   case B.CheckInTime when null then null when '' then null else B.CheckInTime end as CheckInTime,
   Emp.id As EmployeeID ,
   case B.CheckOutTime when null then null when '' then null else B.CheckOutTime end as CheckOutTime,   
   B.SourceId,    
   @rBuilder1 AS Builder1,    
   @rBuilder2 AS Builder2      
  from     
   sHrm.tEmployeeMaster EMP      
   --LEFT JOIN sBiometric.tEmployeeCheckIn B ON B.EmployeeID=EMP.Id    
   --and EMp.OrgId=@rORgId  ANd @rDate=convert(date,B.CheckInTime)    
   LEFT JOIN sBiometric.tProcess B ON B.SourceId=EMP.Id   
   and EMp.OrgId=@rORgId  ANd @rDate=convert(date,B.AtdDate)
   WHERE (Emp.Id = @rEmployeeId OR @rEmployeeId = 0) AND (EMP.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)  AND  ISNULL(EMP.IsOtherUser,0) = 0   
    
END
GO
PRINT N'Altering [sBiometric].[pRptEmployeeWiseMonthlyAttendanceGet]...';


GO
 
ALTER PROCEDURE [sBiometric].[pRptEmployeeWiseMonthlyAttendanceGet]  
    
  @rOrgId int ,  
   @rBuilder1 nvarchar(max)='',  
   @rBuilder2 nvarchar(max)='' ,  
   @rFromMonth int=0,  
   @rFromyear int=0,
   @rEmployeeStatusId int=0  ,
   @rEmployeeId bigint = 0
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
  
 CREATE Table #temptable  
 (  
  EmployeeId bigint,  
  D1 nvarchar(5),D2 nvarchar(5),D3 nvarchar(5),D4 nvarchar(5),D5 nvarchar(5),D6 nvarchar(5),D7 nvarchar(5),D8 nvarchar(5),D9 nvarchar(5),  
  D10 nvarchar(5),D11 nvarchar(5),D12 nvarchar(5),D13 nvarchar(5),D14 nvarchar(5),D15 nvarchar(5),D16 nvarchar(5),D17 nvarchar(5),  
  D18 nvarchar(5),D19 nvarchar(5),D20 nvarchar(5),D21 nvarchar(5),D22 nvarchar(5),D23 nvarchar(5),D24 nvarchar(5),D25 nvarchar(5),  
  D26 nvarchar(5),D27 nvarchar(5),D28 nvarchar(5),D29 nvarchar(5),D30 nvarchar(5),D31 nvarchar(5)  
 )  

 Insert into #temptable  
 (  
  EmployeeId  
 )  
 --select * from sbiometric.tprocess
 Select Distinct B.Sourceid   
  from sHrm.tEmployeeMaster EMP    
  INNER JOIN sbiometric.tprocess B ON B.Sourceid=EMP.Id  
  WHere EMp.OrgId=@rOrgId  AND MONTH(B.AtdDate)=@rFromMonth AND YEAR(B.AtdDate)=@rFromyear   AND  ISNULL(EMP.IsOtherUser,0) = 0
  AND (EMP.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)

  update #temptable set D1='-', D2='-', D3='-', D4='-', D5='-', D6='-', D7='-', D8='-', D9='-', D10='-', D11='-', D12='-', D13='-', D14='-', D15='-',  
   D16='-', D17='-', D18='-', D19='-', D20='-', D21='-', D22='-', D23='-', D24='-', D25='-', D26='-', D27='-', D28='-', D29='-', D30='-', D31='-'  
    
  Update t1 set t1.D1 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=1  
  Update t1 set t1.D2 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=2  
  Update t1 set t1.D3 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=3  
  Update t1 set t1.D4 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=4  
  Update t1 set t1.D5 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=5  
  Update t1 set t1.D6 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=6  
  Update t1 set t1.D7 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=7  
  Update t1 set t1.D8 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=8  
  Update t1 set t1.D9 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=9  
  Update t1 set t1.D10 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=10  
  Update t1 set t1.D11 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=11  
  Update t1 set t1.D12 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=12  
  Update t1 set t1.D13 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=13  
  Update t1 set t1.D14 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=14  
  Update t1 set t1.D15 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=15  
  Update t1 set t1.D16 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=16  
  Update t1 set t1.D17 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=17  
  Update t1 set t1.D18 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=18  
  Update t1 set t1.D19 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=19  
  Update t1 set t1.D20 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=20  
  Update t1 set t1.D21 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=21  
  Update t1 set t1.D22 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=22  
  Update t1 set t1.D23 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=23  
  Update t1 set t1.D24 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=24  
  Update t1 set t1.D25 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=25  
  Update t1 set t1.D26 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=26  
  Update t1 set t1.D27 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=27  
  Update t1 set t1.D28 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=28  
  Update t1 set t1.D29 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=29  
  Update t1 set t1.D30 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=30  
  Update t1 set t1.D31 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=31  
    
  Select   
   EMp.FirstName+' ' +EMp.MiddleName+' '+emp.LastName AS Name,  
   Emp.Id As EmployeeID ,  
    @rBuilder1 AS Builder1,  
    @rBuilder2 AS Builder2,  
    t1.*,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=1  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=1 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D1,  
      
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=2  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=2 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS  D2,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=3  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=3 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D3,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=4  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=4 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D4,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=5  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=5 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D5,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=6  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=6 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D6,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=7  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=7 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D7,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=8  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=8 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D8,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=9  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=9 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D9,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=10  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=10 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D10,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=11  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=11 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D11,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=12  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=12 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D12,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=13  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=13 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D13,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=14  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=14 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D14,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=15  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=15 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D15,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=16  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=16 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D16,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=17  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=17 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D17,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=18  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=18 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D18,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=19  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=19 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D19,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=20  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=20 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D20,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=21  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=21 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D21,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=22  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=22 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D22,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=23  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=23 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D23,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=24  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=24 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D24,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=25  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=25 And EmployeeId=Emp.Id Group by EmployeeId  )  
   --   ELSE  '-' END   
   -- )AS   D25,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=26  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=26 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D26,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=27  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=27 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D27,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=28  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=28 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D28,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=29  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=29  And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D29,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=30  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=30 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D30,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=31  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=31 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS   D31,  
    sCommon.fGetDaysInMonth(@rFromMonth,@rFromyear) As DaysInMonth  
       
      
  from sHrm.tEmployeeMaster EMP    
  INNER JOIN #temptable t1 On t1.EmployeeId =EMp.Id  AND  ISNULL(EMP.IsOtherUser,0) = 0
  WHERE (Emp.Id = @rEmployeeId OR @rEmployeeId = 0)
END
GO
PRINT N'Altering [sBiometric].[pRptMonthlySummaryListGet]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pRptMonthlySummaryListGet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int = 0,
	@rDeptId int = 0,
	@rForYear int=0,
	@rForMonth int=0,	 
	@rEmployeeStatusId int=0,
	@rEmployeeId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		MT.EmployeeId,
		MT.EmpCode,
		EM.FirstName + ' ' + EM.LastName AS EmployeeName,
		MT.Tot_Attn  AS TotalPresentDays,
		MT.Tot_Abs AS TotalAbsentDays,
		MT.Tot_WeekOFF AS TotalWeekOffs,
		MT.Tot_Holiday AS TotalHolidays,
		OM.Id AS OrganizationId,
		OM.DisplayTitle AS OrganizationTitle,
		OM.OrderIndex AS OrganizationOrderIndex,
		EM.Number AS EmployeeNumber,
		DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays		
	FROM
	sBiometric.tMonthTrans MT
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId --AND SourceTypeId = 95
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	WHERE
	YEAR(MT.Attn_Dt) = @rForYear
	AND (MONTH(MT.Attn_dt) = @rForMonth )
	AND (EJD.OrganizationDepartmentId = @rDeptId OR @rDeptId = 0)		 	
	AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
	AND ISNULL(EM.IsOtherUser,0) = 0 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	AND (MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
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)='',
	 @rUserName nvarchar(100)=''
	 
	 
	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,
			L.LCBookNumber,
			SO.GenderId,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(SC.PresentState,'') 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
			,vSA.BatchName AS BatchName,
			CSM.Title As CasteCategory,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SI.StudentPhoto,
			SA.AdmissionFormNumber,
			BM.FromDate as BatchStartDate,
			BM.ToDate as BatchEndDate,
			SO.UIDNumber,
			SC.PresentStreetOne AS Address1,
			SC.PresentStreetTwo AS Address2,
			SC.PresentStreetThree AS Address3,
			SC.PresentCity AS PresentCity,
			SC.PresentZipCode AS PresentZipCode,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			L.TotalDays,
			L.PresentDays,
			ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
		--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
		@rUserName AS UserName,
		EI.EmployeeSign,
		EI1.EmployeeSign AS DivisionInchargeEmployeeSign,
		ISNULL(L.ProofOfDOB,'')AS ProofOfDOB,
		U.LoginTitle AS CreatedUserName
	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 
			INNER JOIN sSecurity.tUser U ON U.Id = L.CreatedUserId
			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
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sSetup.tDivisionInchargeEmployee DIE ON vSA.DivisionId = DIE.DivisionId AND DIE.BatchId = vSA.BatchId
			AND DIE.Number = (SELECT MIN(Number) FROM sSetup.tDivisionInchargeEmployee WHERE  DIE.DivisionId = vSA.DivisionId AND DIE.BatchId = vSA.BatchId)
			LEFT JOIN sHrm.tEmployeeImages EI1 ON EI1.EmployeeId = DIE.EmployeeId
	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 sAlumni.tStudentMapping WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tUserFeedback WHERE CAST(LEFT(UserId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeExpense WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId


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

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

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

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

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


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

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


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

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


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

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


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

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

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

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


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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


GO
 
 
ALTER PROCEDURE [sCommon].[pUploadDocumentAdd]
	 
	@rUploadFunctionalityId smallint,
	@rUserSourceTypeId smallint,
	@rUserSourceId bigint,
	@rDocumentId bigint,
	@rDocumentName nvarchar(200),
	@rCreatedUserId bigint,
	@rDocumentSize decimal (12,2) = 0.00   
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

	INSERT INTO sCommon.tUploadDocument
		(
		UploadFunctionalityId,
		UserSourceTypeId,
		UserSourceId,
		DocumentId,
		DocumentName,
		CreatedUserId,
		CreatedDateTime,
		DocumentSize
		)
	VALUES
		(
		@rUploadFunctionalityId,
		@rUserSourceTypeId,
		@rUserSourceId,
		@rDocumentId,
		@rDocumentName,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rDocumentSize
		)
	 
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sCommunication].[pOnlineLearningLectureListDetailsGet]...';


GO
 
 
ALTER PROCEDURE [sCommunication].[pOnlineLearningLectureListDetailsGet]
	 @rOnlineLearningId bigint ,
	 @rSourceId bigint,
	 @rOrgId int,
	 @rSourceTypeId int,
	 @rIsAdmin bit 
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
		
	IF (@rSourceTypeId = 2001)
	BEGIN 
	DECLARE @lStudentName nvarchar(100), @lClassDivisionName nvarchar(50),@lStudentId bigint
	SELECT @lStudentId= A.StudentId, @lStudentName = [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ), @lClassDivisionName = CM.Title +' ' +DM.Title
				FROM sStudent.tAcademic A 
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
				INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
				WHERE A.Id = @rSourceId 
		SELECT 
			OL.Id As OnlineLearningId,
			ISNULL(OL.Title,'') As Title,
			CONVERT(NVARCHAR,OL.StartTime,108) as FromTime,
			CONVERT(NVARCHAR,OL.EndTime,108) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			@lClassDivisionName AS ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.IsTrackAttendance AS IsTrackAttendance,
			ISNULL(OL.MeetingId ,'') As MeetingId,
			ISNULL(OL.MeetingPassword,'') As MeetingPassword,
			ISNULL(OL.IsAssignment,0) As IsAssignment,
			ISNULL(OL.IsReference,0)AS IsReference,
			ISNULL(OL.IsResource,0) As IsResource,
			ISNULL(OL.IsMeetingStarted,0) AS IsMeetingStarted,
			ISNULL(OL.LecturePath,'')AS LecturePath,
			ISNULL(OL.IsDisplayMeetingId,'') AS IsDisplayMeetingId,
			ISNULL(DM.Title,'') As LearningType,
			@lStudentName As StudentName,
			ISNULL(OL.IsSubmitAssignment,0) As IsSubmitAssignment,
			ISNULL(OL.IsTakeTest ,0) As IsTakeTest,
			ISNULL(OL.TestId ,0) As TestId,
			ISNULL((SELECT sTP.Id FROM sEExam.tTestParticipant sTP Where sTP.SourceId = @lStudentId and sTP.TestId = OL.TestId 
			),0) AS TestParticipantId,
			ISNULL((SELECT CASE WHEN sTp.TestStatusId=545 THEN 'True' ELSE 'False' END FROM sEExam.tTestParticipant sTP Where sTP.SourceId = @lStudentId and sTP.TestId = OL.TestId),'false') As IsTestCompleted,
			--'false' As IsTestCompleted,
			ISNULL(sTM.Title,'') AS TestName,
			[sEExam].[fCheckIsHTMLGet] (sTM.Id) AS IsHtml,
			ISNULL(OMS.IsOnParticipantVideo ,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) As IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) As IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) As IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) As IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) As IsOnHostscreenShare,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			ISNULL(OL.IsMeetingCreated,0) As IsMeetingCreated,
			ISNULL(OMS.APIKey ,'') As APIKey,
			ISNULL(OMS.APISecret ,'') As APISecret,
			'' As AccountEmailId,
			'' As AccountPassword,
			ISNULL(OL.AssignmentRemark,'') As AssignmentRemark,
			ISNULL(OL.IsTrackAssignmentView,0) As IsTrackAssignmentView,
			ISNULL((SELECT ISNULL(EM1.FirstName,'') +' ' + ISNULL(EM1.MiddleName,'') +' ' + ISNULL(EM1.LastName ,'') FROM sHrm.tEmployeeMaster EM1 WHERE EM1.Id = OL.CoTeacherEmployeeId1),'') as CoTeacher1Name,
			ISNULL((SELECT ISNULL(EM1.FirstName,'') +' ' + ISNULL(EM1.MiddleName,'') +' ' + ISNULL(EM1.LastName ,'') FROM sHrm.tEmployeeMaster EM1 WHERE EM1.Id = OL.CoTeacherEmployeeId2),'') as CoTeacher2Name,
			ISNULL(sTM.IsAllowReview,0) As IsAllowReview,
			ISNULL(OLV.AssignmentTeacherRemark,'') AS TeacherAssignmentRemark,
			OL.BatchId,
			ISNULL(CONVERT(NVARCHAR,OL.AssignmentSubmissionEndDate),'') As SubmissionEndDate,
			OL.ClassId,
			OL.SubjectId,
			ISNULL(OL.IsRecording,0) As IsRecording,
			OL.EndDateTime
	 FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId			 			
            INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			LEFT JOIN sEExam.tTestMaster sTM ON sTM.Id = OL.TestId
			LEFT JOIN sAcademic.tOnlineMeetingSettings OMS ON OMS.OnlineLearningId = OL.Id
			LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = @rSourceId
            
	 WHERE
			 OL.Id = @rOnlineLearningId
			AND OL.IsCompleted <> 721
			 
			 
			
			ORDER BY OL.CreatedDateTime
	
		END
		
		IF(@rSourceTypeId = 95)
		BEGIN
		DECLARE @lAdminName nvarchar(200)
			IF (@rIsAdmin = 1)
			SELECT @lAdminName = ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') 
			FROM sHrm.tEmployeeMaster EM WHERE EM.Id = @rSourceId
			
		SELECT 
			OL.Id As OnlineLearningId,
			ISNULL(OL.Title,'') As Title,
			CONVERT(NVARCHAR,OL.StartTime,108) as FromTime,
			CONVERT(NVARCHAR,OL.EndTime,108) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			CASE WHEN @rIsAdmin = 0 THEN ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') 
			WHEN @rIsAdmin = 1 THEN @lAdminName END As TeacherName,
			--SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CM.Title As ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.IsTrackAttendance AS IsTrackAttendance,
			ISNULL(OL.MeetingId ,'') As MeetingId,
			ISNULL(OL.MeetingPassword,'') As MeetingPassword,
			ISNULL(OL.IsAssignment,0) As IsAssignment,
			ISNULL(OL.IsReference,0)AS IsReference,
			ISNULL(OL.IsResource,0) As IsResource,
			ISNULL(OL.IsMeetingStarted,0) AS IsMeetingStarted,
			ISNULL(OL.LecturePath,'')AS LecturePath,
			ISNULL(OL.IsDisplayMeetingId,'') AS IsDisplayMeetingId,
			ISNULL(DM.Title,'') As LearningType,
			'' As StudentName,
			ISNULL(OL.IsSubmitAssignment,0) As IsSubmitAssignment,
			ISNULL(OL.IsTakeTest ,0) As IsTakeTest,
			ISNULL(OL.TestId ,0) As TestId,
			0 As TestParticipantId,
			'' As IsHtml,
			ISNULL(OMS.IsOnParticipantVideo ,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) As IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) As IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) As IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) As IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) As IsOnHostscreenShare,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			ISNULL(OL.IsMeetingCreated,0) As IsMeetingCreated,
			ISNULL(OMS.APIKey ,'') As APIKey,
			ISNULL(OMS.APISecret ,'') As APISecret,
			ISNULL(OMS.APIKey ,'') As APIKey,
			ISNULL(OMS.APISecret ,'') As APISecret,
			CASE WHEN @rIsAdmin = 0 THEN ISNULL(OMS.AccountEmailId ,'') 
			WHEN @rIsAdmin = 1 THEN '' END As AccountEmailId,
			CASE WHEN @rIsAdmin = 0 THEN ISNULL(OMS.AccountPassword,'') 
			WHEN @rIsAdmin = 1 THEN '' END As AccountPassword,
			'' as AssignmentRemark,
			--,
			--ISNULL(TP.Id, 0) AS TestParticipantId,
			--ISNULL(sTM.Title,'') AS TestName,
			--[sEExam].[fCheckIsHTMLGet] (sTM.Id) AS IsHtml
			ISNULL(OL.IsTrackAssignmentView,0) As IsTrackAssignmentView,
			ISNULL((SELECT ISNULL(EM1.FirstName,'') +' ' + ISNULL(EM1.MiddleName,'') +' ' + ISNULL(EM1.LastName ,'') FROM sHrm.tEmployeeMaster EM1 WHERE EM1.Id = OL.CoTeacherEmployeeId1),'') as CoTeacher1Name,
			ISNULL((SELECT ISNULL(EM1.FirstName,'') +' ' + ISNULL(EM1.MiddleName,'') +' ' + ISNULL(EM1.LastName ,'') FROM sHrm.tEmployeeMaster EM1 WHERE EM1.Id = OL.CoTeacherEmployeeId2),'') as CoTeacher2Name,
			ISNULL(sTM.IsAllowReview,0) As IsAllowReview,
			OL.BatchId,
			ISNULL(CONVERT(NVARCHAR,OL.AssignmentSubmissionEndDate),'') As SubmissionEndDate,
			OL.ClassId,
			OL.SubjectId,
			ISNULL(OL.IsRecording,0) As IsRecording,
			OL.EndDateTime
		FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId 
            --INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = OL.ClassId AND SA.OrgId = @rOrgId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            LEFT JOIN sEExam.tTestMaster sTM ON sTM.Id = OL.TestId
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			--LEFT JOIN sE sEExam.tTestParticipant TP ON sTM.Id=TP.TestId
			LEFT JOIN sAcademic.tOnlineMeetingSettings OMS ON OMS.OnlineLearningId = OL.Id
            
		WHERE
			 OL.Id = @rOnlineLearningId
			-- AND OL.TeacherEmployeeId = @rSourceId
			 AND OL.IsCompleted <> 721
			
			ORDER BY OL.CreatedDateTime
			
			END
		
END
GO
PRINT N'Altering [sCommunication].[pRptFeedbackAnswerReviewReport]...';


GO
 
ALTER PROCEDURE [sCommunication].[pRptFeedbackAnswerReviewReport]
	  @rOrgGroupBatchId bigint = 0,
	  @rFeedbackId bigint = 0 ,
	  @rFeedbackForId bigint = 0,
	  @rBuilder1 nvarchar(max)='',
	  @rBuilder2 nvarchar(max)='',
	  @rSourceType nvarchar(20) ='',
	   @rOrgId int =0,
	  @rBatchId int =0
	-- @rUserSourceId bigint=0
	

	 
AS
BEGIN 
 
IF(@rSourceType='Student')
BEGIN
	SELECT @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, OM.DisplayTitle  AS Title,SA.AcademicId AS SourceId,SA.Name AS Name,FBTQ.Question As Question,SA.Code AS Code,
		case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FBTQ.QuestionNumber,
		FBTQ.Id
	FROM sCommunication.tFeedback FB
		INNER JOIN sCommunication.tFeedbackAssign FBA ON  FBA.FeedbackId = FB.Id 
		INNER JOIN sCommunication.tFeedbackFor FBR ON FBR.FeedbackId = FB.Id-- AND ((FBR.Id =@rFeedbackForId) OR (@rFeedbackForId = 0))
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FBA.AssignToSourceId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sCommunication.tFeedbackTemplateQuestion FBTQ ON FBTQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id   AND FR.SourceId = SA.AcademicId AND ((FR.FeedbackForId =@rFeedbackForId) OR (@rFeedbackForId = 0))
		LEFT Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id AND FQR.FeedbackTemplateQuestionID = FBTQ.Id
		LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
	WHERE (FBA.AssignToSourceTypeId =2001)
	AND((FB.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
	AND((FB.Id = @rFeedbackId) OR(@rFeedbackId = 0))
	Order By FBTQ.QuestionNumber Asc
END

ELSE IF(@rSourceType='Employee')
BEGIN
	SELECT @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,OM.DisplayTitle  AS Title,EM.Id AS SourceId,EM.FirstName+' '+EM.LastName  AS Name,FBTQ.Question As Question,EM.Code AS Code,
		case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FBTQ.QuestionNumber,
		FBTQ.Id
	FROM sCommunication.tFeedback FB
		INNER JOIN sCommunication.tFeedbackAssign FBA ON  FBA.FeedbackId = FB.Id 
		INNER JOIN sCommunication.tFeedbackFor FBR ON FBR.FeedbackId = FB.Id --AND ((FBR.Id =@rFeedbackForId) OR (@rFeedbackForId = 0))
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = FBA.AssignToSourceId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		INNER JOIN sCommunication.tFeedbackTemplateQuestion FBTQ ON FBTQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id  AND FR.SourceId = EM.Id AND ((FR.FeedbackForId =@rFeedbackForId) OR (@rFeedbackForId = 0))
		LEFT Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id AND FQR.FeedbackTemplateQuestionID = FBTQ.Id
		LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
	WHERE (FBA.AssignToSourceTypeId =95)
		AND((FB.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
		--AND((SA.BatchId = @rBatchId)OR(@rBatchId=0))
		AND((FB.Id = @rFeedbackId) OR(@rFeedbackId = 0))
		AND  ISNULL(EM.IsOtherUser,0) = 0
	Order By FBTQ.QuestionNumber Asc
END

IF(@rSourceType='Other')
BEGIN
	
	
	SELECT  @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,''  AS Title,0 AS SourceId,FBA.ForName  AS Name,FBTQ.Question As Question,'' Code,
	case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FBTQ.QuestionNumber,
		FBTQ.Id
	FROM sCommunication.tFeedback FB
		INNER JOIN sCommunication.tFeedbackAssign FBA ON  FBA.FeedbackId = FB.Id 
		INNER JOIN sCommunication.tFeedbackFor FBR ON FBR.FeedbackId = FB.Id --AND ((FBR.Id =@rFeedbackForId) OR (@rFeedbackForId = 0))
		INNER JOIN sCommunication.tFeedbackTemplateQuestion FBTQ ON FBTQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id AND ((FR.FeedbackForId =@rFeedbackForId) OR (@rFeedbackForId = 0)) 
		LEFT Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id AND FQR.FeedbackTemplateQuestionID = FBTQ.Id
		LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
	WHERE (FBA.AssignToSourceTypeId =0)
	AND((FB.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
		AND((FB.Id = @rFeedbackId) OR(@rFeedbackId = 0))
	Order By FBTQ.QuestionNumber Asc
END 

ELSE IF(@rSourceType='-ALL-')
BEGIN
	SELECT *
	FROM(
	SELECT @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, OM.DisplayTitle  AS Title,SA.AcademicId AS SourceId,SA.Name AS Name,FBTQ.Question As Question,SA.Code AS Code,
		case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FBTQ.QuestionNumber,
		FBTQ.Id
	FROM sCommunication.tFeedback FB
		INNER JOIN sCommunication.tFeedbackAssign FBA ON  FBA.FeedbackId = FB.Id 
		INNER JOIN sCommunication.tFeedbackFor FBR ON FBR.FeedbackId = FB.Id --AND ((FBR.Id =@rFeedbackForId) OR (@rFeedbackForId = 0))
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FBA.AssignToSourceId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sCommunication.tFeedbackTemplateQuestion FBTQ ON FBTQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id AND FR.SourceId = SA.AcademicId AND ((FR.FeedbackForId =@rFeedbackForId) OR (@rFeedbackForId = 0))
		LEFT Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id AND FQR.FeedbackTemplateQuestionID = FBTQ.Id
		LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
	WHERE (FBA.AssignToSourceTypeId =2001)
	AND((FB.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
	AND((FB.Id = @rFeedbackId) OR(@rFeedbackId = 0))
	
UNION ALL

	SELECT @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,OM.DisplayTitle  AS Title,EM.Id AS SourceId,EM.FirstName+' '+EM.LastName  AS Name,FBTQ.Question As Question,EM.Code AS Code,
		case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FBTQ.QuestionNumber,
		FBTQ.Id
	FROM sCommunication.tFeedback FB
		INNER JOIN sCommunication.tFeedbackAssign FBA ON  FBA.FeedbackId = FB.Id 
		INNER JOIN sCommunication.tFeedbackFor FBR ON FBR.FeedbackId = FB.Id --AND ((FBR.Id =@rFeedbackForId) OR (@rFeedbackForId = 0))
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = FBA.AssignToSourceId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		INNER JOIN sCommunication.tFeedbackTemplateQuestion FBTQ ON FBTQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id AND FR.SourceId = EM.Id AND ((FR.Id =@rFeedbackForId) OR (@rFeedbackForId = 0))
		LEFT Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id AND FQR.FeedbackTemplateQuestionID = FBTQ.Id
		LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
	WHERE (FBA.AssignToSourceTypeId =95)
		AND((FB.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
		--AND((SA.BatchId = @rBatchId)OR(@rBatchId=0))
		AND((FB.Id = @rFeedbackId) OR(@rFeedbackId = 0))
		AND  ISNULL(EM.IsOtherUser,0) = 0

UNION ALL 

	SELECT  @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,''  AS Title,0 AS SourceId,FBA.ForName  AS Name,FBTQ.Question As Question,'' Code,
	case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FBTQ.QuestionNumber,
		FBTQ.Id
	FROM sCommunication.tFeedback FB
		INNER JOIN sCommunication.tFeedbackAssign FBA ON  FBA.FeedbackId = FB.Id 
		INNER JOIN sCommunication.tFeedbackFor FBR ON FBR.FeedbackId = FB.Id --AND ((FBR.Id =@rFeedbackForId) OR (@rFeedbackForId = 0))
		INNER JOIN sCommunication.tFeedbackTemplateQuestion FBTQ ON FBTQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id AND ((FR.FeedbackForId =@rFeedbackForId) OR (@rFeedbackForId = 0)) 
		LEFT JOIN sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id AND FQR.FeedbackTemplateQuestionID = FBTQ.Id
		LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
	WHERE (FBA.AssignToSourceTypeId = 0)
	AND((FB.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
		AND((FB.Id = @rFeedbackId) OR(@rFeedbackId = 0))
	) as a
	Order By a.QuestionNumber Asc
END
END
GO
PRINT N'Altering [sFee].[pChargeReceiptAdd]...';


GO
 
ALTER PROCEDURE [sFee].[pChargeReceiptAdd]
	 
	@rId bigint,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rGuestName nvarchar(200),
	@rReceiptBookId int,
	@rRemark nvarchar(200),
	@rReceiptNumber int,
	@rReceiptDate date,
	@rPayTypeId tinyint,
	@rChequeNo nvarchar(20),
	@rBankName nvarchar(200),
	@rIsObsolete bit,
	@rOrgId int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint,
	@rReceiptAmount Decimal(12,2),
	@rChequeDate date=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	

IF(@rId = 0)	
BEGIN
--  EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2002,@rStoreLocationId = 0, @rNextNumber  = @rReceiptNumber OUTPUT

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

--		IF @rReceiptNumber = '-300'
--	  BEGIN
--		SELECT -300 AS Result, '' AS ReceiptNumber, 0 AS Id 
--		RETURN
--	  END

   SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId
   
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF EXISTS(SELECT 1 from sFee.tChargeReceipt where ReceiptNumber=@rReceiptNumber AND ChargeReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
		BEGIN
			SELECT -102 AS Result
			RETURN
		END
	END
	ELSE	
		SET @rReceiptNumber = sFee.fChargeReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId)
    BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tChargeReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sFee.tChargeReceipt
		(
			Id,
			SourceTypeId,
			SourceId,
			GuestName,
			ChargeReceiptBookId,
			Remark,
			ReceiptNumber,
			ReceiptDate,
			PayTypeId,
			ChequeNo,
			BankName,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			OrgId,
			BatchId,
			OrgGroupBatchId,
			ReceiptAmount,
			ChequeDate
		)
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
			@rGuestName,
			@rReceiptBookId,
			@rRemark,
			@rReceiptNumber,
			@rReceiptDate,
			@rPayTypeId,
			@rChequeNo,
			@rBankName,
			@rIsObsolete,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rOrgId,
			@rBatchId,
			@rOrgGroupBatchId,
			@rReceiptAmount,
			@rChequeDate
		)
		             
END	 
ELSE
BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tChargeReceipt
	    SET
			SourceTypeId=@rSourceTypeId,
			SourceId=@rSourceId,
			GuestName=@rGuestName,
			ChargeReceiptBookId=@rReceiptBookId,
			Remark=@rRemark,
			ReceiptNumber=@rReceiptNumber,
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeNo=@rChequeNo,
			BankName=@rBankName,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ReceiptAmount=@rReceiptAmount,
			ChequeDate=@rChequeDate
	      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 [sFee].[pChargeReceiptListGet]...';


GO
 
ALTER PROCEDURE [sFee].[pChargeReceiptListGet]
	 
	 --@rReceiptNumber int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSourceTypeId smallint,
	 @rSourceCode nvarchar(20),
	 @rGuestName nvarchar(200),
	 @rFromDate date,
	 @rToDate date,
	 @rFromNo int,
	 @rToNo int,
	 @rReceiptBookId int,
	 @rChargeCategoryId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rOrgGroupBatchId int,
	 @rDepartmentId int = 0,
	 @rStudentCode nvarchar(20) = '',
	 @rOrgGroupId int=0,
	 @rStatusId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		 
BEGIN 
		--select 
		--		'' AS Builder1,
		--		'' AS Builder2,
		--		'' AS Id,
		--		'' AS SourceType,
		--		'' AS SourceTypeId
		--		,'' AS GuestName
		--		,'' AS ReceiptNumber
		--		,'' AS ReceiptDate
		--		,'' AS Amount
		--		,'' AS ChargeCategory
		--		,'' AS ReceiptBook
		--		,'' AS ChargeCategoryId
		--		,'' As ReceiptBookId
		--		,'' AS OrgId
		--		,'' AS School
		--		,'' AS OrgGroupId
		--		,'' AS ChargeId

	    ----IF(@rIsSearch=1)
		----BEGIN
			SET @rSourceCode = sCommon.fSearchStringGet(@rSourceCode)
			SET @rGuestName = sCommon.fSearchStringGet(@rGuestName)

			print @rSourceCode
		--Declare @rSourceTypeId smallint
		--select @rSourceTypeId=SourceTypeId from sFee.tChargeReceipt where ReceiptNumber=@rReceiptNumber and OrgId=@rOrgId
		--END
IF @rSourceTypeId=95
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			ISNULL(EM.Code,'') AS Code,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			DM.DisplayTitle AS Class
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = @rSourceTypeId)
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		   INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
		   --AND EM.StatusId=7
		    INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,'')=''))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			AND ((EM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
GROUP BY 
			CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,
			CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,EM.Code

END
ELSE IF @rSourceTypeId=2001
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			ISNULL(SA.Code,'') as Code,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			CMM.DisplayTitle + '-' + DM.DisplayTitle AS Class
			--CLM.Id AS ClassId,
			--CLM.DisplayTitle AS ClassName,
			--DM.Id AS DivisionId,
			--DM.DisplayTitle AS DivisionName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001 --AND SA.StatusId=1
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tClassMaster CMM ON CMM.Id = SA.ClassId
		   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   --INNER JOIN sSetup.tClassMaster CLM ON CLM.Id = SA.ClassId
		   --INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
 GROUP BY   CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CM.ChargeCategoryId,
            CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle, CMM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,SA.Code
            --CLM.Id,CLM.DisplayTitle, DM.Id, DM.DisplayTitle
END
ELSE IF @rSourceTypeId=3
BEGIN
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CR.Id,
		'Other' as SourceType,
		'' AS Code,
		CR.SourceTypeId,
		--EM.Code as SourceCode,
		CR.GuestName as GuestName,
		--CR.Remark,
		CR.ReceiptNumber,
		CR.ReceiptDate,
		  PTM.Title AS PayType,  
		--CR.PayTypeId,
		CR.ChequeNo,
		CR.BankName,
		--CR.IsObsolete,
		--CRD.Id as DetailId,
		--CRD.ChargeId,
		--CRD.Remark as DetailRemark,
		sum(CRD.Amount) as Amount,
		--CM.Code,
		--CM.Title,
		CCM.Title as ChargeCategory,
		CM.ChargeCategoryId,
		CR.OrgId,
		CR.BatchId,
		RBM.Title AS ReceiptBook,
		CR.ChargeReceiptBookId,
		OM.DisplayTitle AS OrganizationName,
		'' AS Class
		--OM.DisplayTitle AS School,
		--OM.OrgGroupId,
		--CM.Id AS ChargeId
		--CRD.IsObsolete
  FROM 
       sFee.tChargeReceipt CR
	   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
	   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
	   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
	   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
	   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
	   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
	   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
		--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
		--AND 
		(ISNULL(CR.SourceTypeId,0)=3)
		AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
		--AND (ISNULL(@rSourceCode,'') = '')
		AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
		AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
		AND (CR.IsObsolete=0)
		AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (CRD.IsObsolete=0) 
		AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
		And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
		,PTM.Title,CR.ChequeNo,CR.BankName

END	
ELSE
BEGIN
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			CR.SourceTypeId,
			ISNULL(EM.Code,'') as Code,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			DM.DisplayTitle AS Class
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = 95) 
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		   INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
		   --AND EM.StatusId=7
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			group by CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,
			CR.BatchId,RBM.Title,CM.ChargeCategoryId,CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,EM.Code

			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			ISNULL(SA.Code,'') as Code,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			CMM.DisplayTitle + '-' + DM.DisplayTitle AS Class
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001
		   INNER JOIN sSetup.tClassMaster CMM ON CMM.Id = SA.ClassId
		   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId 
		   --AND SA.StatusId=1
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			group by CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,
			RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle, CMM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,SA.Code

			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Other' as SourceType,
			CR.SourceTypeId,
			'' AS Code,
			CR.GuestName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			'' AS Class
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			(ISNULL(CR.SourceTypeId,0)=3)
			AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((ISNULL(@rSourceCode,'%') = '%'))
			group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName
END
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


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

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


GO
 
---
--exec [sFee].[pFeeProcessGenerate] @rOrgId=1961,@rBatchId=196100101,@rClassId=196100001,@rCreatedUserId=1961000000003
--,@rDivisionId=110100003,@rAcademicId=1101000000003

ALTER PROCEDURE [sFee].[pFeeProcessGenerate]
	 
		   @rOrgId int,
		   @rBatchId int,
           @rClassId int,
           @rDivisionId int=NULL,
		   @rAcademicId bigint=NULL,
		   @rCreatedUserId bigint,
		   @rFeeSetupId bigint = 0					 

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN


DELETE FAS FROM [sFee].[tFeeAllocationStudent] FAS 
				JOIN sStudent.tAcademic A ON A.Id =FAS.AcademicId
				JOIN sFee.tFeeSetup FS ON FS.Id=FAS.feesetupid AND FS.AdmissionCategoryId = A.AdmissionCategoryId
WHERE FAS.academicid = ISNULL(@rAcademicId,FAS.academicid) AND A.orgid=@rOrgId AND A.batchid=@rBatchId AND A.classid=@rClassId AND A.divisionid=ISNULL(@rDivisionId,A.divisionid) AND ((FS.Id = @rFeeSetupId) OR (@rFeeSetupId = 0))
		
--PRINT 'DELETED Fee Alloc Student, Academic=='+CAST(@academicid AS VARCHAR)+' Fee Setup=='+CAST(@feesetupid AS VARCHAR)


SELECT batchid,classid,id AS academicid,admissioncategoryid,rownumAcademic 
INTO #temptAcademic 
FROM 
(
	SELECT A.batchid,A.classid,A.id,A.admissioncategoryid,ROW_NUMBER() OVER (ORDER BY A.id) rownumAcademic 
	FROM sStudent.tAcademic  A
	--JOIN [sStudent].[tStudentMaster] SM ON SM.Id=A.StudentId AND SM.StatusId=1
	WHERE A.id=ISNULL(@rAcademicId,A.id) AND A.orgid=@rOrgId AND A.batchid=@rBatchId 
	AND A.classid=@rClassId AND A.divisionid=ISNULL(@rDivisionId,A.divisionid)	
	
) AS tStudentAcademic


DECLARE @rowcountAcademic BIGINT=0
SELECT @rowcountAcademic = COUNT(rownumAcademic) FROM #temptAcademic


WHILE (@rowcountAcademic!=0)
BEGIN

	DECLARE @academicid BIGINT=0
	DECLARE @admissioncategoryid BIGINT=0		
	SELECT @academicid=academicid,@admissioncategoryid=admissioncategoryid FROM #temptAcademic WHERE rownumAcademic=@rowcountAcademic


	SELECT rownumFeesetup,id AS feesetupid,amount AS feeamount,IsOptional,IsVariable 
	INTO  #temptFeeSetup 
	FROM
	(SELECT ROW_NUMBER() OVER (ORDER BY FS.id) rownumFeesetup,FS.id,FS.amount,FS.isoptional,FS.isvariable FROM sFee.tFeeSetup FS
	--LEFT JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId AND FM.IsObsolete=0
	--LEFT JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId AND FHM.IsObsolete=0
	WHERE FS.batchid=@rBatchId AND FS.classid=@rClassId AND FS.admissioncategoryid=@admissioncategoryid
	AND FS.FeeId IN (SELECT Id FROM sFee.tFeeMaster WHERE IsObsolete=0) AND 
	FS.ReceiptBookId IN (SELECT Id FROM sFee.tReceiptBookMaster WHERE IsObsolete=0)
	AND ((FS.Id = @rFeeSetupId) OR (@rFeeSetupId = 0))
	) AS tFeeSetup
	
		
	DECLARE @rowcountFeesetup BIGINT=0
	SELECT @rowcountFeesetup = COUNT(rownumFeesetup) FROM #temptFeeSetup


	WHILE (@rowcountFeesetup!=0)
	BEGIN		
		BEGIN TRY

		DECLARE @feesetupid BIGINT=0
		DECLARE @feeAmount DECIMAL(12,2)=0.00			
		DECLARE @IsOptional Bit=0
		DECLARE @IsVariable Bit=0					
		SELECT @IsOptional=isoptional,@IsVariable=isvariable,@feesetupid=feesetupid,@feeAmount=ISNULL(feeamount,0) FROM #temptFeeSetup WHERE rownumFeesetup=@rowcountFeesetup
		
			
		--PRINT 'RowCountAcademic=='+CAST(@rowcountAcademic AS VARCHAR)+' RowCountFeeSetup=='+CAST(@rowcountFeesetup AS VARCHAR)
		--PRINT 'Is Optional=='+CAST(@IsOptional AS VARCHAR)
		--PRINT 'Is Variable=='+CAST(@IsVariable AS VARCHAR)			
						
			
		DECLARE @toPayamount DECIMAL(12,2)=0.00
		DECLARE @paidAmount DECIMAL(12,2)=0.00
		DECLARE @VariableAmount DECIMAL(12,2)=0.00
		DECLARE @DiscountAmount DECIMAL(12,2)=0.00
		DECLARE @AdditionalAmount DECIMAL(12,2)=0.00
		DECLARE @NotApplicableAmount DECIMAL(12,2)=0.00
		DECLARE @Remark NVARCHAR(400)=''


		SELECT @paidAmount=ISNULL(SUM(RD.amount),0) FROM sFee.treceipt  R
		JOIN sFee.tReceiptDetail RD ON RD.receiptid = R.id AND R.IsObsolete = 0
		WHERE R.sourceid=@academicid AND RD.feesetupid=@feesetupid 
		GROUP BY R.sourceid,RD.feesetupid
						
		IF(@IsOptional=1 AND @IsVariable=1)
		BEGIN
				
			--variable amt = var amount from tfeeall and var amt >0 then fee amt = 0				
			SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
			,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')						
			FROM [sFee].[tFeeAllocation] AS FA					  			
			WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid
				
			IF(@VariableAmount>0)BEGIN SET @feeAmount=0 END											
						 
		END
			
		IF(@IsOptional=1 AND @IsVariable=0)
		BEGIN

			--Normal with variable amt 0
			SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
			,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
			FROM [sFee].[tFeeAllocation] AS FA					  			
			WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid

			IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END							

		END

		IF(@IsOptional=0 AND @IsVariable=1)
		BEGIN
				
			--variable amt =0 check isoptional in tfeeoptional with fee set up id and academic id, if 0 no insert else insert

			SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
			,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
			FROM [sFee].[tFeeAllocation] AS FA					  			
			WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid
				
			IF(@VariableAmount>0)BEGIN SET @feeAmount=0 END				

		END

		IF(@IsOptional=0 AND @IsVariable=0)
		BEGIN
				
			--variable amt =0 check isoptional in tfeeoptional with fee set up id and academic id, if 0 no insert else insert

			SELECT @VariableAmount=ISNULL(FA.[VariableAmount],0),@DiscountAmount=ISNULL(FA.[DiscountAmount],0)
			,@AdditionalAmount=ISNULL(FA.[AdditionalAmount],0),@NotApplicableAmount=ISNULL(FA.[NotApplicableAmount],0),@Remark=ISNULL(FA.Remark,'')
			FROM [sFee].[tFeeAllocation] AS FA					  			
			WHERE FA.sourceid=@academicid AND FA.feesetupid=@feesetupid
				
			IF(@VariableAmount>0)BEGIN SET @VariableAmount=0 END			

		END

		--Set pending amount
		SET @toPayamount=(@feeAmount+@VariableAmount+@AdditionalAmount)-(@NotApplicableAmount+@DiscountAmount+@paidamount)
			
			
		--PRINT '@feeAmount Amount==' +CAST(@feeAmount AS VARCHAR)
		--PRINT '@VariableAmount Amount==' +CAST(@VariableAmount AS VARCHAR)
		--PRINT '@AdditionalAmount Amount==' +CAST(@AdditionalAmount AS VARCHAR)
		--PRINT '@NotApplicableAmount Amount==' +CAST(@NotApplicableAmount AS VARCHAR)
		--PRINT '@DiscountAmount Amount==' +CAST(@DiscountAmount AS VARCHAR)			
		--PRINT '@paidamount Amount==' +CAST(@paidamount AS VARCHAR)
		--PRINT 'Pending Amount==' +CAST(@toPayamount AS VARCHAR)
		
			
		--Code to insert based on is optional
		IF(@IsOptional=0)
		BEGIN				
			IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@academicid AND FAS.feesetupid=@feesetupid)
			BEGIN
				IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeClassBatchStatus] WHERE ClassId=@rClassId AND BatchId=@rBatchId)
				BEGIN
					INSERT INTO [sFee].[tFeeClassBatchStatus]
					([ClassId]
					,[BatchId]
					,[StatusId]
					,[UpdatedDateTime])
				VALUES
					(@rClassId
					,@rBatchId 
					,723
					,sCommon.fGetDate())

					--PRINT 'Fee class batch status insert' + CAST(@rowcountFeesetup AS VARCHAR)

				END

				INSERT INTO [sFee].[tFeeAllocationStudent]
						([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
						,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
				VALUES
					(@academicid,@feesetupid,@feeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@toPayamount
					,@paidamount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
				--PRINT 'Fee allocation student insert' + CAST(@rowcountFeesetup AS VARCHAR)
			END
		END

		IF EXISTS (SELECT 1 FROM [sFee].[tFeeOptional] WHERE FeeSetupId=@feesetupid AND SourceId=@academicid AND BatchId=@rBatchId AND (@IsOptional=1))
			BEGIN
			IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeAllocationStudent] FAS WHERE FAS.academicid=@academicid AND FAS.feesetupid=@feesetupid)
			BEGIN
				IF NOT EXISTS (SELECT 1 FROM [sFee].[tFeeClassBatchStatus] WHERE ClassId=@rClassId AND BatchId=@rBatchId)
				BEGIN
					INSERT INTO [sFee].[tFeeClassBatchStatus]
					([ClassId]
					,[BatchId]
					,[StatusId]
					,[UpdatedDateTime])
				VALUES
					(@rClassId
					,@rBatchId 
					,723
					,sCommon.fGetDate())

					--PRINT 'Fee class batch status insert' + CAST(@rowcountFeesetup AS VARCHAR)

				END

				INSERT INTO [sFee].[tFeeAllocationStudent]
						([AcademicId],[FeeSetupId],[FeeAmount],[VariableAmount],[DiscountAmount],[AdditionalAmount],[NotApplicableAmount],[ToPayAmount]
						,[PaidAmount],[Remark],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime])
				VALUES
					(@academicid,@feesetupid,@feeAmount,@VariableAmount,@DiscountAmount,@AdditionalAmount,@NotApplicableAmount,@toPayamount
					,@paidamount,@Remark,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate())				
				
				--PRINT 'Fee allocation student insert' + CAST(@rowcountFeesetup AS VARCHAR)
			END
		END

			
		--PRINT 'Variable Amount=='+CAST(@VariableAmount AS VARCHAR)
		--PRINT 'Fee Amount=='+CAST(@feeAmount AS VARCHAR)					
									
		SET @rowcountFeesetup=@rowcountFeesetup-1

	END TRY
	BEGIN CATCH 		
			PRINT 'fail'+CAST(@rowcountFeesetup AS VARCHAR)
			PRINT 'Academic Id=='+CAST(@academicid AS VARCHAR)
			PRINT 'Fee Setup Id=='+CAST(@feesetupid AS VARCHAR)
			PRINT ERROR_MESSAGE()
			BREAK
	END CATCH			
	END

	--drop table #temptfeesetup
	IF OBJECT_ID(N'tempdb..#temptfeesetup') IS NOT NULL
	BEGIN
		DROP TABLE #temptfeesetup
	END

	--PRINT @rowcountAcademic

	SET @rowcountAcademic=@rowcountAcademic-1
END
	
--drop table #temptAcademic	
IF OBJECT_ID(N'tempdb..#temptAcademic') IS NOT NULL
BEGIN
	DROP TABLE #temptAcademic
END

PRINT 'success'

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


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

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

	INSERT INTO sFee.tFeeSetup
		(
		   Id,
           ClassId,
           AdmissionCategoryId,
           BatchId,
           FeeId,
           IsOptional,
           IsVariable,
           Amount,
           StartDate,
           EndDate,
           ReceiptBookId,
           CreatedUserId,
           CreatedDateTime,
           IsServiceTax,
           CollectionGroupId,
           FeeDuration,
           LevelAmount
        )
	VALUES
		(
			@lNextNumber,
			@rClassId,
			@rAdmissionCategoryId,
            @rBatchId,
            @rFeeId,
            @rIsOptional,
            @rIsVariable,
            @rAmount,
            @rStartDate,
            @rEndDate,
            @rReceiptBookId,
            @rCreatedUserId,
			sCommon.fGetDate(),
			@rIsServiceTax,
			@rCollectionGroupId,
			@rFeeDuration,
			@rLevelAmount
		)

		SELECT 1 AS Result
	END	 
	 ELSE
	 BEGIN
	 
	 SET @lNextNumber = @rId
	    UPDATE  sFee.tFeeSetup
	    SET
			 --ClassId=@rClassId,
			 --AdmissionCategoryId=@rAdmissionCategoryId,
    --         BatchId=@rBatchId,
             IsOptional=@rIsOptional,
             IsVariable=@rIsVariable,
             Amount=@rAmount,
             StartDate=@rStartDate,
             EndDate=@rEndDate,
             ReceiptBookId=@rReceiptBookId,
             UpdatedUserId=@rUpdatedUserId,
			 UpdatedDateTime=sCommon.fGetDate(),
			 IsServiceTax=@rIsServiceTax,
			 CollectionGroupId=@rCollectionGroupId,
			 FeeDuration=@rFeeDuration,
			 LevelAmount=@rLevelAmount
	      WHERE (Id = @rId)
	       --AND (FeeId=@rFeeId) 

	      SELECT 11 AS Result   
	 END  
	
	If Not Exists(Select 1 from sSystem.tPortalSync where OrgGroupId=@rOrgGRoupId)
	BEGIN
		Insert INto sSystem.tPortalSync 
		(
			OrgGRoupId,
			FeeChange
		)
		Values
		(
			@rOrgGRoupId,
			1
		)
	END
	Else
	BEGIN
		Update sSystem.tPortalSync 
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
		
	END

	EXEC [sFee].[pFeeProcessGenerate] @rOrgId,@rBatchId,@rClassId,NULL,NULL,@rCreatedUserId,@lNextNumber

	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptListGet]...';


GO

 
ALTER PROCEDURE [sFee].[pRptFeeReceiptListGet]  
  @rReportId int=0,  
  @rReceiptBookId int=0,  
  @rAdmissionCategoryId int=0,  
  @rClassId int=0,  
  @rDivisionId int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rFromReceiptNo int=0,  
  @rToReceiptNo int=0,  
  @rBatchId int,  
  @rUserId bigint=0,  
  @rBuilder1 nvarchar(max)=0,  
  @rBuilder2 nvarchar(max)=0,  
  @rIsDetail bit=0,  
  @rIsCancel bit=0,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int=0,  
  @rPaytypeId int=0,  
  @rCommonBatch nvarchar(100)='',  
  @rDepartmentId int=0,  
  @rFromRollNo int=0,  
     @rToRollNo int=0,  
     @rCode nvarchar(20),  
     @rIsFilter bit=0,  
     @rIsHeader bit=0,  
     @rCreatedUserName nvarchar(100)='',  
     @rFeeHeadId nvarchar(max) = '',  
     @rIsDisplayOrgGroup bit=0,  
     @rIsDiscount bit = 0,  
     @rFeeId nvarchar(max) = '',  
     @rFilterId int=0,  
     @rCustomGroupId smallint = 0,  
     @rOrgGroupId int=0,  
     @rFeeStatusId int=0,  
     @rFromChequeDate date='',      
  @rToChequeDate date='',      
     @rBankName nvarchar(100)='',  
     @rOrgIds nvarchar(max) = '',  
     @rBankNames nvarchar(max) = '',  
  
  @rFromChequeClearDate Date = '',  
  @rToChequeClearDate Date = '' ,
  @rClassStatusId int=0 ,
  @rPayTypeIds nvarchar(max) = '',
  @rUserAcessUserId bigint = 0
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   
  BEGIN      
  SET @rBankName = sCommon.fSearchStringGet(@rBankName)      
    END   
  IF(@rReportId=10138 OR @rReportId=20547 OR @rReportId=20456)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate ,
		   SA.GenderId
		  FROM   
		   sFee.tReceipt R  
		  --INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  --INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  --INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
    
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 

		  --According UserAccess
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =SA.OrgId
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND OM.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  

		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  
		  --According UserAccess
		  INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013 AND RBM.IsObsolete=0 AND UA.UserId =@rUserAcessUserId 


		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  AND (  
		  (@rFilterId = 0) -- All  
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
			AND ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')     
  
		 ORDER BY R.ReceiptNumber
	END
	ELSE
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate   
		  FROM   
		   sFee.tReceipt R  
		  --INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  --INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  --INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
    
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  AND (  
		  (@rFilterId = 0) -- All  
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
			AND ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')     
  
		 ORDER BY R.ReceiptNumber  
	END
 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END
GO
PRINT N'Altering [sFee].[pRptFeeStatusStudentWisewithDiscountGet]...';


GO
 


ALTER PROCEDURE [sFee].[pRptFeeStatusStudentWisewithDiscountGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	

		CREATE TABLE #tmp
		(
		AcademicId bigint,
		RollNo int,
		Name nvarchar(200),
		Code nvarchar(100),
		ClassId bigint,
		DivisionId bigint,
		ClassName nvarchar(100),
		DivisionName nvarchar(100),
		DivisionOrderIndex int,
		ClassOrderIndex int,
		ClassDivision  nvarchar(200),
		--IsVariable int ,
		Amount decimal(12,2),
		--StartDate date,
	 --   EndDate date,
		FAAmount decimal(12,2),
		DiscountAmount decimal(12,2),
	    AdditionalAmount decimal(12,2),
		NotApplicableAmount decimal(12,2),
		PaidAmount decimal(12,2),
		PendingAmount decimal(12,2),
		--Remark nvarchar(max),
		--ReceiptBookId bigint,
		--FeeName nvarchar(200),
		--FeeCode nvarchar(200),
		OrgId bigint,
		OrgName nvarchar(500),
		OrgOrderIndex int,
		--ReceiptBookTitle nvarchar(500),
		--ReceiptOrderIndex int,
		DepartmentId bigint,
		DepartmentName nvarchar(200),
		--ExemptionTypeId bigint, 
		--ExemptionType nvarchar(200),
		--FeeHeadId bigint,
		--FeeHeadName nvarchar(500),
	    --FeeHeadOrderIndex int,
		--FeeGroup int,
		BatchId bigint,
		BatchName nvarchar(200),
		CancelAmount decimal(12,2),
		Discount decimal(12,2)
		
		)
		INSERT INTO #tmp
		SELECT 
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			--FS.Id AS FeeSetupId,
			--ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			--ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			--ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			--ISNULL(FA.Remark,'') AS Remark,
			--FS.ReceiptBookId,
			--FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			--SA.ExemptionTypeId,
			--ISNULL(ETM.Title,'') AS ExemptionType,
			--FHM.Id AS FeeHeadId,
			--FHM.Title AS FeeHeadName,
			--FHM.OrderIndex AS FeeHeadOrderIndex,
			--@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			(Select ISNULL(SUM(R.DiscountAmount),0) FROM  sFee.tReceipt R Where R.SourceId=SA.AcademicId AND ((R.ReceiptBookId=@rReceiptBookId)OR (@rReceiptBookId=0)) AND (R.ReceiptDate <= @rUptoDate)) AS Discount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					--ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					--ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 

			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		 
		Order by SA.RollNo 
		--Select * from #tmp
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter AS IsFilter,
		@rIsHeader AS IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		AcademicId ,
		RollNo ,
		Name ,
		Code ,
		ClassId ,
		DivisionId ,
		ClassName ,
		DivisionName ,
		DivisionOrderIndex ,
		ClassOrderIndex ,
		ClassDivision  ,
		--IsVariable  ,
		--((select (SUM(Amount)) from #tmp t Where AcademicId=t1.AcademicId AND Amount > 0 )- (select (SUM(Amount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND Amount < 0 ))AS Amount,
		SUM(Amount)AS Amount ,
		--StartDate ,
	    --   EndDate ,
		--((select SUM(FAAmount) from #tmp t Where AcademicId=t1.AcademicId AND FAAmount < 0 )- (select( SUM(FAAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND FAAmount > 0 ))AS FAAmount,
		SUM(FAAmount )AS FAAmount,
		--((select SUM(DiscountAmount) from #tmp t Where AcademicId=t1.AcademicId AND DiscountAmount < 0 )- (select( SUM(DiscountAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND DiscountAmount > 0 ))AS DiscountAmount,
		SUM(DiscountAmount )AS DiscountAmount,
		--((select SUM(AdditionalAmount) from #tmp t Where AcademicId=t1.AcademicId AND AdditionalAmount < 0 )- (select( SUM(AdditionalAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND AdditionalAmount > 0 ))AS AdditionalAmount,
	    SUM(AdditionalAmount)AS AdditionalAmount,
		--((select SUM(NotApplicableAmount) from #tmp t Where AcademicId=t1.AcademicId AND NotApplicableAmount < 0 )- (select( SUM(NotApplicableAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND NotApplicableAmount > 0 ))AS NotApplicableAmount,
		SUM(NotApplicableAmount)AS NotApplicableAmount,
		--((select SUM(PaidAmount) from #tmp t Where AcademicId=t1.AcademicId AND PaidAmount < 0 )- (select( SUM(PaidAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND PaidAmount > 0 ))AS PaidAmount,
		SUM(PaidAmount)AS PaidAmount,
		--((select SUM(PendingAmount) from #tmp t Where AcademicId=t1.AcademicId AND PendingAmount < 0 )- (select( SUM(PendingAmount))*-1 from #tmp t Where AcademicId=t1.AcademicId AND PendingAmount > 0 ))AS PendingAmount,
		SUM(PendingAmount)AS PendingAmount,
		OrgId ,
		OrgName ,
		OrgOrderIndex ,
		DepartmentId ,
		DepartmentName ,
		BatchId ,
		BatchName ,
		Discount 
		--ReceiptBookId ,
		--ReceiptBookTitle
		
	    FROM #tmp 
		--INNER JOIN #tmp t1 ON AcademicId=t1.AcademicId
		Group By AcademicId ,RollNo ,Name ,Code ,ClassId ,DivisionId ,ClassName ,DivisionName ,DivisionOrderIndex ,ClassOrderIndex ,ClassDivision  ,
		OrgId ,OrgName ,OrgOrderIndex ,DepartmentId ,DepartmentName ,BatchId ,BatchName ,Discount 
		--,ReceiptBookId ,ReceiptBookTitle
		
		
		DROP TABLE #tmp
	
	
	--SELECT 
	--	'' Builder1,
	--	'' AS Builder2,
	--	0 AS IsDetail,
	--	0 AS IsFilter,
	--	0 AS IsHeader,
	--	0 AS IsDisplayOrgGroup,
	--	0 AS AcademicId ,
	--	0 AS RollNo ,
	--	''AS Name ,
	--	'' AS Code ,
	--	0 AS ClassId ,
	--	0 AS DivisionId ,
	--	'' AS ClassName ,
	--	'' AS DivisionName ,
	--	0 AS DivisionOrderIndex ,
	--	0 AS ClassOrderIndex ,
	--	'' AS ClassDivision  ,
	--	0 AS IsVariable  ,
	--	0 AS  Amount ,
	--	'' AS StartDate ,
	--    '' AS EndDate ,
	--	0 AS FAAmount,
	--	0 AS DiscountAmount,
	--    0 AS AdditionalAmount,
	--	0 AS NotApplicableAmount,
	--	0 AS PaidAmount,
	--	0 AS PendingAmount,
	--	0 AS OrgId ,
	--    '' AS OrgName ,
	--	0 AS OrgOrderIndex ,
	--	0 AS DepartmentId ,
	--    '' AS DepartmentName ,
	--	0 AS BatchId ,
	--	'' AS BatchName ,
	--	0 AS Discount ,
	--	0 AS ReceiptBookId,
	--	'' AS ReceiptBookTitle
	  
	
END
GO
PRINT N'Altering [sFrontOffice].[pEmployeeGatePassAdd]...';


GO
 
ALTER PROCEDURE [sFrontOffice].[pEmployeeGatePassAdd]
	
	@rOrgId int, 
	@rId int,
	@rEmployeeId bigint,
	@rReasonOfGatePass nvarchar(200),
	@rGatePassDate date,
	@rReturnGatePassDate date,
	@rGatePassTime datetime,
	@rReturnGatePassTime datetime,
	@rEntryModeStatusId smallint,
	@rCreatedUserId bigint,
	@rRemark nvarchar(200)='',
	@rStatusId int=0,
	@rAssignEmployeeId bigint = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION	
IF(@rId = 0)	
BEGIN
	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFrontOffice.tEmployeeGatePass', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	IF(@rStatusId = 0 AND @rAssignEmployeeId = 0)
	BEGIN
		INSERT INTO sFrontOffice.tEmployeeGatePass
		(
			OrgId,
			Id,
			EmployeeId,
			ReasonOfGatePass,
			GatePassDate,
			ReturnGatePassDate,
			GatePassTime,
			EntryModeStatusId,
			CreatedUserId,
			CreatedDateTime,
			Remark,
			ReturnGatePassTime
		)
		VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rEmployeeId,
			@rReasonOfGatePass,
			@rGatePassDate,
			@rReturnGatePassDate,
			@rGatePassTime,
			@rEntryModeStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rRemark,
			@rReturnGatePassTime 
		)
	END
	ELSE
	BEGIN
		INSERT INTO sFrontOffice.tEmployeeGatePass
		(
			OrgId,
			Id,
			EmployeeId,
			ReasonOfGatePass,
			GatePassDate,
			ReturnGatePassDate,
			GatePassTime,
			EntryModeStatusId,
			CreatedUserId,
			CreatedDateTime,
			Remark,
			ReturnGatePassTime,
			AssignEmployeeId,
			StatusId
		)
		VALUES
		(
			@rOrgId,
			@lNextNumber,
			@rEmployeeId,
			@rReasonOfGatePass,
			@rGatePassDate,
			@rReturnGatePassDate,
			@rGatePassTime,
			@rEntryModeStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rRemark,
			@rReturnGatePassTime,
			@rAssignEmployeeId,
			@rStatusId
		)
	END
		             
END	 
	 ELSE
BEGIN
	SET @lNextNumber = @rId
	UPDATE  sFrontOffice.tEmployeeGatePass
	SET
		ReasonOfGatePass=@rReasonOfGatePass,
		EmployeeId=@rEmployeeId,
		GatePassDate=@rGatePassDate,
		ReturnGatePassDate=@rReturnGatePassDate,
		GatePassTime=@rGatePassTime,
		ReturnGatePassTime=@rReturnGatePassTime,
		EntryModeStatusId=@rEntryModeStatusId,
		Remark=@rRemark,
		AssignEmployeeId = @rAssignEmployeeId
		
	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 [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,
   @rStatusId int=0,
   @rUserSourceId bigint = 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,
			ISNULL(EG.ReturnGatePassDate,'') AS ReturnGatePassDate,
			EG.GatePassTime,
			ISNULL(EG.ReturnGatePassTime,'') AS ReturnGatePassTime,
			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,
			ISNULL(EG.StatusId,0) as StatusId,
			SM1.Title as Status,
			ISNULL(EG.AssignEmployeeId,0) as AssignEmployeeId,
			CASE WHEN ISNULL(EG.AssignEmployeeId,0) = 0 THEN '' ELSE (SELECT FirstName+' '+MiddleName+' '+LastName FROM sHrm.tEmployeeMaster WHERE Id = EG.AssignEmployeeId) END AS AssignEmployeeName
		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
			LEFT JOIN sCommon.tStatusMaster SM1 ON SM1.Id = EG.StatusId
		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,'')=''))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND ((ISNULL(EG.StatusId,0) = @rStatusId) OR (ISNULL(@rStatusId,-1) = -1 AND ISNULL(EG.StatusId,0) != 0))
			AND ((EG.EmployeeId = @rUserSourceId) OR (ISNULL(@rUserSourceId,0) = 0))
		ORDER BY EG.GatePassDate,EG.GatePassTime DESC
END
GO
PRINT N'Altering [sHrm].[pStaffAttendaceDashboardGet]...';


GO
 
 
ALTER PROCEDURE [sHrm].[pStaffAttendaceDashboardGet]
	 
	 @rTypeId smallint,
	 @rUptoDate date='',
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDepartmentId int=0,
	 @rCommonOrgGroupBatchId int=0,
	 @rSyncDate int =0,
	 @rUserId bigint =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

if @rTypeId=1
BEGIN
	IF(@rSyncDate=1)
		BEGIN
			DELETE  sHrm.tTempStaffAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			INSERT INTO sHrm.tTempStaffAttendance
	SELECT     
    OGM.Id AS OrgGroupId,
    OGM.Title As OrgGroupTitle,
    0 As OrgId,
	'' As OrgTitle,
 --TotalCount
			ISNULL((SELECT COUNT(EM.Id) FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
			INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
			--INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
			--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 AND  ISNULL(EM.IsOtherUser,0) = 0),0) 
			AS TotalCount,

 --PresentCount
    ISNULL((SELECT 
        COUNT(ETRP.EmployeeId) 
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DME.OrgGroupId=OGM.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
      ),0) AS PresentCount,
--AbsentCount
      ISNULL((SELECT 
         COUNT(ETRP.EmployeeId) 
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
      WHERE DME.OrgGroupId=OGM.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
            AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
      ),0) As AbsentCount,
--LeaveCount
    ISNULL( (SELECT 
        COUNT(EM.Id)
     FROM sHrm.tLeave SHT
          INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId				
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		  INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				
	 WHERE DME.OrgGroupId=OGM.Id  AND COGBM.Id=@rCommonOrgGroupBatchId   and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  AND((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	),0) As LeaveCount,
--AB10Count
	 ISNULL((SELECT 
	    COUNT(EmployeeId) 
	FROM(
         SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,
             (OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR						
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
		WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
		
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	 ) AS Tmp),0) As 'AB10Count',
--AB3DaysCount
    ISNULL((SELECT 
	   COUNT(EmployeeId) FROM(
	      SELECT 
	          ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		      d.EmployeeId,
		      AttendanceDate,
		      d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
              INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			  INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
         WHERE
              DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
              IsPresent IN(0) 
              AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
         GROUP BY d.EmployeeId,AttendanceDate,IsPresent
         ) as sfsf
     WHERE rowno=3),0) as AB3DaysCount,
--Leave3DayCount    
  ISNULL((SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d
		 	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
             INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
             LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
           DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
          d.ToDate=CONVERT(char(10), @rUptoDate,126)
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
    ),0)  As Leave3DayCount,
   
--HundredPerAttnCount		
    ISNULL((SELECT 
      COUNT(EmployeeId) FROM (
          SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,(OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) as PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(numeric(10,2),((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage												
		  FROM sHrm.tEmployeeAttendanceRegister EAR						
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID						
						INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID						
		  WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)		
		  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	   ) AS Tmp),0) As 'HundredPerAttnCount',
--PendingCount	  
	    ISNULL((SELECT 
        COUNT(EM.Id) 
		 FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE OGM.Id=OGMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 AND  ISNULL(EM.IsOtherUser,0) = 0
	 
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ),0) AS PendingCount,
	   
	   @rUptoDate,
		  @rCommonOrgGroupBatchId,GetDate()	
	   
    FROM sSetup.tOrgGroupMaster OGM
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    WHERE OGM.Id<>1 AND COGBM.Id=@rCommonOrgGroupBatchId   AND ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
	And ISNULL(OGM.IsObsolete,0) = 0
	SELECT * FROM sHrm.tTempStaffAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		END
	ELSE
		Print 1
		BEGIN
			  IF  Exists(select 1 from sHrm.tTempStaffAttendance    where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND EmployeeAttendanceDate=  CONVERT(date,@rUptoDate,102)AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
			BEGIN
	
				SELECT * FROM sHrm.tTempStaffAttendance   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN
			DELETE  sHrm.tTempStaffAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			INSERT INTO sHrm.tTempStaffAttendance
--TotalCount	
				SELECT     
    OGM.Id AS OrgGroupId,
    OGM.Title As OrgGroupTitle,
    0 As OrgId,'' As OrgTitle,
	    ISNULL((SELECT 
        COUNT(EM.Id) 
     FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
          --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				    
		  --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		  --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID          
	 WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0),0) AS TotalCount,
  --  (SELECT 
  --      COUNT(EM.Id) 
  --   FROM sHrm.tEmployeeMaster EM
		--  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		--  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--  --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --        --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
  --        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				    
		--  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		--  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID          
	 --WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
	 --and EM.statusid=7) AS Total,

    ISNULL((SELECT 
        COUNT(ETRP.EmployeeId) 
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DME.OrgGroupId=OGM.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
		   and EM.statusid=7
      ),0) AS PresentCount,

     ISNULL((SELECT 
         COUNT(ETRP.EmployeeId) 
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		 INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		 INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
      WHERE DME.OrgGroupId=OGM.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
            AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			 and EM.statusid=7
      ),0) As AbsentCount,
      
    ISNULL((SELECT 
        COUNT(EM.Id)
     FROM sHrm.tLeave SHT
          INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId				
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
		  INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				
	 WHERE DME.OrgGroupId=OGM.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
		  AND((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  and EM.statusid=7
	),0) As LeaveCount,

	ISNULL((SELECT 
	    COUNT(EmployeeId) 
	FROM(
         SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,
             (OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR						
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
		WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
		
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	 ) AS Tmp),0) As 'AB10Count',

   ISNULL((SELECT 
	   COUNT(EmployeeId) FROM(
	      SELECT 
	          ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		      d.EmployeeId,
		      AttendanceDate,
		      d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
              INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			  INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
         WHERE
              DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
              IsPresent IN(0) 
              AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			  and EM.statusid=7
         GROUP BY d.EmployeeId,AttendanceDate,IsPresent
         ) as sfsf
     WHERE rowno=3),0) as AB3DaysCount,
    
 ISNULL((SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d
		 	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
             INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
             LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
           DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
          d.ToDate=CONVERT(char(10), @rUptoDate,126) 
		  and EM.statusid=7
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
    ),0)  As Leave3DayCount,
   
		
   ISNULL((SELECT 
      COUNT(EmployeeId) FROM (
          SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,(OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) as PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(numeric(10,2),((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage												
		  FROM sHrm.tEmployeeAttendanceRegister EAR						
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID						
						INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID						
		  WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)		
		  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	   ) AS Tmp),0) As 'HundredPerAttnCount',

	   ISNULL((SELECT COUNT(EM.Id) 
		 FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		 WHERE OGM.Id=OGMM.Id 
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
							WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ),0) AS PendingCount,
	   @rUptoDate,
		  @rCommonOrgGroupBatchId,GetDate()	
	   
    FROM sSetup.tOrgGroupMaster OGM
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    WHERE OGM.Id<>1 AND COGBM.Id=@rCommonOrgGroupBatchId  AND ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
	And ISNULL(ISNULL(OGM.IsObsolete,0),0) = 0
	SELECT * FROM sHrm.tTempStaffAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			END
		END
  END
  
ELSE IF @rTypeId=2  

BEGIN
IF(@rUserId = 0)
  BEGIN
  SELECT 
     OGMT.Id As OrgGroupId,
     OM.Id AS OrgId, 
     OM.DisplayTitle AS OrgTitle,
     OGMT.Title As OrgGroupTitle,
	 (SELECT 
         COUNT(EM.Id) 
      FROM sHrm.tEmployeeMaster EM
		 INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
         --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
         INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
       WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
       AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) As TotalCount,
   --  (SELECT 
   --      COUNT(EM.Id) 
   --   FROM sHrm.tEmployeeMaster EM
		 --INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 --INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 ----INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --      --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
   --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
   --    WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
   --    AND EM.statusid=7) As Total,
        
      (SELECT 
          COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
       WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=1  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS PresentCount,
        
      (SELECT 
           COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEM ON OMEM.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OMEM.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=0  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS AbsentCount, 	

	   (SELECT 
	         COUNT(EM.Id)
        FROM sHrm.tLeave SHT
           INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
           INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
		   INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		      
		   INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	       LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID				
		 WHERE EJD.OrgId=OM.Id AND				
			  ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			   AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  AND COGBM.Id=@rCommonOrgGroupBatchId		
			   and EM.statusid=7		
		) As LeaveCount,
		
   (SELECT 
	   COUNT(EmployeeId) FROM(
           SELECT    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DME.Id,DME.Code As DeptCode,
              (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  (EC.MobileNumber) AS ContactNo,
			   COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
               CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
			FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID												
			WHERE EJD.OrgId=OM.Id AND 
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
				and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	      ) AS Tmp) As 'AB10Count',
	
	(SELECT COUNT(EmployeeId) from(
	    SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
		FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
              AND COGBM.Id=@rCommonOrgGroupBatchId
			  and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) as T
        WHERE rowno=3) AS AB3DaysCount,
        
     (SELECT 
        COUNT(EmployeeId) FROM(
	       SELECT 
			d.EmployeeId,
			d.FromDate,
			d.ToDate
		  FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
		and EM.statusid=7
        ) AS Temp 
        WHERE (DATEDIFF(d, FromDate, ToDate)=2)
        )  AS Leave3DayCount,
      
    (SELECT 
        COUNT(EmployeeId) FROM  (
           SELECT    
             OGMEL.Id as OrgGroupId,
             OGMEL.Title As OrgGroupTitle,
             OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
             DME.Id,DME.Code As DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 (EC.MobileNumber) AS ContactNo,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
              convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage

            FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		    WHERE EJD.OrgId=OM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                 EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				 and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	     ) AS Tmp) As 'HundredPerAttnCount'
		 ,
	(SELECT  COUNT(EM.Id) 
		FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE OM.Id=OMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ) AS PendingCount,
	   getdate()AS UpdateDate
			
    FROM 
       sSetup.tOrgGroupMaster OGMT 
    INNER JOIN sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId    
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
    WHERE OGMT.Id=@rOrgGroupId AND COGBML.Id=@rCommonOrgGroupBatchId 
	And ISNULL(OGMT.IsObsolete,0) = 0
	ORDER BY OM.OrderIndex
  END   
ELSE IF(@rUserId <> 0)
  BEGIN
  SELECT 
     OGMT.Id As OrgGroupId,
     OM.Id AS OrgId, 
     OM.DisplayTitle AS OrgTitle,
     OGMT.Title As OrgGroupTitle,
	 (SELECT 
         COUNT(EM.Id) 
      FROM sHrm.tEmployeeMaster EM
		 INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
         --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
         INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
       WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
       AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) As TotalCount,
   --  (SELECT 
   --      COUNT(EM.Id) 
   --   FROM sHrm.tEmployeeMaster EM
		 --INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 --INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 ----INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --      --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
   --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
   --    WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
   --    AND EM.statusid=7) As Total,
        
      (SELECT 
          COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
       WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=1  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS PresentCount,
        
      (SELECT 
           COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEM ON OMEM.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OMEM.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=0  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS AbsentCount, 	

	   (SELECT 
	         COUNT(EM.Id)
        FROM sHrm.tLeave SHT
           INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
		   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
		   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
		   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
           INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
		   INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		      
		   INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	       LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID				
		 WHERE EJD.OrgId=OM.Id AND				
			  ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			   AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  AND COGBM.Id=@rCommonOrgGroupBatchId		
			   and EM.statusid=7		
		) As LeaveCount,
		
   (SELECT 
	   COUNT(EmployeeId) FROM(
           SELECT    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DME.Id,DME.Code As DeptCode,
              (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  (EC.MobileNumber) AS ContactNo,
			   COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
               CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
			FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID												
			WHERE EJD.OrgId=OM.Id AND 
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
				and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	      ) AS Tmp) As 'AB10Count',
	
	(SELECT COUNT(EmployeeId) from(
	    SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
		FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
              AND COGBM.Id=@rCommonOrgGroupBatchId
			  and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) as T
        WHERE rowno=3) AS AB3DaysCount,
        
     (SELECT 
        COUNT(EmployeeId) FROM(
	       SELECT 
			d.EmployeeId,
			d.FromDate,
			d.ToDate
		  FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
		and EM.statusid=7
        ) AS Temp 
        WHERE (DATEDIFF(d, FromDate, ToDate)=2)
        )  AS Leave3DayCount,
      
    (SELECT 
        COUNT(EmployeeId) FROM  (
           SELECT    
             OGMEL.Id as OrgGroupId,
             OGMEL.Title As OrgGroupTitle,
             OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
             DME.Id,DME.Code As DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 (EC.MobileNumber) AS ContactNo,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
              convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage

            FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		    WHERE EJD.OrgId=OM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                 EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				 and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
		
	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	     ) AS Tmp) As 'HundredPerAttnCount'
		 ,
	(SELECT  COUNT(EM.Id) 
		FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE OM.Id=OMM.Id 
	 and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ) AS PendingCount,
	   getdate()AS UpdateDate
			
    FROM 
       sSetup.tOrgGroupMaster OGMT 
    INNER JOIN sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId    
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
	INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id
    WHERE OGMT.Id=@rOrgGroupId AND COGBML.Id=@rCommonOrgGroupBatchId 
	And OGMT.IsObsolete = 0 AND U.UserId = @rUserId
  END 
  END
  
  
else if @rTypeId=3   
  BEGIN
--TotalCount
    (SELECT 
      (DME.Id) As DepartmentId,
        DME.Code As DepartmentCode,OGMM.Id AS OrgGroupId,
        OGMM.Title As OrgGroupTitle,0 As OrgId,'' As OrgTitle,
        COUNT(DME.Id) As TotalCount,
--PresentCount
	(SELECT 
            COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	   WHERE DME.Id=DMER.Id 
			and ETRP.IsPresent=1 
			AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
	   ) AS PresentCount,
--AbsentCount			
	  (SELECT COUNT(ETRP.EmployeeId) 
            FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
	   WHERE DME.Id=DMER.Id and ETRP.IsPresent=0 
			AND ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
			and EM.statusid=7
		) AS AbsentCount,
--LeaveCount			
   (SELECT    
        COUNT(EM.Id)
    FROM sHrm.tLeave SHT
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
	WHERE DME.Id=DMER.Id AND				
			((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		     AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))		
			 and EM.statusid=7		
	) AS LeaveCount,
				
--AB10%Count				
     (SELECT 
         COUNT(EmployeeId) 
      FROM (
         SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id) AS FLOAT))*100)) as Percentage		
		FROM sHrm.tEmployeeAttendanceRegister EAR
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
		WHERE DME.Id=DMER.Id AND 
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
	    GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	    HAVING CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id) AS FLOAT))*100))<=90
	     ) AS Tmp) AS 'AB10Count',
	           
--AB3DaysCount	           
      (SELECT 
          COUNT(EmployeeId) FROM(
	         SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
	   FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	    WHERE
            DME.Id=DMER.Id  AND IsPresent IN(0) 
            AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) AS T
        WHERE rowno=3) as AB3DaysCount,
  --Leave3DayCount
   (SELECT COUNT(EmployeeId) FROM(
	   SELECT
			d.EmployeeId,d.FromDate,d.ToDate
	   FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE
			 DME.Id=DMER.Id AND 
			 d.ToDate=CONVERT(char(10), @rUptoDate,126)   
			 and EM.statusid=7     
        ) AS Temp WHERE (DATEDIFF(d, FromDate, ToDate)=2)        
      )  AS Leave3DayCount,
        
--HundredPerAttnCount     
        
  (SELECT 
      COUNT(EmployeeId) FROM(
         SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,
            (OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) as Percentage		
	      FROM sHrm.tEmployeeAttendanceRegister EAR			
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE DME.Id=DMER.Id AND 		
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	  ) AS Tmp) As 'HundredPerAttnCount',

--PendingCount


	  (	select COUNT(*) from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
	where    EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126)) AND DMER.Id = DME.Id AND DMER.OrgGroupId = OGMM.Id and EM.statusid=7) 
	AS PendingCount

	FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
        --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	WHERE OGMM.ID=@rOrgGroupId AND EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 --AND COGBML.Id=@rCommonOrgGroupBatchId AND 
	And ISNULL(OGMM.IsObsolete,0) = 0
	GROUP BY DME.Id,DME.Code,OGMM.Id,OGMM.Title
	) 
					
  END
  
  
else if @rTypeId=4 
  BEGIN     
     SELECT (DME.Id) As DepartmentId,
         DME.Code As DepartmentCode,
         OGMM.Id AS OrgGroupId,OGMM.Title As OrgGroupTitle,
         OM.Id As OrgId,OM.DisplayTitle As OrgTitle,
         COUNT(DME.Id) As TotalCount, 
         (SELECT 
            COUNT(ETRP.EmployeeId) 
          FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE DME.Id=DMER.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId  
			AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7
           ) As PresentCount,
			
	  (SELECT 
	      COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
       WHERE DME.Id=DMER.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId  
	   and EM.statusid=7
	   AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId  
			AND ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
	  ) AS AbsentCount,
			
			
      (SELECT 
       COUNT(EM.Id)
      FROM sHrm.tLeave SHT
            INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id AND  ISNULL(EM.IsOtherUser,0) = 0
	        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	       
	        INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
            LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
	  WHERE DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  				
			((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			 AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			 and EM.statusid=7
	  ) As LeaveCount,
				
				
     (SELECT 
         COUNT(EmployeeId) FROM  (
            SELECT    
                OGMEL.Id as OrgGroupId,
                OGMEL.Title AS OrgGroupTitle,
                OMEL.Id AS OrgId,(OMEL.Title) As OrgTitle,
                DMER.Id,DMER.Code AS DepartmentCode,
                (EM.Id)EmployeeID,
                (EM.FirstName+' '+EM.LastName) AS EmployeeName,
				(EC.MobileNumber) AS ContactNo,
				COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
                CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) as Percentage

			 FROM sHrm.tEmployeeAttendanceRegister EAR				
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
			 WHERE DME.Id=DMER.Id AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
				and EM.statusid=7
			 GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)

	         HAVING CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100))<=90
	       ) AS Tmp) As 'AB10Count',
	           
	           
   (SELECT 
       COUNT(EmployeeId) FROM(
	      SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
			    d.EmployeeId,
			    AttendanceDate,
			    d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId  AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  
			IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, CONVERT(DATE, @rUptoDate, 126)) AND @rUptoDate    
			and EM.statusid=7           
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) AS T
        WHERE rowno=3) AS AB3DaysCount,
        
  (SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT 
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d		
 			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId	
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		  
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE
			 DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND 
			 d.ToDate=CONVERT(CHAR(10), @rUptoDate,126)     
			 and EM.statusid=7   
        ) AS Temp WHERE (DATEDIFF(d, FromDate, ToDate)=2)       
    )  AS Leave3DayCount,
        
        
    (SELECT 
       COUNT(EmployeeId) FROM  (
          SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.MobileNumber) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(Count(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE DME.Id=DMER.Id AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
			and EM.statusid=7
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	) AS Tmp) As 'HundredPerAttnCount',
	 (	select COUNT(*) from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
	where  OM.Id=OMM.Id and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126)) AND DMER.Id = DME.Id AND DMER.OrgGroupId=OGMM.Id and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0) 
	AS PendingCount
  
   FROM sHrm.tEmployeeMaster EM
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
     --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
    INNER JOIN sHrm.tEmployeeJobDetail EJD1 ON EJD1.EmployeeId=EM.ID
    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD1.OrgGroupDepartmentId
	LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID              
  WHERE DME.OrgGroupId=@rOrgGroupId And EJD1.OrgId=@rOrgId and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0 --AND COGBML.Id=@rCommonOrgGroupBatchId 
  And ISNULL(OGMM.IsObsolete,0) = 0
  GROUP BY DME.Id,DME.Code,OGMM.Id,OGMM.Title,OM.Id,OM.DisplayTitle
	 
END  
   
   
else if @rTypeId=5   

BEGIN
   (SELECT(DM.code) As Dept,
          (EM.Id) As EmployeeId,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
          (EC.MobileNumber) AS ContactNo
    FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
			INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DM.Id=@rDepartmentId --AND COGBM.Id=@rCommonOrgGroupBatchId 
	  And ISNULL(OGMM.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
     )
END
   
ELSE IF @rTypeId=31
 BEGIN
     SELECT 
        (OGMM.id) AS OrgGroupId,(OGMM.Title) As OrgGroupTitle,
        (OM.id) OrgId,(OM.Title) OrgTitle,
        (DME.Code) As DepartmentCode,
		(EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
     FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --      INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	    
        LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID                    
	 WHERE DME.OrgGroupId=@rOrgGroupId --AND COGBM.Id=@rCommonOrgGroupBatchId 
	  And ISNULL(OGMM.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	 AND DME.Id=@rDepartmentId--) As Total
	 Order By EM.Code
       
 END   
 
ELSE IF @rTypeId=41 
 BEGIN
	SELECT 
	   (OGMM.id) As OrgGroupId,
	   (OGMM.Title) As OrgGroupTitle,
	   (OM.id) OrgId,(OM.Title) OrgTitle,
	   DME.Code As DepartmentCode,(EM.Id)EmployeeID,
	   (EM.Code)EmployeeCode,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
	   ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
	   (EC.MobileNumber) AS ContactNo
     FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --      INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	   
        LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	WHERE 
		EJD.OrgId=@rOrgId --AND COGBM.Id=@rCommonOrgGroupBatchId 
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0	
		 And ISNULL(OGMM.IsObsolete,0) = 0
		AND ((@rDepartmentId <>1 AND DME.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))   
	Order By EM.Code
 END   
 
ELSE IF @rTypeId=32   

BEGIN
    SELECT 
        (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
        ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
    FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	 WHERE DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId and  ETRP.IsPresent=1
	  And ISNULL(OGME.IsObsolete,0) = 0
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
	Order By EM.Code
END

else if @rTypeId=42  

BEGIN
    SELECT 
        (OGME.id) As OrgGroupId,
        (OGME.Title) As OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code As DepartmentCode,
        (EM.Id)EmployeeID,
		(EM.Code)EmployeeCode,
        (EM.FirstName+' '+EM.LastName) AS EmployeeName,
        ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE EJD.OrgId=@rOrgId
		and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		and  ETRP.IsPresent=1
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		And ISNULL(OGME.IsObsolete,0) = 0
		and ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
	Order By EM.Code
END


else if @rTypeId=33  
  BEGIN
     SELECT 
        (OGME.id) As OrgGroupId,
        (OGME.Title) As OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code As DepartmentCode,
		(EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			
	where DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId and  ETRP.IsPresent=0  AND COGBM.Id=@rCommonOrgGroupBatchId 
	And ISNULL(OGME.IsObsolete,0) = 0
	and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	    AND ETRP.AttendanceDate = CONVERT(CHAR(10),  @rUptoDate,126)
	Order By EM.Code
  END   
  
  ELSE IF @rTypeId=43   
  BEGIN
     SELECT 
       (OGME.id) As OrgGroupId,
       (OGME.Title) As OrgGroupTitle,
 (OME.id) OrgId,(OME.Title) OrgTitle,
       DMER.Code As DepartmentCode,
       (EM.Id)EmployeeID,
	   (EM.Code)EmployeeCode,
       (EM.FirstName+' '+EM.LastName) AS EmployeeName,
       ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
       (EC.MobileNumber) AS ContactNo
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
        INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	  WHERE EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId 
		and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		and  ETRP.IsPresent=0 
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		And ISNULL(OGME.IsObsolete,0) = 0
		and ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
	Order By EM.Code
  END 
   
 ELSE IF @rTypeId=34 
   
   BEGIN
      
       select (OGMEL.id) As OrgGroupId,
              (OGMEL.Title) As OrgGroupTitle,
              (OMEL.id) OrgId,(OMEL.Title) OrgTitle,
              DMER.Code As DepartmentCode,
              (EM.Id)EmployeeID,
			  (EM.Code)EmployeeCode,
              (EM.FirstName+' '+EM.LastName) AS EmployeeName,
              ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
              (EC.MobileNumber) AS ContactNo
       FROM sHrm.tLeave SHT
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	   WHERE DMER.OrgGroupId=@rOrgGroupId AND DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId 
	   And OGMEL.IsObsolete = 0
	   and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	   AND			
				((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		Order By EM.Code
   END
   
   
 ELSE IF @rTypeId=44    
   BEGIN
       SELECT (OGMEL.id) As OrgGroupId,
              (OGMEL.Title) As OrgGroupTitle,
              (OMEL.id) OrgId,(OMEL.Title) OrgTitle,
              DMER.Code As DepartmentCode,
			  (EM.Id)EmployeeID,
              (EM.Code)EmployeeCode,
			  (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
              (EC.MobileNumber) AS ContactNo
       FROM sHrm.tLeave SHT
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	   WHERE EJD.OrgId=@rOrgId	AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And OGMEL.IsObsolete = 0
	   and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
				AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And				
				 ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			     AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		Order By EM.Code
   END
   
 ELSE IF @rTypeId=35 
   
   BEGIN

    select * from (
          select    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,--DMER.Id,DMER.Code As DeptCode,
              (EM.Id)EmployeeID,
			  (EM.Code)EmployeeCode,
			  (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			  (EC.MobileNumber) AS ContactNo,DMER.Code As DepartmentCode,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
			  convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		  FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			
		  WHERE DMER.OrgGroupId=@rOrgGroupId  AND DMER.Id=@rDepartmentId 
		  And OGMEL.IsObsolete = 0
		  
		  AND COGBM.Id=@rCommonOrgGroupBatchId AND
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,EJD.DateOfJoining,EDM.title,
				EM.Id,(EM.Code),(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),DMER.Code
	       HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	   ) AS Tmp
      
   END
   
   
   else if @rTypeId=45 
   
   BEGIN
   
    SELECT * FROM (
          SELECT    
               OGMEL.Id as OrgGroupId,
               OGMEL.Title As OrgGroupTitle,
               OMEL.Id As OrgId,
               (OMEL.Title) As OrgTitle,
               (EM.Id)EmployeeID,
			   (EM.Code)EmployeeCode,
               (EM.FirstName+' '+EM.LastName) AS EmployeeName,
               ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
				(EC.MobileNumber) AS ContactNo,DMER.Code As DepartmentCode,
				count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
                convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		  FROM sHrm.tEmployeeAttendanceRegister EAR				
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId			
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE EJD.OrgId=@rOrgId  AND COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
			    and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) AND
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
				GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,EJD.DateOfJoining,EDM.title
				,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),DMER.Code 
	       HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	    ) AS Tmp
      
   END
   
   
 ELSE IF @rTypeId=36
  
  BEGIN
    (SELECT Temp.OrgGroupId,
            Temp.OrgGroupTitle,
            Temp.OrgId,Temp.OrgTitle,
            (EMR.Id) As EmployeeId,
			EMR.Code As EmployeeCode,
            (EMR.FirstName+' '+EMR.LastName) AS EmployeeName,
            ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
            (ECR.PresentContactNo) AS ContactNo,
			DepartmentCode
     FROM(select ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		    d.EmployeeId,(EM.Code)EmployeeCode,
		    AttendanceDate,d.IsPresent,
		    OGMEL.Id As OrgGroupId,
		    OGMEL.Title As OrgGroupTitle,
		    OMEL.Id As OrgId,OMEL.Title As OrgTitle,
		    DMER.Code As DepartmentCode
          FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
        WHERE
            DMER.OrgGroupId=@rOrgGroupId And DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
			AND 
            IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate       
        Group By d.EmployeeId,EM.Code,AttendanceDate,IsPresent,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Code 
        ) As Temp
            INNER JOIN sHrm.tEmployeeMaster EMR ON EMR.ID=Temp.EmployeeId AND  ISNULL(EMR.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMR.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications ECR on EMR.ID=ECR.EmployeeID        
        where rowno=3
      ) 
       
  END
  
  
  
 ELSE IF @rTypeId=46 
 
  BEGIN
  (SELECT Temp.OrgGroupId,
          Temp.OrgGroupTitle,
          Temp.OrgId,Temp.OrgTitle,
          (EMR.Id) As EmployeeId,
		  EMR.Code As EmployeeCode,
          (EMR.FirstName+' '+EMR.LastName) AS EmployeeName,	
          ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,	
          (ECR.PresentContactNo) AS ContactNo,DepartmentCode
      FROM(
	      select 
	         ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
			 d.EmployeeId,
			 EM.Code As EmployeeCode,
			 AttendanceDate,d.IsPresent,
			 OGMEL.Id As OrgGroupId,
			 OGMEL.Title As OrgGroupTitle,
			 OMEL.Id As OrgId,
			 OMEL.Title As OrgTitle,
			 DMER.Code As DepartmentCode
		   FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
        EJD.OrgId=@rOrgId 
        AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And OGMEL.IsObsolete = 0
		and EM.statusid=7
		AND
        IsPresent IN(0) AND COGBM.Id=@rCommonOrgGroupBatchId 
        AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
        Group By d.EmployeeId,EM.Code,AttendanceDate,IsPresent,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Code 
        ) As Temp
		INNER JOIN sHrm.tEmployeeMaster EMR ON EMR.ID=Temp.EmployeeId AND  ISNULL(EMR.IsOtherUser,0) = 0
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMR.ID
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications ECR on EMR.ID=ECR.EmployeeID
      WHERE rowno=3
    ) 
    
  END

  ELSE IF @rTypeId=37
  
  BEGIN
     (SELECT * FROM(
	     SELECT
			d.FromDate,
			d.ToDate,
			OGMEL.Id As OrgGroupId,
			OGMEL.Title As OrgGroupTitle,
			OMEL.Id As OrgId,
			OMEL.Title As OrgTitle,
			EM.Code As EmployeeId,
			EM.ID As EmployeeCode,
			(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
            (EC.MobileNumber) AS ContactNo,
            DME.Code As DepartmentCode
		FROM sHrm.tLeave d
	 	    INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
		    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		    LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
		    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		    LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE
			d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
			and DME.OrgGroupId=@rOrgGroupId AND DME.Id=@rDepartmentId And OGMEL.IsObsolete = 0
			and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
      ) 
  END

  ELSE IF @rTypeId=47   
  
  BEGIN
  
     (SELECT * from(
	     SELECT
			d.FromDate,
			d.ToDate,
			OGMEL.Id As OrgGroupId,
			OGMEL.Title As OrgGroupTitle,
			OMEL.Id As OrgId,OMEL.Title As OrgTitle,
			EM.Code As EmployeeId,
			EM.Id As EmployeeCode,
			(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			(EC.MobileNumber) AS ContactNo,DME.Code As DepartmentCode
		  FROM sHrm.tLeave d
		 	    INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.BatchId AND BMEL.IsActive = 1
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			    LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			    LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE
          d.ToDate=CONVERT(char(10), @rUptoDate,126)
		  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
          AND EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
          AND ((@rDepartmentId <>1 AND DME.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) 
        ) AS Temp where (DATEDIFF(d, FromDate, ToDate)=2)        
      ) 
  
  
  END 
  
  
  else if @rTypeId=38
  
  BEGIN
      SELECT    
          OGMEL.Id as OrgGroupId,
          OGMEL.Title As OrgGroupTitle,
          OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
          DMER.Id,DMER.Code As DepartmentCode,
          (EM.Id)EmployeeID,
		  (EM.Code)EmployeeCode,
          (EM.FirstName+' '+EM.LastName) AS EmployeeName,
           ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
		  (EC.MobileNumber) AS ContactNo,
		   count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
		   convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
	  FROM sHrm.tEmployeeAttendanceRegister EAR		
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	  WHERE DMER.OrgGroupId=@rOrgGroupId AND DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0 
	  and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	  AND		
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
	  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),EJD.DateOfJoining,EDM.title
	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
  
  END
  
  
  ELSE IF @rTypeId=48 
  
  BEGIN
      
      SELECT    
           OGMEL.Id as OrgGroupId,
           OGMEL.Title As OrgGroupTitle,
           OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
           DMER.Id,DMER.Code As DepartmentCode,
           (EM.Id)EmployeeID,
		   (EM.Code)EmployeeCode,
           (EM.FirstName+' '+EM.LastName) AS EmployeeName,
            ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
			(EC.MobileNumber) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage						
		FROM sHrm.tEmployeeAttendanceRegister EAR			
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.BatchId AND BMEL.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
            INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId		
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId  And OGMEL.IsObsolete = 0
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
			and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.MobileNumber),EJD.DateOfJoining,EDM.title
		HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
  END

  ELSE IF @rTypeId=39   

BEGIN
    SELECT 
       (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
	 from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	where DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId And ISNULL(OGME.IsObsolete,0) = 0
	and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
	AND EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))		
	Order By EM.Code
END

  ELSE IF @rTypeId=49   

BEGIN
    SELECT 
        (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,
		(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
		 ISNULL(Year(EJD.DateOfJoining),'') AS DateOfJoining,
		EDM.title As EmployeeDesignation,
        (EC.MobileNumber) AS ContactNo
	 from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		

		WHERE EJD.OrgId=@rOrgId
		AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		And ISNULL(OGME.IsObsolete,0) = 0
		and EM.statusid=7 AND  ISNULL(EM.IsOtherUser,0) = 0
		AND   EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10),@rUptoDate,126))		
		Order By EM.Code
END


END
GO
PRINT N'Altering [siTax].[pForm16IncomeTaxSlabDetailGet]...';


GO
 
 
ALTER PROCEDURE [siTax].[pForm16IncomeTaxSlabDetailGet]   
@rEmployeeId bigint,
@rAssesmentYearId bigint,
@rOrgGroupId int,
@rGrossAmount DECIMAL(18,2),
@rTaxDeducatedatsourceus192 DECIMAL(18,2)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 
	DECLARE @GenderId INT
	DECLARE @DateOfBirth DATE
	DECLARE @Age INT
	DECLARE @TaxPercentage DECIMAL(18,2) 
	DECLARE @TaxExeption DECIMAL(18,2)
	DECLARE @AmountFROM DECIMAL(18,2) 
	DECLARE @AmountTo DECIMAL(18,2)
	DECLARE @Count INT =0
	DECLARE @Counter INT =0
	DECLARE @TaxAmount DECIMAL(18,2)=0
	DECLARE @EducationCess DECIMAL(18,2)=0
	DECLARE @TaxPayable DECIMAL(18,2)=0
	DECLARE @ReliefUnderSection89 DECIMAL(18,2)=0
	DECLARE @TaxPayable2 DECIMAL(18,2)=0
	DECLARE @TaxSeductedAtSource192 DECIMAL(18,2)=0
	DECLARE @Balance DECIMAL(18,2)=0
	DECLARE @TaxCalculation DECIMAL(18,2)=0


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

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

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

	

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

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

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


			--SELECT @TaxSeductedAtSource192=ISNULL(SUM(Amount),0) 
			--FROM [siTax].[tIncomeTaxChallan] 
			--WHERE 
			--IsObsolete=0 
			--AND AssesmentYearId=@rAssesmentYearId 
			--AND EmployeeId=@rEmployeeId 
			--AND OrgGroupId=@rOrgGroupId 
	

			
			SET @TaxSeductedAtSource192=@TaxSeductedAtSource192+@rTaxDeducatedatsourceus192
			
			IF(@rGrossAmount <= @AmountTo)
			BEGIN
				 IF(@TaxAmount > @ReliefUnderSection89)
				 BEGIN
					SET @Balance=@TaxAmount-@ReliefUnderSection89
				 END
				 ELSE
				 BEGIN
					 SET @ReliefUnderSection89 = @TaxAmount
					 SET @Balance=@TaxAmount-@ReliefUnderSection89
				 END
			END
			ELSE 
			BEGIN
				SET @Balance = @TaxAmount
				SET @ReliefUnderSection89 = 0
			END

 			IF @Balance < 0
			BEGIN			
			SET @Balance = 0
			END
			
			SET @EducationCess =(@Balance*4)/100
			SET @TaxPayable=@Balance
	
			--SET @TaxPayable2 =CASE WHEN @TaxPayable>@ReliefUnderSection89 AND @TaxAmount <= 350000  THEN  @TaxPayable-@ReliefUnderSection89 ELSE 0 END 
			SET @TaxPayable2 =@Balance+@EducationCess
			SET @Balance=@TaxPayable2-@TaxSeductedAtSource192

			print  @TaxPayable2
			print  @TaxSeductedAtSource192
			 
		END

	SELECT ISNULL(@TaxAmount,0) AS TaxAmount
	,ISNULL(@EducationCess,0) AS EducationCess3
	,ISNULL(@TaxPayable,0) AS TaxPayable
	,ISNULL(@ReliefUnderSection89,0) AS ReliefUnderSection89
	, ISNULL(@TaxPayable2,0) AS TaxPayable2
	,ISNULL(@TaxSeductedAtSource192,0) AS TaxSeductedAtSource192
	,ISNULL(@Balance,0) AS Balance
END
GO
PRINT N'Altering [sRecruitment].[pCandidateApplicationAdd]...';


GO

ALTER PROCEDURE [sRecruitment].[pCandidateApplicationAdd]   									
	@rOrgGroupID smallint, 
	@rVacancyId int, 
	@rId bigint, 
	@rApplicationNumber int	,
	@rApplicationPassword nvarchar(100)='',
	@rCandidateNumber int, 
	@rFirstName nvarchar(100), 
	@rMiddleName nvarchar(100), 
	@rLastName nvarchar(100), 
	@rDateOfBirth date, 
	@rGenderId smallint, 
	@rReligionId int, 
	@rMaritalStatusId smallint, 
	@rQualification nvarchar(150),
	@rFamilyCast nvarchar(150), 
	@rCastCategoryId int, 
	@rRecruitmentStatusId smallint, 
	@rMobileNo nvarchar(20), 
	@rPersonalEmail nvarchar(100), 
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint, 	
	@rDataEntryModeId smallint, 
    @rDataEntryStatusId smallint,
    @OutAdmissionFormId BIGINT = NULL OUTPUT,
	@rLastDrawnSalary decimal,
	@rExpectedSalary decimal,
	@rAdditionalRemark nvarchar(500),
	@rReferenceId smallint,
	@rMainSubject nvarchar(100),
	@rOrgId int 

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 IF(@rId = 0)	
 BEGIN
 SELECT  @rCandidateNumber =  ISNULL(MAX(CandidateNumber),0) 
                       FROM  sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupID
                       AND ISNULL(LEN(CandidateNumber),0)=
                       (SELECT ISNULL((MAX(LEN(CandidateNumber))),0) 
                       FROM  sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupID
                       AND Isnumeric(CandidateNumber) = 1)
	
	
	    SET @rCandidateNumber = @rCandidateNumber +1
	
		IF Exists(select ApplicationNumber from sRecruitment.tCandidateMaster where ApplicationNumber=@rApplicationNumber AND OrgGroupID=@rOrgGroupID)
			BEGIN
			select -101 as Result
			RETURN
		END 
 END
 ELSE
 BEGIN
	IF Exists(select @rApplicationNumber from sRecruitment.tCandidateMaster where ApplicationNumber=@rApplicationNumber AND OrgGroupID=@rOrgGroupID And Id <> @rId)
	BEGIN
		select -101 as Result
		RETURN
	END 
 END

	
 BEGIN TRY
 BEGIN TRANSACTION	
 DECLARE @lNextNumber BIGINT
 DECLARE @lBIGID BIGINT
 DECLARE @lSMALLID INT
 
 IF(@rId = 0)	
	BEGIN
	IF(@rApplicationNumber = 0)
	BEGIN
	SELECT @rApplicationNumber = ISNULL(MAX(ApplicationNumber),0) + 1 FROM sRecruitment.tCandidateMaster
	END
	IF(@rApplicationPassword = '')
	BEGIN
	SELECT @rApplicationPassword = @rApplicationNumber
	END
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sRecruitment.tCandidateMaster
		(
				OrgGroupID, 
				VacancyId, 
				Id, 
				ApplicationNumber,	
				ApplicationPassword ,
				CandidateNumber, 
				FirstName, 
				MiddleName, 
				LastName, 
				DateOfBirth, 
				GenderId, 
				ReligionId, 
				MaritalStatusId, 
				Qualification,
				FamilyCast, 
				CastCategoryId, 
				RecruitmentStatusId, 
				MobileNo, 
				PersonalEmail, 
				CreatedUserId, 
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,	
				DataEntryModeId, 
				DataEntryStatusId,
				LastDrawnSalary,
				ExpectedSalary,
				AdditionalRemark,
				ReferenceId,
				MainSubject,
				OrgId
			
		)
	VALUES
		(
			 @rOrgGroupID , 
				@rVacancyId , 
				@lNextNumber , 
				@rApplicationNumber ,	
				@rApplicationPassword ,
				@rCandidateNumber , 
				@rFirstName , 
				@rMiddleName , 
				@rLastName , 
				@rDateOfBirth , 
				@rGenderId , 
				@rReligionId , 
				@rMaritalStatusId , 
				@rQualification ,
				@rFamilyCast, 
				@rCastCategoryId , 
				@rRecruitmentStatusId , 
				@rMobileNo , 
				@rPersonalEmail , 
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rUpdatedUserId,
				sCommon.fGetDate(),	
				@rDataEntryModeId , 
				@rDataEntryStatusId,
				@rLastDrawnSalary,
				@rExpectedSalary,
				@rAdditionalRemark,
				@rReferenceId,
				@rMainSubject,
				@rOrgId
		)
	INSERT INTO sRecruitment.tRecruitmentStatusLog
		(
		OrgGroupId,
		CandidateId,
		RecruitmentStatusId,
		Remark,
		CreatedUserId,
		CreatedDateTime
			
		)
		VALUES
		(
		@rOrgGroupID , 
		@lNextNumber,
		@rRecruitmentStatusId,
		'',
		@rCreatedUserId,
		sCommon.fGetDate()
		)
	END	 
	ELSE
	BEGIN
	SET @lNextNumber = @rId
	    UPDATE  sRecruitment.tCandidateMaster
	    SET
				VacancyId=@rVacancyId, 	
				--ApplicationNumber=@rApplicationNumber,					
				--CandidateNumber=@rCandidateNumber, 
				FirstName=@rFirstName, 
				MiddleName=@rMiddleName, 
				LastName=@rLastName, 
				DateOfBirth=@rDateOfBirth, 
				GenderId=@rGenderId, 
				ReligionId=@rReligionId, 
				MaritalStatusId=@rMaritalStatusId, 
				Qualification=@rQualification,
				FamilyCast=@rFamilyCast, 
				CastCategoryId=@rCastCategoryId, 
				RecruitmentStatusId=@rRecruitmentStatusId, 
				MobileNo=@rMobileNo, 
				PersonalEmail=@rPersonalEmail, 				
				UpdatedUserId=@rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				LastDrawnSalary=@rLastDrawnSalary,
				ExpectedSalary=@rExpectedSalary,
				AdditionalRemark=@rAdditionalRemark,
				ReferenceId = @rReferenceId,
				MainSubject = @rMainSubject,
				OrgId = @rOrgId

	      WHERE Id = @rId 	   
	END  
	SELECT @lNextNumber AS Result
	SET @OutAdmissionFormId=@lNextNumber

	COMMIT TRANSACTION

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


GO
ALTER PROCEDURE [sRecruitment].[pCandidateApplicationConfirmGet]
	 @rCandidateId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
	CM.OrgGroupID,
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				iSNULL(CM.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(CM.DataEntryStatusId,0) as DataEntryStatusId,
			CM.ApplicationNumber,
			CM.ApplicationPassword,
			GM.Title AS Gender,
			RM.Title AS ReligionName,
			CCM.Title AS CastCategoryName,
			CC.PresentStreetOne,
			CC.PresentStreetTwo,
			CC.PresentStreetThree,
			CC.PresentCountry,
			CC.PresentState,
			CC.PresentCity,
			CC.PresentZipCode,
			CC.PresentContactNo,
			CC.PermanentStreetOne,
			CC.PermanentStreetTwo,
			CC.PermanentStreetThree,
			CC.PermanentCountry,
			CC.PermanentState,
			CC.PermanentCity,
			CC.PermanentZipCode,
			CC.PermanentContactNo,
			CI.CandidatePhoto,
			MS.Title AS MaritalStatus,
			CM.LastDrawnSalary,
			CM.ExpectedSalary,
			VM.ConfirmationRemark,
			ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
			DM.Title AS Reference,
			ISNULL(CM.MainSubject,'') AS MainSubject
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			LEFT JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId 
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId 
			LEFT JOIN sRecruitment.tCandidateCommunications	 CC ON 	CC.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tCandidateImages	CI ON CI.CandidateId=CM.Id	
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id=CM.MaritalStatusId	 		 	
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id  = CM.ReferenceId
			AND DM.DataTypeId = 13
  WHERE 
  
      ((CM.Id = @rCandidateId) OR (@rCandidateId = 0))
       
 
END
GO
PRINT N'Altering [sRecruitment].[pCandidateApplicationGet]...';


GO
ALTER PROCEDURE [sRecruitment].[pCandidateApplicationGet]
	@rCandidateId bigint= 0,
	@rApplicationNumber int	,
	@rOrgGroupID smallint
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
				CM.OrgGroupID,
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				iSNULL(CM.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(CM.DataEntryStatusId,0) as DataEntryStatusId,
			CM.ApplicationNumber,
			CM.ApplicationPassword,
			CM.LastDrawnSalary,
			CM.ExpectedSalary,
			ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
			CM.ReferenceId,
			CM.MainSubject,
			CM.OrgId
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId							
		WHERE 
				 CM.OrgGroupID = @rOrgGroupID
		   AND ((CM.Id = @rCandidateId) OR (@rCandidateId = 0))
		   AND ((CM.ApplicationNumber =@rApplicationNumber ) OR (@rApplicationNumber = 0))
		 
 
       
 order by CM.ApplicationNumber
END
GO
PRINT N'Altering [sRecruitment].[pCandidateDetailExportGet]...';


GO
 
ALTER PROCEDURE [sRecruitment].[pCandidateDetailExportGet]
(
		@rOrgGroupID smallint, 
		@rVacancyId int=0,		
		@rCandidateNumber int=0, 
		@rFirstName nvarchar(100), 
		@rLastName nvarchar(100),
		@rRecruitmentStatusId smallint,
		@rFromDate date=null,
		@rToDate date=null 
		
	
 )
AS
SET NOCOUNT ON

BEGIN
 
 		--SET @rCandidateNumber = ISNULL( sCommon.fSearchStringGet(@rCandidateNumber),0)
		SET @rFirstname = ISNULL( sCommon.fSearchStringGet(@rFirstname),'')
		SET @rLastName = ISNULL( sCommon.fSearchStringGet(@rLastName),'')
		
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				--RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				--RSL.RecruitmentStatusId AS RecruitmentStatusId
				CM.RecruitmentStatusId,
				GM.Title AS Gender,
				ISNULL(MS.Title,'') AS MaritalStatus,
				ISNULL(RM.Title,'') AS Religion,
				ISNULL(CCM.Title,'') AS CastCategory,
				ISNULL(CM.FamilyCast,'') AS FamilyCast,
				ISNULL(CM.Qualification,'')AS Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				CM.LastDrawnSalary,
				CM.ExpectedSalary,
				ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
				ISNULL([PresentStreetOne],'') AS PresentStreetOne,
				ISNULL([PresentStreetTwo],'') AS PresentStreetTwo,
				ISNULL([PresentStreetThree],'') AS PresentStreetThree,
				ISNULL([PresentCountry],'') AS PresentCountry,
				ISNULL([PresentState],'') AS PresentState,
				ISNULL([PresentCity],'') AS PresentCity,
				ISNULL([PresentZipCode],'') AS PresentZipCode,
				ISNULL([PresentContactNo],'') AS PresentContactNo,
				ISNULL([PermanentStreetOne],'') AS PermanentStreetOne,
				ISNULL([PermanentStreetTwo],'') AS PermanentStreetTwo,
				ISNULL([PermanentStreetThree],'') AS PermanentStreetThree,
				ISNULL([PermanentCountry],'') AS PermanentCountry,
				ISNULL([PermanentState],'') AS PermanentState,
				ISNULL([PermanentCity],'') AS PermanentCity,
				ISNULL([PermanentZipCode],'') AS PermanentZipCode,
				ISNULL([PermanentContactNo],'') AS PermanentContactNo,
				CM.CreatedDateTime,
				CM.MainSubject,
				ISNULL(DM.Title,'') AS Reference,
				ISNULL(OM.Title,'') AS Organization
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			--LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId		
			--LEFT JOIN sRecruitment.tRecruitmentStatusLog  RSL  ON RSL.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			
			INNER JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id		
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id = CM.MaritalStatusId	
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId
			LEFT JOIN sRecruitment.tCandidateCommunications CC ON CC.CandidateId = CM.Id
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id = CM.ReferenceId AND DM.DataTypeId = 13 AND DM.IsObsolete = 0
			LEFT JOIN sRecruitment.tAssignOrganization AO ON AO.VacancyId = CM.VacancyId AND AO.OrgId = CM.OrgId
			LEFT JOIN sSetup.tOrganizationMaster OM ON AO.OrgId = OM.Id

		WHERE 
		--RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
		--		AND
				((CM.CandidateNumber=@rCandidateNumber ) OR (@rCandidateNumber = 0))
			AND ((CM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((CM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((VM.Id = @rVacancyId) OR (@rVacancyId = 0))	
			AND ((CM.RecruitmentStatusId = @rRecruitmentStatusId) OR (@rRecruitmentStatusId = 0))	
			AND CM.OrgGroupID = @rOrgGroupID
			AND ((CONVERT(date,CM.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,CM.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
			ORDER BY CM.CandidateNumber
END
GO
PRINT N'Altering [sRecruitment].[pCandidateMasterAdd]...';


GO
ALTER PROCEDURE [sRecruitment].[pCandidateMasterAdd]     
	@rOrgGroupID smallint, 
	@rVacancyId int, 
	@rId bigint, 
	@rCandidateNumber int, 
	@rFirstName nvarchar(100), 
	@rMiddleName nvarchar(100), 
	@rLastName nvarchar(100), 
	@rDateOfBirth date, 
	@rGenderId smallint, 
	@rReligionId int, 
	@rMaritalStatusId smallint, 
	@rQualification nvarchar(150),
	@rFamilyCast nvarchar(150), 
	@rCastCategoryId int, 
	@rRecruitmentStatusId smallint, 
	@rMobileNo nvarchar(20), 
	@rPersonalEmail nvarchar(100), 
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint, 	
	@rDataEntryModeId smallint, 
    @rDataEntryStatusId smallint,
	@rLastDrawnSalary decimal(12,2),
	@rExpectedSalary decimal(12,2),
	@rApplicationNumber int,
	@rApplicationPassword int,
	@rAdditionalRemark nvarchar(500),
	@rReferenceId smallint,
	@rMainSubject nvarchar(100),
	@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber BIGINT
	

    

	IF EXISTS(SELECT Id FROM sRecruitment.tCandidateMaster WHERE CandidateNumber=@rCandidateNumber AND OrgGroupID=@rOrgGroupID)
		BEGIN
		SELECT -101 as Result
		RETURN
	END 
	
    
	BEGIN TRY
 	BEGIN TRANSACTION
	
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sRecruitment.tCandidateMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				
		INSERT INTO sRecruitment.tCandidateMaster
			(
				OrgGroupID, 
				VacancyId, 
				Id, 
				CandidateNumber, 
				FirstName, 
				MiddleName, 
				LastName, 
				DateOfBirth, 
				GenderId, 
				ReligionId, 
				MaritalStatusId, 
				Qualification,
				FamilyCast, 
				CastCategoryId, 
				RecruitmentStatusId, 
				MobileNo, 
				PersonalEmail, 
				CreatedUserId, 
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,	
				DataEntryModeId, 
				DataEntryStatusId,
				ApplicationNumber,
				ApplicationPassword,
				LastDrawnSalary,
				ExpectedSalary,
				AdditionalRemark,
				ReferenceId,
				MainSubject,
				OrgId
			)
		VALUES
			(
				@rOrgGroupID , 
				@rVacancyId , 
				@lNextNumber , 
				@rCandidateNumber , 
				@rFirstName , 
				@rMiddleName , 
				@rLastName , 
				@rDateOfBirth , 
				@rGenderId , 
				@rReligionId , 
				@rMaritalStatusId , 
				@rQualification ,
				@rFamilyCast, 
				@rCastCategoryId , 
				@rRecruitmentStatusId , 
				@rMobileNo , 
				@rPersonalEmail , 
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rUpdatedUserId,
				sCommon.fGetDate(),	
				@rDataEntryModeId , 
				@rDataEntryStatusId,
				@rApplicationNumber,
				@rApplicationPassword,
				@rLastDrawnSalary,
				@rExpectedSalary,
				@rAdditionalRemark,
				@rReferenceId,
				@rMainSubject,
				@rOrgId
			)
			INSERT INTO sRecruitment.tRecruitmentStatusLog
			(
			OrgGroupId,
			CandidateId,
			RecruitmentStatusId,
			Remark,
			CreatedUserId,
			CreatedDateTime
			
			)
			VALUES
			(
			@rOrgGroupID , 
			@lNextNumber,
			@rRecruitmentStatusId,
			'',
			@rCreatedUserId,
			sCommon.fGetDate()
			)
			
		SELECT @lNextNumber AS RESULT
		 --@loEmpNumber AS EmpCode FROM sHrm.tEmployeeMaster WHERE  Id = @lNextNumber
		--SET @OutEmployeeId = @lNextNumber -- added for import employee
		
		--BEGIN 
  --      Execute sHrm.pEmployeeJobDetailAdd  
	 --      @rOrgId,@lNextNumber,@rEmployeeDesignationId,@rDepartmentId,@rDateOfJoining,@rCreatedUserId,
	 --      @rEmployeeTypeId,@rEmployeeGradeId,@rEmployeeGroupId,'',@rEmployeeManagerId
	          
	 --    Execute sHrm.pEmployeePersonalDetailAdd @rOrgId,@lNextNumber,'',@rDateOfBirth,@rGenderId,@rReligionId,
	 --    0,'',@rBloodGroupId,@rQualification,@rCreatedUserId,@rFamilyCast,@rCastCategoryId
	     
	      
	     
		--END	

		COMMIT TRANSACTION
	 
		END TRY
		
		BEGIN CATCH
		ROLLBACK TRANSACTION 
 
			--RAISERROR ('Error saving employee Master', -- Message text.
   --            16, -- Severity.
   --            1 -- State.
   --            );           
		 
 
		END CATCH			
 
	
	 
END
GO
PRINT N'Altering [sRecruitment].[pCandidateMasterGet]...';


GO
ALTER PROCEDURE [sRecruitment].[pCandidateMasterGet]
(
		@rOrgGroupID smallint, 
		@rCandidateNumber int=0,		
	@rId [bigint] = 0,
	@rVacancyId int=0
		
	
 )
AS
SET NOCOUNT ON

BEGIN

		
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				CM.LastDrawnSalary,
				CM.ExpectedSalary,
				ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
				CM.ReferenceId,
				ISNULL(CM.MainSubject,'')AS MainSubject,
				CM.OrgId
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
						
		WHERE 
				 CM.OrgGroupID = @rOrgGroupID
		   AND ((CM.Id = @rId) OR (@rId = 0))
		   AND ((CM.CandidateNumber =@rCandidateNumber ) OR (@rCandidateNumber = 0))
		   AND ((CM.VacancyId =@rVacancyId ) OR (@rVacancyId = 0))
END
GO
PRINT N'Altering [sRecruitment].[pCandidateMasterUpdate]...';


GO
 
ALTER PROCEDURE [sRecruitment].[pCandidateMasterUpdate] 
	
    
	@rVacancyId int, 
	@rId bigint, 
	@rCandidateNumber int, 
	@rFirstName nvarchar(100), 
	@rMiddleName nvarchar(100), 
	@rLastName nvarchar(100), 
	@rDateOfBirth date, 
	@rGenderId smallint, 
	@rReligionId int, 
	@rMaritalStatusId smallint, 
	@rQualification nvarchar(150),
	@rFamilyCast nvarchar(150), 
	@rCastCategoryId int, 
	@rRecruitmentStatusId smallint, 
	@rMobileNo nvarchar(20), 
	@rPersonalEmail nvarchar(100), 	
	@rUpdatedUserId bigint,
	@rLastDrawnSalary decimal(12,2),
	@rExpectedSalary decimal(12,2),
	@rAdditionalRemark nvarchar(500),
	@rReferenceId smallint = 0,
	@rMainSubject nvarchar(100) = '',
	@rOrgId int= 0 	


	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	
	DECLARE @lOrgGroupID int
	
	SELECT @lOrgGroupID = OrgGroupID FROM sRecruitment.tCandidateMaster WHERE Id=@rId

	IF EXISTS(SELECT Id FROM sRecruitment.tCandidateMaster WHERE CandidateNumber=@rCandidateNumber AND OrgGroupID=@lOrgGroupID AND Id<>@rId)
		BEGIN
		SELECT -101 as Result
		RETURN
	END 
			
	 UPDATE sRecruitment.tCandidateMaster
		SET
				VacancyId=@rVacancyId, 			
				CandidateNumber=@rCandidateNumber, 
				FirstName=@rFirstName, 
				MiddleName=@rMiddleName, 
				LastName=@rLastName, 
				DateOfBirth=@rDateOfBirth, 
				GenderId=@rGenderId, 
				ReligionId=@rReligionId, 
				MaritalStatusId=@rMaritalStatusId, 
				Qualification=@rQualification,
				FamilyCast=@rFamilyCast, 
				CastCategoryId=@rCastCategoryId, 
				RecruitmentStatusId=@rRecruitmentStatusId, 
				MobileNo=@rMobileNo, 
				PersonalEmail=@rPersonalEmail, 				
				UpdatedUserId=@rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate(),
				LastDrawnSalary=@rLastDrawnSalary,
				ExpectedSalary=@rExpectedSalary,
				AdditionalRemark =@rAdditionalRemark,
				ReferenceId = @rReferenceId ,
				MainSubject = @rMainSubject ,
				OrgId = @rOrgId
	  WHERE 
			Id = @rId
	  
	SELECT @rId AS RESULT
	
	--BEGIN 
	--UPDATE sHrm.tEmployeeJobDetail
	--	SET 
	--		EmployeeDesignationId = @rEmployeeDesignationId,	
	--		OrganizationDepartmentId = @rDepartmentId,
	--		DateOfJoining =	@rDateOfJoining,
	--		UpdatedUserId = @rUpdatedUserId,
	--		EmployeeTypeId = @rEmployeeTypeId,
	--		EmployeeGradeId = @rEmployeeGradeId,
	--		EmployeeGroupId = @rEmployeeGroupId
	--	WHERE 
	--		EmployeeId = @rId
	
	--UPDATE sHrm.tEmployeePersonalDetail
	--	SET 
	--		DateOfBirth	=	@rDateOfBirth,
	--		GenderId	=	@rGenderId,
	--		UpdatedUserId = @rUpdatedUserId
	--	WHERE 
	--		EmployeeId = @rId	
	
	--IF @rStatusId = 9
	--BEGIN
	--	UPDATE sSecurity.tUser
	--		SET 
	--			IsObsolete = 1,
	--			UpdatedUserId = @rUpdatedUserId,
	--			UpdatedDateTime = sCommon.fGetDate()
	--		WHERE 
	--			SourceId = @rId AND SourceTypeId = 95
	--END
	--ELSE IF @rStatusId = 7
	--BEGIN
	--	UPDATE sSecurity.tUser
	--		SET 
	--			IsObsolete = 0,
	--			UpdatedUserId = @rUpdatedUserId,
	--			UpdatedDateTime = sCommon.fGetDate()
	--		WHERE 
	--			SourceId = @rId AND SourceTypeId = 95
	--END
	  
	  --BEGIN
	  --   Execute sHrm.pEmployeeJobDetailModify 
	  --     0,@rId,0,@rEmployeeDesignationId,@rLocationId,@rDepartmentId,@rDateOfJoining,'','',0,0,@rUpdatedUserId,
	  --     0,0,@rEmployeeTypeId,@rProcessTypeId,NULL,NULL,NULL,0,0
	     --Execute sHrm.pEmployeePersonalDetailModify
	     --  0,@rId,'',@rDateOfBirth,@rGenderId,0,0,'','',0,0,'','','','','',0,'',0,'',0,0,@rUpdatedUserId,@rIsBirthDateUnknown
	     
	  --END
END
GO
PRINT N'Altering [sRecruitment].[pRptCandidateApplicationGet]...';


GO
 
ALTER PROCEDURE [sRecruitment].[pRptCandidateApplicationGet]
	 @rCandidateId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
	convert(nvarchar(20),@rCandidateId) AS CandidateIdText,
	CM.OrgGroupID,
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				iSNULL(CM.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(CM.DataEntryStatusId,0) as DataEntryStatusId,
			CM.ApplicationNumber,
			CM.ApplicationPassword,
			GM.Title AS Gender,
			RM.Title AS ReligionName,
			CCM.Title AS CastCategoryName,
			CC.PresentStreetOne,
			CC.PresentStreetTwo,
			CC.PresentStreetThree,
			CC.PresentCountry,
			CC.PresentState,
			CC.PresentCity,
			CC.PresentZipCode,
			CC.PresentContactNo,
			CC.PermanentStreetOne,
			CC.PermanentStreetTwo,
			CC.PermanentStreetThree,
			CC.PermanentCountry,
			CC.PermanentState,
			CC.PermanentCity,
			CC.PermanentZipCode,
			CC.PermanentContactNo,
			CI.CandidatePhoto,
			MS.Title AS MaritalStatus,
			CM.LastDrawnSalary,
			CM.ExpectedSalary,
			CM.CreatedDateTime,
			ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
			DM.Title AS Reference,
			ISNULL(CM.MainSubject,'') AS MainSubject
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			LEFT JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId 
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId 
			LEFT JOIN sRecruitment.tCandidateCommunications	 CC ON 	CC.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tCandidateImages	CI ON CI.CandidateId=CM.Id	
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id=CM.MaritalStatusId	 	
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id  = CM.ReferenceId
			AND DM.DataTypeId = 13
		
  WHERE 
  
      ((CM.Id = @rCandidateId) OR (@rCandidateId = 0))
       
 
END
GO
PRINT N'Altering [sSecurity].[pAppPermissionGet]...';


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

	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard 
			20097, -- View Query
			30249, -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786, --Online Learning 
			30787, --Online learning Student View
			30815, --Consolidate - Fee Status
			30813, --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,   -- Consolidate - Admission Inquiry Summary,
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646   -- Mark Entry From App 
			)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard
			20097, -- View Query
			30249,  -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786 , --Online Learning 
			30787,  --Online learning Student View
			30815,  --Consolidate - Fee Status
			30813,  --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,  -- Consolidate - Admission Inquiry Summary
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646   -- Mark Entry From App
			) 
		) TP 
		GROUP BY TP.TaskId
	END
END
GO
PRINT N'Altering [sSetup].[pHistoryTransfer]...';


GO
 
ALTER PROCEDURE [sSetup].[pHistoryTransfer]
	 @rType smallint = 0,
	 @rDate date = ''
	 	 	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN
BEGIN TRY
		BEGIN TRANSACTION 
	IF(@rType = 1) -- Copy To History Table
	BEGIN

	INSERT INTO [sAlert].[tAlertLogHistory] SELECT * FROM [sAlert].[tAlertLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tAlertLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAlert].[tNotificationLogHistory] SELECT * FROM [sAlert].[tNotificationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tNotificationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAlert].[tWhatsAppLogHistory] SELECT * FROM [sAlert].[tWhatsAppLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tWhatsAppLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAudit].[tActivityLogHistory] SELECT * FROM [sAudit].[tActivityLog] WHERE CAST(AuditDate AS DATE) < @rDate
	DELETE FROM [sAudit].[tActivityLog] WHERE CAST(AuditDate AS DATE) < @rDate

	INSERT INTO [sAudit].[tOperationLogHistory] SELECT * FROM [sAudit].[tOperationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAudit].[tOperationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sHrm].[tLeaveBalanceLogHistory] SELECT * FROM [sHrm].[tLeaveBalanceLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sHrm].[tLeaveBalanceLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sLibrary].[tBookLogHistory] SELECT * FROM [sLibrary].[tBookLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sLibrary].[tBookLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sRecruitment].[tRecruitmentStatusLogHistory] SELECT * FROM [sRecruitment].[tRecruitmentStatusLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sRecruitment].[tRecruitmentStatusLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sSecurity].[tUserLogHistory] SELECT * FROM [sSecurity].[tUserLog] WHERE CAST(LoggedInDateTime AS DATE) < @rDate
	DELETE FROM [sSecurity].[tUserLog] WHERE CAST(LoggedInDateTime AS DATE) < @rDate

	INSERT INTO [sSystem].[tBackupLogHistory] SELECT * FROM [sSystem].[tBackupLog] WHERE CAST(BackupDateTime AS DATE) < @rDate
	DELETE FROM [sSystem].[tBackupLog] WHERE CAST(BackupDateTime AS DATE) < @rDate

	INSERT INTO [sAcademic].[tClassworkViewHistory] SELECT * FROM [sAcademic].[tClassworkView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sAcademic].[tClassworkView] WHERE CAST(ViewByDateTime AS DATE) < @rDate

	INSERT INTO [sAcademic].[tOnlineLearningViewHistory] (OnlineLearningId,AcademicId,IsViewReference,IsViewAssignment,IsViewResource,ViewByUserId,LastViewByDateTime,AssignmentTeacherRemark) SELECT OnlineLearningId,AcademicId,IsViewReference,IsViewAssignment,IsViewResource,ViewByUserId,LastViewByDateTime,AssignmentTeacherRemark FROM [sAcademic].[tOnlineLearningView] WHERE CAST(LastViewByDateTime AS DATE) < @rDate
	DELETE FROM [sAcademic].[tOnlineLearningView] WHERE CAST(LastViewByDateTime AS DATE) < @rDate

	INSERT INTO  [sCommunication].[tAssignmentViewHistory] SELECT * FROM [sCommunication].[tAssignmentView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sCommunication].[tAssignmentView] WHERE CAST(ViewByDateTime AS DATE) < @rDate

	INSERT INTO  [sCommunication].[tCircularViewHistory] SELECT * FROM [sCommunication].[tCircularView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sCommunication].[tCircularView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	END
	ELSE IF(@rType = 2) -- Delete From Exception Table
	BEGIN 
		DELETE FROM [sSystem].[tExceptionLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	END
	COMMIT TRANSACTION			 
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION		
	END CATCH	
END
GO
PRINT N'Creating [sBiometric].[pEmployeeManualPunchToTimeSheetAdd]...';


GO
 
CREATE PROC [sBiometric].[pEmployeeManualPunchToTimeSheetAdd]

@rXmlDoc nvarchar(max) = ''

AS
SET NOCOUNT ON

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

BEGIN TRANSACTION					
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

CREATE TABLE #tTable(
Id bigint identity
,EmployeeId bigint not null
,Attn_Date date not null
,FirstIn varchar(50) null
,LastOut varchar(50) null
)

INSERT INTO #tTable
(			    
EmployeeId
,Attn_Date
,FirstIn
,LastOut
)
SELECT
	A.EmployeeId,
	A.Attn_Date,			
	A.FirstIn,
	A.LastOut
FROM OPENXML (@intDoc, '/Table/TimeSheetUpdate', 1)
	WITH
	(						
		EmployeeId bigint '@EmployeeId',
		Attn_Date datetime '@Attn_Date',
		FirstIn varchar(50) '@FirstIn',
		LastOut varchar(50) '@LastOut'
	) A

EXEC sp_xml_removedocument @intDoc
SELECT * FROM #tTable

DECLARE @lCount int = 1
DECLARE @lTotal int = (SELECT COUNT(Id) FROM #tTable)	
WHILE @lCount <= @lTotal 
BEGIN

DECLARE @rEmployeeId bigint = (SELECT EmployeeId FROM #tTable WHERE Id = @lCount)
DECLARE @rInTime varchar(50) = (SELECT FirstIn FROM #tTable WHERE Id = @lCount)
DECLARE @rOutTime varchar(50) = (SELECT LastOut FROM #tTable WHERE Id = @lCount)
DECLARE @rDate date = (SELECT Attn_Date FROM #tTable WHERE Id = @lCount)


DECLARE @lFlag bit = 0
DECLARE @SQL NVARCHAR(MAX) = ''		
DECLARE @lCode int = 0
DECLARE @lTotalTime varchar(10) = ''
IF(@rOutTime <> '') 
BEGIN SET @lTotalTime = CONVERT(varchar(5),DATEADD(minute,DATEDIFF(minute,@rInTime,@rOutTime),0), 114) 
END
ELSE BEGIN SET @lTotalTime = '00:00' END
DECLARE @lTotalMOnthDays int = (select  day(dateadd(month, datediff(month, 0, @rDate) + 1, -1)))
DECLARE @lTotalAttnDays varchar(10) = ''
DECLARE @lTotalAbsDays varchar(10) = ''
DECLARE @lColumn NVARCHAR(10) = (SELECT DAY(@rInTime))
SET @lColumn = (SELECT CASE WHEN @lColumn BETWEEN 0 AND 9 THEN RIGHT('0' + CAST(@lColumn AS VARCHAR(2)), 2) ELSE CAST(@lColumn AS NVARCHAR(10)) END)

	IF EXISTS(SELECT 1 FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95)
	BEGIN	
		SET @lCode = (SELECT EmpCode FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95)
		SET @lTotalAttnDays = (SELECT Tot_Attn FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95)
		SET @lTotalAbsDays = (SELECT Tot_Abs FROM sBiometric.tMonthTrans WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95)

		SET @SQL = 'IF EXISTS(SELECT 1 FROM sBiometric.tMonthTrans WHERE D'+CAST(@lColumn AS VARCHAR)+' = ''A'' AND EmployeeId = '+CAST(@rEmployeeId AS VARCHAR) + ' AND Attn_Dt = ''' + CAST(@rDate AS VARCHAR) + ''' AND SourceTypeId = 95) BEGIN SET @lFlag = 1 END' 				
		EXEC sp_executesql @SQL, N'@lFlag bit OUTPUT',@lFlag =  @lFlag OUTPUT

		IF(@lFlag = 1) 
		BEGIN
			SET @lTotalAttnDays = @lTotalAttnDays + 1
			SET @lTotalAbsDays = @lTotalAbsDays - 1
		END			
	END
	ELSE
	BEGIN	
		SET @lTotalAttnDays = 1
		SET @lTotalAbsDays = @lTotalMOnthDays - 1
		SET @lCode = (SELECT ISNULL(MAX(EmpCode),0) + 1 FROM sBiometric.tMonthTrans WHERE SourceTypeId = 95)
		INSERT INTO sBiometric.tMonthTrans VALUES(
		@lCode,@rDate,
		'A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A',
		'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
		'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
		'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
		'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
		'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
		'00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00','00:00',
		'XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX','XX',
		 0,0,0,0,'0',0,'00:00','00:00','00:00',0,0,0,0,0,0,0,0,0,0,0,0,@rEmployeeId,95)
	END		

		SET @SQL = 'UPDATE sBiometric.tMonthTrans
		SET D'+CAST(@lColumn AS VARCHAR)+'_IN = '''+CAST(CAST(@rInTime as time) AS VARCHAR(5))+''',
		D'+CAST(@lColumn AS VARCHAR)+'_OUT = '''+CAST(CAST(@rOutTime as time) AS VARCHAR(5))+''',		
		D'+CAST(@lColumn AS VARCHAR)+'_T = '''+CAST(@lTotalTime AS VARCHAR)+''',
		D'+CAST(@lColumn AS VARCHAR)+' = ''P'',Tot_Attn = '+CAST(@lTotalAttnDays AS VARCHAR)+',Tot_Abs = '+CAST(@lTotalAbsDays AS VARCHAR)+'
		WHERE EmployeeId = '+CAST(@rEmployeeId AS VARCHAR) + ' AND Attn_Dt = ''' + CAST(@rDate AS VARCHAR) + ''' AND SourceTypeId = 95'
		
		PRINT @SQL

		EXEC (@SQL)

		IF(@lTotalMOnthDays = 28) 
		BEGIN
			UPDATE sBiometric.tMonthTrans SET D29 = 'XX',D30 = 'XX',D31 = 'XX' WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95 
		END
		ELSE IF(@lTotalMOnthDays = 29) 
		BEGIN
			UPDATE sBiometric.tMonthTrans SET D30 = 'XX',D31 = 'XX' WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95
		END
		ELSE IF(@lTotalMOnthDays = 30) 
		BEGIN
			UPDATE sBiometric.tMonthTrans SET D31 = 'XX' WHERE EmployeeId = @rEmployeeId AND Attn_Dt = @rDate AND SourceTypeId = 95
		END
		
		SET @lCount = @lCount + 1
		END

		SELECT 1 AS RESULT
		DROP TABLE #tTable
		COMMIT TRANSACTION
END
GO
PRINT N'Creating [sFee].[pFeeReceiptChequePendingListGet]...';


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


GO
 
CREATE PROCEDURE [sFrontOffice].[pEmployeeGatePassListingGet]
      
   @rId int,
   @rOrgId int=0,
   @rFromGatePassDate datetime='',
   @rToGatePassDate datetime='',
   @rEntryModeStatusId smallint=0,
   @rCode nvarchar(20)='',
   @rOrgGroupId int=0,
   @rStatusId int=0,
   @rUserSourceId bigint = 0
       
AS
SET NOCOUNT ON
BEGIN
		SELECT  
			EG.Id,
			EM.Code,
			EM.FirstName+' '+EM.MiddleName+' '+EM.LastName AS Name,
			EG.EmployeeId,
			EG.ReasonOfGatePass,
			EG.GatePassDate,
			ISNULL(EG.ReturnGatePassDate,'') AS ReturnGatePassDate,
			Convert(varchar,EG.GatePassTime,108) as GatePassTime,
			ISNULL(Convert(varchar,EG.ReturnGatePassTime,108),'') AS ReturnGatePassTime,
			EG.EntryModeStatusId,
			SM.Title AS EntryModeStatus,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			ISNULL(U.DisplayTitle,'') AS UserName,
			Remark,
			ISNULL(EG.StatusId,0) as StatusId,
			SM1.Title as Status,
			ISNULL(EG.AssignEmployeeId,0) as AssignEmployeeId
		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
			LEFT JOIN sCommon.tStatusMaster SM1 ON SM1.Id = EG.StatusId
		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,'')=''))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND ((ISNULL(EG.StatusId,0) = @rStatusId) OR (ISNULL(@rStatusId,-1) = -1 AND ISNULL(EG.StatusId,0) != 0))
			AND ((EG.AssignEmployeeId = @rUserSourceId) OR (ISNULL(@rUserSourceId,0) = 0))
		ORDER BY EG.GatePassDate,EG.GatePassTime DESC
END
GO
PRINT N'Creating [sHrm].[pLeavePeriodAdd]...';


GO
 
CREATE PROCEDURE [sHrm].[pLeavePeriodAdd]
	 
	@rOrgId int,
	@rLeavePeriodId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION		 
	 INSERT INTO sHrm.tLeavePeriod
		(
			OrgId,
			LeavePeriodId 
		)
		VALUES
		(
			@rOrgId,
			@rLeavePeriodId
		)		
	 	            
		SELECT @rOrgId AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sRecruitment].[pRptRecruitmentOfferLetterGet]...';


GO
 
CREATE PROCEDURE [sRecruitment].[pRptRecruitmentOfferLetterGet]
	 @rCandidateId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 	
				CM.Id AS CandidateId,				
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,				
				VM.Title AS VacancyName,		
				CM.GenderId,		
			ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark
					
		FROM 
		
			sRecruitment.tCandidateMaster CM			
			INNER JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId								
  WHERE 
  
      ((CM.Id = @rCandidateId) OR (@rCandidateId = 0))
       
 
END
GO
PRINT N'Creating [sRecruitment].[pVacancyWiseAssignOrganization]...';


GO
 
CREATE PROCEDURE [sRecruitment].[pVacancyWiseAssignOrganization]
	 
	 @rVacancyId bigint,
     @rXmlDoc nvarchar(MAX)
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	--UPDATE sRecruitment.tAssignOrganization
	--SET
	--	OrgId = A.OrgId,
	--	VacancyId = A.VacancyId
		
		
	--FROM
	--(
	--SELECT
	--	VacancyId,
	--	OrgId
		
	--	FROM OPENXML (@intDoc, '/Table/tAssignOrganization', 1)
	--	WITH
	--	(
	--		OrgId int '@OrgId',
	--		VacancyId Bigint '@VacancyId'
			
		
	--	))A INNER JOIN sRecruitment.tAssignOrganization A1 ON A1.VacancyId = A.VacancyId AND A1.OrgId = A.OrgId
	
	
	Delete From sRecruitment.tAssignOrganization Where VacancyId = @rVacancyId
	
	INSERT INTO sRecruitment.tAssignOrganization
	(
		OrgId,
		VacancyId
	
	)
	SELECT
		A.OrgId,
		A.VacancyId
		
	FROM OPENXML (@intDoc, '/Table/tAssignOrganization', 1)
	WITH
	(
		OrgId int '@OrgId',
		VacancyId Bigint '@VacancyId'
	) A LEFT JOIN sRecruitment.tAssignOrganization A1
	ON A1.VacancyId = A.VacancyId AND A1.OrgId = A.OrgId
	WHERE A1.VacancyId IS NULL  AND A1.OrgId IS NULL

	
	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT -1
	END CATCH
END
GO
 

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

GO 
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('21.10.01',211001,'BEGIN','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO 
 
GO
PRINT N'Altering [sBiometric].[tEmployeeCheckIn]...';


GO
ALTER TABLE [sBiometric].[tEmployeeCheckIn]
    ADD [LatitudeAxis]  NVARCHAR (20)  NULL,
        [LongitudeAxis] NVARCHAR (20)  NULL,
        [Location]      NVARCHAR (200) NULL;


GO
PRINT N'Altering [sCommon].[tUploadDocument]...';


GO
ALTER TABLE [sCommon].[tUploadDocument]
    ADD [OrgGroupBatchId] INT NULL;


GO
PRINT N'Altering [sWorkflow].[tWorkflowFunctionalityMaster]...';


GO
ALTER TABLE [sWorkflow].[tWorkflowFunctionalityMaster]
    ADD [Type] NVARCHAR (50) NULL;


GO

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


GO
 
 

ALTER PROCEDURE [sAdmission].[pAdmissionFormGet]

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

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


GO
 

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

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


	 
	

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

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

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

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


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

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

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

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


 

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

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

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

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

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

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

IF(@cols IS NOT NULL)
BEGIN 
	SET @query = N'SELECT DISTINCT AdmissionFormId,' + @cols + N' INTO ##tempAdmissionCriteriaForm FROM 
				 (
					SELECT DISTINCT  AFF.AdmissionFormId,AdmissionFormFieldResponse, FieldRemark
					FROM 
					sAdmission.tAdmissionCriteriaForm ACF
					INNER JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
					WHERE ACF.BatchId = '+CONVERT(nvarchar(10),@rBatchId)+'
				) x
				PIVOT
				(
					MAX(AdmissionFormFieldResponse)
					FOR FieldRemark IN (' + @cols + N')
				) p '
			
	exec sp_executesql @query

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

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


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

AS
 SET NOCOUNT ON

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 Convert(nvarchar(20),@rRelationShipId) AS RelationShipIdText,
	 AF.Id AdmissionFromId,
	 AF.FormNo,
	 [sStudent].[fStudentNameGet](AF.FirstName , ISNULL(AF.MiddleName,'') , AF.LastName,OM.StudentNameFormatId ) AS Name,
	 AF.FirstName,
	 AF.ForClassId,
	 AF.DateOfBirth AS DateOfBirth,
	 AF.BatchId,
	 CM.Title AS ClassName,
	 AF.OrgId,
	 AF.StreetOne,
	 AF.StreetTwo,
	 AF.StreetThree,
	 AF.Country,
	 AF.City,
	 AF.State,
	 AF.ZipCode,
	 AF.ContactEmail,
	 AF.ContactNo,
	 AF.PreviousSchool,
	 ISNULL(AF.StudentPhoto,0x) As StudentPhoto,
	 ISNULL(AF.ReligionId,0) AS ReligionId,
	 IsNULL(RM.Title,'') AS ReligionName,
	 AF.MeritGrade,
	 AF.MeritMarks,
	 AF.GenderId,
	 GM.Title AS Gender,
	 AF.FamilyCast,
	 AF.FamilySubCast,
	 ISNULL(AF.CastCategoryId,0) AS CastCategoryId,
	 ISNULL(CCM.Title,'') AS CastCategory ,
	 OM.DisplayTitle ,
	 BM.Title As Batch,
	 ISNULL(AFM.FatherName,'') AS FatherName ,
	 ISNULL(AFM.FatherDateOfBirth,'')As FatherDateOfBirth,
	 AFM.FatherOccupation,
	 AFM.FatherOfficeAddress,
	 AFM.FatherIncome,
	 AFM.FatherQualification,
	 AFM.FatherContactNo,
	 AFM.FatherMail,
	 AFM.FatherOrganization,
	 ISNULL(AFM.MotherName,'') AS MotherName,
	 IsNull(AFM.MotherDateOfBirth,'')As MotherDateOfBirth,
	 AFM.MotherIncome,
	 AFM.MotherOccupation,
	 AFM.MotherOfficeAddress,
	 AFM.MotherQualification,
	 AFM.MotherContactNo,
	 AFM.MotherMail,
	 AFM.MotherOrganization,
	 isnull(AFM.RelativeName,'') AS RelativeName ,
	 ISNULL(AFM.RelativeDateOfBirth,'') AS RelativeDateOfBirth,
	 AFM.RelativeOccupation,
	 AFM.RelativeContactNo,
	 AFM.RelativeMail,
	 AFM.RelativeOfficeAddress,
	 AFM.RelativeIncome,
	 AFM.RelativeQualification,
	 AFM.RelationshipName ,
	 ISNULL(AC.IsFixParentAcademic,0) AS IsParentAcademicRequired ,
	 ISNULL (AC.IsStudentAcademicRequired,0) AS IsStudentAcademicRequired ,
	 ISNULL(AC.IsSiblingDetailRequired,0) AS IsSiblingDetailRequired,
	 ISNULL(AC.IsReferenceDetailRequired,0) AS IsReferenceDetailRequired ,
	 ISNULL(AC.IsFamilyDetailRequired,0) AS IsFamilyDetailRequired ,
	 ISNULL(AC.IsFixStudentAcademic,0) AS IsFixStudentAcademic,
	  AC.ConfirmationRemark AS ConfirmationRemark,
	  ISNULL(AC.IsHostelDetailRequired,0) AS IsHostelDetailRequired ,
	 ISNULL (AC.IsTransportDetailRequired,0) AS IsTransportDetailRequired ,
	 ISNULL(AC.IsHealthDetailRequired,0) AS IsHealthDetailRequired,
	 ISNULL(AC.IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired ,
	 ISNULL(AC.IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired ,
	 ISNULL(AC.IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
	
	 AF.IsPysicalDeformity,
	 ISNULL(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
	 AF.IsMajorIllness,
	 ISNULL(AF.MajorIllnessRemark, '') As MajorIllnessRemark,
	 AF.IsAllergy,
	 ISNULL(AF.AllergyRemark,'') As AllergyRemark,
	 ISNULL(AF.BirthPlace,'') As BirthPlace,
	 ISNULL(AF.BirthTaluka,'') As BirthTaluka,
	 ISNULL(AF.BirthDistrict,'') As BirthDistrict,
	 Isnull(BGM.Title,'') As BloodGroupName,
	 AF.AdhaarNumber,
	 AF.IsHostelRequired,
	 AF.IsTransportRequired,
	 ISNULL(AFM.FatherPhoto,0x)As FatherPhoto,
	  ISNULL(AFM.MotherPhoto,0x) As MotherPhoto,
	 ISNULL(AFM.RelativePhoto,0x) As RelativePhoto,
	  AF.BirthState,
	 AF.BirthCountry,
	 AC.CustomField1Remark,
	 AC.CustomField2Remark,
	 AC.CustomField3Remark,
	 ISNULL(AF.CustomField1Answer,'')As CustomField1Answer,
	 ISNULL(AF.CustomField2Answer,'')As CustomField2Answer,
	 ISNULL(AF.CustomField3Answer,'')As CustomField3Answer,
	 ISNULL(AF.Nationality,'') AS Nationality,
	 ISNULL(AF.MotherTongue,'') AS MotherTongue,
	 ISNULL(AF.OtherInformation,'') AS OtherInformation,
	 ISNULL(LWM.Title,'') AS LiveWith,
	 ISNULL(AC.AgeCutOffDate,'') AS AgeCutOffDate,
	 ISNULL(AC.Remark1,'') AS ExtraRemark1,
	 ISNULL(AC.Remark2,'') AS ExtraRemark2,
	 ISNULL(AC.Remark3,'') AS ExtraRemark3,
	 AF.DateOfBirthInWord AS DOBInWords,
	 AF.CreatedDateTime As FormDate,
	  ISNULL(AC.IsFatherDetail,0) AS IsFatherDetail,
	 ISNULL(AC.IsFatherFullDetail,0) AS IsFatherFullDetail,
	 ISNULL (AC.IsFatherAcademic,0) As IsFatherAcademic,
	 ISNULL (AC.IsMotherDetail,0) As IsMotherDetail,
	 ISNULL (AC.IsMotherFullDetail,0)As IsMotherFullDetail,
	 ISNULL (AC.IsMotherAcademic,0)As IsMotherAcademic,
	 ISNULL (AC.IsGuardianDetail,0)As IsGuardianDetail,
	 ISNULL (AC.IsGuardianFullDetail,0)As IsGuardianFullDetail,
	 ISNULL (AC.IsGuardianAcademic,0)As IsGuardianAcademic,
	 ISNULL (AC.IsOtherInformationRequired,0)As IsOtherInformationRequired,
	 ISNULL (AC.IsHealthDetailRequired,0) As IsHealthDetailRequired,
	 ISNULL (AC.IsCustomField1Required,0) As IsCustomField1Required,
	 ISNULL (AC.IsCustomField2Required,0) As IsCustomField2Required,
	 ISNULL (AC.IsCustomField3Required,0) As IsCustomField3Required,
	 ISNULL (AFM.FatherAdhaarNumber,'') AS FatherAadhaarNumber,
	 ISNULL (AFM.MotherAadhaarNumber,'') AS MotherAadhaarNumber,
	 ISNULL (AFM.RelativeAadhaarNumber,'') AS RelativeAadhaarNumber,
	  (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=324
	 )AS IsOtherDetailsLiveWith,
	  (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=323
	 )AS IsOtherDetailsOtherInformation,
	 ISNULL(AF.MiddleName,'') AS MiddleName,
	 ISNULL(AF.LastName,'')AS LastName,
	 ISNULL(PT.Id,0) AS PaymentTransactionId,
	 ISNULL(PT.PayAmount,0.00) AS PayAmount,
	 ISNULL(PT.TransactionStatusId,0) AS TransactionStatusId,
	 ISNULL(PT.PayDateTime,'') AS PayDateTime

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

				
END
GO
PRINT N'Altering [sAssessment].[pCopyExamAdd]...';


GO
ALTER PROCEDURE [sAssessment].[pCopyExamAdd]
	 
	      @rFromBatchId int,
	      @rClassId int,
	      @rOrgId int,
	      @rToBatchId int
		  	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 BEGIN TRANSACTION	
	 
	 
	DECLARE @lNextNumber BIGINT,@lExamdetailNextNumber BIGINT,@lExamCombineNextNumber bigint,@lCombineNextNumber bigint
	Declare @lCount int,@lExamDetailCount int,@lExamCombineCount int,@lCombineCount int ,
	@lClass nvarchar(50)
	 
	
		
	if exists (Select 1  from sAssessment.tExamMaster  WHere BatchId = @rToBatchId And ((ClassID=@rClassId) OR (@rClassId=0)))
	BEGIN
		Select @lClass=CM.Title from sAssessment.tExamMaster EM INNER JOIN sSetup.tClassMaster CM ON CM.Id= EM.ClassID Where EM.BatchId = @rToBatchId AND ((EM.ClassID=@rClassId) OR (@rClassId=0))
		Select 1 as REsult,@lClass As Class
		COMMIT TRANSACTION		
	
		Return
		
	END


	Select @lCount = Count(Id) from sAssessment.tExamMaster where BatchId = @rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0))
	  EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	
	Insert into sAssessment.tExamMaster
	( 
		Id,BatchId,ExamSubGroupId,ClassId,IsRankNo,IsGrade,IsPercentile,IsPercentage,IsSubjectPercentile,
		GradeSetId,RankSetId,LevelSetId,UpdatedUserId,UpdatedDateTime,IsProcessResult,IsMarksInDecimal,
		IsNegativeMarks,IsIncludeCoScholastic,IsOnPrePrinted,ReportId,DisplayTitle,Remark1,Remark2,
		Remark3,IsDisplayPhoto,FooterAdjustment,IsDisplayBirthDate,IsLockForEdit,
		IsDisplaySchoolName,DetailAdjustment,IsDisplayHeightWeight,IsDisplayAttendance,TermScopeId,
		IsResultStatus,ExamMaximum,IsDisplayGradeString,IsIncludeGradeSubject,GradeSubjectGradeSetId,
		IsIncludeSubExam,IsCoScholasticGrade,IsCoScholasticGradeIndicator,
		IsCoScholasticGradeDesIndicator,IsCoScholasticCombine,OldExamId,IsPublished,IsDisplayHighestDivisionMark,
		IsDisplayHighestDivisionGrade,IsDisplayParentName,CoScholasticScopeId,SubjectGroupPerPage,
		IsDisplayTeacherSign,IsDisplayPrincipalSign,PercentileScopeId,CoScholasticGradeSetId,IsExcludeAbsentTotal,
		CoScholasticTitle,IsDisplayMonthlyAttendance,IsDisplayImageHeader,DecimalFormat,IsDisplayTotalMark,
		IsDisplayResultIndicator,IsRemovePercentageForFail,Remark1Caption,Remark2Caption,Remark3Caption,
		TeacherSignCaption,PrincipalSignCaption,ParentSignCaption,IsSubjectWeightage,OldImportExamId,IsDisplayActivityGrade,IsAllExamPassRequired,HeaderAdjustment,IsPublishExamSchedule,LinkExamId,OverallPercentageForGrace,MinimumGracePercetage,GraceMaxMark,KrupaMaxMark,IsApplySiddhiKrupa,IsDisplayGraph,IsGenerateRankNo
	)
	 Select  
		@lNextNumber + ROW_NUMBER() OVER(ORDER BY Id) ,@rToBatchId,ExamSubGroupId,@rClassId,IsRankNo,IsGrade,IsPercentile,IsPercentage,
		IsSubjectPercentile,GradeSetId,RankSetId,LevelSetId,UpdatedUserId,sCommon.fGetDate(),IsProcessResult,
		IsMarksInDecimal,IsNegativeMarks,IsIncludeCoScholastic,IsOnPrePrinted,ReportId,DisplayTitle,Remark1,
		Remark2,Remark3,IsDisplayPhoto,FooterAdjustment,IsDisplayBirthDate,IsLockForEdit,
		IsDisplaySchoolName,DetailAdjustment,IsDisplayHeightWeight,IsDisplayAttendance,TermScopeId,
		IsResultStatus,ExamMaximum,IsDisplayGradeString,IsIncludeGradeSubject,GradeSubjectGradeSetId,
		IsIncludeSubExam,IsCoScholasticGrade,IsCoScholasticGradeIndicator,
		IsCoScholasticGradeDesIndicator,IsCoScholasticCombine,OldExamId,IsPublished,IsDisplayHighestDivisionMark,
		IsDisplayHighestDivisionGrade,IsDisplayParentName,CoScholasticScopeId,SubjectGroupPerPage,IsDisplayTeacherSign,
		IsDisplayPrincipalSign,PercentileScopeId,CoScholasticGradeSetId,IsExcludeAbsentTotal,CoScholasticTitle,
		IsDisplayMonthlyAttendance,IsDisplayImageHeader,DecimalFormat,IsDisplayTotalMark,IsDisplayResultIndicator,
		IsRemovePercentageForFail,Remark1Caption,Remark2Caption,Remark3Caption,TeacherSignCaption,
		PrincipalSignCaption,ParentSignCaption,IsSubjectWeightage,Id,IsDisplayActivityGrade,IsAllExamPassRequired,HeaderAdjustment,IsPublishExamSchedule,LinkExamId,OverallPercentageForGrace,MinimumGracePercetage,GraceMaxMark,KrupaMaxMark,IsApplySiddhiKrupa,IsDisplayGraph,IsGenerateRankNo
	from sAssessment.tExamMaster Where BatchId = @rFromBatchId AND ((ClassId = @rClassId) OR (@rClassId=0))
	
	 SET @lNextNumber  = @lCount + @lNextNumber 
	  EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tExamMaster', @rCurrentNumber = @lNextNumber 

	
	
	
	select @lExamDetailCount =count (Ed.id) from sAssessment.tExamDetail Ed INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId Where ((Em.ClassId=@rClassId) OR (@rClassID=0)) and Em.batchId=@rFromBatchId
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamDetail', 0, 1, 1,@outNextNumber = @lExamdetailNextNumber output

	
	--Delete EC from sAssessment.tExamDetail EC INNER JOIN sAssessment.tExamMaster EM ON EM.Id=EC.ExamID where ((Em.ClassId = @rClassId) OR (@rClassID=0)) AND EM.BatchId=@rToBatchID
	
	Insert into sAssessment.tExamDetail
	( 
		Id,ExamId,ClassSubjectId,Maximum,Minimum,IsIncludeInTotal,IsDisplayInMarksheet,IsShowSubjectGrade,DisplayOrder,GradeSetId,ExamDate,ExamTime,ExamTopic,UpdatedUserId,UpdatedDateTime,NoOfQuestion,IsShowSubjectMark
	)  
	Select
		@lExamdetailNextNumber+ ROW_NUMBER() OVER(ORDER BY ClassSubjectId),
		ExamId = (SELECT Id FROM sAssessment.tExamMaster E1 WHERE E1.OldImportExamId = Ed.ExamId and E1.ClassId=@rClassId)
		,ClassSubjectId,Maximum,Minimum,IsIncludeInTotal,IsDisplayInMarksheet,IsShowSubjectGrade,DisplayOrder,ED.GradeSetId,ExamDate,ExamTime,ExamTopic,ED.UpdatedUserId,sCommon.fGetDate(),NoOfQuestion,IsShowSubjectMark
	from sAssessment.tExamDetail Ed INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
	Where ((Em.ClassId=@rClassId) OR (@rClassID=0)) and Em.batchId=@rFromBatchId
	
	SET @lExamdetailNextNumber  = @lExamDetailCount + @lExamdetailNextNumber 
	EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tExamDetail', @rCurrentNumber = @lExamdetailNextNumber 
	
	Select  @lExamCombineCount = count(EC.id) from sAssessment.tExamCombine Ec INNER JOIN sAssessment.tExamMaster EM ON EM.Id= EC.ExamId
	WHere ((Em.ClassId =@rClassId) OR (@rClassID=0)) ANd BatchId =@rFromBatchId
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAssessment.tExamCombine', 0, 1, 1,@outNextNumber = @lExamCombineNextNumber output
	
	--Delete EC from sAssessment.tExamCombine EC INNER JOIN sAssessment.tExamMaster EM ON EM.Id= EC.ExamId Where Em.batchId=@rToBatchId AND ((Em.ClassId=@rClassID) OR (@rClassID=0))  
	
	Insert into sAssessment.tExamCombine
	(
		Id,ExamId,SubExamId,weightage,ExamOrder,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
	)
	Select
		@lExamCombineNextNumber+ROW_NUMBER() OVER(ORDER BY ExamId),ExamId = (Select Id from sAssessment.tExamMaster E1 where E1.OldImportExamId = Ec.ExamId  and E1.ClassId=@rClassId),
		SubExamId = (Select Id from sAssessment.tExamMaster E1 where E1.OldImportExamId = Ec.SubExamId and E1.ClassId=@rClassId),weightage,ExamOrder,EC.CreatedUserId,SCommon.fGetdate(),EC.UpdatedUserId,sCommon.fGetDate()
	From sAssessment.tExamCombine EC INNER JOIN sAssessment.tExamMaster EM on EM.Id =EC.ExamId where EM.BatchId=@rFromBatchId and ((EM.ClassId=@rClassId) OR (@rClassID=0))
	
	SET @lExamCombineNextNumber  = @lExamCombineCount + @lExamCombineNextNumber 
	EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAssessment.tExamCombine', @rCurrentNumber = @lExamCombineNextNumber 

	
	--DElete EC From sAssessment.tExamCombineSubject EC INNER JOIN sAssessment.tExamMaster  EM ON EM.Id=EC.ExamId WHere ((Em.ClassID =@rClassId) OR (@rClassId=0)) AND EM.BatchId=@rToBatchId
	Insert into sAssessment.tExamCombineSubject
	(
		ExamId,SubExamId,ClassSubjectId,SubjectWeightage
	)
	Select 
		ExamId = (Select Id from sAssessment.tExamMaster E1  Where E1.OldImportExamId = Ec.ExamId),
		
		SubExamId =(select Id from sAssessment.tExamMaster E1 Where  E1.OldImportExamId= ec.SubExamId),
		ClassSubjectId,SubjectWeightage
	from sAssessment.tExamCombineSubject EC INNER JOIN sAssessment.tExamMaster EM ON EM.Id= EC.ExamId where ((EM.ClassId =@rClassId) OR (@rClassId=0)) and Em.BatchID=@rFromBatchId
	
	select 11 as result
COMMIT TRANSACTION		
	 
END
GO
PRINT N'Altering [sAssessment].[pRptCSExamMarkEntryGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptCSExamMarkEntryGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rBatchId int,
	  --@rCCECSId int,
	  @rFilter int,
	  @rBuilder nvarchar(max)='',
	  @rCCECAGroupId int=0,
	  @rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
SELECT
    @rBuilder AS Builder,
    SA.AcademicId,
    SA.Code,
    SA.Name,
    AM.Title,
    SA.RollNo AS RollNo ,
    CASE WHEN @rFilter=1 THEN ISNULL(AIS.ObtianMark,0) 
    ELSE  ISNULL(AIS.ConvertedMark,0) END AS TotalMark
   
    
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	 INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id 
	 AND CL.ClassID=@rClassId
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id 
	AND AIS.ExamId= @rExamId 
	AND (AIS.CCECSId =@rCCECSId OR @rCCECSId = 0) 
	WHERE 
	SA.ClassId=@rClassId
	And SA.DivisionId = @rDivisionID	
	And SA.BatchId = @rBatchId
	And (AM.CCECAGroupId= @rCCECAGroupId  OR @rCCECAGroupId  = 0 )
	Order by AM.OrderIndex
	END
GO
PRINT N'Altering [sAssessment].[pRptCSExamScoreGet]...';


GO
 
 

ALTER PROCEDURE [sAssessment].[pRptCSExamScoreGet]
	  
	   @rOrgId int
	  ,@rExamId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rBatchId int,
	  @rCCECAGroupId int=0,
	  @rCCEMasterId int=0,
	  @rAcademicId bigint=0,
	  @rBuilder1 nvarchar(max)=''
	  
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
			SELECT 		
				--ISNULL(CGM.Title,'') AS CSGroup,
				--ISNULL(CM.Title,'') AS CS,				
				--ISNULL(CC.Grade,'')  AS Grade,
				--ISNULL(CC.GradeIndicator,'') AS Indicator,
				--ISNULL(CC.DescriptiveIndicator,'')  AS DescriptiveIndicator,			
				--ISNULL(SA.AcademicId,0) AS AcademicId,
				--ISNULL(CC.IndicatorIds,'') AS IndicatorIds,
				--CGM.GradeSetId,
				--CM.Id as CMID
				
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.Grade,'') AS Term1Indicator,
				 CCEM.Title AS GroupTitle,
				 AM.Title AS MasterTitle,
				ISNULL(AIS.ConvertedMark,0) AS ConvertedMark,
				ISNULL(AIS.GradeIndicator,'') AS Indicator,
				ISNULL(AIS.DescriptiveIndicator,'')  AS DescriptiveIndicator	,
				CM.Id AS ClassId,
				CM.Title AS ClassTitle,
				DM.Id AS DivisionId,
				DM.Title AS DivisionTitle,
				SA.Code AS Code,
				(SELECT DisplayTitle FROM sAssessment.tExamMaster WHERE Id = @rExamId) AS ExamTitle	
				 
			FROM sStudent.vStudentAcademic SA
				INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1
				INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
				INNER JOIN sAssessment.tCCECSGroupMaster CCEM ON CCEM.Id=AM.CCECAGroupId
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId AND SA.OrgId = CM.OrgId
				INNER JOIN sSetup.tDivisionmaster DM ON DM.Id = SA.DivisionId AND SA.OrgId = DM.OrgId
				LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND CCECSId= AM.Id And AIS.ExamId=@rExamId
			WHERE
				 SA.ClassId=@rClassId 
				And SA.DivisionId =@rDivisionID	
				And SA.BatchId =@rBatchId
				AND AIS.ExamId=@rExamId
				and ((AM.CCECAGroupId=@rCCECAGroupId) OR (@rCCECAGroupId=0))
				AND((AM.Id=@rCCEMasterId) OR (@rCCEMasterId=0))	
				and AM.OrgId=@rOrgId
				and ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
						
			--FROM   
			--	sAssessment.tCCECSMaster CM 
			--	INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id=CM.CCECAGroupId AND CM.OrgId=@rOrgId
			--	INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CGM.Id				
			--	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CL.ClassId 
			--	LEFT JOIN   sAssessment.tCCECSExamScore CC  ON CC.CCECSID=CM.ID  
			--	AND CC.AcademicId = SA.AcademicId AND ExamId=@rExamId	AND CC.AcademicId = @rAcademicId	
			--	WHERE ((SA.AcademicId = @rAcademicId) OR (@rAcademicId=0))
			--		and SA.ClassId=@rClassId and SA.DivisionId=@rDivisionId
		
			 ORDER BY SA.RollNo
			
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END
GO
PRINT N'Altering [sAssessment].[pRptGraphicalStudentGradeAnalysisSubjectWise]...';


GO


ALTER PROCEDURE [sAssessment].[pRptGraphicalStudentGradeAnalysisSubjectWise]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rGroupByid int=0,
	 @rOrgId  int=0,
	 @rSubject nvarchar(MAX)=''
	
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
CREATE TABLE #TempCradeCount
(Id Int Identity (1,1),
 HEADID int,
 Subjectid int, 
 TotalCount int
)
INSERT INTO  #TempCradeCount
SELECT 
CASE WHEN @rGroupByid=1 THEN DM.Id 
				WHEN @rGroupByid=2 THEN CM.Id 
				WHEN @rGroupByid =3 THEN Dept.Id 
				WHEn @rGroupByid =4 THEN OM.Id
				ELSE 0 END AS HeadId,
				SM.Id AS  Subjectid,
					COUNT(R.Id) AS total_count
					FROm sAssessment.tResultDetail  RD
		  INNER JOIN sAssessment.tResult R ON R.Id=Rd.ResultId
		 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		 INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		--LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		--GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
		where 
		  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		GROUP BY CASE WHEN @rGroupByid=1 THEN DM.Id 
				WHEN @rGroupByid=2 THEN CM.Id 
				WHEN @rGroupByid =3 THEN Dept.Id 
				WHEn @rGroupByid =4 THEN OM.Id
				ELSE 0 END,
				SM.Id
				
				
SELECT ISNULL(A.GradeCount,0) AS GradeCount, A.Builder1,A.SubjectGrade,A.SubjectName,A.HeadId,A.HeadName,T.Subjectid,ISNULL(T.TotalCount,0) AS TotalCount,A.OrderIndex FROM(
				
SElect
		COUNT(RD.Id) AS GradeCount,
		@rBuilder1 AS Builder1,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		SM.Id AS SubjectId,
		SM.OrderIndex AS SubjectOrderIndex,
		GD.GradeSetId AS GradeSetId,
		CASE WHEN @rGroupByid=1 THEN DM.Id 
				WHEN @rGroupByid=2 THEN CM.Id 
				WHEN @rGroupByid =3 THEN Dept.Id 
				WHEn @rGroupByid =4 THEN OM.Id
				ELSE 0
				 END AS HeadId,CS.IsOptional ,
				
			case when @rGroupByid=1 THEN ' Division : ' +CM.Title+ ' / '+Dm.DisplayTitle  
		when @rGroupByid=2 THEN ' Class : ' + CM.Title  
		when @rGroupByid=3 THEN 'Department: ' + Dept.Title 
		WHen @rGroupByid=4 THEN  'Organization : '+OM.Title
		
		END  AS HeadName,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
				WHEN @rGroupByid=2  THEN CM.OrderIndex
				WHEN @rGroupByid=3  THEN Dept.Id
				WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex
		from sAssessment.tResultDetail  RD
		  INNER JOIN sAssessment.tResult R ON R.Id=Rd.ResultId
		 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		 INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
	
	where 
		  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		
		Group by RD.SubjectGrade,SM.Title
		 ,GD.GradeSetId,
		 	CASE WHEN @rGroupByid=1 THEN DM.Id 
				WHEN @rGroupByid=2 THEN CM.Id 
				WHEN @rGroupByid =3 THEN Dept.Id 
				WHEn @rGroupByid =4 THEN OM.Id ELSE 0 END ,	SM.Id,
		case when @rGroupByid=1 THEN ' Division : ' +CM.Title+ ' / '+Dm.DisplayTitle 
		when @rGroupByid=2 THEN ' Class : ' + CM.Title    
		when @rGroupByid=3 THEN 'Department: ' + Dept.Title 
		WHen @rGroupByid=4 THEN  'Organization : '+OM.Title END,
		SM.OrderIndex,CS.IsOptional ,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
				WHEN @rGroupByid=2  THEN CM.OrderIndex
				WHEN @rGroupByid=3  THEN Dept.Id
				WHen @rGroupByid=4 THen OM.OrderIndex  END 
		) A 
		INNER JOIN #TempCradeCount T ON T.HEADID=A.HeadId 
		AND T.Subjectid=A.Subjectid
		AND (ISNULL(T.Subjectid,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
		
			
	
END
GO
PRINT N'Altering [sAssessment].[pRptSubjectActivityExamDetailWithTermGradeGet]...';


GO
 


ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailWithTermGradeGet]
	 
		@rOrgId int=0,
		@rExamId int=0,
		@rClass int=0,
		@rDivisionId int=0,
		@rBatchId int=0,
		@rBuilder1 nvarchar(max)='',
		@rAcademicId bigint=0,
		@rCode nvarchar(20)='',
		@rFromRollNo int=0,
		@rToRollNo int=0,
		@rMultiCode nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 
Declare @GradeString nvarchar(500),@GradeSetId int
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)


--Declare @rIsDisplayStudentPhoto bit, @rIsDisplayTeacherSign bit, @rIsDisplayPrincipalSign bit, @rIsDisplayImageHeader bit
--SELECT @rIsDisplayStudentPhoto = ISNULL(IsDisplayPhoto,0), @rIsDisplayTeacherSign = ISNULL(IsDisplayTeacherSign,0),
--	   @rIsDisplayPrincipalSign = ISNULL(IsDisplayPrincipalSign,0),@rIsDisplayImageHeader = ISNULL(IsDisplayImageHeader,0)
--	   From sAssessment.tExamMaster Where Id = @rExamId
	   
		--DECLARE @lAcademicId TABLE (AcademicId bigint, ClassSubjectId int, Term1Grade nvarchar(20), Term2Grade nvarchar(20), AnnualGrade nvarchar(20),
		--Term1PresentDays Int, Term1TotalDays Int, Term2PresentDays Int, Term2TotalDays Int)
		
		--INSERT INTO @lAcademicId (AcademicId, ClassSubjectId)
		--(
		--	SELECT 			 
		--		SA.AcademicId,
		--		CS.ClassSubjectId
		--	FROM 
		--		sStudent.vStudentAcademic SA
		--		INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = SA.ClassId
		--		INNER JOIN sAssessment.tExamDetail ED ON EM.Id = ED.ExamId
		--		INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId = ED.ClassSubjectId 
		--		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
		--	WHERE
		--		((SA.AcademicId=@rAcademicId) OR(@rAcademicId=0))
		--		AND ((CS.ClassId=@rClass) OR (@rClass=0))
		--		And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
		--		And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
		--		And ((EM.Id = @rExamId) OR (@rExamId = 0))
		--		and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		--		AND ((SA.Code = @rCode) OR(@rCode=''))
		--		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		--		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--		AND SA.StatusId = 1
		--)
		
		--Declare @FirstTermExamId AS INT,@SecondTermExamId AS INT, @Term1PresentDays AS INT, @Term1TotalDays AS INT,
		--@Term2PresentDays AS INT, @Term2TotalDays AS INT
		
		--Select @FirstTermExamId=SubExamId  from sAssessment.tExamCombine Where ExamId = @rExamId AND ExamOrder = 1
		
		--Select @SecondTermExamId=SubExamId from sAssessment.tExamCombine Where ExamId = @rExamId AND ExamOrder = 2
		
		
	
		--UPDATE @lAcademicId 
		--SET Term1Grade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @FirstTermExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
	    
		--UPDATE @lAcademicId 
		--SET Term2Grade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @SecondTermExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
		
		--UPDATE @lAcademicId 
		--SET AnnualGrade = ARD.SubjectGrade
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tResult AR ON AR.ExamId = @rExamId AND AR.AcademicId = A.AcademicId
		--INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id 
		--INNER JOIN sAssessment.tExamDetail ED ON ED.Id = ARD.ExamDetailId AND ED.ClassSubjectId = A.ClassSubjectId
		
		--UPDATE @lAcademicId 
		--SET Term1PresentDays = SR.PresentDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @FirstTermExamId AND SR.AcademicId = A.AcademicId
		
		--UPDATE @lAcademicId 
		--SET Term1TotalDays = SR.TotalDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @FirstTermExamId AND SR.AcademicId = A.AcademicId
		
	 --   UPDATE @lAcademicId 
		--SET Term2PresentDays = SR.PresentDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @SecondTermExamId AND SR.AcademicId = A.AcademicId
		
		--UPDATE @lAcademicId 
		--SET Term2TotalDays = SR.TotalDays
		--FROM @lAcademicId A
		--INNER JOIN sAssessment.tStudentRemark SR ON SR.ExamId = @SecondTermExamId AND SR.AcademicId = A.AcademicId
	    
	    --Select * from @lAcademicId
	    
	    SELECT 			 
			Convert(nvarchar(20),SA.Id) AS AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
			@rBuilder1 AS Builder1,
			SA.Id AS AcademicId,
			SA.RollNo,
			StuM.Number,
			AIS.Grade,
			SAM.Title AS SubjectActivityTitle,
			SSA.Title AS SubjectSubActivityTitle,
			SAM.Id AS ActivityId,
			SSA.Id AS SubjectSubActivityId,
			SAM.OrderIndex AS ActivityOrderIndex,
			SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
			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.IsDisplayGradeString,
			EM.IsDisplayParentName,
			StuM.FirstName + ' ' +StuM.MiddleName +' ' +StuM.LastName AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			StuM.code,
			SR.PresentDays,			
			SR.TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto, 
			ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
			CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			CS.OrderIndex,
			EM.SubjectGroupPerPage,
			AIS.GradeIndicator,
			EM.IsCoScholasticGradeIndicator,
			(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
			Em.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsCoScholasticGradeDesIndicator,
			EM.IsCoScholasticGrade,
			Em.IsDisplayParentName,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
			--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
			ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		    ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
			ParentSignCaption,
			SR.ResultRemark3,
			ARD.SubjectGrade,
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign
			--A.Term1Grade,
			--A.Term2Grade,
			--A.AnnualGrade,
			--A.Term1PresentDays,
			--A.Term1TotalDays,
			--A.Term2PresentDays,
			--A.Term2TotalDays			
			
		FROM 
			sAssessment.tCCESubjectSubActivityExamScore AIS 
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id 
			INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId		
			INNER JOIN sStudent.tAcademic SA ON SA.Id = AIS.AcademicId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = CS.Id 		 			 
			INNER JOIN sAssessment.tResult AR ON AR.ExamId = AIS.ExamId AND AIS.AcademicId = AR.AcademicId
			INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id AND ARD.ExamDetailId = ED.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId	
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=DM.ClassId 
			
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.Id = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.Id AND EM.ID=RD.ExamId AND CS.Id=RD.ClassSubjectID 
			LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId	
			--LEFT JOIN @lAcademicId A ON A.AcademicId = SA.AcademicId AND A.ClassSubjectId = ED.ClassSubjectId
			
		WHERE
			((SA.Id=@rAcademicId) OR(@rAcademicId=0))
			AND ((CS.ClassId=@rClass) OR (@rClass=0))
			And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
			And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
			and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			And AIS.ExamId=@rExamId
			AND ((STum.Code = @rCode) OR(@rCode=''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND StuM.StatusId = 1
			AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--ORDER BY 
		--	SA.RollNo ASC,
		--	SAM.OrderIndex ASC,
		--	SSA.OrderIndex ASC;
			
END
GO
PRINT N'Altering [sAssessment].[pSubjectActivityExamIndicatorGet]...';


GO
ALTER PROCEDURE [sAssessment].[pSubjectActivityExamIndicatorGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rSubjectActivityId int,  --@rCCECSGroupId int,
	  @rBatchId int=0,
	  @rSubActivityId int=0 --@rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	

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


select @cols = STUFF((SELECT  ',' + QUOTENAME( Title) FROM sAssessment.tCCESubjectSubActivityMaster 
					 Where  OrgId=@rOrgId AND  SubjectActivityId=@rSubjectActivityId AND (( Id=@rSubActivityId)OR (@rSubActivityId=0))

					-- FROM sAssessment.tCCESubjectActivityMaster CGM
					--INNER JOIN sAssessment.tCCESubjectSubActivityMaster CM ON CM.SubjectActivityId=CGM.Id
					
					--INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=CGM.ClassSubjectId AND CS.ClassSubjectId=@rClassId
					--INNER JOIN sSetup.tClassMaster C ON C.Id=CS.ClassId 
					--	AND CGM.OrgId=@rOrgId AND CGM.Id=@rSubjectActivityId AND ((CM.Id=@rSubActivityId)OR (@rSubActivityId=0))
				  
					 
					Order by  OrderIndex
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
       
	SET @query = 'Select AcademicId,RollNo,Number,Name, ' + @cols + '
	FROM
	(
		SELECT SA.AcademicId,SA.RollNo,SA.Code AS Number,SA.Name,SSA.Title,	 ISNULL(SEC.IndicatorIds,'''') AS Term1Indicator
	FROM  
	 sAssessment.tCCESubjectActivityMaster SAM 	
	INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId  
	INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId
	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CMM.Id AND SA.StatusId=1
	LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SEC  ON SEC.SubjectSubActivityId=SSA.Id AND SEC.AcademicId=SA.AcademicId AND SEC.ExamId= ' + Convert(nvarchar,@rExamId)+ ' AND (SEC.SubjectSubActivityId = ' + convert(nvarchar,@rSubActivityId) + ' OR ' + convert(nvarchar,@rSubActivityId) + ' = 0 )
	 LEFT JOIN sAssessment.tOptionalSubject o on o.AcademicId=SA.AcademicID and o.ClassSubjectId=CS.ClassSubjectId  
			 
				AND SEC.ExamId='+cONVERT(NVARCHAR,@rExamId )+'
	WHERE  SSA.OrgId= '+ CONVERT(nvarchar,@rOrgId) + ' 
	 AND SAM.ClassSubjectId= ' + CONVERT(nvarchar,@rClassId) + ' 
	 AND SSA.SubjectActivityId= '+ CONVERT(nvarchar,@rSubjectActivityId) + ' 
	 AND SA.DivisionId= ' + CONVERT(nvarchar,@rDivisionID) + '
	 And SA.BatchId = ' + CONVERT(nvarchar,@rBatchId) + '	
	  AND ((CS.IsOptional = 1 AND  isnull(o.AcademicId,0)<>0) OR (CS.IsOptional = 0))
	 ) MAIN
	PIVOT
	(
		max(Term1Indicator)
	FOR Title IN (' + @cols + ')
	)pvt Order by RollNo,Number,Academicid'

EXECUTE(@query)

END
GO
PRINT N'Altering [sBiometric].[pEmployeeCheckInAdd]...';


GO
 
 

ALTER PROCEDURE [sBiometric].[pEmployeeCheckInAdd]
	 
	 	@rEmployeeId bigint,
        @rAttendanceDate Datetime='', 
        @rCheckInTime Datetime='',
		@rCheckOutTime Datetime='',
		@rEmployeePhoto varbinary(max)=null,
		@rId int=0,
		@rLatitude nvarchar(20) = '',
		@rLongitude nvarchar(20) = '',
		@rLocation nvarchar(200) = '' 
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	--IF(@rId = 0)	
	--BEGIN 
	IF EXISTS (SELECT 1 FROM sBiometric.tEmployeeCheckIn WHERE EmployeeId = @rEmployeeId AND CAST(AttendanceDate AS DATE) = CAST(@rAttendanceDate AS DATE))
	BEGIN 
		SELECT -1 AS RESULT
		RETURN
	END
	ELSE 
	BEGIN
	INSERT INTO sBiometric.tEmployeeCheckIn
		(
			
			EmployeeId,
			AttendanceDate,
			CheckInTime,
			EmployeePhoto,
			LatitudeAxis,
			LongitudeAxis,
			Location
		)
	VALUES
		( 
			@rEmployeeId,
			@rAttendanceDate,
			@rCheckInTime,
			@rEmployeePhoto,
			@rLatitude,
			@rLongitude,
			@rLocation
		)
	 SELECT 1  As result
	
	END	 

--ELSE
--	 BEGIN
--	    UPDATE sBiometric.tEmployeeCheckIn
--	    SET 
--			EmployeePhoto=@rEmployeePhoto
	      
--	      WHERE EmployeeId = @rEmployeeId AND Id=@rId
--	     SELECT 11 AS Result
--	 END  	

 
END
GO
PRINT N'Altering [sCertificate].[pLeavingBulkGet]...';


GO


ALTER PROCEDURE [sCertificate].[pLeavingBulkGet]
	 
	 @rClassID int,
	 @rDivisionId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rOrderBy int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.Code,
			SA.Name,
			ISNULL(L.Id,0) AS Id,
			ISNULL(L.LCNumber,0) AS LCNumber,
			ISNULL(L.LCDate,'') AS LCDate,
			ISNULL(L.LCRemark,'')AS LCRemark,
			ISNULL(L.LastExamName,'')AS LastExamName,
			ISNULL(L.LastExamResult,'')AS LastExamResult,
			ISNULL(L.RepeatDetail,'')AS RepeatDetail,
			--ISNULL(L.SubjectStudied,'')AS SubjectStudied,
			ISNULL(L.PromoteToClass,'')AS PromoteToClass,
			ISNULL(L.ExtraCurricularActivities,'')As ExtraCurricularActivities,
			ISNULL(L.NCCScoutDetail,'')AS NCCScoutDetail,
			ISNULL(L.TermsInInstitute,'')As TermsInInstitute,
			ISNULL(L.FeeDetail,'')AS FeeDetail,
			ISNULL(L.FeeConcessionDetail,'')AS FeeConcessionDetail,
			ISNULL(AD.TotalDaysAnnual,0)AS TotalDays,
			ISNULL(AD.PresentDaysAnnual,0)AS PresentDays,
			ISNULL(L.ProofOfDOB,'')AS ProofOfDOB,
			CASE WHEN EXISTS(SELECT 1 FROM sSetup.tSubjectMaster S  INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
								WHERE S.OrgId=@rOrgId AND CS.IsOptional=0) THEN
			reverse(STUFF(reverse(isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title from sSetup.tSubjectMaster S  
						   INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
						   WHERE S.OrgId=@rOrgId AND CS.IsOptional=0 FOR XML PATH('')), 1, 1, '')),'') +',' +
			isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title FROM sAssessment.tOptionalSubject OS 
						   INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
						   INNER JOIN sSetup.tSubjectMaster S ON  S.Id = CS.SubjectId 
						   WHERE OS.AcademicId = SA.AcademicId FOR XML PATH('')), 1, 1, '')),'') 
						   ), 1, 1, '')) 
						   
			ELSE

			STUFF(reverse(reverse(isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title from sSetup.tSubjectMaster S  
						   INNER JOIN sSetup.tClassSubject CS ON  S.Id = CS.SubjectId AND CS.ClassId=@rClassId	
						   WHERE S.OrgId=@rOrgId AND CS.IsOptional=0 FOR XML PATH('')), 1, 1, '')),'') +',' +
			isnull([sCommon].[fXMLTagsReplaceReverse](STUFF((SELECT ',' + S.Title FROM sAssessment.tOptionalSubject OS 
						   INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
						   INNER JOIN sSetup.tSubjectMaster S ON  S.Id = CS.SubjectId 
						   WHERE OS.AcademicId = SA.AcademicId FOR XML PATH('')), 1, 1, '')),'') 
						   )), 1, 1, '') END AS SubjectStudied


			
			
  FROM 
			[sStudent].[vStudentAcademic]  SA 
			LEFT OUTER JOIN sCertificate.tLeaving L ON L.AcademicId=SA.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON SA.AcademicId=AD.AcademicId
  WHERE 
			(SA.ClassId=@rClassId OR @rClassId=0)
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND SA.BatchId=@rBatchId
			AND SA.OrgID=@rOrgId 
			AND L.Id IS NULL
			order by
			CASE @rOrderBy WHEN 2 THEN SA.Code END,
			CASE @rOrderBy WHEN 1 THEN SA.RollNo END,
			CASE @rOrderBy WHEN 0 THEN SA.RollNo END
END
GO
PRINT N'Altering [sCommon].[pUploadDocumentAdd]...';


GO
 
 
ALTER PROCEDURE [sCommon].[pUploadDocumentAdd]
	 
	@rUploadFunctionalityId smallint,
	@rUserSourceTypeId smallint,
	@rUserSourceId bigint,
	@rDocumentId bigint,
	@rDocumentName nvarchar(200),
	@rCreatedUserId bigint,
	@rDocumentSize decimal (12,2) = 0.00,
	@rOrgGroupBatchId int = 0   
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	BEGIN TRANSACTION

	INSERT INTO sCommon.tUploadDocument
		(
		UploadFunctionalityId,
		UserSourceTypeId,
		UserSourceId,
		DocumentId,
		DocumentName,
		CreatedUserId,
		CreatedDateTime,
		DocumentSize,
		OrgGroupBatchId
		)
	VALUES
		(
		@rUploadFunctionalityId,
		@rUserSourceTypeId,
		@rUserSourceId,
		@rDocumentId,
		@rDocumentName,
		@rCreatedUserId,
		sCommon.fGetDate(),
		@rDocumentSize,
		@rOrgGroupBatchId
		)
	 
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pChargeReceiptListGet]...';


GO
 
 
ALTER PROCEDURE [sFee].[pChargeReceiptListGet]
	 
	 --@rReceiptNumber int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSourceTypeId smallint,
	 @rSourceCode nvarchar(20),
	 @rGuestName nvarchar(200),
	 @rFromDate date,
	 @rToDate date,
	 @rFromNo int,
	 @rToNo int,
	 @rReceiptBookId int,
	 @rChargeCategoryId int,
	 @rOrgId int,
	 @rBatchId int,
	 @rOrgGroupBatchId int,
	 @rDepartmentId int = 0,
	 @rStudentCode nvarchar(20) = '',
	 @rOrgGroupId int=0,
	 @rStatusId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		 
BEGIN 
		--select 
		--		'' AS Builder1,
		--		'' AS Builder2,
		--		'' AS Id,
		--		'' AS SourceType,
		--		'' AS SourceTypeId
		--		,'' AS GuestName
		--		,'' AS ReceiptNumber
		--		,'' AS ReceiptDate
		--		,'' AS Amount
		--		,'' AS ChargeCategory
		--		,'' AS ReceiptBook
		--		,'' AS ChargeCategoryId
		--		,'' As ReceiptBookId
		--		,'' AS OrgId
		--		,'' AS School
		--		,'' AS OrgGroupId
		--		,'' AS ChargeId

	    ----IF(@rIsSearch=1)
		----BEGIN
			SET @rSourceCode = sCommon.fSearchStringGet(@rSourceCode)
			SET @rGuestName = sCommon.fSearchStringGet(@rGuestName)

			print @rSourceCode
		--Declare @rSourceTypeId smallint
		--select @rSourceTypeId=SourceTypeId from sFee.tChargeReceipt where ReceiptNumber=@rReceiptNumber and OrgId=@rOrgId
		--END
IF @rSourceTypeId=95
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			ISNULL(EM.Code,'') AS Code,
			CR.SourceTypeId,
			--EM.Code as SourceCode,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			DM.DisplayTitle AS Class
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = @rSourceTypeId)
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		   INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
		   --AND EM.StatusId=7
		    INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ReceiptNumber>=@rFromNo) OR (ISNULL(@rFromNo,'')=''))
			AND ((CR.ReceiptNumber<=@rToNo) OR (ISNULL(@rToNo,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			AND ((EM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
GROUP BY 
			CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,
			CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,EM.Code

END
ELSE IF @rSourceTypeId=2001
BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			ISNULL(SA.Code,'') as Code,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			CMM.DisplayTitle + '-' + DM.DisplayTitle AS Class
			--CLM.Id AS ClassId,
			--CLM.DisplayTitle AS ClassName,
			--DM.Id AS DivisionId,
			--DM.DisplayTitle AS DivisionName
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001 --AND SA.StatusId=1
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tClassMaster CMM ON CMM.Id = SA.ClassId
		   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   --INNER JOIN sSetup.tClassMaster CLM ON CLM.Id = SA.ClassId
		   --INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0)) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
 GROUP BY   CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CM.ChargeCategoryId,
            CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle, CMM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,SA.Code
            --CLM.Id,CLM.DisplayTitle, DM.Id, DM.DisplayTitle
END
ELSE IF @rSourceTypeId=3
BEGIN
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CR.Id,
		'Other' as SourceType,
		'' AS Code,
		CR.SourceTypeId,
		--EM.Code as SourceCode,
		CR.GuestName as GuestName,
		--CR.Remark,
		CR.ReceiptNumber,
		CR.ReceiptDate,
		  PTM.Title AS PayType,  
		--CR.PayTypeId,
		CR.ChequeNo,
		CR.BankName,
		--CR.IsObsolete,
		--CRD.Id as DetailId,
		--CRD.ChargeId,
		--CRD.Remark as DetailRemark,
		sum(CRD.Amount) as Amount,
		--CM.Code,
		--CM.Title,
		CCM.Title as ChargeCategory,
		CM.ChargeCategoryId,
		CR.OrgId,
		CR.BatchId,
		RBM.Title AS ReceiptBook,
		CR.ChargeReceiptBookId,
		OM.DisplayTitle AS OrganizationName,
		'' AS Class
		--OM.DisplayTitle AS School,
		--OM.OrgGroupId,
		--CM.Id AS ChargeId
		--CRD.IsObsolete
  FROM 
       sFee.tChargeReceipt CR
	   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
	   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
	   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
	   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
	   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
	   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
	   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
		--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
		--AND 
		(ISNULL(CR.SourceTypeId,0)=3)
		AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
		--AND (ISNULL(@rSourceCode,'') = '')
		AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
		AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
		AND (CR.IsObsolete=0)
		AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (CRD.IsObsolete=0) 
		AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
		And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
		,PTM.Title,CR.ChequeNo,CR.BankName

END	
ELSE
BEGIN
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--CRD.Id as DetailId,
			CR.Id,
			'Employee' as SourceType,
			CR.SourceTypeId,
			ISNULL(EM.Code,'') as Code,
			EM.FirstName+' '+EM.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--Amount=(select sum(Amount) from sFee.tChargeReceiptDetail group by ChargeReceiptId),
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			DM.DisplayTitle AS Class
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=CR.SourceId AND (CR.SourceTypeId = 95) 
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id 
		   INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
		   --AND EM.StatusId=7
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((EM.FirstName+' '+EM.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((EM.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			group by CR.Id,EM.FirstName,EM.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,
			CR.BatchId,RBM.Title,CM.ChargeCategoryId,CR.ChargeReceiptBookId,CR.SourceTypeId,OM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,EM.Code

			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Student' as SourceType,
			CR.SourceTypeId,
			ISNULL(SA.Code,'') as Code,
			SA.FirstName+' '+SA.LastName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			CMM.DisplayTitle + '-' + DM.DisplayTitle AS Class
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001
		   INNER JOIN sSetup.tClassMaster CMM ON CMM.Id = SA.ClassId
		   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId 
		   --AND SA.StatusId=1
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
       
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			((SA.FirstName+' '+SA.LastName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((SA.Code Like @rSourceCode) OR (ISNULL(@rSourceCode,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0)
			AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			group by CR.Id,SA.FirstName,SA.LastName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,
			RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle, CMM.DisplayTitle, DM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName,SA.Code

			UNION ALL
			
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			CR.Id,
			'Other' as SourceType,
			CR.SourceTypeId,
			'' AS Code,
			CR.GuestName as GuestName,
			--CR.Remark,
			CR.ReceiptNumber,
			CR.ReceiptDate,
			  PTM.Title AS PayType,  
			--CR.PayTypeId,
			CR.ChequeNo,
			CR.BankName,
			--CR.IsObsolete,
			--CRD.Id as DetailId,
			--CRD.ChargeId,
			--CRD.Remark as DetailRemark,
			sum(CRD.Amount) as Amount,
			--CM.Code,
			--CM.Title,
			CCM.Title as ChargeCategory,
			CM.ChargeCategoryId,
			CR.OrgId,
			CR.BatchId,
			RBM.Title AS ReceiptBook,
			CR.ChargeReceiptBookId,
			OM.DisplayTitle AS OrganizationName,
			'' AS Class
			--OM.DisplayTitle AS School,
			--OM.OrgGroupId,
			--CM.Id AS ChargeId
			--CRD.IsObsolete
  FROM 
           sFee.tChargeReceipt CR
		   INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id
		   INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		   INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		   INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		   INNER JOIN sFinanceCommon.tPayTypeMaster PTM  ON PTM.Id=CR.PayTypeId 
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		   --INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=CR.OrgGroupBatchId
		   --INNER JOIN sSetup.tOrganizationMaster OM ON OM.OrgGroupId=OBM.OrgGroupId
  WHERE 
			--(CR.ReceiptNumber=@rReceiptNumber OR ISNULL(@rReceiptNumber,'')='')
			--AND 
			(ISNULL(CR.SourceTypeId,0)=3)
			AND	((CR.GuestName Like @rGuestName) OR (ISNULL(@rGuestName,'') = ''))
			AND ((CR.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CR.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((CR.ChargeReceiptBookId = @rReceiptBookId) OR (ISNULL(@rReceiptBookId,0) = 0))
			AND ((CM.ChargeCategoryId = @rChargeCategoryId) OR (ISNULL(@rChargeCategoryId,0) = 0))
			AND (CR.IsObsolete=0)
			AND ((CR.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((CR.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (CRD.IsObsolete=0) 
			AND (OM.OrgGroupId = @rOrgGroupId or @rOrgGroupId=0)
			And ((CR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND ((ISNULL(@rSourceCode,'%') = '%'))
			group by CR.Id,CR.GuestName,CR.ReceiptNumber,CR.ReceiptDate,CCM.Title,CR.OrgId,CR.BatchId,RBM.Title,CR.ChargeReceiptBookId,CM.ChargeCategoryId,CR.SourceTypeId,OM.DisplayTitle
			,PTM.Title,CR.ChequeNo,CR.BankName
END
END
GO
PRINT N'Altering [sFee].[pFeeConsolidateDashBoardGet]...';


GO
 
ALTER PROCEDURE [sFee].[pFeeConsolidateDashBoardGet]
		
	@rType nvarchar(100)='',
	@rCount int =0 ,
	@rDivisionId int  =0,
	@rClassId int  =0,
	@rOrgId int  =0,
	@rOrgGroupId int=0,
	@rOrgGroupBatchId int  =0,
	@rCollectionGroupId int =0,
	@rReceiptBookId int =0,
	@rDays int=0,
	@rCommonOrgGroupBatchId int=0,
	@rFromDate varchar(10)='',
	@rToDate varchar(10)='',
	@rMonth int =0,
	@rSyncDate int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

IF(@rType ='FeeStatusOrganization')
	BEGIN 
	IF(@rSyncDate =1)
		BEGIN
			DELETE  sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				
				CREATE TABLE #tempOrganizationSync(
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrgGroupName nvarchar(200),
				OrgGroupId int
				)
				INSERT INTO #tempOrganizationSync
					SELECT 
						SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
						O.Title AS OrgGroupName,
						O.Id AS OrgGroupId
					FROM 
						sStudent.tAcademic SA
						INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
						INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.ID = SA.OrgId
						
					WHERE	
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  And ISNULL(O.IsObsolete,0) = 0
						  AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
					GROUP BY  o.Id,o.Title

					IF EXISTS (SELECT 1 FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId)
						BEGIN							
						IF(@rOrgGroupId !=0)
							INSERT INTO sFee.tTempOrgGroupFeeStatus
							SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
							ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganizationSync T
							SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
						END
					ELSE
						BEGIN						
						INSERT INTO sFee.tTempOrgGroupFeeStatus
							SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
							ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganizationSync T
							SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
						END
				
				DROP TABLE #tempOrganizationSync			
		END
	ELSE
		BEGIN

			IF  Exists(select 1 from sFee.tTempOrgGroupFeeStatus where CONVERT(date,UpdatedDateTime) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))) 
			BEGIN
	
				SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN
			DELETE  sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempOrganization(
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrgGroupName nvarchar(200),
				OrgGroupId int
				)
			INSERT INTO #tempOrganization
					SELECT 
						SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
						O.Title AS OrgGroupName,
						O.Id AS OrgGroupId
					FROM 
						sStudent.tAcademic SA
						INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
						INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.ID = SA.OrgId
						
					WHERE	
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  And ISNULL(O.IsObsolete,0) = 0
						  AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
					GROUP BY  o.Id,o.Title

						
				IF EXISTS (SELECT 1 FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId)
					BEGIN
						
					IF(@rOrgGroupId !=0)
						INSERT INTO sFee.tTempOrgGroupFeeStatus
						SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganization  T
						SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					END
				ELSE
					BEGIN
					
					INSERT INTO sFee.tTempOrgGroupFeeStatus
						SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganization  T
						SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					END 
					
				DROP TABLE #tempOrganization
			END
		END
		
	
	END
ELSE IF(@rType = 'FeeStatusPaid&UnpaidDetilsClassWise')
	BEGIN 
	IF(@rCount = 1)
	BEGIN

	CREATE TABLE #tempPaidDetailsClassWise(
	OrgGroupId int,
	OrgGroupName nvarchar(50),
	ClassId int,
	ClassName nvarchar(50),
	PaidAmount DECIMAL(12,0),
	StudentCount int
	)
  
	INSERT INTO #tempPaidDetailsClassWise
	SELECT 
		 ISNULL(O.Id,0) AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 ISNULL(SA.ClassId,0)AS ClassId,
		 ISNULL(SA.ClassName,'') AS ClassName,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 COUNT(Distinct(SA.AcademicId)) as StudentCount
	FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
	WHERE
		(O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND
		((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0 AND FAS.PaidAmount > 0
	GROUP by O.Id,SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName
	 

		SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount,T.StudentCount
		FROM #tempPaidDetailsClassWise T
		WHERE T.PaidAmount > 0
			 
	DROP TABLE #tempPaidDetailsClassWise
 
	END
	ELSE IF(@rCount = 2)
	BEGIN

	CREATE TABLE #tempPendingDetailsClassWise(
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(40),
	ClassId int,
	ClassName nvarchar(50),
	PendingAmount DECIMAL(12,0) 
	)
 
	INSERT INTO #tempPendingDetailsClassWise
	SELECT 
		 ISNULL(SA.AcademicId,0) AS AcademicId,
		 ISNULL(O.Id,0) AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 ISNULL(SA.ClassId,0)AS ClassId,
		 ISNULL(SA.ClassName,'') AS ClassName,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
	FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
	WHERE
		(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0
	GROUP by O.Id,SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName,SA.AcademicId

		SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS UnPaidAmount,COUNT(T.PendingAmount)AS StudentCount
		FROM #tempPendingDetailsClassWise T
		WHERE T.PendingAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.ClassId,T.OrgGroupName
		HAVING ISNULL(SUM(T.PendingAmount),0) > 0
        ORDER BY T.ClassId
	 
	DROP TABLE #tempPendingDetailsClassWise
 
	END
	END
ELSE IF(@rType ='FeeStatusPaid&UnpaidDetils')
BEGIN 

	IF(@rCount = 1)
	BEGIN
		CREATE TABLE #tempPaidDetails(
			SourceId bigint,
			OrgGroupId int,
			ClassName nvarchar(50),
			DivisionId int,
			DivisionName nvarchar(50),
			Code nvarchar(20),
			Name nvarchar(200),
			ParentContactNo nvarchar(50),
			PaidAmount DECIMAL(12,0),
			ClassOrderIndex int,
			DivisionOrder int,
			RollNo int
		)
		INSERT INTO #tempPaidDetails
		SELECT 
				ISNULL(SA.AcademicId,0) AS SourceId,
				ISNULL(O.Id,0) AS OrgGroupId,
				ISNULL(SA.ClassName,'') AS ClassName,
				ISNULL(SA.DivisionId,0) AS DivisionId,
				ISNULL(SA.DivisionName,'') AS DivisionName,
				ISNULL(SA.Code,'') As Code,
				ISNULL(SA.Name,'') AS Name,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
				SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
				 SA.ClassOrderIndex,  
				 SA.DivisionOrder,
				 SA.RollNo 
			FROM 		
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
			    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
		 WHERE
				(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND((SA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				And ISNULL(O.IsObsolete,0) = 0
				AND FAS.PaidAmount > 0
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		Having SUM(ISNULL(FAS.PaidAmount,0)) >0
		ORDER BY O.Id,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo

		SELECT T.SourceId, T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,T.DivisionId,
			T.ParentContactNo AS ParentContactNo,T.PaidAmount AS PaidAmount,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
		FROM #tempPaidDetails T
		WHERE T.PaidAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.Name,T.ParentContactNo,T.PaidAmount,T.Code,T.ClassOrderIndex,T.DivisionOrder,T.RollNo,T.DivisionId,T.SourceId
		HAVING T.PaidAmount > 0
		ORDER BY T.OrgGroupId,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
	END
	ELSE IF(@rCount = 2)
	BEGIN
		CREATE TABLE #tempPendingDetails(
			SourceId bigint,
			OrgGroupId int,
			ClassName nvarchar(50),
			DivisionId int,
			DivisionName nvarchar(50),
			Code nvarchar(20),
			Name nvarchar(200),
			ParentContactNo nvarchar(50),
			PendingAmount DECIMAL(12,0),
			ClassOrderIndex int,
			DivisionOrder int,
			RollNo int
		)
		INSERT INTO #tempPendingDetails
		SELECT 
				ISNULL(SA.AcademicId,0) AS SourceId,
				ISNULL(O.Id,0) AS OrgGroupId,
				ISNULL(SA.ClassName,'') AS ClassName,
				ISNULL(SA.DivisionId,0) AS DivisionId,
				ISNULL(SA.DivisionName,'') AS DivisionName,
				ISNULL(SA.Code,'') As Code,
				ISNULL(SA.Name,'') AS Name,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
				SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
				SA.ClassOrderIndex,  
				SA.DivisionOrder,
				SA.RollNo 
			FROM 		
				sStudent.vStudentAcademic SA
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
			    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
			    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
			    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
		
		 WHERE
				(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
				AND((SA.ClassId = @rClassId)OR(@rClassId=0))
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				And ISNULL(O.IsObsolete,0) = 0
				
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.Name,SC.ParentContactNo,SA.Code,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
		ORDER BY O.Id,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo

		SELECT T.SourceId, T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,T.DivisionId,
			T.ParentContactNo AS ParentContactNo,T.PendingAmount AS UnPaidAmount,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
		FROM #tempPendingDetails T
		WHERE T.PendingAmount > 0
		GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.Name,T.ParentContactNo,T.PendingAmount,T.Code,T.ClassOrderIndex,T.DivisionOrder,T.RollNo,T.DivisionId,T.SourceId
		HAVING T.PendingAmount > 0
		ORDER BY T.OrgGroupId,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
	END
END

ELSE IF(@rType ='FeeStatusTotalHeadwiseAmount')
BEGIN 
	IF(@rSyncDate =1)
		BEGIN
		DELETE  sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempTotalPaidDetailsSync (
				FeeHeadId bigint,
				FeeHeadName nvarchar(200),
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				ReceiptBookId bigint,
				RecepitTitle nvarchar(100),
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrderIndex int
			)
			 
			INSERT INTO #tempTotalPaidDetailsSync
			SELECT 
				ISNULL(FHM.Id,0) AS FeeHeadId,
				ISNULL(FHM.code,'') AS FeeHeadName,
				ISNULL(CGM.Id,0) AS CollectionGroupId,
				ISNULL(CGM.Code,'') AS CollectionGroup,
				ISNULL(RBM.Id,'')  AS ReceiptBookId,
				ISNULL(RBM.Title,'')  AS ReceiptTitle,
				SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
				SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
				FHM.OrderIndex
			FROM 
				sStudent.tAcademic SA
				INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			 And ISNULL(O.IsObsolete,0) = 0
			GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Code,RBM.Title,RBM.Id,FHM.OrderIndex

			INSERT INTO sFee.tTempTotalPaidDetails
			SELECT @rOrgGroupId,T.FeeHeadId,ISNULL(T.FeeHeadName,'') AS FeeHeadName,T.CollectionGroupId,
						ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,
						T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
						ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
						ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
						T.OrderIndex,@rCommonOrgGroupBatchId,GETDATE() from #tempTotalPaidDetailsSync T
			GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId,T.OrderIndex
			ORDER BY T.OrderIndex

			SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))		

		--New Temp Table Create-------------
			CREATE TABLE #tempTotalStudentCountSync (
			AcademicId bigint,
			CollectionGroupId bigint,
			CollectionGroup nvarchar(200),
			RecepitTitle nvarchar(100),
			ReceiptBookId bigint,
			EndDate date,
			PaidAmount DECIMAL(12,0),
			PendingAmount DECIMAL(12,0)
			)
	
			--Test
	 
			INSERT INTO #tempTotalStudentCountSync
			SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
					INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					 ORDER BY ReceiptDate DESC) EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA
				INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
		        INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id 
				INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 And ISNULL(O.IsObsolete,0) = 0
			 AND COGBM.Id=@rCommonOrgGroupBatchId 
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	
			INSERT INTO sFee.tTempTotalStudentCount
			SELECT @rOrgGroupId,E.CollectionGroupId,E.CollectionGroup AS CollectionGroup,E.ReceiptBookId AS ReceiptId,E.ReceiptCollection AS ReceiptCollection,
					ISNULL(E.EndDate,'1900-01-01')AS EndDate,
					--E.EndDate AS EndDate,
					SUM(E.TotalStudentCount) AS TotalStudentCount,SUM(E.PaidStudentCount) AS PaidStudentCount,SUM(E.PendingStudentCount) AS PendingStudentCount,@rCommonOrgGroupBatchId,GETDATE() FROM (
			SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(T.CollectionGroup,'') As CollectionGroup,
				ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,T.CollectionGroupId AS CollectionGroupId,
				ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate from #tempTotalStudentCountSync T
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM #tempTotalStudentCountSync --CollectionGroupId,CollectionGroup,
						WHERE PendingAmount  = 0
						GROUP BY CollectionGroupId,ReceiptBookId
					) A ON A.CollectionGroupId = T.CollectionGroupId
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM #tempTotalStudentCountSync
						WHERE PendingAmount !=0
						GROUP BY CollectionGroupId,ReceiptBookId
					)B ON B.CollectionGroupId = T.CollectionGroupId 
					GROUP BY T.CollectionGroupId,T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
					)E
					GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate,E.CollectionGroupId
		
		 SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	


		-------------Create a New Temp Table For Pending date-----------------
			CREATE TABLE #tempPendingCountSync(
			AcademicId bigint,
			CollectionGroupId bigint,
			CollectionGroup nvarchar(200),
			RecepitTitle nvarchar(100),
			ReceiptBookId bigint,
			EndDate date,
			PaidAmount DECIMAL(12,0),
			PendingAmount DECIMAL(12,0)
			)
	 
			INSERT INTO #tempPendingCountSync
			SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
						(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
					INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id 
			
					INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
			
			WHERE  
					(LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
					AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
					And ISNULL(O.IsObsolete,0) = 0
			ORDER BY ReceiptDate DESC) EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA
				INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 And ISNULL(O.IsObsolete,0) = 0
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate

			INSERT INTO sFee.tTempPendingCount
			SELECT @rOrgGroupId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,T.ReceiptBookId AS ReceiptId,
						T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount,@rCommonOrgGroupBatchId,GETDATE()
			FROM   #tempPendingCountSync T
			WHERE PendingAmount !=0
			 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()- @rDays) AND CONVERT(DATE,GETDATE())
			GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup

			SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	 
			DROP TABLE #tempTotalPaidDetailsSync
			DROP TABLE #tempTotalStudentCountSync
			DROP TABLE #tempPendingCountSync

		END
	ELSE
		BEGIN
		IF  Exists(select 1 from sFee.tTempTotalPaidDetails where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
			BEGIN
	
				SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN

			DELETE  sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			DELETE  sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			DELETE  sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

			CREATE TABLE #tempTotalPaidDetails (
				FeeHeadId bigint,
				FeeHeadName nvarchar(200),
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				ReceiptBookId bigint,
				RecepitTitle nvarchar(100),
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0),
				OrderIndex int
				)
			
				INSERT INTO #tempTotalPaidDetails
				SELECT 
					ISNULL(FHM.Id,0) AS FeeHeadId,
					ISNULL(FHM.code,'') AS FeeHeadName,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Id,'')  AS ReceiptBookId,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
					FHM.OrderIndex
				FROM 
					sStudent.tAcademic SA
					INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
					INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				 And ISNULL(O.IsObsolete,0) = 0
				GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Code,RBM.Title,RBM.Id,FHM.OrderIndex

			INSERT INTO sFee.tTempTotalPaidDetails
				SELECT @rOrgGroupId,T.FeeHeadId,ISNULL(T.FeeHeadName,'') AS FeeHeadName,T.CollectionGroupId,
				ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
				ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
				ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
				T.OrderIndex,@rCommonOrgGroupBatchId,GETDATE()from #tempTotalPaidDetails T
				GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId,T.OrderIndex
				ORDER BY T.OrderIndex

			SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	

					--New Temp Table Create-------------
				CREATE TABLE #tempTotalStudentCount (
				AcademicId bigint,
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				RecepitTitle nvarchar(100),
				ReceiptBookId bigint,
				EndDate date,
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0)
				)
	
				--Test
	
				INSERT INTO #tempTotalStudentCount
				SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
					(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
					INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
					WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					 ORDER BY ReceiptDate DESC) EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
				FROM 
					sStudent.tAcademic SA
					INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id 
					INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				 And ISNULL(O.IsObsolete,0) = 0
				 AND COGBM.Id=@rCommonOrgGroupBatchId 
				GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	
			INSERT INTO sFee.tTempTotalStudentCount
			SELECT @rOrgGroupId,E.CollectionGroupId,E.CollectionGroup AS CollectionGroup,E.ReceiptBookId AS ReceiptId,E.ReceiptCollection AS ReceiptCollection,
					ISNULL(E.EndDate,'1900-01-01')AS EndDate,
					--E.EndDate AS EndDate,
					SUM(E.TotalStudentCount) AS TotalStudentCount,SUM(E.PaidStudentCount) AS PaidStudentCount,SUM(E.PendingStudentCount) AS PendingStudentCount,@rCommonOrgGroupBatchId,GETDATE() FROM (
			SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(T.CollectionGroup,'') As CollectionGroup,
				ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,T.CollectionGroupId AS CollectionGroupId,
				ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate from #tempTotalStudentCount T
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM #tempTotalStudentCount --CollectionGroupId,CollectionGroup,
						WHERE PendingAmount  = 0
						GROUP BY CollectionGroupId,ReceiptBookId
					) A ON A.CollectionGroupId = T.CollectionGroupId
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM #tempTotalStudentCount
						WHERE PendingAmount !=0
						GROUP BY CollectionGroupId,ReceiptBookId
					)B ON B.CollectionGroupId = T.CollectionGroupId 
					GROUP BY T.CollectionGroupId,T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
					)E
					GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate,E.CollectionGroupId
				 
				 SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))

					-------------Create a New Temp Table For Pending date-----------------
				CREATE TABLE #tempPendingCount(
				AcademicId bigint,
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				RecepitTitle nvarchar(100),
				ReceiptBookId bigint,
				EndDate date,
				PaidAmount DECIMAL(12,0),
				PendingAmount DECIMAL(12,0)
				)
				
				INSERT INTO #tempPendingCount
				SELECT 
					ISNULL(SA.Id,0) AS AcademicId,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					ISNULL(RBM.Id,0) As ReceiptBookId,
						(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
					INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
					INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
					INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id 
					INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
			  WHERE  
					(LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
					AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
					And ISNULL(O.IsObsolete,0) = 0
			  ORDER BY ReceiptDate DESC) EndDate,
					SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount
			FROM 
				sStudent.tAcademic SA
				INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
				LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
				INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.Id
				INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
				INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
			WHERE
			 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
			 And ISNULL(O.IsObsolete,0) = 0
			 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
			GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
		
		INSERT INTO sFee.tTempPendingCount
				SELECT @rOrgGroupId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,T.ReceiptBookId AS ReceiptId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount,@rCommonOrgGroupBatchId,GETDATE()
				FROM   #tempPendingCount T
				WHERE PendingAmount !=0
				 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()- @rDays) AND CONVERT(DATE,GETDATE())
				 GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup
		SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	
				DROP TABLE #tempTotalPaidDetails
				DROP TABLE #tempTotalStudentCount
				DROP TABLE #tempPendingCount
			END
		END
END

ELSE IF(@rType ='FeeStatusPaidSubPartAmount')
BEGIN 
	CREATE TABLE #tempPaidSubPart (
	OrgGroupId int,
	OrgGroupName nvarchar(50),
	ClassId bigint,
	ClassName nvarchar(50),
	--DivisionId bigint,
	--DivisionName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	ClassOrderIndex int,
	StudentCount int
	--,DivisionOrder int
	)
    
IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPaidSubPart
	SELECT 
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		 ISNULL(CGM.Id,0) AS CollectionGroupId,
		 ISNULL(CGM.Code,'') AS CollectionGroup,
		 ISNULL(RBM.Title,'')  AS ReceiptTitle,
		 ISNULL(RBM.Id,0) As ReceiptBookId,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		 SA.ClassOrderIndex,
		 COUNT(Distinct(FAS.AcademicId)) as StudentCount
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	    	
	WHERE
		(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
		And ISNULL(O.IsObsolete,0) = 0
		AND FAS.PaidAmount > 0
	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.ClassId,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	HAVING ISNULL(SUM(FAS.PaidAmount),0) > 0
	ORDER BY SA.ClassOrderIndex

		select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount, T.StudentCount AS StudentCount,
			ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex,
			'' as MonthName 
		from #tempPaidSubPart T
		 

	END 
	ELSE 
	BEGIN
	INSERT INTO #tempPaidSubPart
		
	SELECT 
		 SA.OrgId AS OrgGroupId,SA.OrganizationName As OrgGroupName,
		 SA.ClassId As ClassId,
		 SA.ClassName AS ClassName,
		 ISNULL(CGM.Id,0) AS CollectionGroupId,
		 ISNULL(CGM.Code,'') AS CollectionGroup,
		 ISNULL(RBM.Title,'')  AS ReceiptTitle,
		 ISNULL(RBM.Id,0) As ReceiptBookId,
		 SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		 SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		 SA.ClassOrderIndex,
		 COUNT(Distinct(FAS.AcademicId)) as StudentCount
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FAS.FeeSetupId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
		 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
		 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
		 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		 And ISNULL(O.IsObsolete,0) = 0
		 AND FAS.PaidAmount > 0
    GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.ClassId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	HAVING ISNULL(SUM(FAS.PaidAmount),0) > 0
	ORDER BY SA.ClassOrderIndex

	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,T.PaidAmount AS PaidAmount,T.StudentCount As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex,
		'' as MonthName 
		from #tempPaidSubPart T
	END
	
	DROP TABLE #tempPaidSubPart

END

ELSE IF(@rType ='FeeStatusPaidSubPartAmountMonthWise')
BEGIN 
	CREATE TABLE #tempPaidSubPartMonthWise (
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	MonthName nvarchar(15),
	)
   
    CREATE TABLE #tempPFSMonthWise (
       Id INT,
       Amount DECIMAL(12,0),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    
    INSERT INTO #tempPFSMonthWise	
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
	   (FS1.IsOptional=0)
	   --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate   
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))


     CREATE TABLE #tempPRMonthWise (
         PaidAmount DECIMAL(12,0),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPRMonthWise	
     SELECT 
		  ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 FROM
		  sFee.tReceipt R 
		  INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		  INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		  INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		  INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
		  INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		  INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		  INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		  
		  INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		 
	WHERE		
		  (R.SourceTypeId = 2001)
		   AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		   AND (R.IsObsolete = 0) --AND BM.IsActive=1 
		   AND COGBM.Id=@rCommonOrgGroupBatchId 
		   And ISNULL(O.IsObsolete,0) = 0
		   --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
		   --AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
 

IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPaidSubPartMonthWise
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR.PaidAmount,0.00))AS PendingAmount,
		TPR.ReceiptDate		 
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN #tempPFSMonthWise TPFS ON TPFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=TPFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise TPR ON TPR.FeeSetupId = TPFS.Id AND SA.AcademicId = TPR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN sFee.tReceiptBookMaster RBM ON TPFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON TPFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=TPFS.FeeHeadId	    	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	And ISNULL(O.IsObsolete,0) = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.PaidAmount,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempPFSMonthWise1 (
       Id INT,
       Amount DECIMAL(12,0),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    INSERT INTO #tempPFSMonthWise1
    SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		 SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		 INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	     INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	     INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	     INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	     INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			 
		 INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		 --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		 AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		 And ISNULL(O.IsObsolete,0) = 0
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		 --AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		
	WHERE
				
		(FS1.IsOptional=1) AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
    
    CREATE TABLE #tempPRMonthWise1(
         PaidAmount DECIMAL(12,0),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPRMonthWise1
     SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		

	WHERE		
		(R.SourceTypeId = 2001)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		AND (R.IsObsolete = 0) 
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate  
   
	
	INSERT INTO #tempPaidSubPartMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,		
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR1.PaidAmount,0.00))AS PendingAmount,
		TPR1.ReceiptDate
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPFSMonthWise1 TPFS1 ON TPFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TPFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise1 TPR1 ON TPR1.FeeSetupId = TPFS1.Id AND SA.AcademicId = TPR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TPFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TPFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TPFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	And ISNULL(O.IsObsolete,0) = 0
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR1.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount,COUNT(T.AcademicId) As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END
	
	DROP TABLE #tempPaidSubPartMonthWise
	DROP TABLE #tempPFSMonthWise
	DROP TABLE #tempPRMonthWise
	DROP TABLE #tempPFSMonthWise1
	DROP TABLE #tempPRMonthWise1
	
END

ELSE IF(@rType ='FeeStatusPendingSubPartAmount')
BEGIN 
CREATE TABLE #tempPendingSubPart(
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(50),
	ClassId bigint ,
	ClassName nvarchar(50),
	--DivisionId bigint,
	--DivisionName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,0),
	PendingAmount DECIMAL(12,0),
	ClassOrderIndex int
	--,DivisionOrder int
	)

IF(@rCollectionGroupId = 0)
	BEGIN

	INSERT INTO #tempPendingSubPart
    SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId  AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex
	FROM 
		sStudent.vStudentAcademic SA 
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
		(FS.IsOptional=0)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) 
		And ISNULL(O.IsObsolete,0) = 0
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId = 0))
	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassId,SA.ClassName,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	
	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,COUNT(T.AcademicId)AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex from #tempPendingSubPart T
		WHERE T.PendingAmount >0
     group by T.OrgGroupId,T.OrgGroupName,T.ClassName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex
		ORDER BY T.ClassOrderIndex
		
    DROP TABLE #tempPendingSubPart
		
	END 
	ELSE 
	BEGIN
	
	INSERT INTO #tempPendingSubPart
	SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex  
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
		(FS.IsOptional=0)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) 
		And ISNULL(O.IsObsolete,0) = 0
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
		AND ((FS.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId = 0))
	 GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	
	SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex from #tempPendingSubPart T
	WHERE T.PendingAmount >0
	GROUP BY T.OrgGroupId,T.ClassName,T.OrgGroupName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex
	--HAVING ISNULL(SUM(T.PendingAmount),0) > 0
	ORDER BY T.ClassOrderIndex	
		
   
	   DROP TABLE #tempPendingSubPart
		
	END
	END

ELSE IF(@rType ='FeeStatusPendingSubPartDetails')
BEGIN 
CREATE TABLE #tempPendingSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
)

IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPendingSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And ISNULL(O.IsObsolete,0) = 0
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
		select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
			ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPendingSubPartDetails T
		WHERE T.PendingAmount >0
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempPendingSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 And ISNULL(O.IsObsolete,0) = 0
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

		select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPendingSubPartDetails T
		WHERE T.PendingAmount >0
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.RollNo
		
		 
	END
	
	DROP TABLE #tempPendingSubPartDetails
	 
END	
	
ELSE IF(@rType ='FeeStatusTotalSubPartAmount')
BEGIN 
CREATE TABLE #tempTotalSubPart (
AcademicId bigint,
OrgGroupId int,
OrgGroupName nvarchar(50),
ClassId bigint,
ClassName nvarchar(50),
--DivisionId bigint,
--DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
ClassOrderIndex int
--,DivisionOrder int
)

IF(@rCollectionGroupId = 0)
	BEGIN

	INSERT INTO #tempTotalSubPart
	SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		SA.OrgId AS OrgGroupId,
		SA.OrganizationName AS OrgGroupName,
		SA.ClassId AS ClassId,
		SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE 
		   ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId=0))

	GROUP by SA.OrgId,SA.OrganizationName, SA.ClassId,SA.ClassName--,SA.DivisionName
		,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex--,SA.DivisionOrder
	

	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from #tempTotalSubPart T
	group by T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName,T.CollectionGroupId,T.ReceiptBookId
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		
	END 
	ELSE 
	BEGIN
	
	INSERT INTO #tempTotalSubPart
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		  SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex--,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE 
		   ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			And ISNULL(O.IsObsolete,0) = 0
			AND ((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId=0))

	GROUP by SA.OrgId,SA.OrganizationName,SA.ClassId,SA.ClassName--,SA.DivisionName
		,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex--,SA.DivisionOrder

		 
	SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from #tempTotalSubPart T
	GROUP BY T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName--,T.ClassOrderIndex,T.DivisionOrder
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		--ORDER BY T.ClassOrderIndex,T.DivisionOrder
		
	END
	
	DROP TABLE #tempTotalSubPart
	
  END	
ELSE IF(@rType ='FeeStatusTotalSubPartDetails')
BEGIN 
CREATE TABLE #tempTotalSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
)

 
IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempTotalSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND  ISNULL(CGM.Id,0)=0
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 And ISNULL(O.IsObsolete,0) = 0
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempTotalSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
	ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempTotalSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And ISNULL(O.IsObsolete,0) = 0
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempTotalSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId--,T.ClassOrderIndex,T.DivisionOrder 
	HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
	ORDER BY T.RollNo
		
	 
	END
	
	DROP TABLE #tempTotalSubPartDetails
	
END
  
ELSE IF(@rType ='FeeStatusPaidSubPartDetails')
BEGIN 
CREATE TABLE #tempPaidSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
)

 
IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPaidSubPartDetails
	SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND  ISNULL(CGM.Id,0)=0
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And ISNULL(O.IsObsolete,0) = 0
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetails T
	group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
	HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
	ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	insert into #tempPaidSubPartDetails
	SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(FAS.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(FAS.ToPayAmount,0.00))AS PendingAmount,
		SA.RollNo
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId = SA.AcademicId
		INNER JOIN sFee.tFeeSetup FS ON FAS.FeeSetupId = FS.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId 
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	 AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	 And ISNULL(O.IsObsolete,0) = 0
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetails T
		
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
		
	END
	
	DROP TABLE #tempPaidSubPartDetails
END

ELSE IF(@rType ='FeeStatusPaidSubPartDetailsMonthWise')
BEGIN 
CREATE TABLE #tempPaidSubPartDetailsMonthWise(
AcademicId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,0),
PendingAmount DECIMAL(12,0),
RollNo int
)

CREATE TABLE #tempDFSMonthWise(
     Id INT,
     Amount DECIMAL(12,0),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

)

INSERT INTO #tempDFSMonthWise
	 SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And ISNULL(O.IsObsolete,0) = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
	   (FS1.IsOptional=1) --AND BM.IsActive=1 
	   AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And ISNULL(O.IsObsolete,0) = 0
	   --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
	    --AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
	    --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
		


CREATE TABLE #tempDRMonthWise(
       PaidAmount DECIMAL(12,0),
	   FeeSetupId INT,
	   SourceId BIGINT,
	   ReceiptDate DATE
)
INSERT INTO #tempDRMonthWise
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
		,R.ReceiptDate
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
	WHERE		
		(R.SourceTypeId = 2001) 
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And ISNULL(O.IsObsolete,0) = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate     
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate



IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPaidSubPartDetailsMonthWise
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise TDFS ON TDFS.AcademicId=SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDRMonthWise TDR ON TDR.FeeSetupId = TDFS.Id AND SA.AcademicId = TDR.SourceId
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	AND((DATEPART(M, TDR.ReceiptDate)  =@rMonth)OR(@rMonth=0))
	And ISNULL(O.IsObsolete,0) = 0
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetailsMonthWise T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempDFSMonthWise1(
     Id INT,
     Amount DECIMAL(12,0),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT  

    )
    
    INSERT INTO #tempDFSMonthWise1
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And ISNULL(O.IsObsolete,0) = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And ISNULL(O.IsObsolete,0) = 0
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	
CREATE TABLE #tempDRMonthWise1(
       PaidAmount DECIMAL(12,0),
	   FeeSetupId INT,
	   SourceId BIGINT,
	   ReceiptDate DATE
)
INSERT INTO #tempDRMonthWise1
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId,
		R.ReceiptDate
	FROM
		sFee.tReceipt R 
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId 
		INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		And ISNULL(O.IsObsolete,0) = 0
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
	
	
	
	insert into #tempPaidSubPartDetailsMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR1.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise1 TDFS1 ON TDFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDRMonthWise TDR1 ON TDR1.FeeSetupId = TDFS1.Id AND SA.AcademicId = TDR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
	    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
	    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND((DATEPART(M, TDR1.ReceiptDate)  =@rMonth)OR(@rMonth=0))
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	And ISNULL(O.IsObsolete,0) = 0
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetailsMonthWise T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName
		--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
		
		DROP TABLE #tempDFSMonthWise1
	DROP TABLE #tempDRMonthWise1
	END
	
	DROP TABLE #tempPaidSubPartDetailsMonthWise
	DROP TABLE #tempDFSMonthWise
	DROP TABLE #tempDRMonthWise
	
	
	
END

ELSE IF(@rType='ReceiptOrganization')
  BEGIN
	IF(@rSyncDate =1)
		BEGIN
				DELETE  sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				CREATE TABLE #tempReceiptOrganizationSync(
				OrgGroupId int,
				OrgGroupName nvarchar(500),
				ReceiptId bigint,
				TotalReceiptAmount DECIMAL(12,0),
				IsObsolete bit
				)
				INSERT INTO #tempReceiptOrganizationSync
				SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,R.Id AS ReceiptCount,R.ReceiptAmount,R.IsObsolete
				FROM  sFee.tReceipt R
				INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
				INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
				WHERE R.SourceTypeId = 2001
				AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND (COGBM.Id=@rCommonOrgGroupBatchId )
				And ISNULL(O.IsObsolete,0) = 0 
				AND (R.ReceiptDate between @rFromDate and @rToDate)    
			
			INSERT INTO sFee.tTempReceiptOrganization
				SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate() FROM #tempReceiptOrganizationSync T  
				LEFT JOIN (
				SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganizationSync WHERE IsObsolete = 1
				GROUP BY OrgGroupId,OrgGroupName
				) A ON A.OrgGroupId=t.OrgGroupId
				WHERE IsObsolete = 0
				GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
				ORDER BY OrgGroupId
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				
				DROP TABLE #tempReceiptOrganizationSync
		END 
	ELSE
		BEGIN
			IF  Exists(select 1 from sFee.tTempReceiptOrganization where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND CONVERT(date,ReceiptDate) =@rFromDate AND CONVERT(date,ReceiptDate) =@rToDate )
			BEGIN
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
	ELSE
			BEGIN 
			DELETE  sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				CREATE TABLE #tempReceiptOrganization(
				OrgGroupId int,
				OrgGroupName nvarchar(500),
				ReceiptId bigint,
				TotalReceiptAmount DECIMAL(12,0),
				IsObsolete bit
				)
				INSERT INTO #tempReceiptOrganization
				SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,R.Id AS ReceiptCount,R.TotalReceiptAmount,R.IsObsolete
				FROM  sFee.tReceipt R
				INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
				INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
				WHERE R.SourceTypeId = 2001
				AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND (COGBM.Id=@rCommonOrgGroupBatchId ) 
				AND (R.ReceiptDate between @rFromDate and @rToDate)    
			
				INSERT INTO sFee.tTempReceiptOrganization
				SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate() FROM #tempReceiptOrganization T  
				LEFT JOIN (
				SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganization WHERE IsObsolete = 1
				GROUP BY OrgGroupId,OrgGroupName
				) A ON A.OrgGroupId=t.OrgGroupId
				WHERE IsObsolete = 0
				GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
				ORDER BY OrgGroupId
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DROP TABLE #tempReceiptOrganization
			END
		END
  END
ELSE IF(@rType='ReceiptBookCollectionGroup')
  BEGIN
	CREATE TABLE #tempReceiptBookCollection (
	RecepitTitle nvarchar(200),
	--CollectionTitle nvarchar(200),
	ReceiptCount int,
	ReceiptAmount DECIMAL(12,0),
	ReceiptId bigint,
	--CollectionGroupId bigint,
	IsObsolete bit
)

INSERT INTO #tempReceiptBookCollection
 SELECT ISNULL(RBM.Title,'')  AS RecepitTitle ,
			--ISNULL(CGM.Code,'') AS CollectionTitle,
			ISNULL(COUNT(DISTINCT R.Id),0) AS ReceiptCount,CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
			ISNULL(RBM.Id,0) AS ReceiptId,
			--ISNULL(CGM.Id,0) AS CollectionGroupId,
			R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					
			INNER JOIN  sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id 			
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId 
			AND FS.AdmissionCategoryId=SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			
			--LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id 
			--AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND (R.IsObsolete = 1) 
			--AND(BM.IsActive =1) 
			AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))AND R.ReceiptDate between @rFromDate and @rToDate 
			And ISNULL(O.IsObsolete,0) = 0   
			GROUP BY RBM.Title,RBM.Id,R.ReceiptBookId,R.IsObsolete,R.Id,R.ReceiptAmount
			
			--SELECT  TRC.RecepitTitle +'-'+ TRC.CollectionTitle AS ReceictCollection,TRC.ReceiptId AS ReceiptId,TRC.CollectionGroupId AS CollectionGroupId,ISNULL(COUNT(TRC.ReceiptCount),0) AS ReceiptCount,SUM(ReceiptAmount) AS ReceiptAmount ,
			--ISNULL(A.CancelReceiptCount,0)AS CancelAmount FROM #tempReceiptBookCollection TRC 
			--LEFT JOIN (
			--SELECT ReceiptId,CollectionGroupId,SUM(ReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptBookCollection WHERE IsObsolete = 1
			--GROUP BY ReceiptId,CollectionGroupId
			--) A ON A.ReceiptId=TRC.ReceiptId AND A.CollectionGroupId=TRC.CollectionGroupId
			
			--WHERE IsObsolete = 0
			--GROUP BY TRC.RecepitTitle,TRC.CollectionTitle,A.ReceiptId,A.CancelReceiptCount,TRC.ReceiptId,TRC.CollectionGroupId,TRC.ReceiptCount 

			SELECT  TRC.RecepitTitle AS ReceictCollection,TRC.ReceiptId AS ReceiptId,0 AS CollectionGroupId,ISNULL(COUNT(TRC.ReceiptCount),0) AS ReceiptCount,SUM(ReceiptAmount) AS ReceiptAmount ,
			ISNULL(A.CancelReceiptCount,0)AS CancelAmount FROM #tempReceiptBookCollection TRC 
			LEFT JOIN (
			SELECT ReceiptId,SUM(ReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptBookCollection WHERE IsObsolete = 1
			GROUP BY ReceiptId
			) A ON A.ReceiptId=TRC.ReceiptId
			
			WHERE IsObsolete = 0
			GROUP BY TRC.RecepitTitle,A.ReceiptId,A.CancelReceiptCount,TRC.ReceiptId,TRC.ReceiptCount 
		DROP TABLE #tempReceiptBookCollection
  END
ELSE IF(@rType='ReceiptBookCollectionGroupDetail')
  BEGIN
  CREATE TABLE #tempReceiptBookCollectionDetail(
  SourceId bigint,
Code nvarchar(200),
Name nvarchar(200),
ReceiptNumber bigint,
ReceiptAmount DECIMAL(12,0),
ReceiptId bigint,
IsObsolete bit
)
  
	INSERT INTO #tempReceiptBookCollectionDetail
 SELECT ISNULL(SA.Id,0) AS SourceId,SM.Code AS Code,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) As Name,R.ReceiptNumber AS ReceiptNumber,CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,R.Id AS ReceiptId,R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
			INNER JOIN sStudent.tStudentMaster SM1 ON SA.StudentId = SM1.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		    INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
		    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
			INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId=SM.Id	
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.AdmissionCategoryId =  SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND (R.IsObsolete = 0) 
			--AND(BM.IsActive =1) 
			And ISNULL(O.IsObsolete,0) = 0			
			AND COGBM.Id=@rCommonOrgGroupBatchId AND R.ReceiptDate between @rFromDate and @rToDate     
			GROUP BY SA.Id,SM.Code,R.ReceiptNumber,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId), R.ReceiptBookId,R.Id,R.IsObsolete,R.ReceiptAmount 
			--ORDER BY 
	 
  SELECT *  FROM #tempReceiptBookCollectionDetail ORDER BY ReceiptNumber
  
  DROP TABLE #tempReceiptBookCollectionDetail
  END
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


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

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


GO
 

 
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
						
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date='',
			@rClassId int = 0,
			@rOrgIds nvarchar(max) = '',
			@rReceiptPrintGroupId nvarchar(100)=''
	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,
			
			--changes by Jash on 06/11/2020--%
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),ISNULL(FR.PaymentTransactionId,''))  END AS ChequeNo,
			--CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo
			--	WHEN ISNULL(PT.BankTransactionId,'') = '' THEN  CONVERT(nvarchar(20),FR.PaymentTransactionId)
			--	ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) +' - '+ CONVERT(nvarchar(20),PT.BankTransactionId) END AS ChequeNo,
			--%


			--ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,			
			
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN @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,
			(CASE WHEN  U.SourceTypeId = 2003 
			  THEN -- Navrachana
				'Online Generated'
				ELSE ISNULL(U.DisplayTitle,'') END) AS UserName,
			--ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0  THEN 
			--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	
				  
			  
			(CASE WHEN  RBM.ReportId = 20576
			      THEN -- HM patel report
				  [sFee].[fReceiptMonthDetailGet](FR.ID,0)
			      WHEN RBM.ReportId = 30457 
			      THEN
				  [sFee].[fReceiptMonthDetailGet](FR.ID,1)		
			      WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
				  [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Head wise Month name in detail
				  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN				
				  [sFee].[fFeeMonthNameGet](FR.ID,FM.Id) -- Fee wise Month name in detail
			ELSE '' END) 
			AS MonthDetail,    

			
			(CASE WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
					 Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
					sFee.tReceipt FR1				
					INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
					INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
					INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
					INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
					Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					Order By FS1.StartDate
					FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' )    -- Fee Head wise Fee Duration
				  WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN
					FS.FeeDuration -- Fee wise Fee Duration
				 ELSE '' END) AS FeeDuration,
			
			--Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
			--sFee.tReceipt FR1				
			--INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
			--INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
			--INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
			--INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
			--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
			----Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			-- Order By FS.StartDate
			--FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' ) AS FeeDuration,
			
			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN  FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN  FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
	        ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue ,
	        SF.FatherName,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,

			(ISNULL((CASE WHEN SC.PresentStreetOne IS NOT NULL AND SC.PresentStreetOne!='' THEN ''+ SC.PresentStreetOne END),'')+
			ISNULL((CASE WHEN SC.PresentStreetTwo IS NOT NULL AND SC.PresentStreetTwo!=''  THEN ', '+ SC.PresentStreetTwo END),'')+
			ISNULL((CASE WHEN SC.PresentStreetThree IS NOT NULL AND SC.PresentStreetThree!=''  THEN ', '+ SC.PresentStreetThree END),'')+
			ISNULL((CASE WHEN SC.PresentCity IS NOT NULL AND SC.PresentCity!=''  THEN ', ' + SC.PresentCity  END),'')+
			ISNULL((CASE WHEN SC.PresentState IS NOT NULL AND SC.PresentState!=''  THEN  ', '+ SC.PresentState END),'')+
			ISNULL((CASE WHEN SC.PresentZipCode IS NOT NULL AND SC.PresentZipCode!=''  THEN  ', '+ SC.PresentZipCode  END),''))
			 AS PresentAdress,
			--ISNULL(SC.PresentStreetOne +','+ SC.PresentStreetTwo +','+ SC.PresentStreetThree +','+ SC.PresentCity +','+ SC.PresentState +'-'+ SC.PresentZipCode ,'') AS PresentAdress,
			SC.ParentContactNo,
			ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount,
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,0),0) END) AS PendingFeeAmount,
			SA.FirstName,
			SA.LastName,
			ISNULL([sFee].[fFeeAmountSumGet](FR.SourceId),0) AS FeeAmount,
			ISNULL([sFee].[fFeeReceiptDiscountSumGet](FR.SourceId),0) AS ExemptionAmountSum,
			[sFee].[fTransportBusRouteGet](SA.StudentId,FR.OrgGroupBatchId) AS TransportBusRoute,
			ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber
	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptListGet]...';


GO
 
ALTER PROCEDURE [sFee].[pRptFeeReceiptListGet]  
  @rReportId int=0,  
  @rReceiptBookId int=0,  
  @rAdmissionCategoryId int=0,  
  @rClassId int=0,  
  @rDivisionId int=0,  
  @rFromDate date='',  
  @rToDate date='',  
  @rFromReceiptNo int=0,  
  @rToReceiptNo int=0,  
  @rBatchId int,  
  @rUserId bigint=0,  
  @rBuilder1 nvarchar(max)=0,  
  @rBuilder2 nvarchar(max)=0,  
  @rIsDetail bit=0,  
  @rIsCancel bit=0,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int=0,  
  @rPaytypeId int=0,  
  @rCommonBatch nvarchar(100)='',  
  @rDepartmentId int=0,  
  @rFromRollNo int=0,  
     @rToRollNo int=0,  
     @rCode nvarchar(20),  
     @rIsFilter bit=0,  
     @rIsHeader bit=0,  
     @rCreatedUserName nvarchar(100)='',  
     @rFeeHeadId nvarchar(max) = '',  
     @rIsDisplayOrgGroup bit=0,  
     @rIsDiscount bit = 0,  
     @rFeeId nvarchar(max) = '',  
     @rFilterId int=0,  
     @rCustomGroupId smallint = 0,  
     @rOrgGroupId int=0,  
     @rFeeStatusId int=0,  
     @rFromChequeDate date='',      
  @rToChequeDate date='',      
     @rBankName nvarchar(100)='',  
     @rOrgIds nvarchar(max) = '',  
     @rBankNames nvarchar(max) = '',  
  
  @rFromChequeClearDate Date = '',  
  @rToChequeClearDate Date = '' ,
  @rClassStatusId int=0 ,
  @rPayTypeIds nvarchar(max) = '',
  @rUserAcessUserId bigint = 0,
  @rReceiptBookIds nvarchar(max) = ''
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   
  BEGIN      
  SET @rBankName = sCommon.fSearchStringGet(@rBankName)      
    END   
  IF(@rReportId=10138 OR @rReportId=20547 OR @rReportId=20456)
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate ,
		   SA.GenderId
		  FROM   
		   sFee.tReceipt R  
		  --INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  --INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  --INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
    
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 

		  --According UserAccess
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id =SA.OrgId
		  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND OM.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  

		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  
		  --According UserAccess
		  INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=RBM.Id AND UA.SourceTypeId=2013 AND RBM.IsObsolete=0 AND UA.UserId =@rUserAcessUserId 


		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  AND (  
		  (@rFilterId = 0) -- All  
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
			AND ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')
		 AND (ISNULL(R.ReceiptBookId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
  
		 ORDER BY R.ReceiptNumber
	END
	ELSE
	BEGIN
		SELECT   
		  @rBuilder1 AS Builder1,  
		  @rBuilder2 AS Builder2,  
		  @rIsDetail AS IsDetail,  
		  (CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
		  --@rIsCancel AS IsCancel,  
		  @rIsFilter As IsFilter,  
		  @rIsHeader As IsHeader,  
		  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		  R.Id AS ReceiptId,  
		  R.ReceiptNumber,  
		  SA.ClassId,  
		  --SA.ClassName,  
		  SA.DivisionId,  
		  --SA.DivisionName,  
		  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
		  SA.RollNo,  
		  SA.Code,  
		  SA.Name,  
		  ISNULL(PTM.Title,'') AS PayType,  
		  --ISNULL(R.ChequeNo,'') AS ChequeNo,  
		  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
		  ISNULL(R.BankName,'') AS BankName,  
		  R.ReceiptAmount,  
		  --R.ReceiptDate,  
		  CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
		  R.CreatedUserId,  
		  ISNULL(U.LoginTitle,'') AS UserName,  
		  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
		  ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
		  ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
		  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
		  ISNULL((CASE @rReportId WHEN 20461 THEN [sFee].[fReceiptFeeDetailGet](R.Id)  
		   WHEN 30940 THEN [sFee].[fReceiptFeeDetailGet](R.Id) ELSE '' END),'') AS FeeDetail,  
		   R.Remark,  
		   R.DiscountAmount,  
		   ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
		   SA.OrgId,  
		   SA.OrganizationName,  
		   ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
		   ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
		   ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
		   ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
		   ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
		   @rCustomGroupId AS CustomGroupId,  
		   SA.OrgGroupBatchId AS BatchId,  
		   SA.BatchName,  
		   R.ChequeDate,  
		   R.ChequeClearDate   
		  FROM   
		   sFee.tReceipt R  
		  --INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		  --INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
		  --INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
    
		  INNER JOIN sStudent.vStudentAcademic SA  
		   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
		   ON PTM.Id=R.PayTypeId  
		  INNER JOIN sFee.tReceiptBookMaster RBM   
		   ON RBM.Id=R.ReceiptBookId  
		  LEFT JOIN sSecurity.tUser U  
		   ON U.Id=R.CreatedUserId  
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
			LEFT JOIN  
		 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
			ON RT.SourceId = SA.StudentId   
			AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
			AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId)  
		WHERE   
		 R.SourceTypeId = 2001  
		 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
		 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
		 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
		 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
		 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
		 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
		 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
		 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
		 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
		 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
		 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
		 AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
		  ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
		  OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
		  OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
		  )))  
		 AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
		 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
		 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
		 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
		 AND ((SA.Code=@rCode) OR (@rCode=''))  
		 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
		 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
		 AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
		  AND (  
		  (@rFilterId = 0) -- All  
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
			)  
			AND ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
		 AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
		 AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
		 AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
		 AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
		 AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
		 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')    		 
  
		 ORDER BY R.ReceiptNumber  
	END
 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END
GO
PRINT N'Altering [sHrm].[pLeaveAdd]...';


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

BEGIN

IF EXISTS (SELECT 1 FROM  sHrm.tLeaveTypeMaster WHERE Id = @rLeaveTypeId AND isLwp = 0)
BEGIN
   DECLARE @lMainLeaveTypeId tinyint
   SET @lMainLeaveTypeId =0
   SELECT @lMainLeaveTypeId = ISNULL(MainLeaveTypeId,0) FROM sHrm.tLeaveTypeMaster WHERE Id = @rLeaveTypeId
   
   DECLARE @lMaxInMonth decimal(5,2)
   DECLARE @lNumberOfLeave decimal(5,2)
   SET @lMaxInMonth =0
   SET @lNumberOfLeave =0
   
   DECLARE @lFirstDate date
   DECLARE @lLastDate date
   
   SET @lFirstDate = DATEADD(mm, DATEDIFF(mm, 0, @rFromDate), 0)
   SET @lLastDate = DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, @rFromDate) + 1, 0))

   
   
   SELECT @lMaxInMonth = ISNULL(LB.MaxInMonth,0) FROM sHrm.tEmployeeJobDetail EJD 
   INNER JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EJD.EmployeeId AND LB.BatchId = @rBatchId
   WHERE EJD.OrgId = @rOrgId AND LB.LeaveTypeId=@rLeaveTypeId AND EJD.EmployeeId=@rEmployeeId
   
   -- For Employee Specific 08/11/2017 - by Ramesh Gurjar
   IF(@lMaxInMonth=0)
   BEGIN
		SELECT @lMaxInMonth = ISNULL(LTGS.MaxInMonth,0) FROM sHrm.tEmployeeJobDetail EJD 
		INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON EJD.EmployeeGradeId=LTGS.EmployeeGradeId 
		WHERE LTGS.OrgId = @rOrgId 
		AND LTGS.LeaveTypeId=@rLeaveTypeId 
		AND  EJD.EmployeeId=@rEmployeeId
   END
   -- End
   
   SELECT  @lNumberOfLeave= ISNULL(SUM(L.NoOfLeave),0) 
   FROM     
   sHrm.tLeave L  
   WHERE  
   L.EmployeeId=@rEmployeeId 
   AND (L.FromDate>=@lFirstDate) AND (L.FromDate<=@lLastDate)
   AND L.LeaveTypeId=@rLeaveTypeId AND L.StatusId = 550
   GROUP BY L.EmployeeId

 
			 --IF (@lMaxInMonth < (@lNumberOfLeave+@rNoOfLeave) AND @lMainLeaveTypeId!=3)  -- comment due to validate at page side
				--BEGIN
				--	SELECT -105  AS RESULT
				--	RETURN
				--END
		
  END
     
   DECLARE @1Leave int
    
	BEGIN TRY
	
	BEGIN TRANSACTION

	DECLARE @lNextNumber bigint
	 
    IF (@rId = 0)
     BEGIN
       
       IF(@rLeavePeriodId = 2) --For Half Leave	  	
       SELECT @1Leave = SUM(NoOfLeave) from sHrm.tLeave where EmployeeId = @rEmployeeId AND OrgId = @rOrgId AND FromDate = @rFromDate 
       ELSE
         SET @1Leave = 1
     		
	   IF NOT EXISTS(SELECT 1 FROM sHrm.tLeave WHERE EmployeeId = @rEmployeeId 
	   AND(( FromDate  BETWEEN @rFromDate AND @rToDate) OR (ToDate BETWEEN @rFromDate AND @rToDate)
	   OR (@rFromDate  BETWEEN FromDate AND ToDate) OR (@rToDate BETWEEN FromDate AND ToDate)) AND OrgId = @rOrgId AND BatchId = @rBatchId AND StatusId!=551)-- OR @1Leave != 1
	   BEGIN
	    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tLeave', 0, 1, 1,@outNextNumber = @lNextNumber output	
	    
		  INSERT INTO [sHrm].[tLeave]
           (
            [Id]
           ,[EmployeeId]
           ,[ReportDate]
           ,[FromDate]
           ,[ToDate]
           ,[LeavePeriodId]
           ,[LeaveTypeId]
           ,[LeaveReason]
           ,NoOfLeave
           ,BatchId
           ,[OrgId]           
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[StatusId]
           ,[FromTime]
           ,[ToTime]
           )
     VALUES
           (
            @lNextNumber
           ,@rEmployeeId 
           ,@rReportDate 
           ,@rFromDate 
           ,@rToDate 
           ,@rLeavePeriodId 
           ,@rLeaveTypeId 
           ,@rLeaveReson 
           ,@rNoOfLeave
           ,@rBatchId
           ,@rOrgId 
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rCreatedUserId 
           ,sCommon.fGetDate()
           ,@rStatusId       
           ,@rFromTime
           ,@rToTime      
           )
            END
          ELSE
            SET @lNextNumber = -101            
          END
	ELSE
	BEGIN
	SET @lNextNumber = @rId
		UPDATE sHrm.tLeave
		SET 	 
		   [EmployeeId]= @rEmployeeId 
		  ,[ReportDate]= @rReportDate 
		  ,[FromDate]= @rFromDate 
		  ,[ToDate]= @rToDate 
		  ,[LeavePeriodId]= @rLeavePeriodId 
		  ,[LeaveTypeId]= @rLeaveTypeId 
		  ,[LeaveReason]= @rLeaveReson 
		  ,NoOfLeave = @rNoOfLeave
		  ,[OrgId]= @rOrgId        
		  ,[UpdatedUserId]= @rCreatedUserId
		  ,[UpdatedDateTime]= sCommon.fGetDate()
		  ,[FromTime] = @rFromTime
          ,[ToTime] = @rToTime    
		WHERE Id = @rId
	 END 
	   SELECT @lNextNumber AS Result	   
	   COMMIT TRANSACTION
	   		
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Altering [sRecruitment].[pCandidateApplicationConfirmGet]...';


GO
ALTER PROCEDURE [sRecruitment].[pCandidateApplicationConfirmGet]
	 @rCandidateId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
	CM.OrgGroupID,
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				iSNULL(CM.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(CM.DataEntryStatusId,0) as DataEntryStatusId,
			CM.ApplicationNumber,
			CM.ApplicationPassword,
			GM.Title AS Gender,
			RM.Title AS ReligionName,
			CCM.Title AS CastCategoryName,
			CC.PresentStreetOne,
			CC.PresentStreetTwo,
			CC.PresentStreetThree,
			CC.PresentCountry,
			CC.PresentState,
			CC.PresentCity,
			CC.PresentZipCode,
			CC.PresentContactNo,
			CC.PermanentStreetOne,
			CC.PermanentStreetTwo,
			CC.PermanentStreetThree,
			CC.PermanentCountry,
			CC.PermanentState,
			CC.PermanentCity,
			CC.PermanentZipCode,
			CC.PermanentContactNo,
			CI.CandidatePhoto,
			MS.Title AS MaritalStatus,
			CM.LastDrawnSalary,
			CM.ExpectedSalary,
			VM.ConfirmationRemark,
			ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
			ISNULL(DM.Title,'') AS Reference,
			ISNULL(CM.MainSubject,'') AS MainSubject,
			ISNULL(OM.Title,'') AS Organization
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			LEFT JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId 
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId 
			LEFT JOIN sRecruitment.tCandidateCommunications	 CC ON 	CC.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tCandidateImages	CI ON CI.CandidateId=CM.Id	
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id=CM.MaritalStatusId	 		 	
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id  = CM.ReferenceId
			AND DM.DataTypeId = 13
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId

  WHERE 
  
      ((CM.Id = @rCandidateId) OR (@rCandidateId = 0))
       
 
END
GO
PRINT N'Altering [sRecruitment].[pCandidateApplicationGet]...';


GO
ALTER PROCEDURE [sRecruitment].[pCandidateApplicationGet]
	@rCandidateId bigint= 0,
	@rApplicationNumber int	,
	@rOrgGroupID smallint
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
				CM.OrgGroupID,
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				iSNULL(CM.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(CM.DataEntryStatusId,0) as DataEntryStatusId,
			CM.ApplicationNumber,
			CM.ApplicationPassword,
			CM.LastDrawnSalary,
			CM.ExpectedSalary,
			ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
			ISNULL(CM.ReferenceId,0)AS ReferenceId,
			ISNULL(CM.MainSubject,'')AS MainSubject,
			ISNULL(CM.OrgId,0) AS OrgId
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId							
		WHERE 
				 CM.OrgGroupID = @rOrgGroupID
		   AND ((CM.Id = @rCandidateId) OR (@rCandidateId = 0))
		   AND ((CM.ApplicationNumber =@rApplicationNumber ) OR (@rApplicationNumber = 0))
		 
 
       
 order by CM.ApplicationNumber
END
GO
PRINT N'Altering [sRecruitment].[pCandidateMasterGet]...';


GO
ALTER PROCEDURE [sRecruitment].[pCandidateMasterGet]
(
		@rOrgGroupID smallint, 
		@rCandidateNumber int=0,		
	@rId [bigint] = 0,
	@rVacancyId int=0
		
	
 )
AS
SET NOCOUNT ON

BEGIN

		
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				CM.LastDrawnSalary,
				CM.ExpectedSalary,
				ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
				ISNULL(CM.ReferenceId,0) AS ReferenceId,
				ISNULL(CM.MainSubject,'')AS MainSubject,
				ISNULL(CM.OrgId,0) AS OrgId
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
						
		WHERE 
				 CM.OrgGroupID = @rOrgGroupID
		   AND ((CM.Id = @rId) OR (@rId = 0))
		   AND ((CM.CandidateNumber =@rCandidateNumber ) OR (@rCandidateNumber = 0))
		   AND ((CM.VacancyId =@rVacancyId ) OR (@rVacancyId = 0))
END
GO
PRINT N'Altering [sRecruitment].[pRptCandidateApplicationGet]...';


GO
 
ALTER PROCEDURE [sRecruitment].[pRptCandidateApplicationGet]
	 @rCandidateId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
	convert(nvarchar(20),@rCandidateId) AS CandidateIdText,
	CM.OrgGroupID,
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				CM.GenderId,
				CM.MaritalStatusId,
				CM.ReligionId,
				CM.CastCategoryId,
				CM.FamilyCast,
				CM.Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				iSNULL(CM.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(CM.DataEntryStatusId,0) as DataEntryStatusId,
			CM.ApplicationNumber,
			CM.ApplicationPassword,
			GM.Title AS Gender,
			RM.Title AS ReligionName,
			CCM.Title AS CastCategoryName,
			CC.PresentStreetOne,
			CC.PresentStreetTwo,
			CC.PresentStreetThree,
			CC.PresentCountry,
			CC.PresentState,
			CC.PresentCity,
			CC.PresentZipCode,
			CC.PresentContactNo,
			CC.PermanentStreetOne,
			CC.PermanentStreetTwo,
			CC.PermanentStreetThree,
			CC.PermanentCountry,
			CC.PermanentState,
			CC.PermanentCity,
			CC.PermanentZipCode,
			CC.PermanentContactNo,
			CI.CandidatePhoto,
			MS.Title AS MaritalStatus,
			CM.LastDrawnSalary,
			CM.ExpectedSalary,
			CM.CreatedDateTime,
			ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
			ISNULL(DM.Title,'') AS Reference,
			ISNULL(CM.MainSubject,'') AS MainSubject,
			ISNULL(OM.Title,'') AS Organization
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			LEFT JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId 
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId 
			LEFT JOIN sRecruitment.tCandidateCommunications	 CC ON 	CC.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tCandidateImages	CI ON CI.CandidateId=CM.Id	
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id=CM.MaritalStatusId	 	
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id  = CM.ReferenceId
			AND DM.DataTypeId = 13
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
		
  WHERE 
  
      ((CM.Id = @rCandidateId) OR (@rCandidateId = 0))
       
 
END
GO
PRINT N'Altering [sSecurity].[pAppPermissionGet]...';


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

	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard 
			20097, -- View Query
			30249, -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786, --Online Learning 
			30787, --Online learning Student View
			30815, --Consolidate - Fee Status
			30813, --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,   -- Consolidate - Admission Inquiry Summary,
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App 
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947    -- CW/HW Data Search
			)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard
			20097, -- View Query
			30249,  -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786 , --Online Learning 
			30787,  --Online learning Student View
			30815,  --Consolidate - Fee Status
			30813,  --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,  -- Consolidate - Admission Inquiry Summary
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947    -- CW/HW Data Search
			) 
		) TP 
		GROUP BY TP.TaskId
	END
END
GO
PRINT N'Altering [sWorkflow].[pApprovalRequestGet]...';


GO
ALTER  PROCEDURE [sWorkflow].[pApprovalRequestGet]
			@rWorkflowFunctionalityId bigint=0,
			 @rFromDate date=null,
			 @rToDate date=null,
			 @rStatusId int=0,
			 @rCode nvarchar(200) =''
			 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
		SELECT
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			--CASE WHEN ParticipantSourceTypeId= 1019 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 2015 THEN EM.Id END AS SourceId,
			--CASE WHEN ParticipantSourceTypeId= 1019 THEN SA.Code WHEN ParticipantSourceTypeId= 2015 THEN EM.Code END AS Code ,
			--CASE WHEN ParticipantSourceTypeId= 1019 THEN SA.Name WHEN ParticipantSourceTypeId= 2015 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		WHERE ((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId =0)) 
			AND ((AR.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
			AND ((AR.CreatedDateTime <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
			AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
			AND (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
END
GO
PRINT N'Altering [sWorkflow].[pPopUpStatusGet]...';


GO
ALTER  PROCEDURE [sWorkflow].[pPopUpStatusGet]
			 @rCode nvarchar(50) =0,
			 @rStatusId int=0,
			 @rParticipantSourceId bigint = 0
			 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
			SELECT 

			ADM.Title AS DepartmentTitle,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.CreatedDateTime AS CreatedDateTime,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status
			--(select Title from sWorkflow.tActionStatusMaster WHERE Id=3) AS Status 
			--CASE WHEN @rStatusId= 0 THEN (select Top 1 Title from sWorkflow.tActionStatusMaster WHERE Id=3) WHEN ASM.Id = @rStatusId THEN ASM.Title  END AS Status
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
			INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
			INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId
			LEFT JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
		WHERE  (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode =0)))
		AND((ASM.Id = @rStatusId) OR (@rStatusId =0)) 
		AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
		AND ISNULL(EM.IsOtherUser,0) = 0

		UNION 

		SELECT 

			ADM.Title AS DepartmentTitle,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.CreatedDateTime AS CreatedDateTime,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status
			--(select Title from sWorkflow.tActionStatusMaster WHERE Id=3) AS Status 
			--CASE WHEN @rStatusId= 0 THEN (select Top 1 Title from sWorkflow.tActionStatusMaster WHERE Id=3) WHEN ASM.Id = @rStatusId THEN ASM.Title  END AS Status
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
			INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
			INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId
			LEFT JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
		WHERE  (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode =0)))
		AND((ASM.Id = @rStatusId) OR (@rStatusId =0)) 
		AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
		AND ISNULL(EM.IsOtherUser,0) = 0
	END
GO
PRINT N'Altering [sWorkflow].[pWorkflowQueuesGet]...';


GO
 
ALTER  PROCEDURE [sWorkflow].[pWorkflowQueuesGet]
			 @rWorkflowFunctionalityId bigint=0,
			 @rFromDate date=null,
			 @rToDate date=null,
			 @rStatusId int=0,
			 @rCode int =0,
			 @rDepartmentId int=0,
			 @rUserId bigint 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
Declare @lRoleId int
Select @lRoleId = RoleId from [sSecurity].[tUserRole] Where UserId = @rUserId
--Select @lRoleId
SELECT
	AA.Id AS ApprovalActionId,
	ADM.Id AS DepartmentId,
	WFM.Title AS WorkFlowName,
	WFM.Id AS WorkFlowId,
	AR.Id AS ApprovalRequestId,
	ADM.Title AS DepartmentTitle,
	CONVERT(DATE,AR.CreatedDateTime, 103) AS CreatedDateTime,
	AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
	AR.Remark AS Remark,
	(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
	(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status
			
		
from sWorkflow.tApprovalRequest AR
INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId
INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID
LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
WHERE R.Id = @lRoleId
AND ((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId =0)) 
AND ((Convert(Date,AR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
AND ((Convert(Date,AR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
AND (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode =0)))
AND((ADM.Id = @rDepartmentId) OR (@rDepartmentId =0))
AND  ISNULL(EM.IsOtherUser,0) = 0

UNION

SELECT
	AA.Id AS ApprovalActionId,
	ADM.Id AS DepartmentId,
	WFM.Title AS WorkFlowName,
	WFM.Id AS WorkFlowId,
	AR.Id AS ApprovalRequestId,
	ADM.Title AS DepartmentTitle,
	CONVERT(DATE,AR.CreatedDateTime, 103) AS CreatedDateTime,
	AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
	AR.Remark AS Remark,
	(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
	(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status
			
		
from sWorkflow.tApprovalRequest AR
INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId
INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2019
LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID
LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
WHERE U.Id = @rUserId
AND ((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId =0)) 
AND ((Convert(Date,AR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
AND ((Convert(Date,AR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
AND (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode =0)))
AND((ADM.Id = @rDepartmentId) OR (@rDepartmentId =0))
AND  ISNULL(EM.IsOtherUser,0) = 0
END
GO
PRINT N'Creating [sBiometric].[pRptManualPunchGet]...';


GO
 
 
CREATE PROCEDURE [sBiometric].[pRptManualPunchGet]    
             
   @rBuilder1 nvarchar(max)='',    
   @rBuilder2 nvarchar(max)='',    
   @rToDate date='',
   @rFromDate date='',
   @rEmployeeStatusId int=0,
   @rEmployeeId bigint = 0,
   @rOrganizationDepartmentId int = 0,
   @rLocationConfig nvarchar(50) = '',
   @rOrgId int = 0
       
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
BEGIN     
  Select 
  EM.Code AS EmployeeCode,    
   ISNULL(ECI.EmployeePhoto,0) AS EmployeePhoto,
   EM.FirstName+' ' +EM.MiddleName+' '+EM.LastName AS Name,    
   ISNULL(ECI.CheckInTime,'') AS CheckInTime,
   ISNULL(ECI.CheckOutTime,'') AS CheckOutTime,
   EM.ID As EmployeeID ,      
   @rBuilder1 AS Builder1,    
   @rBuilder2 AS Builder2,
   ISNULL(LatitudeAxis,'') AS Latitude,
   ISNULL(LongitudeAxis,'') AS Longitude,
   ISNULL(Location,'') AS Location,
   @rLocationConfig AS LocationConfig,
   CAST(ECI.AttendanceDate AS DATE) AS AttendanceDate
  FROM
	   sBiometric.tEmployeeCheckIn ECI      
	   INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = ECI.EmployeeId
	   LEFT JOIN sHrm.tEmployeeJobDetail ED ON ED.EmployeeId = EM.Id     
   WHERE 
	   (EM.Id = @rEmployeeId OR @rEmployeeId = 0) 
	   AND (CAST(ECI.AttendanceDate AS DATE) >= @rFromDate OR (ISNULL(@rFromDate,'')=''))
       AND (CAST(ECI.AttendanceDate AS DATE) <= @rToDate OR (ISNULL(@rToDate,'')=''))
	   AND EM.OrgId = @rOrgId
	   AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)
	   AND (ED.OrganizationDepartmentId =@rOrganizationDepartmentId Or @rOrganizationDepartmentId= 0 )	   
	   AND  ISNULL(EM.IsOtherUser,0) = 0	   	   
    
	ORDER BY ECI.AttendanceDate DESC
END
GO
PRINT N'Creating [sErp].[pCurrentStudentStrengthDetailGet]...';


GO
 
CREATE PROCEDURE [sErp].[pCurrentStudentStrengthDetailGet]
	 	 
		@rOrgGroupId smallint=0,
		@rOrgGroupBatchId bigint = 0,
		@rCommonOrgGroupBatchId int = 0,
		@rFlag int = 0
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

Declare @strStudentCount VarChar (MAX)
Declare @strEmployeeCount VarChar(MAX)
Declare @strFeeReceiptDate VarChar (MAX)
Declare @strExamStatusDate VarChar (MAX)
Declare @strBonafiesCertificateDate VarChar (MAX)
Declare @strLCCertificateDate VarChar (MAX)
Declare @strAttendanceDate VarChar (MAX)
Declare @strEmployeeDate VarChar (MAX)
Declare @strAlertDate VarChar (MAX)
DECLARE @strMobileUserCount varchar(MAX)
DECLARE @rstrStudentUser VARCHAR(MAX)
DECLARE @rstrEmployeeUser VARCHAR(MAX)
DECLARE @strAppModuleSummary VARCHAR(MAX)
DECLARE @strAppUserSummary VARCHAR(MAX)

--SET @strSQL = 'SELECT * FROM ' + @rDatabaseName+ '.sSetup.tOrgGroupSetting WHERE OrgGroupId = '+ convert (nvarchar,@rOrgGroupId)

			SET @strStudentCount =  'SELECT ISNULL(NoOfStudent,0) As NoOfStudent,ISNULL(StudentExtraCap,0) As StudentExtraCap FROM sSetup.tOrgGroupSetting OS'+
			+' WHERE '+ 
			+' OS.OrgGroupId ='+ convert (nvarchar,@rOrgGroupId)
			+' SELECT COUNT(SM.AcademicId) AS ActiveStudent FROM sStudent.vStudentAcademic SM '+ 
			--+'INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId '+
			--+'INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SM.BatchId  '+
			+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SM.OrgGroupBatchId'
			+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId'
			+' WHERE OGBM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+ ' and SM.StatusID=1 AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)
			--AND BM.IsActive = 1 
			+' SELECT COUNT(SM.AcademicId) as TotalStudent FROM sStudent.vStudentAcademic SM '+ 
			--+'INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId '+
			--+'INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SM.BatchId '+
			+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SM.OrgGroupBatchId'+
			+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId'+
			+' WHERE OGBM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+'AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 
			--AND BM.IsActive = 1'		
			print @strStudentCount 

			SET @strFeeReceiptDate = 'SELECT DATEDIFF(DAY,MAX(FR.CreatedDateTime),sCommon.fGetDate())AS FeeDays,MAX(FR.CreatedDateTime)AS LastFeeDate FROM sFee.tReceipt FR 
			INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=FR.OrgGroupBatchId 
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId 
			WHERE OBM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+'AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 
			--print @strFeeReceiptDate
			SET @strExamStatusDate= 'SELECT DATEDIFF(DAY,MAX(ES.UpdatedDateTime),sCommon.fGetDate())AS ExamDays,MAX(ES.UpdatedDateTime)AS LastExamDate FROM sAssessment.tResult ES'+
			--+' INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=ES.DivisionId'+
			--+' INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)
			+' INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId =ES.AcademicId '+
			+' INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId '+
			+' INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId '+
			+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId '+
			+' WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId) +'AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 
			--print @strExamStatusDate
			SET @strAttendanceDate ='SELECT  DATEDIFF(DAY,MAX(SR.AttendanceDate),sCommon.fGetDate())AS AttendancDays,MAX(SR.AttendanceDate)AS LastAttendanceDate FROM sAttendance.tStudentRegister SR '+ 
			+'INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId =  SR.AcademicId '+
			+'INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId '+
			+'INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId '+
			+'INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId '+
			+'WHERE OBM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)+' and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 

			--WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)
			print @strAttendanceDate

			SET @strEmployeeDate ='SELECT DATEDIFF(DAY,MAX(EM.CreatedDateTime),sCommon.fGetDate())AS EmployeeDays,MAX(EM.CreatedDateTime)AS LastEmployeeDate FROM sHrm.tEmployeeMaster EM'+
			+' INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId '+
			+'INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId '+
			+'INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId '+
			+'WHERE OBM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)+' and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 
			

			SET @strAlertDate= 'SELECT DATEDIFF(DAY,MAX(AL.CreatedDateTime),sCommon.fGetDate())AS AlertDays,MAX(AL.CreatedDateTime)AS LastAlertDate FROM sAlert.tAlertLog AL'+
			+' INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId '+
			+'INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId '+
			+'INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId '+
			+'WHERE OBM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)+' and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 
			
			--WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)

			SET @strBonafiesCertificateDate = 'SELECT DATEDIFF(DAY,MAX(B.CreatedDateTime),sCommon.fGetDate())AS BonafiedDays,MAX(B.CreatedDateTime)AS BonafiedDate FROM sCertificate.tBonafide  B'+
			+' INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=B.OrgId '+
			+'INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId '+
			+'INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId '+
			+'WHERE OBM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)+' and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 
			
			--WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)


			SET @strLCCertificateDate = 'SELECT DATEDIFF(DAY,MAX(L.CreatedDateTime),sCommon.fGetDate())AS LCDays,MAX(L.CreatedDateTime)AS LCDate FROM sCertificate.tLeaving  L'+
			+' INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=L.OrgId '+
			+'INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId '+
			+'INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId '+
			+'WHERE OBM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)+' and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId) 
			
			--WHERE OM.OrgGroupId='+convert (nvarchar,@rOrgGroupId)


			SET @strMobileUserCount = 'SELECT  
				
				ISNULL((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU 
				INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND((O1.Id = '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) 
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SC.BatchId 
				INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM1.OrgGroupId 
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId 
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 2003 AND SC.StatusId = 1 AND BM.IsActive =1 and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+'),0) +
				
				ISNULL((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU 
				INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM1.OrgGroupId 
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId 
				AND(OM1.Id !=1) AND((O1.Id =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+') 
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 95),0) AS Registered,
				
				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				LEFT JOIN (SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers) AS A ON A.UserId = U1.Id
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SC.BatchId 
				INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId
				WHERE U1.IsObsolete = 0 AND((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0))
				and COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+' 
				AND(OM.Id !=1) AND SC.StatusId = 1 AND U1.SourceTypeId= 2003 AND A.UserId IS NULL),0)+ 
				
				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId 
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+'
				LEFT JOIN (SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers) AS A ON A.UserId = U1.Id
				WHERE U1.IsObsolete = 0 AND((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) 
				AND(OM.Id !=1) AND U1.SourceTypeId = 95 AND A.UserId IS NULL ),0)
				AS NotRegistered
				FROM
				sSecurity.tUser U
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
				INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM.OrgGroupId 
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId
				LEFT JOIN (
				SELECT RU.UserId AS  UserId  
				FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId=OM1.OrgGroupId 
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+'
				AND(OM1.Id !=1) 
				AND((O1.Id ='+convert (nvarchar,@rOrgGroupId) +')OR('+convert (nvarchar,@rOrgGroupId)+'=0))
				WHERE U1.IsObsolete = 0 GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
				 
				WHERE U.IsObsolete = 0
				--AND((OM.Id =  1101)OR(1101=0))
				AND((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) 
				AND(OM.Id !=1)
				AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+'
				GROUP BY OM.OrgGroupId'
				

			SET @strEmployeeCount = 'SELECT COUNT(EM.Id) as ActiveEmployeeCount FROM sHrm.tEmployeeMaster EM '+ 
			+'INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id '+
			+'INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId '+
			+'INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id '+
			+'INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId '+
			+'INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4 '+
			+'INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId '+
			--+'INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id  '+
			--+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId'
			--+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId '
			--+'INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017'
			+' WHERE OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+ ' and EM.StatusId=7 AND EM.IsOtherUser = 0 '+

			+' SELECT COUNT(EM.Id) as EmployeeCount FROM sHrm.tEmployeeMaster EM '+ 
			+'INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id '+
			+'INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId '+
			+'INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id '+
			+'INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId '+
			+'INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4 '+
			+'INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId '+
			--+'INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id  '+
			--+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId'
			--+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId '
			--+'INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017'
			+' WHERE OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+ ' AND EM.IsOtherUser = 0 '

			
			
			SET @rstrStudentUser = 'SELECT ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId '+
				+'LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId '+
				+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SC.OrgGroupBatchId '+
			+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId '+
				+'WHERE U1.IsObsolete = 0 AND OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM.Id !=1) AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+' AND SC.StatusId = 1 AND U1.SourceTypeId=2003),0) AS StudentCreatedUsers'

			+' SELECT ISNULL((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId '+
				+'LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId '+
				+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SC.OrgGroupBatchId '+
			+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId '+
				+'WHERE U1.IsObsolete = 0 AND OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM.Id !=1) AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+' AND SC.StatusId = 1 AND U1.SourceTypeId=2003),0) AS StudentRegisteredUsers'

			+' SELECT ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId LEFT JOIN (SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers) AS A ON A.UserId = U1.Id '+
				+'LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId '+
				+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SC.OrgGroupBatchId '+
			+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId '+
				+'WHERE U1.IsObsolete = 0 AND OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM.Id !=1) AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+' AND SC.StatusId = 1 AND U1.SourceTypeId=2003 AND A.UserId IS NULL),0) AS StudentNotRegisteredUsers'



			SET @rstrEmployeeUser = 'SELECT ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId '+
			--	+' INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id  '+
			--	+' INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId '+
			--+' INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId '+
				+'WHERE U1.IsObsolete = 0 AND OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM.Id !=1) AND U1.SourceTypeId=95),0) AS EmployeeCreatedUsers'

			+' SELECT ISNULL((SELECT COUNT(RU.UserId) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId '+
			+' INNER JOIN (SELECT RU.UserId AS  UserId FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U2 ON RU.UserId = U2.Id '+
				+' INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U2.OrgId '+
				+'WHERE U2.IsObsolete = 0 AND OM1.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM1.Id !=1) AND U2.IsObsolete = 0 AND U2.SourceTypeId= 95 GROUP BY RU.UserId ) RU ON RU.UserId = U1.Id '+
				+'WHERE U1.IsObsolete = 0 AND OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM.Id !=1) AND U1.SourceTypeId=95),0) AS EmployeeRegisteredUsers'


			+
				' SELECT ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId '+
				+'WHERE U1.IsObsolete = 0 AND OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM.Id !=1) AND U1.SourceTypeId=95),0) '
				+' - (SELECT ISNULL((SELECT COUNT(RU.UserId) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId '+
			+' INNER JOIN (SELECT RU.UserId AS  UserId FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U2 ON RU.UserId = U2.Id '+
				+' INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U2.OrgId '+
				+'WHERE U2.IsObsolete = 0 AND OM1.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM1.Id !=1) AND U2.IsObsolete = 0 AND U2.SourceTypeId= 95 GROUP BY RU.UserId ) RU ON RU.UserId = U1.Id '+
				+'WHERE U1.IsObsolete = 0 AND OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+' AND(OM.Id !=1) AND U1.SourceTypeId=95),0)) AS EmployeeNotRegisteredUsers'



			SET @strAppModuleSummary = 
			'SELECT ''Circular'' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()),0)) AS Summary,MAX(C.CreatedDateTime) as LastUsed,CASE WHEN DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN ''InActive'' WHEN DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()) > 30 THEN ''InActive'' ELSE ''Active'' End as ''Status'' FROM sCommunication.tCircular C WHERE OrgGroupId = '+convert (nvarchar,@rOrgGroupId)
			
			+' SELECT ''Assignment'' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(A.CreatedDateTime),sCommon.fGetDate()),0))AS Summary,MAX(A.CreatedDateTime) as LastUsed,CASE  WHEN DATEDIFF(DAY,MAX(A.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN ''InActive'' WHEN DATEDIFF(DAY,MAX(A.CreatedDateTime),sCommon.fGetDate()) > 30 THEN ''InActive'' ELSE ''Active'' End as ''Status'' FROM sCommunication.tAssignment A INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=BM.OrgGroupBatchId INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId WHERE COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+' AND OBM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)
			
			+' SELECT ''CW/HW'' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()),0)) AS Summary,MAX(C.CreatedDateTime) as LastUsed,CASE WHEN DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN ''InActive'' WHEN DATEDIFF(DAY,MAX(C.CreatedDateTime),sCommon.fGetDate()) > 30 THEN ''InActive'' ELSE ''Active'' End as ''Status'' FROM sAcademic.tClasswork C INNER JOIN sSetup.tBatchMaster BM ON BM.Id = C.BatchId INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=BM.OrgGroupBatchId INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId WHERE COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)+' AND OBM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)
			
			+' SELECT ''Query'' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(Q.CreatedDateTime),sCommon.fGetDate()),0)) AS Summary,MAX(Q.CreatedDateTime) as LastUsed,CASE WHEN DATEDIFF(DAY,MAX(Q.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN ''InActive'' WHEN DATEDIFF(DAY,MAX(Q.CreatedDateTime),sCommon.fGetDate()) > 30 THEN ''InActive'' ELSE ''Active'' End as ''Status'' FROM sCommunication.tQuery Q WHERE OrgGroupId = '+convert (nvarchar,@rOrgGroupId)
			
			+' SELECT ''Video'' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(V.CreatedDateTime),sCommon.fGetDate()),0)) AS Summary,MAX(V.CreatedDateTime) as LastUsed,CASE WHEN DATEDIFF(DAY,MAX(V.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN ''InActive'' WHEN DATEDIFF(DAY,MAX(V.CreatedDateTime),sCommon.fGetDate()) > 30 THEN ''InActive'' ELSE ''Active'' End as ''Status'' FROM sSupport.tVideoMaster V INNER JOIN sSetup.tOrganizationMaster OM ON V.OrgId = OM.Id WHERE OM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)
			
			+' SELECT ''Event'' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(E.CreatedDateTime),sCommon.fGetDate()),0)) AS Summary,MAX(E.CreatedDateTime) as LastUsed,CASE WHEN DATEDIFF(DAY,MAX(E.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN ''InActive'' WHEN DATEDIFF(DAY,MAX(E.CreatedDateTime),sCommon.fGetDate()) > 30 THEN ''InActive'' ELSE ''Active'' End as ''Status'' FROM sActivity.tEventSchedule E INNER JOIN sSetup.tBatchMaster BM ON BM.Id = E.BatchId INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.Id=BM.OrgGroupBatchId INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OBM.CommonOrgGroupBatchId WHERE OBM.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)+ ' AND COGBM.Id = '+convert (nvarchar,@rCommonOrgGroupBatchId)
			
			+' SELECT ''Gallery'' as Module,CONVERT(NVARCHAR,ISNULL(DATEDIFF(DAY,MAX(P.CreatedDateTime),sCommon.fGetDate()),0)) AS Summary,MAX(P.CreatedDateTime) as LastUsed,CASE WHEN DATEDIFF(DAY,MAX(P.CreatedDateTime),sCommon.fGetDate()) IS NULL THEN ''InActive'' WHEN DATEDIFF(DAY,MAX(P.CreatedDateTime),sCommon.fGetDate()) > 30 THEN ''InActive'' ELSE ''Active'' End as ''Status'' FROM sCommunication.tPhotoCategoryMaster P  WHERE P.OrgGroupId = '+convert (nvarchar,@rOrgGroupId)

			SET @strAppUserSummary = 'SELECT 
				OM2.ID AS OrgId,
				OM2.DisplayTitle AS OrgName,
				OM2.Code, 
				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND OM.Id = OM2.Id  AND((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) 
				AND(OM.Id !=1) AND ((SC.OrgGroupBatchId ='+convert (nvarchar,@rOrgGroupBatchId)+') OR ('+convert (nvarchar,@rOrgGroupBatchId)+' = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003),0) AS ''StudentCreatedUser'',

				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId WHERE U1.IsObsolete = 0 AND ((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0))
				 AND(OM2.Id !=1) AND U1.SourceTypeId = 95 AND OM.Id = OM2.Id) ,0) AS ''EmployeeCreatedUser'',
 
				ISNULL((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND OM1.Id = OM2.Id AND((O1.Id =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 2003 AND ((SC.OrgGroupBatchId = '+convert (nvarchar,@rOrgGroupBatchId)+') OR ('+convert (nvarchar,@rOrgGroupBatchId)+' = 0)) AND SC.StatusId = 1),0) AS ''StudentRegister'',

				ISNULL((SELECT COUNT(RU.UserId) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId INNER JOIN (SELECT RU.UserId AS  UserId FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U2 ON RU.UserId = U2.Id
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U2.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId AND (OM1.Id !=1) AND((O1.Id =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) WHERE U2.IsObsolete = 0 AND U2.SourceTypeId= 95 GROUP BY RU.UserId ) RU ON RU.UserId = U1.Id
				WHERE U1.IsObsolete = 0 AND ((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) AND (OM2.Id !=1) AND U1.SourceTypeId = 95 AND OM.Id = OM2.Id) ,0) AS ''EmployeeRegister'',

				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId LEFT JOIN (SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers) AS A ON A.UserId = U1.Id
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND OM.Id = OM2.Id AND((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) 
				AND(OM.Id !=1) AND ((SC.OrgGroupBatchId = '+convert (nvarchar,@rOrgGroupBatchId)+') OR ('+convert (nvarchar,@rOrgGroupBatchId)+' = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003 AND A.UserId IS NULL),0) AS ''StudentNotRegister'',

				ISNULL((ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId WHERE U1.IsObsolete = 0 AND ((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0))
				 AND(OM2.Id !=1) AND U1.SourceTypeId = 95 AND OM.Id = OM2.Id) ,0) - ISNULL((SELECT COUNT(RU.UserId) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId INNER JOIN (SELECT RU.UserId AS  UserId FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U2 ON RU.UserId = U2.Id
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U2.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId AND (OM1.Id !=1) AND((O1.Id =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) WHERE U2.IsObsolete = 0 AND U2.SourceTypeId= 95 GROUP BY RU.UserId ) RU ON RU.UserId = U1.Id
				WHERE U1.IsObsolete = 0 AND ((OM.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) AND (OM2.Id !=1) AND U1.SourceTypeId = 95 AND OM.Id = OM2.Id) ,0)),0) ''EmployeeNotRegister''
				 
				FROM
				 
				sSecurity.tUser U
				INNER JOIN sSetup.tOrganizationMaster OM2 ON OM2.Id = U.OrgId 
				LEFT JOIN (
				SELECT RU.UserId AS  UserId  
				FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1)
				AND((O1.Id =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0))
				WHERE U1.IsObsolete = 0 GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
				 
				WHERE U.IsObsolete = 0
				AND((OM2.OrgGroupId =  '+convert (nvarchar,@rOrgGroupId)+')OR('+convert (nvarchar,@rOrgGroupId)+'=0)) 
				AND(OM2.Id !=1)
				GROUP BY OM2.Id,OM2.DisplayTitle,OM2.Code'
				



			
			exec (@strStudentCount)
			exec (@strMobileUserCount)
			exec (@strEmployeeCount)
			

			IF(@rFlag > 0 AND @rFlag < 4)
			BEGIN
				exec (@strFeeReceiptDate)
				exec (@strExamStatusDate)
				exec (@strBonafiesCertificateDate)
				exec (@strLCCertificateDate)
				exec (@strAttendanceDate)
				exec (@strEmployeeDate)
				exec (@strAlertDate)
				exec (@rstrStudentUser)
				exec (@rstrEmployeeUser)
				exec (@strAppModuleSummary)
			END
			ELSE IF(@rFlag = 4)
			BEGIN
				exec (@strAppUserSummary)
			END
END
GO
PRINT N'Creating [sWorkflow].[pLCApprovalStatusGet]...';


GO
CREATE PROCEDURE [sWorkflow].[pLCApprovalStatusGet]
			 @rCode nvarchar(50) =0,
			 @rStatusId int=0,
			 @rParticipantSourceId bigint = 0,
			 @rApprovingDepartmentId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
			SELECT 

			ADM.Title AS DepartmentTitle,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.CreatedDateTime AS CreatedDateTime,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status
			--(select Title from sWorkflow.tActionStatusMaster WHERE Id=3) AS Status 
			--CASE WHEN @rStatusId= 0 THEN (select Top 1 Title from sWorkflow.tActionStatusMaster WHERE Id=3) WHEN ASM.Id = @rStatusId THEN ASM.Title  END AS Status
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
			INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
			INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId
			LEFT JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
		WHERE  (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode =0)))
		AND((ASM.Id = @rStatusId) OR (@rStatusId =0)) 
		AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		AND FAD.ApprovingDepartmentId = @rApprovingDepartmentId

		UNION 

		SELECT 

			ADM.Title AS DepartmentTitle,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.CreatedDateTime AS CreatedDateTime,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status
			--(select Title from sWorkflow.tActionStatusMaster WHERE Id=3) AS Status 
			--CASE WHEN @rStatusId= 0 THEN (select Top 1 Title from sWorkflow.tActionStatusMaster WHERE Id=3) WHEN ASM.Id = @rStatusId THEN ASM.Title  END AS Status
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
			INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
			INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId
			LEFT JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
		WHERE  (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode =0)))
		AND((ASM.Id = @rStatusId) OR (@rStatusId =0)) 
		AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		AND FAD.ApprovingDepartmentId = @rApprovingDepartmentId
	END
GO
PRINT N'Creating [sWorkflow].[pMyApprovalRequestGet]...';


GO

CREATE  PROCEDURE [sWorkflow].[pMyApprovalRequestGet]
			 @rWorkflowFunctionalityId bigint=0,
			 @rFromDate date=null,
			 @rToDate date=null,
			 @rStatusId int=0,
			 @rCode nvarchar(200) ='',
			 @rUserId bigint = 0,
			 @rUserSourceTypeId int,
			 @rParticipantSourceId bigint = 0
			 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
		IF(@rUserSourceTypeId = 2001)
		BEGIN
			SELECT
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		WHERE ((WFM.Id = 0) OR (0 =0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND AR.CreatedUserId = @rUserId AND AR.ParticipantSourceTypeId = 2001
			AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
		
UNION 

SELECT
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		WHERE ((WFM.Id = 0) OR (0 =0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND AR.ParticipantSourceTypeId = 2001
			AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
		END
		ELSE IF(@rUserSourceTypeId = 95)
		BEGIN
			SELECT
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		WHERE ((WFM.Id = 0) OR (0 =0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND AR.CreatedUserId = @rUserId AND AR.ParticipantSourceTypeId = 95
			AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
		
UNION 

SELECT
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		WHERE ((WFM.Id = 0) OR (0 =0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND AR.ParticipantSourceTypeId = 95
			AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
		END
		ELSE
		BEGIN
			SELECT
			--U.SourceTypeId,
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
			--INNER JOIN [sSecurity].[tUser] U ON AR.CreatedUserId = U.Id
		WHERE ((WFM.Id = 0) OR (0 =0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
		END
END
GO
  
 
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('21.10.01',211001,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)

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

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


GO
ALTER TABLE [sAdmission].[tAdmissionInquiry]
    ADD [MotherName] NVARCHAR (100) NULL;


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


GO
ALTER TABLE [sCommunication].[tAssignmentView]
    ADD [Remark] NVARCHAR (MAX) NULL;


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


GO
ALTER TABLE [sCommunication].[tStudentDocumentUpload] ALTER COLUMN [StudentDocumentTypeId] INT NOT NULL;


GO
PRINT N'Altering [sFrontOffice].[tVisitorLog]...';


GO
ALTER TABLE [sFrontOffice].[tVisitorLog]
    ADD [StatusId] SMALLINT NULL;


GO
PRINT N'Creating [sBiometric].[tBiometricDeviceSyncDetail]...';


GO
CREATE TABLE [sBiometric].[tBiometricDeviceSyncDetail] (
    [AutoId]     INT           IDENTITY (1, 1) NOT NULL,
    [DeviceName] NVARCHAR (50) NOT NULL,
    [SyncTime]   DATETIME      NULL,
    PRIMARY KEY CLUSTERED ([AutoId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF)
);


GO
PRINT N'Creating [sCommon].[tPublishDocumentMaster]...';


GO
CREATE TABLE [sCommon].[tPublishDocumentMaster] (
    [Id]              INT           NOT NULL,
    [Code]            NVARCHAR (50) NOT NULL,
    [Title]           NVARCHAR (50) NOT NULL,
    [IsObsolete]      BIT           NOT NULL,
    [CreatedUserId]   BIGINT        NOT NULL,
    [CreatedDateTime] DATETIME      NOT NULL,
    [UpdatedUserId]   BIGINT        NOT NULL,
    [UpdatedDateTime] DATETIME      NOT NULL,
    [OrgGroupId]      SMALLINT      NULL
);


GO
PRINT N'Creating PK_tPublishDocumentMaster...';


GO
ALTER TABLE [sCommon].[tPublishDocumentMaster]
    ADD CONSTRAINT [PK_tPublishDocumentMaster] 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 [sTimetable].[vEmployeeProxySetting]...';


GO







/******************************************************************************  
 Purpose          : To get Employee For Proxy Setting 
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sTimetable].[vEmployeeProxySetting]  
  
AS  
  
Select  
		TT.EmployeeId,
		EM.FirstName+' '+EM.LastName AS Employee,
		DivisionId,
		DayId,
		LectureNumber,
		TimeTableSchemaId
From 
		sTimetable.tTimeTable TT
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TT.EmployeeId 
WHERE 
	EmployeeId NOT IN (Select DISTINCT EmployeeId FROM sTimetable.tProxySetting Where ProxyDate = CONVERT(DATE,GETDATE(),23))
GO

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


GO
 
 -- exec [sAcademic].[pOnlineLearningGet] 1101000000438,'','','',0,0,0,0,0,-1,110100110
ALTER PROCEDURE [sAcademic].[pOnlineLearningGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100) ='',
	 @rFromDate date = '',
	 @rToDate date = '',
	 @rClassId int = 0,
	 @rSubjectId int = 0,
	 @rTopicId int = 0,
	 @rEmployeeId bigint = 0,
	 @rLearningTypeId int = 0,
	 @rIsCompleted int = -1,
	 @rBatchId int,
	 @rType int = 0,
	 @rUserId bigint = 0,
	 @rOnlineMeetingAccountId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
if(@rType = 0)
BEGIN
	if(@rId = 0)
	BEGIN 
	
	SELECT
			OL.Id,
			SM.Title as Subject,
			ISNULL(CM.DisplayTitle,'') as Class,
			ISNULL(TM.Title,'') as Topic,
			--EM.FirstName +' ' +EM.LastName as Teacher,
			[sHrm].[fEmployeeNameGet](EM.FirstName , EM.MiddleName, EM.LastName,ISNULL(OM.EmployeeNameFormatId,1)) AS Teacher,
			DM.Title as LearningType,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDateTime,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDateTime,
			OL.IsCompleted as Status,
		    ISNULL(OL.Title,'') as Title,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tClassMaster CM ON OLS.SourceId = CM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tDivisionMaster DM ON OLS.SourceId = DM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2005
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as Source ,
			  OL.StartDateTime AS TeacherStartDateTime,
			  OL.EndDateTime AS TeacherEndDateTime,
			  (SELECT ISNULL(ISNULL(FirstName, ' ') + ' ' + ISNULL(LastName, ' '), ' ') FROM sHrm.tEmployeeMaster WHERE Id = OL.CoTeacherEmployeeId1) AS CoTeacherEmployee1,
			  (SELECT ISNULL(ISNULL(FirstName, ' ') + ' ' + ISNULL(LastName, ' '), ' ') FROM sHrm.tEmployeeMaster WHERE Id = OL.CoTeacherEmployeeId2) AS CoTeacherEmployee2,
			  OL.CoTeacherEmployee1StartDateTime,
			  OL.CoTeacherEmployee1EndDateTime,
			  OL.CoTeacherEmployee2StartDateTime,
			  OL.CoTeacherEmployee2EndDateTime
	  FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN (SELECT DISTINCT OM.Id FROM sSetup.vUserOrganization OM 
			WHERE ((OM.UserId = @rUserId) OR (@rUserId = 0)) ) A ON A.Id = EM.OrgID
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
 	  WHERE 
				((OL.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OL.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((OL.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			AND ((OL.TopicId = @rTopicId) OR (@rTopicId = 0))
			AND ((OL.TeacherEmployeeId = @rEmployeeId) OR (@rEmployeeId = -1))
			AND ((OL.LearningTypeId = @rLearningTypeId) OR (@rLearningTypeId = 0))
			AND ((CONVERT(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
			AND (OL.BatchId = @rBatchId)
			AND ((OL.MeetingAccountId = @rOnlineMeetingAccountId) OR (@rOnlineMeetingAccountId = 0))
	 ORDER BY
			OL.StartDate , OL.StartTime asc
		
	END
	ELSE
	BEGIN
		SELECT 
			OL.Id,
			SM.Title as Subject,
			SM.Id as SubjectId,
			ISNULL(CM.Title,'') as Class,
			ISNULL(CM.Id,0) as ClassId,
			ISNULL(TM.Title,'') as Topic,
			ISNULL(TM.Id,0) as TopicId,
			EM.FirstName +' '+ EM.LastName as Teacher,
			Em.Id as TeacherId,
			DM.Title as LearningType,
			DM.Id as LearningTypeId,
			CONVERT(NVARCHAR,OL.StartDate) as StartDate,
			CONVERT(NVARCHAR,OL.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OL.EndDate) as EndDate,
			CONVERT(NVARCHAR,OL.EndTime,108) as EndTime,
			OL.IsCompleted as Status,
			OL.LecturePath,
			OL.Title as LearningTitle,
			OL.Description,
			OL.IsDisplayMeetingId,
			OL.MeetingId,
			OL.MeetingPassword,
			ISNULL(OL.IsTrackAttendance,0) as IsTrackAttendance,
			ISNULL(OL.IsAssignment,0) as IsAssignment,
			ISNULL(OL.IsSubmitAssignment,0) as IsSubmitAssignment,
			ISNULL(OL.IsTakeTest,0) as IsTakeTest,
			ISNULL(OL.IsReference,0) as IsReference,
			ISNULL(OL.IsResource,0) as IsResource,
			ISNULL(OL.IsCompleted,0) as IsCompleted,
			ISNULL(OL.IsMeetingStarted,0) as IsMeetingStarted,
			ISNULL(TestM.Id,0) AS TestId,
			ISNULL(TestM.Title,'')AS Test,
			ISNULL(OMS.IsOnParticipantVideo,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) AS IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) AS IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) AS IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) AS IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) AS IsOnHostscreenShare,
			ISNULL(OL.MeetingAccountId,0) AS MeetingAccountId,
			ISNULL(OL.IsMeetingCreated,0) AS IsMeetingCreated,
			ISNULL(OL.AssignmentRemark,'') AS AssignmentRemark,
			ISNULL(OL.IsTrackAssignmentView,0) as IsTrackAssignmentView,
			ISNULL(OL.CoTeacherEmployeeId1,0) as CoTeacherEmployeeId1,
			ISNULL(OL.CoTeacherEmployeeId2,0) as CoTeacherEmployeeId2,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			(Select EmployeeName FROM sHrm.vExtEmployee  WHERE  EmployeeId = ISNULL(OL.CoTeacherEmployeeId1,0)) AS CoTeacherEmployee1,
			(Select EmployeeName FROM sHrm.vExtEmployee  WHERE EmployeeId = ISNULL(OL.CoTeacherEmployeeId2,0)) AS CoTeacherEmployee2,
			ISNULL(CONVERT(NVARCHAR,OL.AssignmentSubmissionEndDate),'') As SubmissionEndDate,
			OL.StartDateTime AS TeacherStartDateTime,
			OL.EndDateTime AS TeacherEndDateTime,
			ISNULL(OL.IsRecording,0) AS IsRecording,
			BM.Id AS BatchId,
			BM.Title AS BatchName,
			OM.Id AS OrgId,
			OM.Title AS OrganizationName
	  FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			LEFT JOIN sEExam.tTestMaster TestM ON OL.ClassId=TestM.ClassId AND OL.TestId=TestM.Id
			LEFT JOIN sAcademic.tOnlineMeetingSettings OMS ON OMS.OnlineLearningId = OL.Id 
			INNER JOIN sSetup.tBatchMaster BM ON OL.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON BM.OrgId=OM.Id
	  WHERE 
			(OL.Id = @rId) AND (OL.BatchId = @rBatchId)
	  ORDER BY
			OL.StartDate , OL.StartTime asc
	END
END
ELSE IF(@rType = 1)
BEGIN
		if(@rId = 0)
	BEGIN 
	
	SELECT 
			OL.Id,
			SM.Title as Subject,
			ISNULL(CM.DisplayTitle,'') as Class,
			ISNULL(TM.Title,'') as Topic,
			EM.FirstName +' '+ EM.LastName as Teacher,
			DM.Title as LearningType,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR(5),OL.StartTime,108) as StartDateTime,
			CONVERT(NVARCHAR,OL.EndDate,103)+' '+CONVERT(NVARCHAR(5),OL.EndTime,108) as EndDateTime,
			OL.IsCompleted as Status,
		    ISNULL(OL.Title,'') as Title,
			OL.StartDateTime AS TeacherStartDateTime,
			OL.EndDateTime AS TeacherEndDateTime
	  FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
	  WHERE 
  
				((OL.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
			AND ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OL.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((OL.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			AND ((OL.TopicId = @rTopicId) OR (@rTopicId = 0))
			AND ((OL.TeacherEmployeeId = @rEmployeeId) OR (@rEmployeeId = -1))
			AND ((OL.LearningTypeId = @rLearningTypeId) OR (@rLearningTypeId = 0))
			AND ((CONVERT(int,OL.IsCompleted)=@rIsCompleted) OR (@rIsCompleted = -1))
			AND (OL.BatchId = @rBatchId)
			AND OL.IsCompleted <> 721			
	 ORDER BY
			
			OL.StartDate , OL.StartTime asc
		
	END
	ELSE
	BEGIN
		SELECT 
			OL.Id,
			SM.Title as Subject,
			SM.Id as SubjectId,
			ISNULL(CM.Title,'') as Class,
			ISNULL(CM.Id,0) as ClassId,
			ISNULL(TM.Title,'') as Topic,
			ISNULL(TM.Id,0) as TopicId,
			EM.EmployeeName as Teacher,
			Em.EmployeeId as TeacherId,
			DM.Title as LearningType,
			DM.Id as LearningTypeId,
			CONVERT(NVARCHAR,OL.StartDate) as StartDate,
			CONVERT(NVARCHAR,OL.StartTime,108) as StartTime,
			CONVERT(NVARCHAR,OL.EndDate) as EndDate,
			CONVERT(NVARCHAR,OL.EndTime,108) as EndTime,
			OL.IsCompleted as Status,
			OL.LecturePath,
			OL.Title as LearningTitle,
			OL.Description,
			OL.IsDisplayMeetingId,
			OL.MeetingId,
			OL.MeetingPassword,
			ISNULL(OL.IsTrackAttendance,0) as IsTrackAttendance,
			ISNULL(OL.IsAssignment,0) as IsAssignment,
			ISNULL(OL.IsSubmitAssignment,0) as IsSubmitAssignment,
			ISNULL(OL.IsTakeTest,0) as IsTakeTest,
			ISNULL(OL.IsReference,0) as IsReference,
			ISNULL(OL.IsResource,0) as IsResource,
			ISNULL(OL.IsCompleted,0) as IsCompleted,
			ISNULL(OL.IsMeetingStarted,0) as IsMeetingStarted,
			ISNULL(TestM.Id,0) AS TestId,
			ISNULL(TestM.Title,'')AS Test,
			ISNULL(OMS.IsOnParticipantVideo,0) AS IsOnParticipantVideo,
			ISNULL(OMS.IsOnParticipantAudio,0) AS IsOnParticipantAudio,
			ISNULL(OMS.IsOnHostVideo,0) AS IsOnHostVideo,
			ISNULL(OMS.IsOnHostAudio,0) AS IsOnHostAudio,
			ISNULL(OMS.IsOnParticipantScreenShare,0) AS IsOnParticipantScreenShare,
			ISNULL(OMS.IsOnHostscreenShare,0) AS IsOnHostscreenShare,
			ISNULL(OL.MeetingAccountId,0) AS MeetingAccountId,
			ISNULL(OL.IsMeetingCreated,0) AS IsMeetingCreated,
			ISNULL(OL.AssignmentRemark,'') AS AssignmentRemark,
			ISNULL(OL.IsTrackAssignmentView,0) as IsTrackAssignmentView,
			ISNULL(OL.CoTeacherEmployeeId1,0) as CoTeacherEmployeeId1,
			ISNULL(OL.CoTeacherEmployeeId2,0) as CoTeacherEmployeeId2,
			ISNULL(OMS.MeetingProviderId,0) As MeetingProviderId,
			(Select EmployeeName FROM sHrm.vExtEmployee  WHERE  EmployeeId = ISNULL(OL.CoTeacherEmployeeId1,0)) AS CoTeacherEmployee1,
			(Select EmployeeName FROM sHrm.vExtEmployee  WHERE EmployeeId = ISNULL(OL.CoTeacherEmployeeId2,0)) AS CoTeacherEmployee2,
			ISNULL(CONVERT(NVARCHAR,OL.AssignmentSubmissionEndDate),'') As SubmissionEndDate,
			OL.StartDateTime AS TeacherStartDateTime,
			OL.EndDateTime AS TeacherEndDateTime,
			ISNULL(OL.IsRecording,0) AS IsRecording,
			BM.Id AS BatchId,
			BM.Title AS BatchName,
			OM.Id AS OrgId,
			OM.Title AS OrganizationName
	  FROM 
			sAcademic.tOnlineLearning OL
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId
			INNER JOIN sHrm.vExtEmployee EM ON EM.EmployeeId = OL.TeacherEmployeeId 
			INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			LEFT JOIN sEExam.tTestMaster TestM ON OL.ClassId=TestM.ClassId AND OL.TestId=TestM.Id
			LEFT JOIN sAcademic.tOnlineMeetingSettings OMS ON OMS.OnlineLearningId = OL.Id 
			INNER JOIN sSetup.tBatchMaster BM ON OL.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON BM.OrgId=OM.Id
	  WHERE 
			(OL.Id = @rId) AND (OL.BatchId = @rBatchId) AND OL.IsCompleted <> 721
	  ORDER BY
			OL.StartDate , OL.StartTime asc
	END
END
END
GO
PRINT N'Altering [sAdmission].[pAdmissionInquiryAdd]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionInquiryAdd]
		 @rId bigint
		,@rFirstName nvarchar(100)
		,@rMiddleName nvarchar(100)
		,@rLastName nvarchar(100)
		,@rForClassId int
		,@rForBatchId	int =0
		--,@rForBatch	nvarchar(20)
		,@rDateOfBirth date
		,@rOrgId smallint
		--,@rStatusId	smallint
		,@rInquiryStatusMasterId int
		,@rStreetOne nvarchar(50)
		,@rStreetTwo nvarchar(50)
		,@rStreetThree nvarchar(50)
		,@rCountry nvarchar(50)
		,@rState nvarchar(50)
		,@rCity	nvarchar(50)
		,@rZipCode nvarchar(20)
		,@rContactNo nvarchar(20)
		,@rContactEmail	nvarchar(50)
		,@rRemark nvarchar(200)
		,@rInquiryModeId tinyint
		,@rInquiryReferenceId int
		,@rAdmissionCategoryId int
		,@rPreviousSchool nvarchar(200)
		,@rMeritMarks decimal(10,2) 
		,@rMeritGrade nvarchar(20)
		,@rMeritMarksBreakup nvarchar(100)
		,@rGenderId tinyint
		,@rFollowupDate date
		,@rFollowupRemark nvarchar(150)
		,@rCreatedUserId bigint
		,@rInquiryDate date
		,@rNumber bigint 
		,@rHandledBy nvarchar(100) 
		,@rOrgGroupId int,
		@rCastCategoryId int=0,
		@rIsHostelRequired bit=0,
		@rIsTransportRequired bit=0,
		@rIsValidateInquiryAsPerAdmission bit=0,
		@rIsGivenAdmissionForm bit=0,
		@rAlternateContactNo nvarchar(100)='',
		@rAlternateContactEmail	nvarchar(200) = '',
		@rMotherName nvarchar(100)=''
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DECLARE @lOrgGroupBatchId int=0
	
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster BM WHERE BM.Id = @rForBatchId
	
	DECLARE @lConfigValue nvarchar(50)=''
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 341 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	 
	
	IF(@lConfigValue='OrgGroupBatch')
	BEGIN
		SELECT @rNumber = (ISNULL(MAX(Number),0) + 1) FROM sAdmission.tAdmissionInquiry AI
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId 
		WHERE BM.OrgGroupBatchId = @lOrgGroupBatchId
	END
	ELSE IF(@lConfigValue='Batch')
	BEGIN
		SELECT @rNumber = (ISNULL(MAX(Number),0) + 1) FROM sAdmission.tAdmissionInquiry AI
		WHERE AI.ForBatchId = @rForBatchId
	END
	
	Declare @lStatusId smallint,@lIsValidateBirthdate bit,@lFromDateOfBirth date,@lToDateOfBirth date
	SET @lStatusId= 0
	
	if(@rIsValidateInquiryAsPerAdmission=1)
	Begin
		Select @lIsValidateBirthdate=IsValidateBirthdate,@lFromDateOfBirth=FromDateOfBirth,@lToDateOfBirth=ToDateOfBirth from  sAdmission.tAdmissionCriteria where ClassId=@rForClassId AND BatchID=@rForBatchId
		
		if(@lIsValidateBirthdate=1 AND @rDateOfBirth NOT between @lFromDateOfBirth And @lToDateOfBirth)
		BEGIN
			Select  -101 AS Result
			return
		End
	End
	 
 BEGIN TRANSACTION	
IF(@rId = 0)	
	BEGIN	

 DECLARE @lNextNumber BIGINT 
 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionInquiry', 0, 1, 1,@outNextNumber = @lNextNumber output
			
	INSERT INTO sAdmission.tAdmissionInquiry
		(
			 Id
			,FirstName
			,MiddleName
			,LastName
			,ForClassId			 
			,ForBatchId
			,DateOfBirth
			,OrgId
			,StatusId
			,StreetOne
			,StreetTwo
			,StreetThree
			,Country
			,State
			,City
			,ZipCode
			,ContactNo
			,ContactEmail
			,Remark
			,InquiryModeId
			,InquiryReferenceId
			,AdmissionCategoryId
			,PreviousSchool
			,MeritMarks
			,MeritGrade
			,MeritMarksBreakup
			,GenderId
			,FollowupDate
			,FollowupRemark
			,CreatedUserId
			,CreatedDateTime
			,InquiryDate
			,Number
			,HandledBy
			,OrgGroupId
			,InquiryStatusId,
			CastCategoryId,
			IsHostelRequired,
			IsTransportRequired,
			IsGivenAdmissionForm,
			AlternateContactNo,
			AlternateContactEmail,
			MotherName
		)
	VALUES
		(
			 @lNextNumber
			,@rFirstName
			,@rMiddleName
			,@rLastName
			,@rForClassId
			,@rForBatchId			 
			,@rDateOfBirth
			,@rOrgId
			,@lStatusId
			,@rStreetOne
			,@rStreetTwo
			,@rStreetThree
			,@rCountry
			,@rState
			,@rCity
			,@rZipCode
			,@rContactNo
			,@rContactEmail
			,@rRemark
			,@rInquiryModeId
			,@rInquiryReferenceId
			,@rAdmissionCategoryId
			,@rPreviousSchool
			,@rMeritMarks
			,@rMeritGrade
			,@rMeritMarksBreakup
			,@rGenderId
			,@rFollowupDate
			,@rFollowupRemark
			,@rCreatedUserId
			,sCommon.fGetDate()
			,@rInquiryDate
			,@rNumber
			,@rHandledBy
			,@rOrgGroupId
			,@rInquiryStatusMasterId,
			@rCastCategoryId,
			@rIsHostelRequired,
			@rIsTransportRequired,
			@rIsGivenAdmissionForm,
			@rAlternateContactNo,
			@rAlternateContactEmail,
			@rMotherName
		)
		    SELECT @lNextNumber AS Result         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sAdmission.tAdmissionInquiry
	    SET
			 FirstName=@rFirstName
			,MiddleName=@rMiddleName
			,LastName=@rLastName
			,ForClassId=@rForClassId
			,ForBatchId = @rForBatchId		 
			,DateOfBirth=@rDateOfBirth
			,OrgId=@rOrgId
			,StatusId=@lStatusId
			,StreetOne=@rStreetOne
			,StreetTwo=@rStreetTwo
			,StreetThree=@rStreetThree
			,Country=@rCountry
			,State=@rState
			,City=@rCity
			,ZipCode=@rZipCode
			,ContactNo=@rContactNo
			,ContactEmail=@rContactEmail
			,Remark=@rRemark
			,InquiryModeId=@rInquiryModeId
			,InquiryReferenceId=@rInquiryReferenceId 
			,AdmissionCategoryId=@rAdmissionCategoryId
			,PreviousSchool=@rPreviousSchool
			,MeritMarks=@rMeritMarks
			,MeritGrade=@rMeritGrade
			,MeritMarksBreakup=@rMeritMarksBreakup
			,GenderId=@rGenderId
			,FollowupDate=@rFollowupDate
			,FollowupRemark=@rFollowupRemark
			,UpdatedUserId=@rCreatedUserId
			,UpdatedDateTime=sCommon.fGetDate()
			,InquiryDate=@rInquiryDate
			,HandledBy=@rHandledBy
			,InquiryStatusId = @rInquiryStatusMasterId,
			CastCategoryId = @rCastCategoryId,
			IsHostelRequired=@rIsHostelRequired,
			IsTransportRequired=@rIsTransportRequired,
			IsGivenAdmissionForm =@rIsGivenAdmissionForm,
			AlternateContactNo = @rAlternateContactNo,
			AlternateContactEmail = @rAlternateContactEmail,
			MotherName = @rMotherName
	      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 [sAdmission].[pAdmissionInquiryGet]...';


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

BEGIN 
	
	IF(@rIsGivenAdmissionForm=1)
		SET @rIsGivenAdmissionForm = 1
  	IF(@rIsGivenAdmissionForm=2)
		SET @rIsGivenAdmissionForm =0
	 
	 
	 SET @rToDate = DATEADD(d,1,@rToDate)
	 --IF @rIsSearch = 1
		BEGIN
			SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName= sCommon.fSearchStringGet(@rLastName)
			SET @rHandledBy= sCommon.fSearchStringGet(@rHandledBy)
			--SET @rContactNo= sCommon.fSearchStringGet(@rContactNo)
		END
	
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rAdmissionInquiryIdText AS AdmissionInquiryIdText,
			 AI.Id
			,AI.ForBatchId
			,AI.ForClassId
			,AI.StatusId
			,ISNULL(SM.Id,0) AS InquiryStatusMasterId
			,ISNULL(AI.GenderId,0) AS GenderId
			,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
			,ISNULL(IMM.Title,'') AS InquiryMode
			,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		    ,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		    ,AI.OrgId
		    ,ISNULL(AI.Number,0) AS InquiryNumber
		    ,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		    ,OM.DisplayTitle AS OrgName
		    ,BM.Title AS ForBatch
			,ISNULL(CM.Title,'') AS ClassName	
			,AI.FirstName
			,AI.MiddleName
			,AI.LastName
			,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
			,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
			,ISNULL(AI.DateOfBirth,'') As DateOfBirth
			,ISNULL(GM.Title,'') As Gender			
			,AI.ContactNo
			,AI.ContactEmail			
			,AI.StreetOne
			,AI.StreetTwo
			,AI.StreetThree
			,AI.Country
			,AI.State
			,AI.City
			,AI.ZipCode
			,ISNULL(AI.Remark,'') AS Remark						
		    ,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
			,ISNULL(AI.MeritMarks,0) AS MeritMarks
			,ISNULL(AI.MeritGrade,'') AS MeritGrade
			,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
			,SM.Title as StatusName	
			--,cast(replace(FollowupDate,'/','-') as date) As FollowupDate
			,ISNULL(AI.FollowupDate,'') As FollowupDate
			,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
			,ISNULL(IRM.Title ,'') AS InquiryReference	
			,ISNULL(SCM.Title,'') AS AdmissionCategory		
			,ISNULL(AI.HandledBy,'') AS HandledBy
			,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
			,ISNULL(AI.StudentId,0) AS StudentId,
			ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
			ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
			ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
			CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
			--ISNULL(AI.IsGivenAdmissionForm,0) AS IsGivenAdmissionForm,
			ISNULL(SM.HighlightColor,'') AS HighlightColor,
			ISNULL(SA.PreviousStandard,'') As PreviousStandard,
			AI.AlternateContactNo,
			AI.AlternateContactEmail
			,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
			ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
			ISNULL(AI.MotherName,'') AS MotherName
  FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
           --INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AI.StatusId AND StatusTypeId=104
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
			LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  --AND ((AI.StatusId=@rStatusId) OR (@rStatusId=0))
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (@rNumber=0))
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
	  
	  AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=0)OR (@rIsGivenAdmissionForm=-1))

	  AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN ISNULL(AI.IsTransportRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	  
	  AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN ISNULL(AI.IsHostelRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	 --AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=-1))
      --AND (AI.IsGivenAdmissionForm = CASE @rIsGivenAdmissionForm WHEN 0 THEN ISNULL(AI.IsGivenAdmissionForm,0) WHEN 2 THEN 1 WHEN 1 THEN 0 END)
	 AND ((AI.ContactNo = @rContactNo) OR (@rContactNo=''))
	 AND ((AI.HandledBy like @rHandledBy) OR (@rHandledBy=''))
	  --AND ((AI.IsTransportRequired=@rIsTransportRequired) OR (@rIsTransportRequired=0))	   
	    --AND ((AI.IsHostelRequired =@rIsHostelRequired) OR (@rIsHostelRequired=0))
	  Order by Case @rOrderBy When 1 then AI.MeritMarks END desc ,
			    Case @rOrderBy when 0 then AI.Number Else 
			    AI.Number END desc  
			    
END
GO
PRINT N'Altering [sAdmission].[pRptAdmissionFormGet]...';


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

AS
 SET NOCOUNT ON

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 Convert(nvarchar(20),@rRelationShipId) AS RelationShipIdText,
	 AF.Id AdmissionFromId,
	 AF.FormNo,
	 [sStudent].[fStudentNameGet](AF.FirstName , ISNULL(AF.MiddleName,'') , AF.LastName,OM.StudentNameFormatId ) AS Name,
	 AF.FirstName,
	 AF.ForClassId,
	 AF.DateOfBirth AS DateOfBirth,
	 AF.BatchId,
	 CM.Title AS ClassName,
	 AF.OrgId,
	 AF.StreetOne,
	 AF.StreetTwo,
	 AF.StreetThree,
	 AF.Country,
	 AF.City,
	 AF.State,
	 AF.ZipCode,
	 AF.ContactEmail,
	 AF.ContactNo,
	 AF.PreviousSchool,
	 ISNULL(AF.StudentPhoto,0x) As StudentPhoto,
	 ISNULL(AF.ReligionId,0) AS ReligionId,
	 IsNULL(RM.Title,'') AS ReligionName,
	 AF.MeritGrade,
	 AF.MeritMarks,
	 AF.GenderId,
	 GM.Title AS Gender,
	 AF.FamilyCast,
	 AF.FamilySubCast,
	 ISNULL(AF.CastCategoryId,0) AS CastCategoryId,
	 ISNULL(CCM.Title,'') AS CastCategory ,
	 OM.DisplayTitle ,
	 BM.Title As Batch,
	 ISNULL(AFM.FatherName,'') AS FatherName ,
	 ISNULL(AFM.FatherDateOfBirth,'')As FatherDateOfBirth,
	 AFM.FatherOccupation,
	 AFM.FatherOfficeAddress,
	 AFM.FatherIncome,
	 AFM.FatherQualification,
	 AFM.FatherContactNo,
	 AFM.FatherMail,
	 AFM.FatherOrganization,
	 ISNULL(AFM.MotherName,'') AS MotherName,
	 IsNull(AFM.MotherDateOfBirth,'')As MotherDateOfBirth,
	 AFM.MotherIncome,
	 AFM.MotherOccupation,
	 AFM.MotherOfficeAddress,
	 AFM.MotherQualification,
	 AFM.MotherContactNo,
	 AFM.MotherMail,
	 AFM.MotherOrganization,
	 isnull(AFM.RelativeName,'') AS RelativeName ,
	 ISNULL(AFM.RelativeDateOfBirth,'') AS RelativeDateOfBirth,
	 AFM.RelativeOccupation,
	 AFM.RelativeContactNo,
	 AFM.RelativeMail,
	 AFM.RelativeOfficeAddress,
	 AFM.RelativeIncome,
	 AFM.RelativeQualification,
	 AFM.RelationshipName ,
	 ISNULL(AC.IsFixParentAcademic,0) AS IsParentAcademicRequired ,
	 ISNULL (AC.IsStudentAcademicRequired,0) AS IsStudentAcademicRequired ,
	 ISNULL(AC.IsSiblingDetailRequired,0) AS IsSiblingDetailRequired,
	 ISNULL(AC.IsReferenceDetailRequired,0) AS IsReferenceDetailRequired ,
	 ISNULL(AC.IsFamilyDetailRequired,0) AS IsFamilyDetailRequired ,
	 ISNULL(AC.IsFixStudentAcademic,0) AS IsFixStudentAcademic,
	  AC.ConfirmationRemark AS ConfirmationRemark,
	  ISNULL(AC.IsHostelDetailRequired,0) AS IsHostelDetailRequired ,
	 ISNULL (AC.IsTransportDetailRequired,0) AS IsTransportDetailRequired ,
	 ISNULL(AC.IsHealthDetailRequired,0) AS IsHealthDetailRequired,
	 ISNULL(AC.IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired ,
	 ISNULL(AC.IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired ,
	 ISNULL(AC.IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
	
	 AF.IsPysicalDeformity,
	 ISNULL(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
	 AF.IsMajorIllness,
	 ISNULL(AF.MajorIllnessRemark, '') As MajorIllnessRemark,
	 AF.IsAllergy,
	 ISNULL(AF.AllergyRemark,'') As AllergyRemark,
	 ISNULL(AF.BirthPlace,'') As BirthPlace,
	 ISNULL(AF.BirthTaluka,'') As BirthTaluka,
	 ISNULL(AF.BirthDistrict,'') As BirthDistrict,
	 Isnull(BGM.Title,'') As BloodGroupName,
	 AF.AdhaarNumber,
	 AF.IsHostelRequired,
	 AF.IsTransportRequired,
	 ISNULL(AFM.FatherPhoto,0x)As FatherPhoto,
	  ISNULL(AFM.MotherPhoto,0x) As MotherPhoto,
	 ISNULL(AFM.RelativePhoto,0x) As RelativePhoto,
	  AF.BirthState,
	 AF.BirthCountry,
	 AC.CustomField1Remark,
	 AC.CustomField2Remark,
	 AC.CustomField3Remark,
	 ISNULL(AF.CustomField1Answer,'')As CustomField1Answer,
	 ISNULL(AF.CustomField2Answer,'')As CustomField2Answer,
	 ISNULL(AF.CustomField3Answer,'')As CustomField3Answer,
	 ISNULL(AF.Nationality,'') AS Nationality,
	 ISNULL(AF.MotherTongue,'') AS MotherTongue,
	 ISNULL(AF.OtherInformation,'') AS OtherInformation,
	 ISNULL(LWM.Title,'') AS LiveWith,
	 ISNULL(AC.AgeCutOffDate,'') AS AgeCutOffDate,
	 ISNULL(AC.Remark1,'') AS ExtraRemark1,
	 ISNULL(AC.Remark2,'') AS ExtraRemark2,
	 ISNULL(AC.Remark3,'') AS ExtraRemark3,
	 AF.DateOfBirthInWord AS DOBInWords,
	 AF.CreatedDateTime As FormDate,
	  ISNULL(AC.IsFatherDetail,0) AS IsFatherDetail,
	 ISNULL(AC.IsFatherFullDetail,0) AS IsFatherFullDetail,
	 ISNULL (AC.IsFatherAcademic,0) As IsFatherAcademic,
	 ISNULL (AC.IsMotherDetail,0) As IsMotherDetail,
	 ISNULL (AC.IsMotherFullDetail,0)As IsMotherFullDetail,
	 ISNULL (AC.IsMotherAcademic,0)As IsMotherAcademic,
	 ISNULL (AC.IsGuardianDetail,0)As IsGuardianDetail,
	 ISNULL (AC.IsGuardianFullDetail,0)As IsGuardianFullDetail,
	 ISNULL (AC.IsGuardianAcademic,0)As IsGuardianAcademic,
	 ISNULL (AC.IsOtherInformationRequired,0)As IsOtherInformationRequired,
	 ISNULL (AC.IsHealthDetailRequired,0) As IsHealthDetailRequired,
	 ISNULL (AC.IsCustomField1Required,0) As IsCustomField1Required,
	 ISNULL (AC.IsCustomField2Required,0) As IsCustomField2Required,
	 ISNULL (AC.IsCustomField3Required,0) As IsCustomField3Required,
	 ISNULL (AFM.FatherAdhaarNumber,'') AS FatherAadhaarNumber,
	 ISNULL (AFM.MotherAadhaarNumber,'') AS MotherAadhaarNumber,
	 ISNULL (AFM.RelativeAadhaarNumber,'') AS RelativeAadhaarNumber,
	  (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=324
	 )AS IsOtherDetailsLiveWith,
	  (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=323
	 )AS IsOtherDetailsOtherInformation,
	 ISNULL(AF.MiddleName,'') AS MiddleName,
	 ISNULL(AF.LastName,'')AS LastName,
	 ISNULL(PT.Id,0) AS PaymentTransactionId,
	 ISNULL(PT.PayAmount,0.00) AS PayAmount,
	 ISNULL(PT.TransactionStatusId,0) AS TransactionStatusId,
	 ISNULL(PT.PayDateTime,'') AS PayDateTime

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

				
END
GO
PRINT N'Altering [sAssessment].[pOptionalAcativityAdd]...';


GO
 

ALTER PROCEDURE [sAssessment].[pOptionalAcativityAdd]
  
	@rAcademicId bigint=0,
	@rCCECSId int=0,
	@rIsOptional int=0,
	@rXmlDoc nvarchar(max) = ''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
BEGIN
		SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT			

	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc	
	
	CREATE TABLE #tTable  
	(
		 Id bigint identity
		,Academicid bigint not null
		,CCECSId int not null
		,IsOptional bit null		
	)


	INSERT INTO #tTable
			   (			    
			   Academicid
			   ,CCECSId
			   ,IsOptional			   	   		   
			   )
	SELECT		
		A.AdademicId,
		A.CCECSId,			
		A.IsOptional		
		
	FROM OPENXML (@intDoc, '/Table/CCEOptionalActivity', 1)
	WITH
	(						
		AdademicId bigint '@AdademicId',
		CCECSId int '@CCECSId',
		IsOptional bit '@IsOptional'		
	)A 

	SELECT * FROM #tTable		

	EXEC sp_xml_removedocument @intDoc

	DECLARE @lCount int = 1
	DECLARE @lTotal int = (SELECT COUNT(Id) FROM #tTable)	
	WHILE @lCount <= @lTotal 
	BEGIN						
		DECLARE @lAcademicId bigint = (SELECT AcademicId FROM #tTable WHERE Id = @lCount)		
		DECLARE @lCCECSId bigint = (SELECT CCECSId FROM #tTable WHERE Id = @lCount)		
		DECLARE @lIsOptional bigint = (SELECT IsOptional FROM #tTable WHERE Id = @lCount)	
		
		
		DELETE FROM sAssessment.tOptionalCCECS WHERE AcademicId=@lAcademicId AND CCECSId=@lCCECSId

	--	if Exists(Select 1 From sAssessment.tOptionalCCECS WHere AcademicId=@lAcademicId AND CCECSId=@lCCECSId AND 	@lIsOptional=0)
	--			BEGIN
	--				Delete from sAssessment.tOptionalCCECS where academicid=@lAcademicId AND CCECSId=@lCCECSId  
	--				Select 1 As result 
	--			END
	--		ELSe
	--		BEGIn
	--			IF exists(Select 1 from sAssessment.tOptionalCCECS where AcademicId=@lAcademicId AND CCECSId=@lCCECSId  AND @lIsOptional=1)	
	--			BEGIN
	--			Update  sAssessment.tOptionalCCECS 
	--			Set	 
	--				CCECSId=@lCCECSId
	--				Where academicid=@lAcademicId
	--				Select 1 As Result
	--		END
	--		ELSE
	--BEGIn	
	IF @lIsOptional=1
		BEGIN
			INSERT INTO sAssessment.tOptionalCCECS 
			   (
			    academicid
			   ,CCECSId
			   )
		 VALUES
			   (
				@lAcademicId
			   ,@lCCECSId	 
			   )			   	

		END
		SET @lCount = @lCount + 1	
	END	
	Select 1 as Result
END
GO
PRINT N'Altering [sAssessment].[pRptAllClassSubjectPercentageAnalysis]...';


GO


ALTER PROCEDURE [sAssessment].[pRptAllClassSubjectPercentageAnalysis]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	DECLARE @GradeSetId int
	 Declare @M1 nvarchar(20),@M2 nvarchar(20),@M3 nvarchar(20),@M4 nvarchar(20),@M5 nvarchar(20),@M6 nvarchar(20),@M7 nvarchar(20),@M8 nvarchar(20),@M9 nvarchar(20),@M10 nvarchar(20)	
	 Declare @G1 nvarchar(20),@G2 nvarchar(20),@G3 nvarchar(20),@G4 nvarchar(20),@G5 nvarchar(20),@G6 nvarchar(20),@G7 nvarchar(20),@G8 nvarchar(20),@G9 nvarchar(20),@G10 nvarchar(20)	
	 --Set @GradeSetId =(select TOP(1)GradeSetId from sAssessment.tExamMaster  where ExamSubGroupId = 130100010 AND BatchId=130100001)
	 Set @GradeSetId =(Select AnalysisGradeSetId from sAssessment.tConfiguration Where OrgId=@rOrgId)
		  
	CREATE Table #Temp
	(
		Id Int Identity (1,1),
		MarkRange nvarchar(20),
		MinimumScore decimal(6,2)
	)
	Insert into #Temp
	
		select MarkRange,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId ORDER BY MarkRange DESC

		 Set @M1=(Select MarkRange from #Temp where Id=1) 
	 	 Set @M2=(Select MarkRange from #Temp where Id=2) 
	 	 Set @M3=(Select MarkRange from #Temp where Id=3) 
	 	 Set @M4=(Select MarkRange from #Temp where Id=4) 
	     Set @M5=(Select MarkRange from #Temp where Id=5) 
         Set @M6=(Select MarkRange from #Temp where Id=6) 
	     Set @M7=(Select MarkRange from #Temp where Id=7) 
	 	 Set @M8=(Select MarkRange from #Temp where Id=8) 
	 	 Set @M9=(Select MarkRange from #Temp where Id=9) 
		 Set @M10=(Select MarkRange from #Temp where Id=10) 

		-- Select * from #Temp
		CREATE Table #Temp1
	(
		Id Int Identity (1,1),
		GradeCode nvarchar(20),
		MinimumScore decimal(6,2),
	)
	Insert into #Temp1
	
		select GradeCode,MinimumScore from  sAssessment.tGradeSetDetail where GradeSetId=@GradeSetId ORDER BY MinimumScore DESC
	 --Select * from #Temp1
	 	 Set @G1=(Select MinimumScore from #Temp1 where Id=1) 
	 	 Set @G2=(Select MinimumScore from #Temp1 where Id=2) 
	 	 Set @G3=(Select MinimumScore from #Temp1 where Id=3) 
	 	 Set @G4=(Select MinimumScore from #Temp1 where Id=4) 
	     Set @G5=(Select MinimumScore from #Temp1 where Id=5) 
         Set @G6=(Select MinimumScore from #Temp1 where Id=6) 
	     Set @G7=(Select MinimumScore from #Temp1 where Id=7) 
	 	 Set @G8=(Select MinimumScore from #Temp1 where Id=8) 
	 	 Set @G9=(Select MinimumScore from #Temp1 where Id=9) 
		 Set @G10=(Select MinimumScore from #Temp1 where Id=10)

		 --Select @G2

		 CREATE TABLE #DetailData 
		 (
		 AcademicId bigint,
		 Maximum int,
		 Obtain int,
		 Marks decimal,
		 ClassId int,
		 SubjectId int,
		 DivisionId int
		 )

INSERT INTO #DetailData
		Select R.AcademicId,
		ED.Maximum,
		RD.Obtain,
		(RD.Obtain * 100 /ED.Maximum),
		CS.ClassId,
		CS.SubjectId,
		A.DivisionId
		from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	    INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	    INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	    where 
	    EM.ExamSubGroupId = @rExamSubGroupId 
		AND EM.BatchId = @rBatchId 
		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) 
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		AND (EM.ClassId=@rClassId OR @rClassId=0) 

		--SELECT * FROM #DetailData  Where (Marks Between @G2 AND @G1) AND ClassId=130100002 AND SubjectId=130100001 AND DivisionId=130100003
		--Where Marks>=90

		--SELECT * FROM #DetailData

		SELECT 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
		
	  (select COUNT(RD.Id) from    sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	  INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS NoOfStudent,
	  
	  (select MAX(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS HighestPerMark,

	  (select AVG(RD.Obtain) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R  ON RD.ResultId = R.Id   
	    INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	   INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS AveragePerMark,
	  
	  (select MIN(RD.Obtain) from sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id 
	  INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	    INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS LowestPerMark ,
	
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   Marks >= @G1  AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount1,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	  --AND Marks >=80 AND Marks<90
	   ((Marks >= @G2 )AND (Marks < @G1)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount2,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G3)AND (Marks < @G2)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount3,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G4 )AND (Marks < @G3)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount4,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G5 )AND (Marks < @G4)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount5,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G6)AND (Marks < @G5)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount6,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G7)AND (Marks < @G6)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount7,
	   (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G8)AND (Marks < @G7)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount8,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G9)AND (Marks < @G8)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount9,
	  (Select COUNT(AcademicId) FROM #DetailData DD WHERE 
	  DD.DivisionId = DM.Id AND 
	   ((Marks >= @G10)AND (Marks < @G9)) AND DD.SubjectId=Sm.Id AND DD.ClassId=CM.ClassId 
	  )AS MarkCount10,
   
	  ISNULL(@M1,'-') AS Mark1,
	  ISNULL(@M2,'-') AS Mark2,
	  ISNULL(@M3,'-') AS Mark3,
	  ISNULL(@M4,'-') AS Mark4,
	  ISNULL(@M5,'-') As Mark5,
	  ISNULL(@M6,'-') As Mark6,
	  ISNULL(@M7,'-') AS Mark7,
	  ISNULL(@M8,'-') AS Mark8,
	  ISNULL(@M9,'-') AS Mark9,
	 ISNULL(@M10,'-')  AS Mark10,
	 Sm.Id AS SubjectId,
	  SM.Title AS SubjectName,
	  CS.OrderIndex AS OrderIndex 
	  

	 from

		sAssessment.tExamDetail ED		
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
		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 sSetup.tClassMaster CLM ON CLM.Id=EM.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CLM.Id
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	
		WHERE 
 
			EM.BatchId = @rBatchId 
			AND (EM.ClassId=@rClassId OR @rClassId=0) 
			AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
			AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
			AND CM.BatchId = @rBatchId
			AND (ISNULL(CLM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
			AND CLM.IsObsolete = 0 AND DM.IsObsolete = 0 

		 	DROP TABLE #Temp
			DROP Table #Temp1
			DROP TABLE #DetailData
	   
  	
	
 -- select 
	--	@rBuilder1 AS Builder1,
	--	0 As ClassId,
	--	0 As DivisionId,
	--	'' As Classname,
	--	'' As DivisionName,
		
		 
	--  0 AS NoOfStudent,
	  
	 

	--  0 AS HighestPerMark,

	--  0 AS AveragePerMark,
	  
	--  0 AS LowestPerMark ,
	  
	--  0 AS MarkCount1,
	  
 -- 0 AS MarkCount2,
	 

 -- 0 AS MarkCount3,
	 

 --0 AS MarkCount4,
	 
 --0 AS MarkCount5,
	 
 -- 0 AS MarkCount6,
	 
 --0 AS MarkCount7,
	 
 -- 0 AS MarkCount8,
	 
 -- 0 AS MarkCount9,
	 
 -- 0 AS MarkCount10,
	  
	  
   
	--  0 AS Mark1,
	--  0 AS Mark2,
	--  0 AS Mark3,
	--  0 AS Mark4,
	--  0 As Mark5,
	--  0 As Mark6,
	--  0 AS Mark7,
	--  0 AS Mark8,
	--  0 AS Mark9,
	-- 0  AS Mark10,
	--0 AS SubjectId,
	--  '' AS SubjectName,
	--  0 AS OrderIndex 
	 
	
END
GO
PRINT N'Altering [sAssessment].[pRptCSExamMarkEntryGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptCSExamMarkEntryGet]
	  @rClassId bigint,
	  @rDivisionID Bigint,
	  @rExamId int,
	  @rOrgId int,
	  @rBatchId int,
	  --@rCCECSId int,
	  @rFilter int,
	  @rBuilder nvarchar(max)='',
	  @rCCECAGroupId int=0,
	  @rCCECSId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
SELECT
    @rBuilder AS Builder,
    SA.AcademicId,
    SA.Code,
    SA.Name,
    AM.Title,
    SA.RollNo AS RollNo ,
    CASE WHEN @rFilter=1 THEN ISNULL(AIS.ObtianMark,0) 
    ELSE  ISNULL(AIS.ConvertedMark,0) END AS TotalMark,
	(CASE EM.IsDisplayPhoto WHEN 1 THEN
	SI.StudentPhoto
	ELSE NULL END)AS StudentPhoto,
	EM.IsDisplayPhoto,
	EM.IsOnPrePrinted,
	ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
	(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
	OI.MarksheetHeaderA4 
	ELSE 
	NULL END) AS MarksheetHeaderA4
   
    
	FROM sStudent.vStudentAcademic SA
	INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1
	INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
	 INNER JOIN sAssessment.tCCECSForClass CL ON CL.CCECSID= AM.Id 
	 AND CL.ClassID=@rClassId
	LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.CCECSId= AM.Id 
	AND AIS.ExamId= @rExamId 
	AND (AIS.CCECSId =@rCCECSId OR @rCCECSId = 0) 
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id = AIS.ExamId
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	WHERE 
	SA.ClassId=@rClassId
	And SA.DivisionId = @rDivisionID	
	And SA.BatchId = @rBatchId
	And (AM.CCECAGroupId= @rCCECAGroupId  OR @rCCECAGroupId  = 0 )
	Order by AM.OrderIndex
	END
GO
PRINT N'Altering [sAssessment].[pRptCSExamScoreGet]...';


GO
 
 

ALTER PROCEDURE [sAssessment].[pRptCSExamScoreGet]
	  
	   @rOrgId int
	  ,@rExamId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rBatchId int,
	  @rCCECAGroupId int=0,
	  @rCCEMasterId int=0,
	  @rAcademicId bigint=0,
	  @rBuilder1 nvarchar(max)=''
	  
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
BEGIN TRY
			SELECT 		
				--ISNULL(CGM.Title,'') AS CSGroup,
				--ISNULL(CM.Title,'') AS CS,				
				--ISNULL(CC.Grade,'')  AS Grade,
				--ISNULL(CC.GradeIndicator,'') AS Indicator,
				--ISNULL(CC.DescriptiveIndicator,'')  AS DescriptiveIndicator,			
				--ISNULL(SA.AcademicId,0) AS AcademicId,
				--ISNULL(CC.IndicatorIds,'') AS IndicatorIds,
				--CGM.GradeSetId,
				--CM.Id as CMID
				
				 @rBuilder1 AS Builder1,
				 SA.AcademicId,
				 SA.RollNo,
				 SA.Number,
				 SA.Name,
				  
				 ISNULL(AIS.Grade,'') AS Term1Indicator,
				 CCEM.Title AS GroupTitle,
				 AM.Title AS MasterTitle,
				ISNULL(AIS.ConvertedMark,0) AS ConvertedMark,
				ISNULL(AIS.GradeIndicator,'') AS Indicator,
				ISNULL(AIS.DescriptiveIndicator,'')  AS DescriptiveIndicator	,
				CM.Id AS ClassId,
				CM.Title AS ClassTitle,
				DM.Id AS DivisionId,
				DM.Title AS DivisionTitle,
				SA.Code AS Code,
				(SELECT DisplayTitle FROM sAssessment.tExamMaster WHERE Id = @rExamId) AS ExamTitle	,
				(CASE EM.IsDisplayPhoto WHEN 1 THEN
		        SI.StudentPhoto
			    ELSE NULL END)AS StudentPhoto,
				EM.IsDisplayPhoto,
				EM.IsOnPrePrinted,
				ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
				(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
				OI.MarksheetHeaderA4 
				ELSE 
				NULL END) AS MarksheetHeaderA4
								 
			FROM sStudent.vStudentAcademic SA
				INNER JOIN sAssessment.tCCECSClass CA ON CA.ClassId = SA.ClassId AND SA.StatusId = 1
				INNER JOIN sAssessment.tCCECSMaster AM ON CA.CCECSGroupId=AM.CCECAGroupId
				INNER JOIN sAssessment.tCCECSGroupMaster CCEM ON CCEM.Id=AM.CCECAGroupId
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId AND SA.OrgId = CM.OrgId
				INNER JOIN sSetup.tDivisionmaster DM ON DM.Id = SA.DivisionId AND SA.OrgId = DM.OrgId
				LEFT JOIN sAssessment.tCCECSExamScore AIS ON AIS.AcademicId =SA.AcademicId AND CCECSId= AM.Id And AIS.ExamId=@rExamId
				INNER JOIN sAssessment.tExamMaster EM ON EM.Id = AIS.ExamId
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
				LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			WHERE
				 SA.ClassId=@rClassId 
				And SA.DivisionId =@rDivisionID	
				And SA.BatchId =@rBatchId
				AND AIS.ExamId=@rExamId
				and ((AM.CCECAGroupId=@rCCECAGroupId) OR (@rCCECAGroupId=0))
				AND((AM.Id=@rCCEMasterId) OR (@rCCEMasterId=0))	
				and AM.OrgId=@rOrgId
				and ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))
						
			--FROM   
			--	sAssessment.tCCECSMaster CM 
			--	INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id=CM.CCECAGroupId AND CM.OrgId=@rOrgId
			--	INNER JOIN sAssessment.tCCECSClass CL ON CL.CCECSGroupId = CGM.Id				
			--	INNER JOIN sStudent.vStudentAcademic SA ON   SA.ClassId = CL.ClassId 
			--	LEFT JOIN   sAssessment.tCCECSExamScore CC  ON CC.CCECSID=CM.ID  
			--	AND CC.AcademicId = SA.AcademicId AND ExamId=@rExamId	AND CC.AcademicId = @rAcademicId	
			--	WHERE ((SA.AcademicId = @rAcademicId) OR (@rAcademicId=0))
			--		and SA.ClassId=@rClassId and SA.DivisionId=@rDivisionId
		
			 ORDER BY SA.RollNo
			
END TRY
BEGIN CATCH
	SELECT -1 AS RESULT
END CATCH
END
GO
PRINT N'Altering [sAssessment].[pRptResultListGet]...';


GO
 
ALTER PROCEDURE [sAssessment].[pRptResultListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rDepartmentid int=0,
	 @rStatus int =1,
	 @rGenderId int,
	 @rClassStatusId int=0,
	 @rResultStatus nvarchar(20)='',
	 @rMultiCode nvarchar(max)='',
	 @rOrderBy int = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			Convert(nvarchar(20),A.Id) AS   AcademicIdText,	
	CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
	CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
	CONVERT (nvarchar(20),@rBatchId) AS BatchIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0))AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			SM.Code,
			  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			 DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			EM.IsMarksInDecimal,
			SI.StudentPhoto,
			EM.DisplayTitle,
			OM.SmallAddress1,
			R.ResultRemark,
			R.OtherRemark1,
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			SR.ResultRemark2,
			Em.GradeSetId,
			R.ResultStatus,
			SR.ResultRemark1,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			EI.EmployeeSign,
			EM.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsOnPrePrinted,
			Em.IsDisplayPhoto,
			SR.PresentDays ,			
			SR.TotalDays,
			EM.DecimalFormat,
			CM.Id AS ClassId
      
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId=A.Id AND SR.ExamId = EM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			
			 
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (EM.ClassId=@rClassId OR @rClassId=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 ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		AND ((A.Id =@rAcademicId) OR (@rAcademicId=0))
		
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		ANd SM.StatusId= @rStatus
		AND ((SO.GenderId=@rGenderId) OR (@rGenderId=0))
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND (ISNULL(SM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')

		ORDER BY 
			CASE @rOrderBy WHEN 0 THEN SM.Code END , 
			CASE @rOrderBy WHEN 1 THEN R.RankNumber END , 
			CASE @rOrderBy WHEN 2 THEN A.RollNo END, 
			CASE @rOrderBy WHEN 3 THEN SM.FirstName END
			
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,
	 @rFromStudentCode nvarchar(20)='',
	 @rToStudentCode nvarchar(20)=''
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),
	Gender tinyint

)
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,
	Gender
)
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
	 SO.GenderId
	 
    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))
	           AND ((SA.Code >= @rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	           AND ((SA.Code <= @rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))
	           AND  ISNULL(EM.IsOtherUser,0) = 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,@rClassId,@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 ,@rClassId,@rDivisionId , isnull([1],''),@rOrgId )  AS P1,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,2 ,@rBatchId ,@rClassId,@rDivisionId , isnull([2],''),@rOrgId )  AS P2,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,3 ,@rBatchId ,@rClassId,@rDivisionId , isnull([3],''),@rOrgId )  AS P3,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,4 ,@rBatchId ,@rClassId,@rDivisionId , isnull([4],''),@rOrgId )  AS P4,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,5 ,@rBatchId ,@rClassId,@rDivisionId , isnull([5],''),@rOrgId )  AS P5,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,6 ,@rBatchId ,@rClassId,@rDivisionId , isnull([6],''),@rOrgId ) AS P6,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,7 ,@rBatchId ,@rClassId,@rDivisionId , isnull([7],''),@rOrgId ) AS P7,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,8 ,@rBatchId ,@rClassId,@rDivisionId , isnull([8],''),@rOrgId ) AS P8,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,9 ,@rBatchId ,@rClassId,@rDivisionId , isnull([9],''),@rOrgId ) AS P9,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,10 ,@rBatchId ,@rClassId,@rDivisionId , isnull([10],''),@rOrgId ) AS P10,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,11 ,@rBatchId ,@rClassId,@rDivisionId , isnull([11],''),@rOrgId ) AS P11,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,12 ,@rBatchId ,@rClassId,@rDivisionId , isnull([12],''),@rOrgId ) AS P12,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,13 ,@rBatchId ,@rClassId,@rDivisionId , isnull([13],''),@rOrgId ) AS P13,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,14 ,@rBatchId ,@rClassId,@rDivisionId , isnull([14],''),@rOrgId ) AS P14,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,15 ,@rBatchId ,@rClassId,@rDivisionId , isnull([15],''),@rOrgId ) AS P15,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,16 ,@rBatchId ,@rClassId,@rDivisionId , isnull([16],''),@rOrgId ) AS P16,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,17 ,@rBatchId ,@rClassId,@rDivisionId , isnull([17],''),@rOrgId ) AS P17,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,18 ,@rBatchId ,@rClassId,@rDivisionId , isnull([18],''),@rOrgId ) AS P18,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,19 ,@rBatchId ,@rClassId,@rDivisionId , isnull([19],''),@rOrgId ) AS P19,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,20 ,@rBatchId ,@rClassId,@rDivisionId , isnull([20],''),@rOrgId ) AS P20,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,21 ,@rBatchId ,@rClassId,@rDivisionId , isnull([21],''),@rOrgId ) AS P21,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,22 ,@rBatchId ,@rClassId,@rDivisionId , isnull([22],''),@rOrgId ) AS P22,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,23 ,@rBatchId ,@rClassId,@rDivisionId , isnull([23],''),@rOrgId ) AS P23,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,24 ,@rBatchId ,@rClassId,@rDivisionId , isnull([24],''),@rOrgId ) AS P24,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,25 ,@rBatchId ,@rClassId,@rDivisionId , isnull([25],''),@rOrgId ) AS P25,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,26 ,@rBatchId ,@rClassId,@rDivisionId , isnull([26],''),@rOrgId ) AS P26,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,27 ,@rBatchId ,@rClassId,@rDivisionId , isnull([27],''),@rOrgId ) AS P27,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,28 ,@rBatchId ,@rClassId,@rDivisionId , isnull([28],''),@rOrgId ) AS P28,
			CASE WHEN @Days>=29 THEN  [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,29 ,@rBatchId,@rClassId ,@rDivisionId , isnull([29],''),@rOrgId ) end AS P29,
			CASE WHEN @Days>=30 THEN [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,30 ,@rBatchId ,@rClassId,@rDivisionId , isnull([30],''),@rOrgId ) end AS P30,
			CASE WHEN @Days>=31 THEN [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,31 ,@rBatchId ,@rClassId,@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,Gender
--,
--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 AND ST.AttendanceTagId = 3 THEN 'N' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 4 THEN 'G' 
			      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,Gender
      -- 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))
	        AND ((SA.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	        AND ((SA.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))

			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))
	        AND ((SA.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	        AND ((SA.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))

			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))
	        AND ((SA.Code>=@rFromStudentCode) OR (ISNULL(@rFromStudentCode,'')=''))
	        AND ((SA.Code<=@rToStudentCode) OR (ISNULL(@rToStudentCode,'')=''))

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


GO

ALTER PROCEDURE [sAttendance].[pMonthlyRegisterStudentviewGet]
	 	 
	 	 @rBatchId int,
	 	 @rAcademicId bigint,
	 	 @rAttendanceTypeId tinyint
	 	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
declare @lAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid1 nvarchar(max)=''

IF NOT EXISTS(select 1 From sAttendance.tMonthlyRegister where AcademicId=@rAcademicId and ForMonth=Month(GETDATE()) and ForYear=Year(GETDATE()))
BEGIN

--Current Month Details Add
		DECLARE @PresentCount DECIMAL(10,2)
		DECLARE @AbsentCount DECIMAL(10,2)
		DECLARE @AveragePresence DECIMAL(10,2)
		DECLARE @CurrentMonthDays DECIMAL(10,2)
		DECLARE @AttendanceCount INT 
		SET @CurrentMonthDays = (SELECT DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,getdate()),0))))
		DECLARE @YearNumber INT
		DECLARE @AbsentDays nvarchar(max)

		SET @YearNumber =Year(GETDATE())



		SET @PresentCount = (select count(AttendanceDate) AS PresentCount from sAttendance.tStudentRegister 
		where IsPresent=1 and AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()) AND (AttendanceTypeId=@rAttendanceTypeId))		

		SET @AbsentCount = (select count(AttendanceDate) AS AbsentCount from sAttendance.tStudentRegister 
		where IsPresent=0 and AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()) AND (AttendanceTypeId=@rAttendanceTypeId))		


		SET @AttendanceCount = (select count(AttendanceDate) AS PresentCount from sAttendance.tStudentRegister 
		where AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()) AND (AttendanceTypeId=@rAttendanceTypeId))		

		SET @AveragePresence= (@PresentCount/@AttendanceCount)*100

		SET @AbsentDays=(SELECT SUBSTRING(
		(SELECT ',' + CONVERT(varchar(10), Day(AttendanceDate))
		FROM  sAttendance.tStudentRegister s
		where AcademicId=@rAcademicId and IsPresent=0 and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate())	AND (AttendanceTypeId=@rAttendanceTypeId)		

		ORDER BY AcademicId
		FOR XML PATH('')),2,200000) AS CSV
)
END


SET 
	@lCuurentMonthAttedanceGrid = @lCuurentMonthAttedanceGrid + '<tr>
	<td align="left" scope="col">' + Isnull(LEFT(DATENAME(MONTH,Getdate()),10),'')  + '</td>
	<td align="left" scope="col">' +convert(varchar, isnull( @YearNumber,0))+ '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(@AttendanceCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(CAST(@PresentCount as INTEGER),0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(CAST(@AbsentCount as INTEGER),0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(@AveragePresence,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(@AbsentDays,0)) + '</td>
	<tr>'


	Select 
	@lAttedanceGrid = @lAttedanceGrid + '<tr>
	<td align="left" scope="col">' + Isnull(MY.MonthTitle,'')  + '</td>
	<td align="left" scope="col">' +convert(varchar, isnull( MY.YearNumber,0))+ '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AttendanceCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.PresentCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AbsentCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AveragePresence,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AbsentDays,0),103) + '</td>
	<tr>'
		
	From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND MR.AttendanceTypeId=@rAttendanceTypeId
		AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
	WHERE
		SN.AcademicId=@rAcademicId
	
	ORDER BY MY.YearNumber,MY.MonthNumber
 
		SELECT  isnull(@lAttedanceGrid ,'') + isnull(@lCuurentMonthAttedanceGrid ,'') AS AttedanceGrid
		
		
		
END
GO
PRINT N'Altering [sAttendance].[pSubjectwiseAttendanceGet]...';


GO
 

ALTER PROCEDURE [sAttendance].[pSubjectwiseAttendanceGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
		 @rAttendanceDate date,
		 @rSubjectId int,
	 	 @rBatchId int,
	 	 @rOrgId int,
	 	 @rAttendanceGroupId int = 0,
	 	 @rPeriodNo int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

    DECLARE @lIsOptional bit=0
	SELECT @lIsOptional = ISNULL(IsOptional,0) FROM sSetup.vClassSubject  WHERE SubjectId=@rSubjectId and classid = @rClassId
	IF (@lIsOptional=0)
	BEGIN
		IF(@rAttendanceGroupId=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(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				SA.StudentId
			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=5)
					AND (SR.AttendanceDate=@rAttendanceDate)
					AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
					AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
					AND  ISNULL(SR.AttendanceGroupId,0) = @rAttendanceGroupId
				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 (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
				AND (AD.AdmissionDate <= @rAttendanceDate)
				AND (SA.StatusId NOT IN(2,3))
				ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,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,
				ISNULL(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				SA.StudentId
			FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sAttendance.tAttendanceGroupStudent AGS ON AGS.AcademicId = SA.AcademicId 
				AND AGS.AttendanceGroupId=@rAttendanceGroupId
			INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
				AND (SR.AttendanceTypeId=5)
				AND (SR.AttendanceDate=@rAttendanceDate)
				AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
				AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
				AND SR.AttendanceGroupId=@rAttendanceGroupId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			WHERE 
			(SA.OrgId = @rOrgId)
			AND (SA.BatchId = @rBatchID)
			AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rAttendanceDate)
			AND (SA.StatusId NOT IN(2,3))
			ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
		END	
	END 
	ELSE 
	BEGIN
		IF(@rAttendanceGroupId=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(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				SA.StudentId
			FROM 
				sStudent.vStudentAcademic SA 
				INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
				INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId= SA.AcademicId
				INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id= CS.SubjectId AND (SubjectId=@rSubjectId OR @rSubjectId=0)
				LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
					AND (SR.AttendanceTypeId=5)
					AND (SR.AttendanceDate=@rAttendanceDate)
					AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
					AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
					AND  ISNULL(SR.AttendanceGroupId,0) = @rAttendanceGroupId
				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 (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
				AND (AD.AdmissionDate <= @rAttendanceDate)
				AND (SA.StatusId NOT IN(2,3))
				ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,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,
				ISNULL(SR.PeriodNo,0) AS PeriodNo,
				SA.ClassName+' - '+SA.DivisionName AS Class,
				SA.StudentId
			FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sAttendance.tAttendanceGroupStudent AGS ON AGS.AcademicId = SA.AcademicId 
				AND AGS.AttendanceGroupId=@rAttendanceGroupId
			INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			INNER JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId= SA.AcademicId
				INNER JOIN sSetup.tClassSubject CS ON CS.Id = OS.ClassSubjectId 
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id= CS.SubjectId AND (SubjectId=@rSubjectId OR @rSubjectId=0)
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
				AND (SR.AttendanceTypeId=5)
				AND (SR.AttendanceDate=@rAttendanceDate)
				AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
				AND ((ISNULL(SR.PeriodNo,0)=@rPeriodNo) OR (@rPeriodNo=0))
				AND SR.AttendanceGroupId=@rAttendanceGroupId
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
			WHERE 
			(SA.OrgId = @rOrgId)
			AND (SA.BatchId = @rBatchID)
			AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
			AND (AD.AdmissionDate <= @rAttendanceDate)
			AND (SA.StatusId NOT IN(2,3))
			ORDER BY SA.ClassOrderIndex,SA.DivisionOrder,RollNo
		END 
	END
END
GO
PRINT N'Altering [sBiometric].[pBiometricDailyReportGet]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pBiometricDailyReportGet]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 0,	
	 @rStatus nvarchar(max) = '',
	 @rEmployeeStatusId int=0,
	 @rOrderBy smallint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
DECLARE  @rToDate Date
SET @rToDate = @rFromDate

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 
AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
AND ISNULL(EM.IsOtherUser,0) = 0 

DECLARE @lCount int
DECLARE @lCount1 int
Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lMonth as nvarchar(3)
DECLARE @lYear as nvarchar(4)

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)
		Select @lMonth = RIGHT('00' + CAST(DATEPART(MM,@lDate) AS varchar(2)), 2)
		Select @lYear  = RIGHT('0000' + CAST(DATEPART(yyyy,@lDate) AS varchar(4)), 4)
		
		set @lQuery = 'INSERT INTO #TempMonthTrans
						SELECT Distinct ' + convert(nvarchar(15),@lEmployeeId) + ',''' + convert(nvarchar(15),@lDate) + ''',
						substring(DATENAME( dw, ''' + convert(nvarchar(15),@lDate) + '''),1,3) AS DN1,
											 

											 CASE When [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', ' + convert(nvarchar(10),@lYear) + ',' + convert(nvarchar(10),@lMonth) + ',' + convert(nvarchar(15),@lDay)+',
											 ' + convert(nvarchar(15),@lBatchId) + ',' + Convert(nvarchar(10),@rOrganizationDepartmentId) + ',' + convert(nvarchar(10),@rOrgId) + ') <> ''-'' then 
											 [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', ' + convert(nvarchar(10),@lYear) + ',' + convert(nvarchar(10),@lMonth) + ',' + convert(nvarchar(15),@lDay)+',
											 ' + convert(nvarchar(15),@lBatchId) + ',' + Convert(nvarchar(10),@rOrganizationDepartmentId) + ',' + convert(nvarchar(10),@rOrgId) + ') 
											 else D'+convert(nvarchar(15),@lDay)+' end AS 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)'
						--print @lQuery
			execute (@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1	
	END
	
	
	--Select * from #TempMonthTrans
	--return
	

	SET @strQuery = 'select Day(T.Attn_Date), T.*,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	Emp.Code AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,''' +CAST(@rOrderBy AS NVARCHAR(3)) + ''' AS OrderBy,
	DM.Displaytitle DeptName, Emp.Number AS Number	
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 
	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 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 PresentStatus IN ' + @rStatus + ' AND (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0) Order By T.Attn_Date,T.EmployeeId'
	--WHERE (PresentStatus IN '+ '''' + @rStatus + '''' + ' OR (PresentStatus like ''%L%'')) Order By T.Attn_Date,T.EmployeeId' 


	--WHERE 1=1 and (ED.EmployeeGradeId in (' + convert(nvarchar(100),@rGRadeId) + ') OR (' + convert(nvarchar(100),@rGRadeId) + ') = 0) )' 
	
	
	print (@strQuery)
	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 TotEarly,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as IsFirstIn,
	--'' as IsLastOut,
	--'' as IsOT,
	--'' as IsLateBy,
	--'' as IsEarlyBy,
	--'' as IsDuration,
	--'' as OrderBy,
	--'' as Number
END

	--CASE 
	--					When [sHrm].[fWeekHOffGetBio](' + 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) + ') in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
	--					When [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',' + CONVERT(nvarchar(13),@rOrganizationDepartmentId) + ',' + convert(nvarchar(15),@rOrgId) + ') Not in (''-'',''XX'') 
	--					Then [sHrm].[fWeekHOffGetBio](' + 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
GO
PRINT N'Altering [sBiometric].[pEmployeeCheckInGet]...';


GO
 

ALTER PROCEDURE [sBiometric].[pEmployeeCheckInGet]
	 
	 @rOrgId int = 0,
	 @rEmployeeId bigint=0,
	 @rFromDate date = '',
	 @rToDate date = ''
		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	 Select 
		U.LoginTitle,B.EmployeePhoto ,EMp.FirstName+' ' +ISNULL(EMp.MiddleName,'')+' '+emp.LastName AS Name,CONVERT(VARCHAR(10),B.CheckInTime,3) AS [DATE],CAST(B.CheckInTime AS TIME) AS CheckInTime,Emp.Id As EmployeeID ,CAST(B.CheckOutTime AS TIME) AS CheckOutTime,B.Id,emp.Code,
		ISNULL(LatitudeAxis,'') AS LatitudeAxis, ISNULL(LongitudeAxis,'') AS LongitudeAxis, ISNULL(Location,'') AS Location, EMp.Code
	 from sSecurity.tUser 
	 U INNER JOIN sHrm.tEmployeeMaster EMP ON  EMP.Id=U.SourceId
	 INNER JOIN sBiometric.tEmployeeCheckIn B ON B.EmployeeID=EMP.Id
	 WHere U.SourceTypeId =95 AND (U.OrgId=@rORgId OR @rORgId = 0)
	 AND ((B.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0)) AND  ISNULL(EMP.IsOtherUser,0) = 0 
	 AND ((CAST(B.AttendanceDate AS DATE) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 AND ((CAST(B.AttendanceDate AS DATE) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	
END
GO
PRINT N'Altering [sCommon].[pOrgGroupSetupRemove]...';


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

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




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

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

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


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

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

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

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

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

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

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

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

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

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

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

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

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

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

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

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

DELETE FROM sErp.tCustomerMaster WHERE OrgGroupId = @rOrgGroupId

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

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

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


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


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

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


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

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

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

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


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

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

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


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

	-- special case will come orgwise and orggroupwise

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


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


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

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

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

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

DELETE FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @rOrgGroupId



DELETE FROM sCommon.tOrgGroupDepartmentMaster WHERE OrgGroupId = @rOrgGroupId

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


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

DELETE FROM sErp.tCustomerPlugInLog WHERE OrgGroupId= @rOrgGroupId

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

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

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


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

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

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

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

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

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


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


GO
 

ALTER PROCEDURE [sCommunication].[pAssignmentAdd]
	 
        @rId bigint,
        @rSubjectId int,
		@rTitle nvarchar(100),
		@rRemark nvarchar(max),
		@rStartDate date,
		@rEndDate date,
		@rCreatedUserId bigint,
		@rBatchId int,
		@rOrgId int,
		@rIsAssignmentDocumentUpload bit = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		--If Exists(select Id from sCommunication.tAssignment where Code=@rCode AND BatchId=@rBatchId)
		--	BEGIN
		--	select -102 as Result
		--	RETURN
		--END 
	
		If Exists(select Id from sCommunication.tAssignment where Title=@rTitle AND BatchId=@rBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		--If Exists(select Id from sCommunication.tAssignment where Code=@rCode AND BatchId=@rBatchId AND Id<>@rId)
		--Begin
		--	select -102 as Result
		--	RETURN
		--End
		If  Exists(select Id from sCommunication.tAssignment where Title=@rTitle AND BatchId=@rBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End

	END
	
	
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommunication.tAssignment', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tAssignment
		(
			Id,
			SubjectId,
			Title,
			Remark,
			StartDate,
			EndDate,
			CreatedUserId,
			CreatedDateTime,
			BatchId,
			IsAssignmentDocumentUpload
		)
	VALUES
		(
			@lNextNumber,
			@rSubjectId,
			@rTitle,
			@rRemark,
			@rStartDate,
			@rEndDate,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rBatchId,
			@rIsAssignmentDocumentUpload
		)
		    SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION         
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tAssignment
	    SET
			SubjectId=@rSubjectId,
			Title=@rTitle,
			StartDate=@rStartDate,
			EndDate=@rEndDate,
			Remark=@rRemark,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			IsAssignmentDocumentUpload = @rIsAssignmentDocumentUpload
	      
	      WHERE Id = @rId
	      
	      --DELETE FROM sCommunication.tAssignmentView WHERE AssignmentId=@rId
	      
	      SELECT @lNextNumber AS Result
	
		--COMMIT TRANSACTION
	 END  	

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


GO

ALTER PROCEDURE [sCommunication].[pRptFeedbackAnalysistReport]
	  @rOrgGroupBatchId bigint = 0,
	  @rFeedbackId bigint = 0 ,
	  @rFeedbackForId bigint = 0,
	  @rBuilder1 nvarchar(max)='',
	  @rBuilder2 nvarchar(max)='',
	  @rReportId int = 0	
	-- @rUserSourceId bigint=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
DECLARE @lFeedBackTemplateId bigint
DECLARE @lMaxFeedBackPoint Decimal(10,2)
DECLARE @lSourceTypeId int
select @lFeedBackTemplateId = FeedbackTemplateId from sCommunication.tFeedback F WHERE F.Id = @rFeedbackId
--SELECT * FROM sCommunication.tFeedbackFor WHERE Id= @lSourceTypeId

SELECT  @lMaxFeedBackPoint = ISNULL(MAX(FeedbackPoint),0) FROM sCommunication.tFeedbackTemplateQuestion TQ
INNER  JOIN sCommunication.tFeedbackAnswerTypeMaster FAT ON FAT.Id = TQ.FeedbackAnswerTypeId 
INNER JOIN  sCommunication.tFeedbackAnswerTypeDetail FATD ON FAT.Id = FATD.FeedbackAnswerTypeId
 WHERE TQ.FeedbackTemplateId = @lFeedBackTemplateId

 IF(@rReportId = 30927)
 BEGIN
	SELECT	
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		FQ.Id As TempateQuestionId,
		FQ.QuestionNumber,
		FQ.Question ,
		FQ.FeedbackAnswerTypeID,			 
		ISNULL(FQR. FeedbackAnswerTypeDetailId,0) AS FeedbackAnswerTypeDetailId,
		FR.SourceId ,
		 
		case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FATD.FeedbackPoint,
		@lMaxFeedBackPoint AS FeedbackPointMax
					
					
		from sCommunication.tFeedback FB 
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id 
		INNER JOIN	sCommunication.tFeedbackTemplateQuestion FQ ON FQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id 
		AND FQR.FeedbackTemplateQuestionID = FQ.Id
		INNER JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
		INNER JOIN sCommunication.tFeedbackAnswerTypeMaster FAT ON FAT.Id=FATD.FeedbackAnswerTypeId
		
		--AND FQR.FeedBackResponseId = 1001000000001
		--LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FA ON FA.ID=FQR.FeedbackAnswerTypeDetailId
		WHERE ((FB.Id = @rFeedbackId) OR (@rFeedbackId = 0))
			  AND ((FR.FeedbackForId =@rFeedbackForId) OR (@rFeedbackForId = 0)) 
		      ANd ((OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
 END
 ELSE
 BEGIN
	SELECT	
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		FQ.Id As TempateQuestionId,
		FQ.QuestionNumber,
		FQ.Question ,
		FQ.FeedbackAnswerTypeID,			 
		ISNULL(FQR. FeedbackAnswerTypeDetailId,0) AS FeedbackAnswerTypeDetailId,
		FR.SourceId ,
		 
		case  ISNULL(FATD.Title,'')
		when 
			''
		Then
			ISNULL(FQR.FeedbackAnswerDescription,'')
		Else
			ISNULL(FATD.Title,'') 
		END
		AS FeedbackAnswerDescription,
		FATD.FeedbackPoint,
		@lMaxFeedBackPoint AS FeedbackPointMax
					
					
		from sCommunication.tFeedback FB 
		INNER JOIN	sCommunication.tFeedbackTemplateQuestion FQ ON FQ.FeedbackTemplateId = FB.FeedbackTemplateId
		INNER JOIN sCommunication.tFeedbackResponse FR ON FR.FeedbackId = FB.Id AND ((FR.FeedbackForId =@rFeedbackForId) OR (@rFeedbackForId = 0)) 
		INNER Join sCommunication.tFeedbackQuestionResponse FQR ON  FQR.FeedBackResponseId = FR.Id 
		AND FQR.FeedbackTemplateQuestionID = FQ.Id
		INNER JOIN sCommunication.tFeedbackAnswerTypeDetail FATD ON FATD.Id=FQR.FeedbackAnswerTypeDetailId
		INNER JOIN sCommunication.tFeedbackAnswerTypeMaster FAT ON FAT.Id=FATD.FeedbackAnswerTypeId
		
		--AND FQR.FeedBackResponseId = 1001000000001
		--LEFT JOIN sCommunication.tFeedbackAnswerTypeDetail FA ON FA.ID=FQR.FeedbackAnswerTypeDetailId
		WHERE ((FB.Id = @rFeedbackId) OR (@rFeedbackForId = 0))
		 ANd ((OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
 END
		
	  
		 END
GO
PRINT N'Altering [sCommunication].[pStudentDocumentUploadAdd]...';


GO
 
 

ALTER PROCEDURE [sCommunication].[pStudentDocumentUploadAdd]
	 
        @rId int,
        @rTitle nvarchar(100),
        @rDocumentUploadDate date,
		@rDivisionId int,
		@rIsObsolete bit,
		@rBatchId int,
		@rOrgId int,
		@rCreatedUserId bigint,
		@rStudentDocumentType int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sCommunication.tStudentDocumentUpload where Title=@rTitle AND DivisionId=@rDivisionId
		 AND BatchId=@rBatchId)
			BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from sCommunication.tStudentDocumentUpload where Title=@rTitle AND DivisionId=@rDivisionId 
		AND BatchId=@rBatchId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCommunication.tStudentDocumentUpload', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tStudentDocumentUpload
		(
			Id,
			Title,
			DocumentUploadDate,
			DivisionId,
			IsObsolete,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			StudentDocumentTypeId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rDocumentUploadDate,
			@rDivisionId,
			@rIsObsolete, 
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rStudentDocumentType 
		)
	END	 

ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE sCommunication.tStudentDocumentUpload
	    SET
			Title=@rTitle,
			DocumentUploadDate=@rDocumentUploadDate,
			DivisionId=@rDivisionId,
			IsObsolete=@rIsObsolete,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			StudentDocumentTypeId=@rStudentDocumentType
	      WHERE Id = @rId
	 END  	
	SELECT @lNextNumber AS Result
	COMMIT TRANSACTION		
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


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

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


GO
 
ALTER PROC [sFee].[pRptDepositWisetransactionList] 
		
	 @rDepositHeadId int,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(20)='',
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
     @rBatchId int,
     @rBuilder1 nvarchar(max)='',
     @rBuilder2 nvarchar(max)='',
     @rDepartmentId int=0,
     @rClassId int=0,
     @rDivisionId int=0,
     @rStudentName  nvarchar(100)='',
     @rFromDate date='',
     @rToDate date=''
   
      
AS
BEGIN

--select '' DepositDate,
--		0 as Amount,
--		0 AS Credit,
--		0 AS Debit,
--		0 As Balance,
--		'' as Code,
--		'' as StudentName,
--		0 as StudentId,
--convert(bigint,0) as StudentId,
--		'' as Class,
--		'' as SUId,
--		'' as GroupType,
--		0 as GroupID
	
	SELECT * 
	FROM	
	(
	SELECT 
			
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Amount,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    'DepositeAdd' As GroupType,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		    DA.CreatedDateTime,
		    VA.StudentId,
		    @rBuilder1 As builder1,
		    DA.DepositNumber AS Number

			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
			Where 
		   ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.DepositHeadId = @rDepositHeadId)
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
		    AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
		    AND ((convert(date,DA.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    AND ((convert(date,DA.CreatedDateTime)<=@rToDate) OR (ISNUll(@rToDate,'')=''))
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			-ISnull (DAJ.Amount,0) As Amount,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    'DepositeAdjustment' As GroupType,
		    
		    VA.Name As StudentName, 
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     DAJ.CreatedDateTime,
		     VA.StudentId,
		     @rBuilder1 As builder1,
		     DAJ.AdjustmentNumber AS Number
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			Where 
			((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
		    AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
			AND ((convert(date,DAJ.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((convert(date,DAJ.CreatedDateTime)<=@rToDate) OR (ISNULL(@rToDate,'')=''))
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			-ISnull (DR.RefundAmount,0) AS Amount,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    'DepositeRefund' As GroupType,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') AS  SUId,
		    DR.CreatedDateTime,
		    VA.StudentId,
		    @rBuilder1 As builder1,
		    DR.RefundNumber AS Number
		     
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			Where 
			((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
			AND ((convert(date,DR.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((convert(date,DR.CreatedDateTime)<=@rTodate) OR (ISNULL(@rToDate,'')=''))
    ) A
	Order by A.DepositDate Asc
 
END
GO
PRINT N'Altering [sFee].[pRptFeeInvoiceGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeeInvoiceGet]
		
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rReportId int,
		@rIsFilter bit,
	    @rIsDisplayOrgGroup bit,
	    @rIsFeeInvoiceHeadwise bit,
		@rOrgGroupBatchId int,
		@rCommonBatch nvarchar(100),
		@rReceiptBookId int,
		@rOrgId int,
		@rBatchId int,
		@rDepartmentId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rStatusId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rCollectionGroupId int=0,
	    @rFeeHeadId nvarchar(max) = '',
	    @rFeeId nvarchar(max) = '',
	    @rFilterId int=0,
	    @rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0    
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	IF(@rReportId != 20886)
	BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		FS.AcademicId,
		FS.Name,
		FS.ClassId,
		FS.ClassName,
		FS.DivisionId,
		FS.DivisionName,
		FS.DivisionOrder,
		FS.RollNo,
		FS.Code,
		FS.DepartmentId,
		FS.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		--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) AS FeeAmount,
		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 FeeAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		FS.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		RBM.GroupTitle AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		ISNULL(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
		ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
			        
	         CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader
  FROM 
		sFee.tFeeMaster FM 
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			    FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
				WHERE FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = SA.BatchId AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
				AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=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,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
			INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=SA.AcademicId) AND(FO.SourceTypeId=2001)
			WHERE FS1.BatchId = SA.BatchId AND FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=1 
			AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId 
		AND FS.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=FS.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = FS.StudentId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=FS.AcademicId) AND(FA.SourceTypeId=2001)
		
         LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=FS.StudentId AND AR.SourceTypeId=2003 AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = FS.StudentId AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
    
    LEFT  JOIN
	(
	    SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,
				RD.FeeSetupId,
				R.SourceId
	    FROM
				sFee.tReceipt R 
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = R.PayTypeId
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			
			--AND (R.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId=0)
			--AND (R.CollectionGroupId=@rCollectionGroupId OR @rCollectionGroupId=0)
		WHERE		
			(R.SourceTypeId = 2001)
			AND (R.IsObsolete = 0) 
			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND ((SA1.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
				GROUP BY FeeSetupId,R.SourceId,R.ReceiptNumber,R.ReceiptDate,PTM.Title,R.ChequeNo,R.BankName,R.ChequeDate
	) R ON R.FeeSetupId = FS.Id AND FS.AcademicId = R.SourceId
    
WHERE 
		(FS.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((FS.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((FS.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((FS.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((FS.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((FS.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((FS.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((FS.Code=@rCode) OR (@rCode=''))
		AND ((FS.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		--AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) > 0  
		AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0  
         AND (
			 (@rFilterId = 0) -- All
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			 ) 
	END
	ELSE
	BEGIN
		SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		FS.AcademicId,
		FS.Name,
		FS.ClassId,
		FS.ClassName,
		FS.DivisionId,
		FS.DivisionName,
		FS.DivisionOrder,
		FS.RollNo,
		FS.Code,
		FS.DepartmentId,
		FS.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		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) AS FeeAmount,
		--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 FeeAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		FS.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		RBM.GroupTitle AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		ISNULL(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
		ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
			        
	         CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader
  FROM 
		sFee.tFeeMaster FM 
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			    FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
				WHERE FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = SA.BatchId AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
				AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=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,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
			INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=SA.AcademicId) AND(FO.SourceTypeId=2001)
			WHERE FS1.BatchId = SA.BatchId AND FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=1 
			AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId 
		AND FS.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=FS.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = FS.StudentId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=FS.AcademicId) AND(FA.SourceTypeId=2001)
		
         LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=FS.StudentId AND AR.SourceTypeId=2003 AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = FS.StudentId AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))        
    
WHERE 
		(FS.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((FS.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((FS.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((FS.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((FS.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((FS.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((FS.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((FS.Code=@rCode) OR (@rCode=''))
		AND ((FS.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) > 0  
		--AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0  
         AND (
			 (@rFilterId = 0) -- All
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			 ) 
	END
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptDetailListGet]...';


GO
 
 
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailListGet]  
  @rReportId int,  
  @rReceiptBookId int,  
  @rAdmissionCategoryId int,  
  @rClassId int,  
  @rDivisionId int,  
  @rFromDate date,  
  @rToDate date,  
  @rFromReceiptNo int,  
  @rToReceiptNo int,  
  @rBatchId int,  
  @rUserId bigint,  
  @rBuilder1 nvarchar(max),  
  @rBuilder2 nvarchar(max),  
  @rIsCancel bit,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int,  
  @rCommonBatch nvarchar(100),  
  @rDepartmentId int,  
  @rFromRollNo int,  
     @rToRollNo int,  
     @rCode nvarchar(20),  
     @rIsDetail bit=0,  
  @rIsFilter bit,  
  @rIsHeader bit,  
  @rCreatedUserName nvarchar(100)='',  
  @rFeeHeadId nvarchar(max) = '',  
  @rIsDisplayOrgGroup bit=0,  
  @rPayTypeId int=0,  
  @rFeeId nvarchar(max) = '',  
  @rFilterId int=0,
  @rOrgIds nvarchar(max) = '',
  @rClassStatusId int=0,
  @rPayTypeIds nvarchar(max) = ''  
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN    
 SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.AcademicId,  
  SA.FirstName,  
  SA.MiddleName,  
  SA.LastName,  
  SA.Code,  
  SA.Name,  
  PTM.Title AS PayType,  
  --R.ChequeNo,  
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
  R.BankName,  
  --R.ReceiptAmount,  ,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
  R.ReceiptDate,  
  FM.Title AS FeeDetail,  
  FM.Code AS FeeCode,  
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
  ISNULL(FHM.Title,'') AS FeeHead,  
  ISNULL(FHM.Code,'') AS FeeHeadCode,  
  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
  SA.OrgId,  
  O.DisplayTitle AS OrgName,  
  O.OrderIndex AS OrgOrderIndex,  
  ISNULL(R.Remark,'') AS Remark,  
  DM.Id AS DepartmentId,  
  DM.Title AS DepartmentName,  
  SA.ClassOrderIndex,  
  ISNULL(SO.GenderId,0) AS GenderId,  
  ISNULL(SA.BatchName,'') BatchName,  
  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
  R.ChequeDate,  
  ISNULL(FM.Id,0) AS FeeId,  
  ISNULL(FM.Title,'') AS Fee,  
  ISNULL(SF.FatherName,'' ) AS FatherName,  
  ISNULL(SF.MotherName,'' ) AS MotherNameDiscount,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
  RD.Amount AS PaidAmount,
  ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex
  FROM   
   sFee.tReceipt R  
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  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 FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId  
  --LEFT JOIN sSecurity.tUser U  
  -- ON U.Id=R.CreatedUserId  
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.StudentId = SA.StudentId  
    LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
     LEFT JOIN  
 (SELECT AT.SourceId FROM sTransport.tAssignRoute AT   
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 --AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
 AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
 AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))  
 AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
   )  
  AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')     
 ORDER BY R.ReceiptNumber  
 --ORDER BY R.Id 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END
GO
PRINT N'Altering [sFrontOffice].[pVisitorLogAdd]...';


GO
ALTER PROCEDURE [sFrontOffice].[pVisitorLogAdd]
	 
	@rId int,
	@rVisitorName nvarchar(100),	
	@rNoOfVisitor int,
	@rPurposeOfVisit nvarchar(200),
	@rWhomToMeet bigint=0,	
	@rWhomToMeetName nvarchar(100),
	@rInTime datetime,
	@rOutTime datetime,
	@rVisitorPhoto varbinary(max),
	@rOrgId int,
	@rCreatedUserId bigint,
	@rVisitDate date,
	@rRemark nvarchar(300)='',
	@rVisitorContactNumber nvarchar(100),
	@rStudentId nvarchar(100)='',
	@rStatusId int=0
	
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	
	
	--	IF(@rId = 0)	
	--BEGIN
	--	If Exists(select Id from sCommunication.tQueryCategoryMaster where Title=@rTitle AND OrgId=@rOrgId)
	--		BEGIN
	--		select -103 as Result
	--		RETURN
	--	END 
 
	--END
	--ELSE
	--BEGIN
 
	--	If  Exists(select Id from sCommunication.tQueryCategoryMaster where Title=@rTitle AND OrgId =@rOrgId AND Id<>@rId)
	--	Begin
	--		select -103 as Result
	--		RETURN
	--	End

	--END
	
	
	
	
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber INT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFrontOffice.tVisitorLog', 0, 1, 1,@outNextNumber = @lNextNumber output


	INSERT INTO sFrontOffice.tVisitorLog
		(
			Id,
			VisitorName,
			NoOfVisitor,
			PurposeOfVisit,
			WhomToMeet,
			WhomToMeetName,
			InTime,
			OutTime,
			VisitorPhoto,
			VisitDate,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			Remark,
			VisitorContactNumber,
			StudentId,
			StatusId
		)
	VALUES
		(
			@lNextNumber,
			@rVisitorName,	
			@rNoOfVisitor,
			@rPurposeOfVisit,
			@rWhomToMeet,	
			@rWhomToMeetName,
			@rInTime,
			@rOutTime,
			@rVisitorPhoto,
			@rVisitDate,
			@rOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rRemark,
			@rVisitorContactNumber,
			@rStudentId,
			@rStatusId
		)
		             
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sFrontOffice.tVisitorLog
	    SET
	   
	       VisitorName=@rVisitorName,
			NoOfVisitor=@rNoOfVisitor,
			PurposeOfVisit=@rPurposeOfVisit,
			WhomToMeet=@rWhomToMeet,
			WhomToMeetName=@rWhomToMeetName,
			InTime=@rInTime,
			OutTime=@rOutTime,
			VisitorPhoto=@rVisitorPhoto,
			OrgId=@rOrgId,
			CreatedUserId=@rCreatedUserId,
			VisitDate=@rVisitDate,
			Remark	=@rRemark,
			VisitorContactNumber=@rVisitorContactNumber,
			StudentId=@rStudentId
		
	      
	      
	      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 [sFrontOffice].[pVisitorLogGet]...';


GO
ALTER PROCEDURE [sFrontOffice].[pVisitorLogGet]
          
           @rVisitorId int=0,
           --@rOutTimeFrom datetime,
           --@rOutTimeTo datetime,
           @rFromVisitDate datetime,
           @rToVisitDate datetime,
           @rOrgId int=0,
           @rWhomToMeetName nvarchar(100)='',
           @rIsPrintView bit=0,
           @rOrgGroupId int =0,
           @rTypeId int=0 ,
		   @rStatusId int=0 
           --@rIsWildCardSearch bit
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rWhomToMeetName = sCommon.fSearchStringGet(@rWhomToMeetName)
		--END
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId


BEGIN
SELECT  
	   VL.Id As VisitorId,
       VL.VisitorName,
       VL.NoOfVisitor,
       VL.PurposeOfVisit,
       VL.WhomToMeet AS WhomToMeetId,
       VL.WhomToMeetName,
       VL.InTime,
       VL.OutTime,
       ISNULL(VL.VisitDate,'1900-01-01 00:00:00') AS VisitDate,
       --VL.CreatedDateTime ,
       (CASE  WHEN @rIsPrintView=1 THEN 
				VL.VisitorPhoto		
			ELSE ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
       --ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
       VL.OrgId,
       ISNULL(OM.DisplayTitle,'') AS Organization,
       ISNULL(Remark,'') AS Remark,
       @GatePassConfig AS ConfigValue,
	   ISNUll(VisitorContactNumber,'') AS VisitorContactNumber,
	   ISNULL(StudentId,0) AS StudentId,
	   (CASE WHEN ISNULL(VL.StudentId,0)=0 THEN 'Visitor'
			 ELSE 'Parents' END) AS VisitorType,
	   (CASE WHEN ISNULL(VL.OutTime,'00:00:00')='00:00:00' THEN 0
			 ELSE 1 END) AS InOutStatus,
		OM.OrgGroupId AS OrgGroupId,
		SM.Title as Status,
		ISNULL(VL.StatusId,0) as StatusId
		
  FROM  sFrontOffice.tVisitorLog VL 
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId
  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = VL.StatusId
 
  WHERE 
	(VL.OrgId=@rOrgId OR @rOrgId=0) AND OM.OrgGroupId=@rOrgGroupId
	AND (VL.Id=@rVisitorId OR @rVisitorId=0)
	AND ((VL.WhomToMeetName LIKE @rWhomToMeetName) OR (ISNULL(@rWhomToMeetName,'')=''))
	AND (VL.VisitDate>=@rFromVisitDate OR ISNULL(@rFromVisitDate,'')='')
	AND (VL.VisitDate<=@rToVisitDate OR ISNULL(@rToVisitDate,'')='')
	AND ( (ISNULL(VL.StudentId,1) = @rTypeId) OR  (@rTypeId=0) OR (((VL.StudentId > 0 AND @rTypeId=2) OR  @rTypeId=0))) -- Visitor 
	AND ((VL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0)) 
	 -- Parents
  ORDER BY VL.VisitDate DESC,VL.InTime DESC
END
GO
PRINT N'Altering [siTax].[pRptTDSReport]...';


GO
ALTER PROCEDURE [siTax].[pRptTDSReport]
	@rEmployeeID bigint,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rAssessmentYearId bigint,
	@rBuilder1 VARCHAR(MAX)=null,
	@rBuilder2 VARCHAR(MAX)=null,
	@rStatusId smallint=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	
	--DECLARE @rOrgId int =1001
	--DECLARE @rEmployeeID BIGINT=3333000000044,1001000000160
	--DECLARE @rOrgGroupId smallint=1001
	--DECLARE @rAssessmentYearId bigint=1001000000009




	DECLARE @year int,@AssessmentYear VARCHAR(1000),@FromDate Date,@ToDate Date,@Place VARCHAR(1000),@rItemValue NVARCHAR(50)
	DECLARE @Quarter1 Decimal(18,2),@Quarter2 Decimal(18,2),@Quarter3 Decimal(18,2),@Quarter4 Decimal(18,2),@Total Decimal(18,2),@AmountWord  VARCHAR(500)

	SELECT @year=SUBSTRING(Title,0,5),@AssessmentYear=Title 
	FROm [siTax].[tAssessmentYear] 
	WHERE id=@rAssessmentYearId 
	
	SET @year=ISNULL(@year,2000)
	SET @FromDate= CONVERT(DATE, CAST( CAST((@year-1) AS varchar(10)) +'-'+  '4' +'-'+ '1' AS VARCHAR(100)))
	SET @ToDate= CONVERT(DATE, CAST( CAST(@year AS varchar(10)) +'-'+  '3' +'-'+ '31' AS VARCHAR(100)))





	
	
	DECLARE   @EmployeeMaster TABLE(RowID int Identity(1,1),EmployeeID bigint)
	
	
	
	DECLARE	 @QuarterDetails TABLE 
		(
			RowID int Identity(1,1),
			EmployeeID bigint,
			Quarter1 Decimal(18,2),
			Quarter2 Decimal(18,2),
			Quarter3 Decimal(18,2),
			Quarter4 Decimal(18,2),
			Total Decimal(18,2),
			AmountWord NVARCHAR(500),
			TotalHTML NVARCHAR(500)
		)

	INSERT INTO @EmployeeMaster(EmployeeID)
	SELECT EMP.ID 
	FROM sHrm.vExtEmployeeMaster  AS EMP
	INNER JOIN [siTax].[tForm16] AS F16 ON f16.EmployeeId=EMP.ID
	WHERE EMP.OrgID=@rOrgId AND ((EMP.StatusId=@rStatusId) OR (@rStatusId=0)) AND F16.AssesmentYearId=@rAssessmentYearId

	
	select @rItemValue=ISNULL(CGS.ItemValue,CNF.ItemValue) from [sConfig].[tConfigurationMaster] AS CNF
	LEFT JOIN [sConfig].[tConfigurationSetup] AS CGS ON CGS.ConfigurationId=CNF.Id AND CGS.SourceTypeId = 2010 AND CGS.SourceId = @rOrgGroupId
	WHERE CNF.id=211 

	PRINT @rItemValue
		

	DECLARE @Count int = (SELECT COUNT(0) FROM   @EmployeeMaster)
	DECLARE @EmpID Bigint=null


	While (@Count<>0) 
	BEGIN

		SELECT @EmpID=EmployeeID FROM @EmployeeMaster WHERE RowID=@Count
	
		SELECT 
			@Quarter1=ISNULL(SUM(amount),0) 
		FROM [siTax].[tIncomeTaxChallan] 
		WHERE IsObsolete=0 AND   
			  EmployeeId =@EmpID AND 
			  OrgGroupId=@rOrgGroupId AND 
			  AssesmentYearId=@rAssessmentYearId AND 
			  YearFor=(@year-1) AND 
			  MonthFor IN (4,5,6)
		
		SELECT 
			@Quarter2=ISNULL(SUM(amount),0) 
		FROM [siTax].[tIncomeTaxChallan] 
		WHERE IsObsolete=0 AND   
			EmployeeId =@EmpID AND 
			OrgGroupId=@rOrgGroupId AND 
			AssesmentYearId=@rAssessmentYearId AND 
			YearFor=(@year-1) AND -- updated by Kundan : Assessment year is next year for current Finanacial Year
			MonthFor IN (7,8,9)
		
		SELECT 
			@Quarter3=ISNULL(SUM(amount),0) 
		FROM [siTax].[tIncomeTaxChallan] 
		WHERE IsObsolete=0 AND   
			  EmployeeId =@EmpID AND 
			  OrgGroupId=@rOrgGroupId AND 
			  AssesmentYearId=@rAssessmentYearId AND 
			  YearFor=(@year-1) AND 
			  MonthFor IN (10,11,12)
		
		SELECT 
			@Quarter4=ISNULL(SUM(amount),0) 
		FROM [siTax].[tIncomeTaxChallan] 
		WHERE IsObsolete=0 AND   
			  EmployeeId =@EmpID AND 
			  OrgGroupId=@rOrgGroupId AND 
			  AssesmentYearId=@rAssessmentYearId AND 
			  YearFor=(@year) AND 
			  MonthFor IN (1,2,3)
		
		SET @Total=@Quarter1+@Quarter2+@Quarter3+@Quarter4
		SET @AmountWord = [sFinanceCommon].[fNumberToWordsWithDecimal](@Total,0,2,0)+ ' Only'
		
		INSERT INTO 
		@QuarterDetails 
		(
			EmployeeID,
			Quarter1,
			Quarter2,
			Quarter3,
			Quarter4,
			Total,
			AmountWord,
			TotalHTML
		)
		SELECT 
			@EmpID, 
			@Quarter1,
			@Quarter2,
			@Quarter3,
			@Quarter4,
			@Total,
			@AmountWord,
			'<U>'+ CAST(@Total AS NVARCHAR(50)) + '</U>'
	
	
		PRINT @Count 
		PRINT @EmpID 
		SET @Count=@Count-1
	END

	SELECT 
		 CASE WHEN @rItemValue='False' THEN  ISNULL(OM.Title,'') ELSE OG.Title END AS OrgName
		,ISNULL(OM.StreetOne,'') +', '+ISNULL(OM.StreetTwo,'') AS OrgAddLine1
		,ISNULL(OM.CityName,'')+'-'+ISNULL(OM.ZipCode,'')   +' ,'+ISNULL(OM.StateName,'') +' ,'+ISNULL(OM.CountryName,'') AS OrgAddLine2
		,ISNULL(OM.PhoneNo,'') AS PhoneNo
		,ISNULL(OM.Email,'')  AS EmailID
		,ISNULL(oo.PANNumber,'') AS PANNumber
		,ISNULL(oo.TANNumber,'') AS TANNumber
		,ISNULL(oo.TaxOfficeDetail,'') AS TaxOfficeDetail
		,ISNULL(FirstName,'') +' '+ISNULL(MiddleName,'')+' '+ ISNULL(LastName,'') as EmpName
		,ISNULL(EMO.PanNumber,'') AS PANNumberEmp
		,ISNULL(ECM.PresentStreetOne,'') +' '+ ISNULL(ECM.PresentStreetTwo,'')+' '+ ISNULL(ECM.PresentStreetThree,'') AS EmpAddLine1
		,ISNULL(ECM.PresentCity,'') +'-'+ISNULL(ECM.PresentZipCode,'') +' '+ISNULL(ECM.PresentState,'') +' '+ ISNULL(ECM.PresentCountry,'')   AS EmpAddLine2
		,ISNULL(oo.TaxCertifyAuthorityName,'') AS Name
		,ISNULL(oo.TaxCertifyAuthorityFatherName,'') AS FatherName
		,ISNULL(oo.TaxCertifyAuthorityDesignation,'') as Designation
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityName,'')+ '</U>' AS NameHTML
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityDesignation,'')+ '</U>' AS DesignationHTML
		,'<U>'+ ISNULL(oo.TaxCertifyAuthorityFatherName,'')+ '</U>' AS FatherNameHTML
		,ISNULL(oo.TaxCertifyAuthorityRelation,'') as Relation
		,ISNULL(StreetThree,'') +' - '+ISNULL(CityName,'') AS Place
		,ISNULL(@AssessmentYear,'') AS AssessmentYear
		,REPLACE(CONVERT(VARCHAR,@FromDate,106),' ','-')AS FromDate
		,REPLACE(CONVERT(VARCHAR,@ToDate,106),' ','-') as ToDate
		,QD.Quarter1 as Quarter1
		,QD.Quarter2 as Quarter2	
		,QD.Quarter3 as Quarter3
		,QD.Quarter4 as Quarter4
		,EMP.id  as EmployeeID	
		,@rOrgGroupId as OrgGroupId	
		,@rAssessmentYearId AS AssessmentYearId
		,REPLACE(CONVERT(VARCHAR,sCommon.fGetDate(),106),' ','-')AS Date
		,QD.Total as Total
		,QD.TotalHTML as TotalHTML
		,'<U>'+  QD.AmountWord +'</U>' as AmountWord
		,ISNULL(ITC.Amount,0) as Amount
		,ITC.BankCode as BankCode
		,ISNULL(CONVERT(VARCHAR(20),ITC.ChallanDate ,103),'') AS ChallanDate
		,ITC.ChallanNo as ChallanNo
		,ROW_NUMBER() OVER (PARTITION BY EMP.id ORDER BY EMP.id, ITC.YearFor, ITC.MonthFor) AS RowNumber
		,CAST(EMP.id AS VARCHAR)  as EmployeeIDText	
		,CAST(@rOrgGroupId AS VARCHAR) as OrgGroupIdText	
		,CAST(@rOrgId	 AS VARCHAR) as OrgIdText		
		,CAST (@rAssessmentYearId AS VARCHAR) AS AssessmentYearIdText,
		ITC.Id AS ChallanId
	FROM sHrm.tEmployeeMaster  AS EMP 
		INNER JOIN sHrm.tEmployeeStatutoryAndOther                         AS EMO ON EMO.EmployeeId=EMP.Id
		INNER JOIN sHrm.tEmployeeCommunications                            AS ECM ON ECM.EmployeeId=EMP.Id
		INNER JOIN sHrm.tEmployeeJobDetail                                 AS EJD ON EMP.Id = EJD.EmployeeId 
	    INNER JOIN sHrm.tEmployeePersonalDetail							   AS EPD ON EMP.Id = EPD.EmployeeId	
		LEFT JOIN sSetup.tOrganizationMaster                               AS OM  ON OM.Id=EMP.OrgID
		LEFT JOIN sSetup.tOrganizationOtherDetail                          AS oo  ON oo.OrgId=om.id
		LEFT JOIN [siTax].[tIncomeTaxChallan]                              AS ITC ON ITC.EmployeeId=EMP.id  AND ITC.IsObsolete=0 AND  ITC.AssesmentYearId=@rAssessmentYearId 
		INNER JOIN @QuarterDetails                                         AS QD  ON QD.EmployeeID=EMP.Id
		LEFT JOIN [sSetup].[tOrgGroupMaster] OG ON  OG.id=OM.OrgGroupId
	WHERE EMP.OrgID=@rOrgId 
		AND ((EMP.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((EMP.id=@rEmployeeID) OR (@rEmployeeID=0))
	ORDER BY EMP.id,ITC.YearFor, ITC.MonthFor,ISNULL(FirstName,'') +' '+ISNULL(MiddleName,'')+' '+ ISNULL(LastName,'')

END
GO
PRINT N'Altering [sMis].[pRptCastCategorywiseStudentGet]...';


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

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

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


GO

 
 
ALTER PROCEDURE [sSecurity].[pSecuritySummaryDashboard]
	@rType nvarchar(40)='',
	@rOrgId int =0,
	@rOrgGroupId int =0,
	@rOrgGroupBatchId int=0,
	@rDepositHeadId int =0,
	--@rLibraryId int =0
	@rBatchId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'SecurityList')
		BEGIN
				SELECT 
				CASE WHEN U.SourceTypeId = 95 THEN  'Employee' 
				WHEN U.SourceTypeId = 2003 THEN  'Student' ELSE  'NA' END AS 'Source Type',

				CASE WHEN U.SourceTypeId = 2003 THEN ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND((OM.Id =  @rOrgId)OR(@rOrgId=0)) AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003),0) WHEN U.SourceTypeId = 95 THEN ISNULL(COUNT(U.Id),0) END AS 'Created User',

				CASE WHEN U.SourceTypeId = 2003 THEN ISNULL((SELECT COUNT(ISNULL(U.Id,0)) FROM sStudent.vStudentCommunication SC LEFT JOIN  sSecurity.tUser U ON SC.StudentId = U.SourceId AND U.SourceTypeId=2003
            	WHERE ((U.LoginPassWord is Null)) AND (SC.OrgId = @rOrgId) AND SC.StatusId = 1 AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0))),0) WHEN U.SourceTypeId = 95 THEN ISNULL((SELECT COUNT(ISNULL(U.Id,0)) FROM sHrm.vEmployeeCommunication EC LEFT JOIN  sSecurity.tUser U ON EC.EmployeeId = U.SourceId
            	WHERE ((U.LoginPassWord is Null)) AND (EC.OrgId = @rOrgId) AND EC.StatusId = 7),0) ELSE 0 END As 'Pending User' ,

				CASE WHEN U.SourceTypeId = 2003 THEN  ISNULL((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND ((OM1.Id =  @rOrgId)OR(@rOrgId=0)) AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0)) LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 2003 AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1),0) WHEN U.SourceTypeId = 95 THEN ISNULL(COUNT(RU.UserId),0) END  AS 'Registered',

				 
				CASE WHEN U.SourceTypeId = 2003 THEN ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId LEFT JOIN (SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers) AS A ON A.UserId = U1.Id
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND((OM.Id =  @rOrgId)OR(@rOrgId=0)) AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003 AND A.UserId IS NULL),0) WHEN U.SourceTypeId = 95 THEN ISNULL((COUNT(U.Id) - COUNT(RU.UserId)),0) END AS 'Not Registered',

				CASE WHEN U.SourceTypeId = 2003 THEN ISNULL(Convert(decimal(10,2),((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND ((OM1.Id =  @rOrgId)OR(@rOrgId=0)) AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0)) LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 2003 AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1)*100)/(SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND((OM.Id =  @rOrgId)OR(@rOrgId=0)) AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003)),0.00)
				WHEN U.SourceTypeId = 95 THEN ISNULL(Convert(decimal(10,2),(COUNT(RU.UserId)*100)/COUNT(U.Id)),0.00) END AS Percentage

				FROM
				 
				sSecurity.tUser U
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
				LEFT JOIN (
				SELECT RU.UserId AS  UserId  
				FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND ((OM1.Id =  @rOrgId)OR(@rOrgId=0))
				AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
				WHERE U1.IsObsolete = 0 GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
				 
				WHERE U.IsObsolete = 0
				AND((OM.Id =  @rOrgId)OR(@rOrgId=0))
				AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1)
				GROUP BY U.SourceTypeId
		END
		 ELSE IF (@rType = 'StudentRegisteredUsers')
			BEGIN
				SELECT CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision
				,COUNT(U.Id) AS UserCount,	COUNT(RU.UserId) AS RegisteredUsers
				,(COUNT(U.Id)-COUNT(RU.UserId)) As NotRegister
				FROM  sStudent.vStudentCommunication SC
				INNER JOIN sSecurity.tUser U ON SC.StudentId=U.SourceId AND U.SourceTypeId = 2003
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SC.DivisionId  
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
				LEFT JOIN ( 				
				SELECT RU.UserId AS  UserId  
				FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1)AND((OM1.Id =  @rOrgId)OR(@rOrgId=0))
				AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
				WHERE U1.IsObsolete = 0 GROUP BY RU.UserId				
				) RU ON RU.UserId = U.Id 
				WHERE ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0)) AND SC.StatusId = 1
				AND(OM.Id !=1) AND ((OM.Id = @rOrgId) OR (@rOrgId=0)) AND ((SC.BatchId = @rBatchId) OR (@rBatchId = 0)) 
				GROUP BY CM.DisplayTitle,DM.DisplayTitle,DM.Id	
			END
			ELSE IF (@rType = 'EmployeeRegisteredUsers')
				BEGIN
					SELECT R.Title AS RoleName,COUNT(U.Id) AS UserCount,COUNT(RU.UserId) AS RegisteredUsers,
						(COUNT(U.Id)- COUNT(RU.USerId)) AS NotRegisterUsers
						FROM sSecurity.tUser U
						INNER JOIN sSecurity.tUserRole UR ON U.Id = UR.UserId
						INNER JOIN sSecurity.tRole R ON R.Id = UR.RoleId AND R.Title != 'SuperAdmin'
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId 
						INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId
						--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = O.Id
						--INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
						LEFT JOIN (SELECT RU.UserId AS UserId  
						FROM sCommunication.tRegisteredUsers RU   
						GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
						INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
						WHERE ((O.Id = @rOrgGroupId) OR (@rOrgGroupId=0)) AND  U.IsObsolete = 0 AND UR.IsObsolete=0
						AND ((U.CreatedUserId != 1) OR (U.DisplayTitle = 'Admin'))
						AND ((U.SourceTypeId = 95)OR(95=0))
						AND(OM.Id !=1) AND ((OM.Id = @rOrgId) OR (@rOrgId=0))
						--AND ((COGBM.Id=1 )OR(1=0 ))
						GROUP BY R.Title,R.Id
				END
END
GO
PRINT N'Altering [sSecurity].[pUserLogDetailGet]...';


GO
 
 
ALTER PROCEDURE [sSecurity].[pUserLogDetailGet]
	@rOrgId [smallint],
	@rDisplayTitle [nvarchar](100),
	@rLoginTitle [nvarchar](20),
	@rRoleId int,
	@rSourceTypeId smallint,
	@rSourceCode nvarchar(20),
	@rSourcename nvarchar(100),
	@rIsCommon bit,
	@rOrgGroupId smallint,
	@rFromDate date,
	@rToDate date,
	@rOsTypeId smallint=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rDisplayTitle = sCommon.fSearchStringGet(@rDisplayTitle)
SET @rLoginTitle = sCommon.fSearchStringGet(@rLoginTitle) 
SET @rSourceCode= sCommon.fSearchStringGet(@rSourceCode)
SET @rSourceName= sCommon.fSearchStringGet(@rSourcename)

SET @rToDate = DATEADD(day,1,@rToDate)

IF(@rSourceTypeId = 2003)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Student' AS UserSourceTypeName,
			Users.IsObsolete,
			SN.Code AS EmployeeCode,
			SN.Name AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users			
			INNER JOIN sStudent.vStudentName SN
				ON SN.StudentId = Users.SourceId AND Users.SourceTypeId = @rSourceTypeId						
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SN.BatchId  AND BM.IsActive = 1
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLog UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  
		 AND((SN.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((SN.Name like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))               
		  Order By UL.Id DESC
END
ELSE IF(@rSourceTypeId = 95)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Employee' AS UserSourceTypeName,
			Users.IsObsolete,
			Emp.Code AS EmployeeCode,
			(Emp.FirstName +  ' ' + Emp.LastName) AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users			
			INNER JOIN sHrm.vExtEmployeeMaster Emp
				ON Emp.Id = Users.SourceId AND Users.SourceTypeId = @rSourceTypeId							
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLog UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  
		 AND((Emp.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((Emp.EmployeeName like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))           
		  Order By UL.Id DESC
END
ELSE IF(@rSourceTypeId = 1)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Other' AS UserSourceTypeName,
			Users.IsObsolete,
			Users.DisplayTitle AS EmployeeCode,
			Users.LoginTitle AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users						
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLog UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  		  
		 AND((Users.DisplayTitle like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((Users.DisplayTitle like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))                            
		  Order By UL.Id DESC
END       
END
GO
PRINT N'Altering [sTimetable].[pRptFreeTeacherTimetableGet]...';


GO
 
 
ALTER PROCEDURE [sTimetable].[pRptFreeTeacherTimetableGet]

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

BEGIN   
 
	SELECT

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


GO

ALTER  PROCEDURE [sWorkflow].[pMyApprovalRequestGet]
			 @rWorkflowFunctionalityId bigint=0,
			 @rFromDate date=null,
			 @rToDate date=null,
			 @rStatusId int=0,
			 @rCode nvarchar(200) ='',
			 @rUserId bigint = 0,
			 @rUserSourceTypeId int,
			 @rParticipantSourceId bigint = 0,
			 @rApprovalRequestId int = 0
			 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
		IF(@rUserSourceTypeId = 2001)
		BEGIN
			SELECT
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId 
		WHERE ((WFM.Id = 0) OR (0 =0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND AR.CreatedUserId = @rUserId AND AR.ParticipantSourceTypeId = 2001
			AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
			AND ((AR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))
			AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
		
UNION 

SELECT
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId 
		WHERE ((WFM.Id = 0) OR (0 =0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND AR.ParticipantSourceTypeId = 2001
			AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
			AND ((AR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))
			AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
		END
		ELSE IF(@rUserSourceTypeId = 95)
		BEGIN
			SELECT
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		WHERE ((WFM.Id = 0) OR (0 =0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND AR.CreatedUserId = @rUserId AND AR.ParticipantSourceTypeId = 95
			AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
			AND ((AR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))
			AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
		
UNION 

SELECT
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		WHERE ((WFM.Id = 0) OR (0 =0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND AR.ParticipantSourceTypeId = 95
			AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
			AND ((AR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))
			AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
		END
		ELSE
		BEGIN
			SELECT
			--U.SourceTypeId,
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
			--INNER JOIN [sSecurity].[tUser] U ON AR.CreatedUserId = U.Id
		WHERE ((WFM.Id = 0) OR (0 =0)) 
			AND ((AR.CreatedDateTime >= '') OR (ISNULL('','') = ''))
			AND ((AR.CreatedDateTime <= '') OR (ISNULL('','') = ''))
			AND ((ASM.Id = 0) OR (0 =0))
			AND (((SA.Code = '') OR ('' ='')) OR ((EM.Code = '') OR ('' =0)))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
		END
END
GO
PRINT N'Altering [sWorkflow].[pWorkflowQueuesGet]...';


GO
 
ALTER  PROCEDURE [sWorkflow].[pWorkflowQueuesGet]
			 @rWorkflowFunctionalityId bigint=0,
			 @rFromDate date=null,
			 @rToDate date=null,
			 @rStatusId int=0,
			 @rCode int =0,
			 @rDepartmentId int=0,
			 @rUserId bigint ,
			 @rApprovalRequestId int = 0
			 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
Declare @lRoleId int
Select @lRoleId = RoleId from [sSecurity].[tUserRole] Where UserId = @rUserId
--Select @lRoleId
SELECT
	AA.Id AS ApprovalActionId,
	ADM.Id AS DepartmentId,
	WFM.Title AS WorkFlowName,
	WFM.Id AS WorkFlowId,
	AR.Id AS ApprovalRequestId,
	ADM.Title AS DepartmentTitle,
	CONVERT(DATE,AR.CreatedDateTime, 103) AS CreatedDateTime,
	AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
	AR.Remark AS Remark,
	(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
	(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status
			
		
from sWorkflow.tApprovalRequest AR
INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId
INNER JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID
LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
WHERE R.Id = @lRoleId
AND ((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId =0)) 
AND ((Convert(Date,AR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
AND ((Convert(Date,AR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
AND (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode =0)))
AND((ADM.Id = @rDepartmentId) OR (@rDepartmentId =0))
AND  ISNULL(EM.IsOtherUser,0) = 0
AND ((AR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

UNION

SELECT
	AA.Id AS ApprovalActionId,
	ADM.Id AS DepartmentId,
	WFM.Title AS WorkFlowName,
	WFM.Id AS WorkFlowId,
	AR.Id AS ApprovalRequestId,
	ADM.Title AS DepartmentTitle,
	CONVERT(DATE,AR.CreatedDateTime, 103) AS CreatedDateTime,
	AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
	CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
	AR.Remark AS Remark,
	(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
	(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status
			
		
from sWorkflow.tApprovalRequest AR
INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId
INNER JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID
LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
WHERE U.Id = @rUserId
AND ((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId =0)) 
AND ((Convert(Date,AR.CreatedDateTime)>= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
AND ((Convert(Date,AR.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
AND (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode =0)))
AND((ADM.Id = @rDepartmentId) OR (@rDepartmentId =0))
AND  ISNULL(EM.IsOtherUser,0) = 0
AND ((AR.Id = @rApprovalRequestId) OR (@rApprovalRequestId = 0))

END
GO
PRINT N'Creating [sAlert].[pQueryCommentGet]...';


GO
 
CREATE PROCEDURE [sAlert].[pQueryCommentGet]
	 	 
	 	 @rQueryId bigint,	 	 
	 	 @rSubject nvarchar(100),
		 @rRemark nvarchar(1000),
	 	 @rTemplate nvarchar(max),
	 	 @rFromSourceTypeId smallint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	IF(@rFromSourceTypeId=2003)
		BEGIN
		   SELECT 
		     ISNULL(SC.ParentEmail,'') AS EmailId,
		       --'mohit.patel@vidyalayaschoolsoftware.com' AS EmailId,
				ISNULL(SC.ParentContactNo,'') AS MobileNo,
			replace (	
				replace (
				    replace (
				         replace(
				                  --@rTemplate,'[User]',SC.Name),
								  @rTemplate,'[User]','Student'),
								   '[Comment]',@rRemark),
								   --'[Time]',QM.CreatedDateTime),
								   '[Time]',GetDate()),
								 '[Query]',QM.Title) 
				            AS MsgText,
		     
		       @rSubject AS Subject,
			   2003 AS ReceiverSourceTypeId,
			   SC.StudentId AS ReceiverSourceId  ,
			   SC.Name AS Name,
			   (CASE WHEN QM.StatusId = 209 THEN 'Open' WHEN QM.StatusId = 210 THEN 'Closed' WHEN QM.StatusId = 709 THEN 'Hold' ELSE '' END) [Status],
				QM.number AS QueryNo,
				SC.WhatsAppContactNo
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN [sStudent].[vStudentCommunication] SC ON QM.FromSourceId=SC.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId
			
		
	      WHERE
		    QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId AND BM.IsActive=1 AND SC.IsBlockAllAlert=0
		END
   
   IF(@rFromSourceTypeId=95)
		BEGIN
		
		   SELECT 
		     ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		    replace (	
		      replace (	
				 replace (
				         replace(
				                  --@rTemplate,'[User]',EM.EmployeeName),
								   @rTemplate,'[User]','Employee'),
								  '[Comment]',@rRemark),
								  --'[Time]',QM.CreatedDateTime),
								  '[Time]',GetDate()),
								  '[Query]',QM.Title) 
				            AS MsgText,
		     
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId  
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId 
		
	      WHERE
		    QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId
		
		END
	ELSE
	BEGIN
		   SELECT 
		     ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		    replace (	
		      replace (	
				 replace (
				         replace(
				                  --@rTemplate,'[User]',EM.EmployeeName),
								   @rTemplate,'[User]','Admin'),
								  '[Comment]',@rRemark),
								  --'[Time]',QM.CreatedDateTime),
								  '[Time]',GetDate()),
								  '[Query]',QM.Title) 
				            AS MsgText,
		     
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId  
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId 
		
	      WHERE
		    QM.Id = @rQueryId AND FromSourceTypeId=@rFromSourceTypeId
	END

	
		
END
GO
PRINT N'Creating [sCommon].[pPublishDocumentMasterAdd]...';


GO

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

	END
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
IF(@rId = 0)	
BEGIN
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommon.tPublishDocumentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO sCommon.tPublishDocumentMaster
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId]
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rIsObsolete
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,0
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   )
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  sCommon.tPublishDocumentMaster
	    SET
	          Code=@rCode
	         ,Title=@rTitle
             ,IsObsolete = @rIsObsolete                          
             ,UpdatedUserId = @rCreatedUserId
             ,UpdatedDateTime = sCommon.fGetDate()          
             
	      WHERE Id = @rId 	
	 END  
	      SELECT @lNextNumber AS Result
			COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sCommon].[pPublishDocumentMasterGet]...';


GO

CREATE PROCEDURE [sCommon].[pPublishDocumentMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId smallint
AS
SET NOCOUNT ON

	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)

BEGIN

	SELECT PDM.Id 
		  ,PDM.Code
		  ,PDM.Title AS Name
		  ,PDM.IsObsolete
		  ,OrgGroupId
     
	  FROM sCommon.tPublishDocumentMaster PDM
     
	  WHERE 
			((PDM.Id = @rId) OR (@rId = 0))
		AND ((PDM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
		AND ((PDM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND (PDM.OrgGroupId = @rOrgGroupId)

END
GO
PRINT N'Creating [sCommunication].[pFollowupTypeMasterAdd]...';


GO
CREATE PROCEDURE [sCommunication].[pFollowupTypeMasterAdd]
	 
		@rId bigint,
		@rCode nvarchar(100),
		@rTitle nvarchar(200),
		@rOrderIndex int,
		@rIsPublish bit,
		@rIsObsolete bit = 0,
		@rOrgGroupId smallint,
		@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from [sCommunication].[tFollowupTypeMaster] where Title=@rTitle AND Code=@rCode AND OrgGroupId=@rOrgGroupId)
		BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from [sCommunication].[tFollowupTypeMaster] where OrderIndex=@rOrderIndex)
		BEGIN
			select -1003 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from [sCommunication].[tFollowupTypeMaster] where Title=@rTitle AND Code=@rCode AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If Exists(select Id from [sCommunication].[tFollowupTypeMaster] where OrderIndex=@rOrderIndex)
		BEGIN
			select -1003 as Result
			RETURN
		END
	END
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
		BEGIN
		
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFollowupTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
		INSERT INTO [sCommunication].[tFollowupTypeMaster]
			   ([Id]
			   ,[Code]
			   ,[Title]
			   ,[OrderIndex]
			   ,[IsPublish]
			   ,[IsObsolete]
			   ,[OrgGroupId]
			   ,[CreatedUserId]
			   ,[CreatedDateTime])
		 VALUES
			   (@lNextNumber,
			    @rCode ,
				@rTitle ,
				@rOrderIndex ,
				@rIsPublish ,
				@rIsObsolete ,
				@rOrgGroupId ,
				@rCreatedUserId ,
				sCommon.fGetDate())

		SELECT 1 AS Result
		SELECT @lNextNumber AS Id
		END	 
	ELSE
		 BEGIN
		 SET @lNextNumber = @rId
			UPDATE [sCommunication].[tFollowupTypeMaster]
				SET 
				  [Code] = @rCode ,
				  [Title] = @rTitle ,
				  [OrderIndex] = @rOrderIndex ,
				  [IsPublish] = @rIsPublish ,
				  [IsObsolete] = @rIsObsolete ,
				  [OrgGroupId] = @rOrgGroupId ,
				  [UpdatedUserId] = @rCreatedUserId ,
				  [UpdatedDateTime] = sCommon.fGetDate()  
				WHERE [Id] = @rId
			  
			  SELECT 11 AS Result
		SELECT @lNextNumber AS Id
		 END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sCommunication].[pFollowupTypeMasterDelete]...';


GO
CREATE PROCEDURE [sCommunication].[pFollowupTypeMasterDelete]
	 
	 @rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN TRY
		
		BEGIN TRANSACTION		
			DELETE FROM [sCommunication].[tFollowupTypeMaster] WHERE Id=@rId
			SELECT 1 AS Result
	
	COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END
GO
PRINT N'Creating [sCommunication].[pFollowupTypeMasterGet]...';


GO

CREATE PROCEDURE [sCommunication].[pFollowupTypeMasterGet]
	@rCode nvarchar(100),
	@rTitle nvarchar(200),
	@rOrgGroupId int,
	@rId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
 	 SELECT 
			Id,
			Code,
			Title,
			OrderIndex,
			ISNULL(IsPublish,0) As IsPublish,
			IsObsolete,
			OrgGroupId,
			CreatedUserId,
			ISNULL(UpdatedUserId,0) AS UpdatedUserId
			  
	   FROM  [sCommunication].[tFollowupTypeMaster]
	    
	   WHERE ((Code LIKE '%'+@rCode+'%') OR (ISNULL(@rCode, '') = ''))
	   AND	((Title LIKE @rTitle+'%') OR (ISNULL(@rTitle, '') = ''))
	   AND ((id = @rId) OR (ISNULL(@rId,0) = 0))
	   AND OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Creating [sCommunication].[pRptPollAnalysisGet]...';


GO
CREATE PROCEDURE sCommunication.pRptPollAnalysisGet
@rPollId bigint
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	SELECT 
		PR.PollId,
		PR.CreatedUserId,
		PR.CreatedDateTime,
		U.DisplayTitle,
		CASE WHEN U.SourceTypeId = 95 THEN 'Employee' ELSE 'Student' END AS [Source],
		P.Title AS Poll,
		CASE WHEN U.SourceTypeId = 95 THEN (SELECT Code FROM sHrm.tEmployeeMaster WHERE Id = U.SourceId) ELSE (SELECT Code FROM sStudent.tStudentMaster WHERE Id = U.SourceId) END AS Code,
		PA.Title AS PollAnswer
	FROM 
		sCommunication.tPollResult PR
		INNER JOIN sSecurity.tUser U ON U.Id = PR.CreatedUserId
		INNER JOIN sCommunication.tPoll P ON P.Id = PR.PollId		
		INNER JOIN sCommunication.tPollAnswer PA ON PA.Id = PR.PollAnswerId
	WHERE
		PR.PollId = @rPollId AND P.IsOpen = 0
END
GO
PRINT N'Creating [sFrontOffice].[pVisitorLogListingGet]...';


GO
 
CREATE PROCEDURE [sFrontOffice].[pVisitorLogListingGet]
       
    @rVisitorId int=0,
    @rFromVisitDate datetime='',
    @rToVisitDate datetime='',
    @rOrgId int=0,
    @rWhomToMeetName nvarchar(100)='',
    @rIsPrintView bit=0,
    @rOrgGroupId int =0,
    @rTypeId int=0 ,
	@rStatusId int=0 ,
	@rUserSourceId bigint = 0
          
AS
SET NOCOUNT ON

		--IF @rIsWildCardSearch = 1
		--BEGIN
			SET @rWhomToMeetName = sCommon.fSearchStringGet(@rWhomToMeetName)
		--END
		Declare @GatePassConfig nvarchar(20)=''
		SELECT @GatePassConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 241 AND SourceId = @rOrgGroupId


BEGIN
SELECT  
	   VL.Id As VisitorId,
       VL.VisitorName,
       VL.NoOfVisitor,
       VL.PurposeOfVisit,
       VL.WhomToMeet AS WhomToMeetId,
       VL.WhomToMeetName,
       CONVERT(Varchar,VL.InTime,108)AS InTime,
       CONVERT(Varchar,VL.OutTime,108)AS OutTime,
       ISNULL(VL.VisitDate,'1900-01-01 00:00:00') AS VisitDate,
       --VL.CreatedDateTime ,
       (CASE  WHEN @rIsPrintView=1 THEN 
				VL.VisitorPhoto		
			ELSE ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) END) AS VisitorPhoto,
       --ISNULL(VL.VisitorPhoto, CONVERT(VARBINARY(MAX), 0)) AS VisitorPhoto,
       VL.OrgId,
       ISNULL(OM.DisplayTitle,'') AS Organization,
       ISNULL(Remark,'') AS Remark,
       @GatePassConfig AS ConfigValue,
	   ISNUll(VisitorContactNumber,'') AS VisitorContactNumber,
	   ISNULL(StudentId,0) AS StudentId,
	   (CASE WHEN ISNULL(VL.StudentId,0)=0 THEN 'Visitor'
			 ELSE 'Parents' END) AS VisitorType,
	   (CASE WHEN ISNULL(VL.OutTime,'00:00:00')='00:00:00' THEN 0
			 ELSE 1 END) AS InOutStatus,
		OM.OrgGroupId AS OrgGroupId,
		ISNULL(VL.StatusId,0) as StatusId,
		SM.Title as Status
		
  FROM  sFrontOffice.tVisitorLog VL 
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=VL.OrgId
  LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = VL.StatusId
 
  WHERE 
	(VL.OrgId=@rOrgId OR @rOrgId=0) 
	AND OM.OrgGroupId=@rOrgGroupId
	AND (VL.Id=@rVisitorId OR @rVisitorId=0)
	AND ((VL.WhomToMeetName LIKE @rWhomToMeetName) OR (ISNULL(@rWhomToMeetName,'')=''))
	AND (VL.VisitDate>=@rFromVisitDate OR ISNULL(@rFromVisitDate,'')='')
	AND (VL.VisitDate<=@rToVisitDate OR ISNULL(@rToVisitDate,'')='')
	AND ( (ISNULL(VL.StudentId,1) = @rTypeId) OR  (@rTypeId=0) OR (((VL.StudentId > 0 AND @rTypeId=2) OR  @rTypeId=0))) -- Visitor
	AND ((VL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0)) 
	--AND (ISNULL(VL.StatusId,0) != 0)
	AND ((VL.WhomToMeet = @rUserSourceId) OR (ISNULL(@rUserSourceId,0) = 0))
	
  ORDER BY VL.VisitDate DESC,VL.InTime DESC
END
GO
  
  
 
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('21.10.18',211018,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)

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

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


GO
ALTER TABLE [sCommunication].[tFollowup] DROP COLUMN [FollowupHandleById], COLUMN [FollowupRelationId];


GO
ALTER TABLE [sCommunication].[tFollowup] ALTER COLUMN [FollowupOtherRemark] NVARCHAR (500) NULL;

ALTER TABLE [sCommunication].[tFollowup] ALTER COLUMN [FollowupRemark] NVARCHAR (500) NULL;


GO
ALTER TABLE [sCommunication].[tFollowup]
    ADD [FollowupRelationRemark] NVARCHAR (500) NULL,
        [CreatedUserId]          BIGINT         NOT NULL,
        [CreatedDateTime]        DATETIME       NOT NULL,
        [UpdatedUserId]          BIGINT         NULL,
        [UpdatedDateTime]        DATETIME       NULL;


GO

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


GO
 
 
ALTER PROCEDURE [dbo].[pEmployeeMasterGet]
@rOrgId int = 0,
 @rBuilder1 nvarchar(max)='',
 @rBuilder2 nvarchar(max)='',
 @rEmployeeStatusId int=0,
 @rEmployeeId bigint = 0
AS

BEGIN
	UPDATE sHrm.tEmployeeMaster SET PunchId = NULL
	--IF EXISTS (SELECT EM.PunchId FROM sHrm.tEmployeeMaster EM INNER JOIN sBiometric.BioDetailMapping BM ON BM.EmpID = EM.Id WHERE EM.PunchId is null)
	--BEGIN
	UPDATE EM
	SET
		PunchId = BM.EmpPunchID
	FROM
	    sHrm.tEmployeeMaster EM
		INNER JOIN sBiometric.BioDetailMapping AS BM
		ON BM.EmpID = EM.Id
		WHERE PunchId is null
	--END
	
	select *,isnull(FirstName,'') +' '+ isnull(MiddleName,'') as 'FullName',
	(SELECT Title FROM sSetup.tOrganizationMaster WHERE Id = OrgID) AS OrganizationTitle
 from sHrm.tEmployeeMaster
	where PunchId is not null
	and (OrgID = @rOrgId OR @rOrgId = 0)
	AND (StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0) 
	AND ISNULL(IsOtherUser,0) = 0
END
GO
PRINT N'Altering [sActivity].[pStudentHolidayGet]...';


GO
 
ALTER PROCEDURE [sActivity].[pStudentHolidayGet]
	 	 
	 	 @rUserSourceId bigint,
	 	 @rBatchId int,
	 	 @rOrgId int, 
	 	 @rForMonth int=0,
	 	@rToDate int=0,
	 	@rForYear int=0,
	 	@rToYear int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN  
	 
	SELECT 
			 Day(EP.FromDate) AS FromDay,
			 Day(EP.ToDate) As ToDay,
			  Month(EP.FromDate) AS FromMonth,
			 Month(EP.ToDate) As ToMonth,
			  YEar(EP.FromDate) AS FromYEar,
			 YEar(EP.ToDate) As ToYEar,
			 CASE WHEN EP.FromDate = EP.ToDate THEN 1 ELSE DATEDIFF(day, EP.FromDate, EP.ToDate) END AS DayCount
  FROM   
			sActivity.tEventAssign EA 
		 INNER JOIN    sActivity.tEventSchedule EP ON EP.Id=EA.EventScheduleid
		 INNER JOIN sSetup.tDivisionMaster D ON D.Id = EA.SourceId AND EA.SourceTypeId=2005
		 INNER JOIN sStudent.tAcademic A ON A.DivisionId= D.Id
					 
			 
  WHERE 
		 
        (A.OrgId = @rOrgId)
      AND (EP.BatchId = @rBatchID)
      AND A.Id=@rUserSourceId
      AND Month(EP.FromDate)=@rForMonth
      AND Month(EP.ToDate)=@rToDate
      AND Year(EP.FromDate)=@rForYear
       AND Year(EP.ToDate)=@rToYear
      AND EP.IsHoliday=1
      
END
GO
PRINT N'Altering [sAdmission].[pRptAdmissionFormGet]...';


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

AS
 SET NOCOUNT ON

BEGIN 
	
	select 
	 Convert(nvarchar(20),AF.Id) AS AdmissionFormIdText,
	 Convert(nvarchar(20),@rRelationShipId) AS RelationShipIdText,
	 ISNULL(AF.Id,0) AS AdmissionFromId,
	 ISNULL(AF.FormNo,0) AS FormNo,
	 [sStudent].[fStudentNameGet](AF.FirstName , ISNULL(AF.MiddleName,'') , AF.LastName,OM.StudentNameFormatId ) AS Name,
	 ISNULL(AF.FirstName,'')AS FirstName,
	 ISNULL(AF.ForClassId,0) AS ForClassId,
	 ISNULL(AF.DateOfBirth,'') AS DateOfBirth,
	 ISNULL(AF.BatchId,0)AS BatchId,
	 ISNULL(CM.Title,'') AS ClassName,
	 ISNULL(AF.OrgId,0)AS OrgId,
	 ISNULL(AF.StreetOne,'')AS StreetOne,
	 ISNULL(AF.StreetTwo,'')AS StreetTwo,
	 ISNULL(AF.StreetThree,'')AS StreetThree,
	 ISNULL(AF.Country,'')AS Country,
	 ISNULL(AF.City,'')AS City,
	 ISNULL(AF.State,'')AS State,
	 ISNULL(AF.ZipCode,'') AS ZipCode,
	 ISNULL(AF.ContactEmail,'')AS ContactEmail,
	 ISNULL(AF.ContactNo,'') AS ContactNo,
	 ISNULL(AF.PreviousSchool,'')AS PreviousSchool,
	 ISNULL(AF.StudentPhoto,0x) As StudentPhoto,
	 ISNULL(AF.ReligionId,0) AS ReligionId,
	 IsNULL(RM.Title,'') AS ReligionName,
	 ISNULL(AF.MeritGrade,'')AS MeritGrade,
	 ISNULL(AF.MeritMarks,0) AS MeritMarks,
	 ISNULL(AF.GenderId,0) AS GenderId,
	 ISNULL(GM.Title,'') AS Gender,
	 ISNULL(AF.FamilyCast,'')AS FamilyCast,
	 ISNULL(AF.FamilySubCast,'')AS FamilySubCast,
	 ISNULL(AF.CastCategoryId,0) AS CastCategoryId,
	 ISNULL(CCM.Title,'') AS CastCategory ,
	 ISNULL(OM.DisplayTitle,'')AS DisplayTitle ,
	 ISNULL(BM.Title,'') As Batch,
	 ISNULL(AFM.FatherName,'') AS FatherName ,
	 ISNULL(AFM.FatherDateOfBirth,'')As FatherDateOfBirth,
	 ISNULL(AFM.FatherOccupation,'') AS FatherOccupation,
	 ISNULL(AFM.FatherOfficeAddress,'') AS FatherOfficeAddress,
	 ISNULL(AFM.FatherIncome,0) AS FatherIncome,
	 ISNULL(AFM.FatherQualification,'') AS FatherQualification,
	 ISNULL(AFM.FatherContactNo,'') AS FatherContactNo ,
	 ISNULL(AFM.FatherMail,'') AS FatherMail,
	 ISNULL(AFM.FatherOrganization,'') AS FatherOrganization,
	 ISNULL(AFM.MotherName,'') AS MotherName,
	 IsNull(AFM.MotherDateOfBirth,'')As MotherDateOfBirth,
	 ISNULL(AFM.MotherIncome,0) AS MotherIncome,
	 ISNULL(AFM.MotherOccupation,'') AS MotherOccupation,
	 ISNULL(AFM.MotherOfficeAddress,'') AS MotherOfficeAddress,
	 ISNULL(AFM.MotherQualification,'') AS MotherQualification,
	 ISNULL(AFM.MotherContactNo,'') AS MotherContactNo,
	 ISNULL(AFM.MotherMail,'') AS MotherMail,
	 ISNULL(AFM.MotherOrganization,'') AS MotherOrganization,
	 isnull(AFM.RelativeName,'') AS RelativeName ,
	 ISNULL(AFM.RelativeDateOfBirth,'') AS RelativeDateOfBirth,
	 ISNULL(AFM.RelativeOccupation,'') AS RelativeOccupation,
	 ISNULL(AFM.RelativeContactNo,'') AS RelativeContactNo,
	 ISNULL(AFM.RelativeMail,'') AS RelativeMail,
	 ISNULL(AFM.RelativeOfficeAddress,'') ASRelativeOfficeAddress,
	 ISNULL(AFM.RelativeIncome,0) AS RelativeIncome,
	 ISNULL(AFM.RelativeQualification,'') AS RelativeQualification,
	 ISNULL(AFM.RelationshipName,'') AS RelationshipName ,
	 ISNULL(AC.IsFixParentAcademic,0) AS IsParentAcademicRequired ,
	 ISNULL (AC.IsStudentAcademicRequired,0) AS IsStudentAcademicRequired ,
	 ISNULL(AC.IsSiblingDetailRequired,0) AS IsSiblingDetailRequired,
	 ISNULL(AC.IsReferenceDetailRequired,0) AS IsReferenceDetailRequired ,
	 ISNULL(AC.IsFamilyDetailRequired,0) AS IsFamilyDetailRequired ,
	 ISNULL(AC.IsFixStudentAcademic,0) AS IsFixStudentAcademic,
	 ISNULL(AC.ConfirmationRemark,'') AS ConfirmationRemark,
	 ISNULL(AC.IsHostelDetailRequired,0) AS IsHostelDetailRequired ,
	 ISNULL (AC.IsTransportDetailRequired,0) AS IsTransportDetailRequired ,
	 ISNULL(AC.IsHealthDetailRequired,0) AS IsHealthDetailRequired,
	 ISNULL(AC.IsBirthPlaceDetailRequired,0) AS IsBirthPlaceDetailRequired ,
	 ISNULL(AC.IsAadhaarDetailRequired,0) AS IsAadhaarDetailRequired ,
	 ISNULL(AC.IsBloodGroupDetailRequired,0) AS IsBloodGroupDetailRequired,
	
	 ISNULL(AF.IsPysicalDeformity,0) AS IsPysicalDeformity,
	 ISNULL(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
	 ISNULL(AF.IsMajorIllness,0) AS IsMajorIllness,
	 ISNULL(AF.MajorIllnessRemark, '') As MajorIllnessRemark,
	 ISNULL(AF.IsAllergy,0)AS IsAllergy,
	 ISNULL(AF.AllergyRemark,'') As AllergyRemark,
	 ISNULL(AF.BirthPlace,'') As BirthPlace,
	 ISNULL(AF.BirthTaluka,'') As BirthTaluka,
	 ISNULL(AF.BirthDistrict,'') As BirthDistrict,
	 Isnull(BGM.Title,'') As BloodGroupName,
	 ISNULL(AF.AdhaarNumber,'') AS AdhaarNumber,
	 ISNULL(AF.IsHostelRequired,0)AS IsHostelRequired,
	 ISNULL(AF.IsTransportRequired,0)AS IsTransportRequired,
	 ISNULL(AFM.FatherPhoto,0x)As FatherPhoto,
	  ISNULL(AFM.MotherPhoto,0x) As MotherPhoto,
	 ISNULL(AFM.RelativePhoto,0x) As RelativePhoto,
	 ISNULL(AF.BirthState,'')AS BirthState,
	 ISNULL(AF.BirthCountry,'') AS BirthCountry,
	 ISNULL(AC.CustomField1Remark,'') AS CustomField1Remark,
	 ISNULL(AC.CustomField2Remark,'') AS CustomField2Remark,
	 ISNULL(AC.CustomField3Remark,'') AS CustomField3Remark,
	 ISNULL(AF.CustomField1Answer,'')As CustomField1Answer,
	 ISNULL(AF.CustomField2Answer,'')As CustomField2Answer,
	 ISNULL(AF.CustomField3Answer,'')As CustomField3Answer,
	 ISNULL(AF.Nationality,'') AS Nationality,
	 ISNULL(AF.MotherTongue,'') AS MotherTongue,
	 ISNULL(AF.OtherInformation,'') AS OtherInformation,
	 ISNULL(LWM.Title,'') AS LiveWith,
	 ISNULL(AC.AgeCutOffDate,'') AS AgeCutOffDate,
	 ISNULL(AC.Remark1,'') AS ExtraRemark1,
	 ISNULL(AC.Remark2,'') AS ExtraRemark2,
	 ISNULL(AC.Remark3,'') AS ExtraRemark3,
	 ISNULL(AF.DateOfBirthInWord,'') AS DOBInWords,
	 ISNULL(AF.CreatedDateTime,'') As FormDate,
	  ISNULL(AC.IsFatherDetail,0) AS IsFatherDetail,
	 ISNULL(AC.IsFatherFullDetail,0) AS IsFatherFullDetail,
	 ISNULL (AC.IsFatherAcademic,0) As IsFatherAcademic,
	 ISNULL (AC.IsMotherDetail,0) As IsMotherDetail,
	 ISNULL (AC.IsMotherFullDetail,0)As IsMotherFullDetail,
	 ISNULL (AC.IsMotherAcademic,0)As IsMotherAcademic,
	 ISNULL (AC.IsGuardianDetail,0)As IsGuardianDetail,
	 ISNULL (AC.IsGuardianFullDetail,0)As IsGuardianFullDetail,
	 ISNULL (AC.IsGuardianAcademic,0)As IsGuardianAcademic,
	 ISNULL (AC.IsOtherInformationRequired,0)As IsOtherInformationRequired,
	 ISNULL (AC.IsHealthDetailRequired,0) As IsHealthDetailRequired,
	 ISNULL (AC.IsCustomField1Required,0) As IsCustomField1Required,
	 ISNULL (AC.IsCustomField2Required,0) As IsCustomField2Required,
	 ISNULL (AC.IsCustomField3Required,0) As IsCustomField3Required,
	 ISNULL (AFM.FatherAdhaarNumber,'') AS FatherAadhaarNumber,
	 ISNULL (AFM.MotherAadhaarNumber,'') AS MotherAadhaarNumber,
	 ISNULL (AFM.RelativeAadhaarNumber,'') AS RelativeAadhaarNumber,
	 ISNULL( (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=324
	 ),0)AS IsOtherDetailsLiveWith,
	 ISNULL( (SELECT (CASE WHEN DFO.DisplayFieldId Is Null THEN 0  ELSE 1 END) 
	 FROM sConfig.tDisplayFieldMaster DFM LEFT JOIN sConfig.tDisplayFieldOrg DFO ON 
	 DFO.DisplayFieldId = DFM.Id AND DFO.OrgId =AF.OrgId AND DFO.OrgId=AF.OrgId
	 WHERE DFM.Id=323
	 ),0)AS IsOtherDetailsOtherInformation,
	 ISNULL(AF.MiddleName,'') AS MiddleName,
	 ISNULL(AF.LastName,'')AS LastName,
	 ISNULL(PT.Id,0) AS PaymentTransactionId,
	 ISNULL(PT.PayAmount,0.00) AS PayAmount,
	 ISNULL(PT.TransactionStatusId,0) AS TransactionStatusId,
	 ISNULL(PT.PayDateTime,'') AS PayDateTime

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

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


GO
 
ALTER PROCEDURE [sAlert].[pQueryCommentGet]
	 	 
	 	 @rQueryId bigint,	 	 
	 	 @rSubject nvarchar(100),
		 @rRemark nvarchar(1000),
	 	 @rTemplate nvarchar(max),
	 	 @rFromSourceTypeId smallint,
		 @rQueryFrom varchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rQueryFrom = 'QueryList')
	BEGIN
	   SELECT 
		     ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		     ISNULL(EM.MobileNumber,'') AS MobileNo,
		    replace (	
		      replace (	
				 replace (
				         replace(
				                  --@rTemplate,'[User]',EM.EmployeeName),
								   @rTemplate,'[User]',
								   CASE WHEN @rFromSourceTypeId = 2003 THEN 'Student' 
								   WHEN @rFromSourceTypeId = 95 THEN 'Employee' 
								   ELSE 'Admin' END),
								  '[Comment]',@rRemark),
								  --'[Time]',QM.CreatedDateTime),
								  '[Time]',GetDate()),
								  '[Query]',QM.Title) 
				            AS MsgText,
		     
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId  
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QCM.Id = QM.QueryCategoryId
			INNER JOIN sCommunication.tQueryCategoryAssignedTo QCA ON QCA.QueryCategoryId = QCM.Id
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = QCA.SourceId
		
	      WHERE
		    QM.Id = @rQueryId 
	END
	ELSE
	BEGIN
	IF(@rFromSourceTypeId=2003)
		BEGIN
	
		 SELECT 
		    ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			replace (	
				replace (
				    replace (
				         replace(
				                  --@rTemplate,'[User]',SC.Name),
								  @rTemplate,'[User]','Student'),
								   '[Comment]',@rRemark),
								   --'[Time]',QM.CreatedDateTime),
								   '[Time]',GetDate()),
								 '[Query]',QM.Title) 
				            AS MsgText,
		     
		       @rSubject AS Subject,
			   2003 AS ReceiverSourceTypeId,
			   SC.StudentId AS ReceiverSourceId  ,
			   SC.Name AS Name,
			   (CASE WHEN QM.StatusId = 209 THEN 'Open' WHEN QM.StatusId = 210 THEN 'Closed' WHEN QM.StatusId = 709 THEN 'Hold' ELSE '' END) [Status],
				QM.number AS QueryNo,
				SC.WhatsAppContactNo
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN [sStudent].[vStudentCommunication] SC ON QM.FromSourceId=SC.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SC.BatchId

	      WHERE
		    QM.Id = @rQueryId AND BM.IsActive=1 
		
		END
   
   IF(@rFromSourceTypeId=95)
		BEGIN
			SELECT 
		    ISNULL(EM.CompanyEmail,'') AS EmailId,		    
		    ISNULL(EM.MobileNumber,'') AS MobileNo,
		    replace (	
		      replace (	
				 replace (
				         replace(
				                  --@rTemplate,'[User]',EM.EmployeeName),
								   @rTemplate,'[User]','Employee'),
								  '[Comment]',@rRemark),
								  --'[Time]',QM.CreatedDateTime),
								  '[Time]',GetDate()),
								  '[Query]',QM.Title) 
				            AS MsgText,
		     
		     @rSubject AS Subject,
			 95 AS ReceiverSourceTypeId,
			 EM.EmployeeId AS ReceiverSourceId  
		     
	       FROM 
			sCommunication.tQuery QM
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON QM.FromSourceId=EM.EmployeeId
		
	      WHERE
		    QM.Id = @rQueryId 

		END
	END
	
		
END
GO
PRINT N'Altering [sAssessment].[pCSExamScoreConvertTo]...';


GO

ALTER PROCEDURE [sAssessment].[pCSExamScoreConvertTo]
	 	
	@rStrXml [nvarchar](max),
	@rOrgId int,
	@rExamId int=0,
	@rCSGroupId int=0,
	@rBatchId int=0
	
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT,@lIsMarkIndecimal bit,@lDecimalPlace nvarchar(10),@lGradeSetId int

EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
Select @lIsMarkIndecimal = IsMarksInDecimal from sAssessment.tExamMaster where id= @rExamId
Select @lDecimalPlace = DecimalFormat from sAssessment.tExamMaster where id= @rExamId
 
Select  @lGradeSetId=GradeSetId FROM sAssessment.tCCECSMaster CSM 
 INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
			WITH ( 	 
						CCECSId int  
				  ) A 	ON CSM. Id = A.CCECSId  
 INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.ID = CSM.CCECAGroupId
  
WHERE CGM.Id =  @rCSGroupId AND CSM.Id = A. CCECSId AND CGM.OrgId =@rOrgId
	--Select @lGradeSetId		 
--Select @lIsMarkIndecimal, @lDecimalPlace
BEGIN
	BEGIN TRY
	 BEGIN	
	 
		Create Table #temp
		(
			AcademicId bigint,	
			CCECSId int,
			ExamId int,
			TotalMarks decimal(12,2),
			 ClassId int
		)
		Insert Into #temp
		(
			AcademicId,
			CCECSId,
			ExamId,
			TotalMarks,
			ClassId
		)		
		
		Select * from OPENXML (@loDoc, '/Table/CSExamGrade', 1)
		WITH ( 				
						AcademicId bigint,	
						CCECSId int,
						ExamId int,
						TotalMarks decimal(12,2),
						 ClassId int
		)
		
		Create Table #tempT
		(
			Id INT IDENTITY (1, 1),
			AcademicId bigint,	
			CCECSId int,
			ExamId int,
			TotalMarks decimal(12,2) 
		)
		Insert Into #tempT
		(
			AcademicId,
			CCECSId,
			ExamId,
			TotalMarks
		)
		Select * from OPENXML (@loDoc, '/Table/CSExamGrade', 1)
		WITH ( 				
					AcademicId bigint,	
					CCECSId int,
					ExamId int,
					TotalMarks decimal(12,2) 
			)
			
		 --Select * from #tempT
		 --Select * from sAssessment.tCCECSExamScore Where AcademicId = '1991000002213' AND CCECSId = '199100001'AND ExamId = '199100222'
		UPDATE AI 
		SET  
				AI.ConvertedMark =ROund( ( T.TotalMarks * CC.ConvertToMark)/CC.TotalMark,0)
				--(CASE WHEN @lIsMarkIndecimal=1 AND @lDecimalPlace ='0.0'
				--					THEN  ROund(( A.TotalMarks* CC.ConvertToMark)/CC.TotalMark,1)
				--					  WHEN @lIsMarkIndecimal=1 AND @lDecimalPlace ='0.00'
				--					THEN ROund( ( A.TotalMarks  * CC.ConvertToMark)/CC.TotalMark,2)
				--					ELSE 
				--						ROund( ( A.TotalMarks * CC.ConvertToMark)/CC.TotalMark,0)
				--					END 
				--				  )
		 FROM sAssessment.tCCECSExamScore AI
		 INNER JOIN #temp T On T.AcademicId = AI.AcademicId AND T.CCECSId = AI.CCECSId AND T.ExamId =AI.ExamId
		 INNER JOIN sAssessment.tCCECSForClass CC ON CC.CCECSId =AI.CCECSId AND CC.ClassId =T.ClassId
		 WHERE T.TotalMarks = AI.ObtianMark AND CC.BatchId = @rBatchId
		 
		-- INNER JOIN OPENXML (@loDoc, '/Table/CSExamGrade', 1)
		--	WITH ( 				
		--				AcademicId bigint,	
		--				CCECSId int,
		--				ExamId int,
		--				TotalMarks decimal(12,2),
		--				 ClassId int
		--				--GradeTitle nvarchar(50)
									
		--		  ) A 	ON AI.AcademicId = A.AcademicId AND AI.ExamId=A.ExamId
				  
		--AND A.CCECSId = AI.CCECSId 
		--INNER JOIN sAssessment.tCCECSForClass CC ON CC.CCECSId = AI.CCECSId AND CC.ClassId = A.ClassId	
		--WHERE A.TotalMarks = AI.ObtianMark AND CC.BatchId = @rBatchId
		Create Table #Gradetemp
		(
			Id int,
			GradeSetId bigint,	
			MinimumScore int,
			GradeCode nvarchar(20),
			GradeTitle nvarchar(50),
			GradePoint int,
			MarkRange nvarchar(50)

		)
		INSERT INTO #Gradetemp
		Select * from sAssessment.tGradeSetDetail Where GradeSetId = @lGradeSetId
		Order By MinimumScore DESC

		--Select * from #Gradetemp

			DECLARE @lCount int ,@AcademicId bigint ,@ExamId1 int,@CCECSId1 int
			SELECT @lCount =  COUNT(AcademicId) FROM #tempT
			--Select @lCount
		while (@lCount > 0)
		BEGIN
				Select @AcademicId= AcademicId FROM #tempT Where Id=@lCount
				Select @ExamId1= ExamId FROM #tempT Where Id=@lCount
				Select @CCECSId1= CCECSId FROM #tempT Where Id=@lCount
				 
				 Update AI 
					Set Grade = GS.GradeCode ,GradeIndicator=GS.GradeTitle
					from  sAssessment.tCCECSExamScore AI 
					INNER JOIN #tempT T ON T.AcademicId=AI.AcademicId AND T.ExamId=AI.ExamId AND T.CCECSId=AI.CCECSId
					INNER JOIN sAssessment.tCCECSMaster CSM ON CSM.Id = T.CCECSId
					INNER JOIN sAssessment.tCCECSGroupMaster CGM ON CGM.Id =CSM.CCECAGroupId
					INNER JOIN #Gradetemp GS ON GS.GradeSetId =CGM.GradeSetId
					Where CGM.GRadeSetId=@lGradeSetId AND AI.ConvertedMark>=GS.MinimumScore
					AND T.ExamId=@ExamId1 AND T.CCECSId=@CCECSId1 AND AI.AcademicId=@AcademicId 
					SET @lCount = @lCount - 1
					SET @AcademicId=0
		END
		DROP TABLE #temp
		DROP TABLE #tempT
		DROP TABLE #Gradetemp
 	 SELECT  @lGradeSetId AS Result
	END		
	END TRY
	
	BEGIN CATCH 
	
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAssessment].[pRptProgressCardGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptProgressCardGet]	 	 
	 @rClassId int,
	 @rBatchId int,
	 @rDivisionId int,	 
	 @rClassSubjectIdStr nvarchar(max),
	 @rExamGroupIdStr nvarchar(max),
	 @rFromDate Date='',
	 @rToDate Date='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

 --Select * from dbo.TempTableForProgress
	--SELECT 
	--	'' AS ACADEMICID,
	--	'' AS ExamDate,
	--	0 AS Maximum,
	--	0 AS Obtain,
	--	0 AS Percentage,
	--	'' AS ExamTopic,
	--	'' AS SubjectName,
	--	'' AS ExamGroup,
	--	'' AS StudentPhoto,
	--	'' AS ClassName,
	--	'' AS DivisionName,
	--	'' AS StudentName,
	--	'' AS RollNo,
	--    '' AS IsMarksInDecimal,
	--	'' AS Year,
	--	'' AS MonthFrom,
	--	'' AS MonthTo,
	--	'' AS Code,
	--	'' AS EXAMNAME,
	--	'' AS ResultStatus

		

	CREATE TABLE #tempProgressCard
	(
		Id int Identity,
		AcademicId Bigint,
		ClassSubjectId bigint,
		ExamDate Date,
		Obtain Decimal(6,2),
		Maximum Decimal(6,2),
		Percentage Decimal(6,2),
		ExamId int
		
	)
 
 DECLARE @query  AS NVARCHAR(MAX)
 set @query = 'INSERT INTO #tempProgressCard 
 SELECT	R.AcademicId,ED.ClassSubjectId,ED.ExamDate ,SUM(RD.Obtain) AS Obtain,SUM(ED.Maximum) AS Maximum,
 (SUM(RD.Obtain)/SUM(ED.Maximum))*100 AS PERCENTAGE,ED.ExamId
FROM sAssessment.tExamMaster EM INNER JOIN sAssessment.tResult R ON R.ExamId = EM.Id
INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = R.Id
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id AND ED.Id = RD.ExamDetailId
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = ESGM.ExamGroupId
INNER JOIN sStudent.tAcademic AM ON AM.Id = R.AcademicId
WHERE RD.ISPRESENT = 1 AND EM.ClassId =' + CONVERT(NVARCHAR,@rClassId) + '
 

AND AM.DivisionId = ' + CONVERT(NVARCHAR(500),@rDivisionId) + '
AND EGM.Id IN (' + CONVERT(NVARCHAR(500),@rExamGroupIdStr) + ')
AND ED.ClassSubjectId IN (' + CONVERT(NVARCHAR(500),@rClassSubjectIdStr) + ')
AND ED.EXAMDATE >= ''' + CONVERT(NVARCHAR,@rFromDate) +
''' AND ED.EXAMDATE <= ''' + CONVERT(NVARCHAR,@rToDate) +
''' AND ((AM.RollNo >= '''+ CONVERT(NVARCHAR(10),@rFromRollNo)+''') OR (' + CONVERT(NVARCHAR(10),@rFromRollNo)+'='''+ CONVERT(NVARCHAR(10),0) + ''')) 
AND ((AM.RollNo <= '''+ CONVERT(NVARCHAR(10),@rToRollNo) + ''' ) OR (' + CONVERT(NVARCHAR(10),@rToRollNo)+'='''+ CONVERT(NVARCHAR(10),0) + ''')) 
GROUP BY R.AcademicId,ED.ClassSubjectId,ED.ExamDate,ED.ExamId'
 print @query
execute(@query)

-- To maintain Group Footer length add in report row	
--select 1, '.' + replicate('`', 600)  + '.'   font size 1

SELECT
T.AcademicId,
T.ExamDate,
T.Maximum,T.Obtain,T.Percentage,
CASE WHEN ED.ExamTopic = '0' THEN '' ELSE ED.ExamTopic  END AS ExamTopic,
CS.SubjectName AS SubjectName,
EGM.Title AS ExamGroup,
SF.StudentPhoto as StudentPhoto , 
SF.ClassName,
SF.DivisionName,
SF.Name AS StudentName,SF.RollNo, 
EM.IsMarksInDecimal,
SF.Code,
sCommon.fGetMonthName(DatePart(MM,@rFromDate)) AS MonthFrom,
sCommon.fGetMonthName(DatePart(MM,@rToDate)) AS MonthTo,
BM.Title AS Year,
ISNULL(ESGM.Title,'') AS EXAMNAME ,
(Select ResultStatus FROM sAssessment.tResult Where AcademicId = T.AcademicId AND  ExamId = EM.Id)AS ResultStatus



FROM #tempProgressCard T 
INNER JOIN sAssessment.tExamMaster EM on EM.Id=T.ExamId
INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = T.ExamId AND EM.Id=ED.ExamId AND T.ExamDate = ED.ExamDate
INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id = ESGM.ExamGroupId
--INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id
INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId = ED.ClassSubjectId AND CS.ClassSubjectId=T.ClassSubjectId 
INNER JOIN sStudent.vStudentFull SF ON SF.AcademicId	= T.AcademicId AND SF.StatusId=1
INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SF.BatchId
Order By SF.RollNo,CS.OrderIndex,T.ExamDate Desc



DROP TABLE #tempProgressCard

END
GO
PRINT N'Altering [sBiometric].[pBiometricReportData]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pBiometricReportData]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int,
	@rDeptId int,
	@rForYear int=0,
	@rForMonth int=0,
	@rIsFirstIn bit=0,
	@rIsLastOut bit=0,
	@rIsOT bit=0,
	@rIsLateBy	bit=0,
	@rIsEarlyBy bit=0,
	@rIsDuration  bit=0,
	@rEmployeeStatusId int=0,
	@rEmployeeId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

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

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

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

		case when @Days >= 29 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,29,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D29,
		case when @Days >= 30 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,30,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D30,
		case when @Days >= 31 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,31,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D31,


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


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 @lEmpDepartmentID 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))

truncate table #TempMonthTrans

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,@lEmpDepartmentID = OrganizationDepartmentId  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)

		DECLARE @weekoffstatus nvarchar(20)

		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@rEmployeeId , @rForYear ,@rForMonth ,@rDay ,@rBatchId ,@rDepartmentId ,@rOrgId , @rBiometricStatus )
		SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(@lDate)  ,Month(@lDate), @lDay, @lBatchId,@lEmpDepartmentID,@rOrgId)		
		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(''' + convert(nvarchar(15),@lDate) + 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) + ')


		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 ''' +@weekoffstatus +''' in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
						When ''' +@weekoffstatus +''' Not in (''-'',''XX'') 
						Then ''' +@weekoffstatus +''' 
						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 
						INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId AND (ED.OrganizationDepartmentId ='''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+'''= 0 )
						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 (ISNULL(T1.SourceTypeId,95) = 95 OR T1.SourceTypeId = 0)'				
						
		Execute(@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1			
	END

	--SELECT * FROM #TempMonthTrans
	
	SET @strQuery = 'select  Day(T.Attn_Date), T.*,isnull(A.TotAbsent,0) AS TotAbsent,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,isnull(TotEarly,0) AS TotEarly,
	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,
	OM.Id AS OrgId,
	OM.Title AS OrganizationTitle
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID 
	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'',''PW'',''PH'') 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 IN (''W'',''PW'',''PHW'') group by EmployeeId) 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  (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0)
	AND (Emp.OrgId = ' + convert(nvarchar(15),@rOrgId) + ' OR ' + convert(nvarchar(15),@rOrgId) + ' = 0) AND (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 TotEarly,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as IsFirstIn,
	--'' as IsLastOut,
	--'' as IsOT,
	--'' as IsLateBy,
	--'' as IsEarlyBy,
	--'' as IsDuration,
	--'' as OrgId,
	--'' as OrganizationTitle
END
GO
PRINT N'Altering [sBiometric].[pRptDateWiseTimeSheetSummary]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pRptDateWiseTimeSheetSummary]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rToDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 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',
	 @rEmployeeStatusId int=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 
INNER 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 
AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)
AND ISNULL(EM.IsOtherUser,0) = 0 


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 @lEmpDepartmentID 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,Leave nvarchar(100),DayNumber nvarchar(8),PresentStatus nvarchar(25),
		FirstIn nvarchar(20),LastOut nvarchar(20),OverTime nvarchar(20),LateBy nvarchar(20),Duration nvarchar(20),EarlyBy nvarchar(20))

truncate table #TempMonthTrans

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,@lEmpDepartmentID = OrganizationDepartmentId  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)

		DECLARE @weekoffstatus nvarchar(20)

		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@rEmployeeId , @rForYear ,@rForMonth ,@rDay ,@rBatchId ,@rDepartmentId ,@rOrgId , @rBiometricStatus )
		SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(@lDate)  ,Month(@lDate), @lDay, @lBatchId,@lEmpDepartmentID,@rOrgId)		
		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(''' + convert(nvarchar(15),@lDate) + 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) + ')

		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 ''' +@weekoffstatus +''' in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
						When ''' +@weekoffstatus +''' Not in (''-'',''XX'') 
						Then ''' +@weekoffstatus +''' 
						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 
						INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId AND (ED.OrganizationDepartmentId ='''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+'''= 0 )
						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 (ISNULL(T1.SourceTypeId,95) = 95 OR T1.SourceTypeId = 0)'				
						
		Execute(@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1			
	END
	--Select * from #TempMonthTrans
	
	UPDATE tmp 
	SET PresentStatus='A'
	FROM  #TempMonthTrans tmp
	INNER JOIN sHrm.tLeave L ON tmp.EmployeeId=L.EmployeeId
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE L.StatusId = 550 AND L.EmployeeId = tmp.EmployeeId AND CAST(Attn_Date AS DATE) BETWEEN L.FromDate AND L.ToDate

	UPDATE tmp 
	SET Leave=LTM.Code + '/' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
	FROM  #TempMonthTrans tmp
	INNER JOIN sHrm.tLeave L ON tmp.EmployeeId=L.EmployeeId
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE L.StatusId = 550 AND L.EmployeeId = tmp.EmployeeId AND CAST(Attn_Date AS DATE) BETWEEN L.FromDate AND L.ToDate


	--Select * from #TempMonthTrans

	SET @strQuery = 'select  Day(T.Attn_Date), T.*,isnull(A.TotAbsent,0) AS TotAbsent,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,isnull(TotEarly,0) AS TotEarly,
	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,
	OM.Id AS OrgId,
	OM.Title AS OrganizationTitle
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID
	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'',''PW'',''PH'') 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 IN (''W'',''PW'',''PHW'') group by EmployeeId) 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 (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0) AND (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 Leave,
	--'' 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 TotEarly,
	--'' 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 [sBiometric].[pRptEmployeeCheckInGet]...';


GO
 
ALTER PROCEDURE [sBiometric].[pRptEmployeeCheckInGet]    
      
   @rOrgId int ,    
   @rBuilder1 nvarchar(max)='',    
   @rBuilder2 nvarchar(max)='',    
   @rdate date='',
   @rEmployeeStatusId int=0,
   @rEmployeeId bigint = 0    
       
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
BEGIN     
  Select     
   convert(binary,null,0) as EmployeePhoto ,    
   EMp.FirstName+' ' +EMp.MiddleName+' '+emp.LastName AS Name,    
   case B.CheckInTime when null then null when '' then null else B.CheckInTime end as CheckInTime,
   Emp.id As EmployeeID ,
   case B.CheckOutTime when null then null when '' then null else B.CheckOutTime end as CheckOutTime,   
   B.SourceId,    
   @rBuilder1 AS Builder1,    
   @rBuilder2 AS Builder2,
   OM.Id AS OrgId,
   OM.Title AS OrganizationTitle      
  from     
   sHrm.tEmployeeMaster EMP      
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EMP.OrgId
   --LEFT JOIN sBiometric.tEmployeeCheckIn B ON B.EmployeeID=EMP.Id    
   --and EMp.OrgId=@rORgId  ANd @rDate=convert(date,B.CheckInTime)    
   LEFT JOIN sBiometric.tProcess B ON B.SourceId=EMP.Id
   ANd @rDate=convert(date,B.AtdDate)
   WHERE (Emp.Id = @rEmployeeId OR @rEmployeeId = 0) AND (EMp.OrgId=@rORgId OR @rORgId = 0) AND(EMP.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)  AND  ISNULL(EMP.IsOtherUser,0) = 0     
    
END
GO
PRINT N'Altering [sBiometric].[pRptEmployeeWiseMonthlyAttendanceGet]...';


GO
 

ALTER PROCEDURE [sBiometric].[pRptEmployeeWiseMonthlyAttendanceGet]  
    
  @rOrgId int ,  
   @rBuilder1 nvarchar(max)='',  
   @rBuilder2 nvarchar(max)='' ,  
   @rFromMonth int=0,  
   @rFromyear int=0,
   @rEmployeeStatusId int=0  ,
   @rEmployeeId bigint = 0
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
  
 CREATE Table #temptable  
 (  
  EmployeeId bigint,  
  D1 nvarchar(5),D2 nvarchar(5),D3 nvarchar(5),D4 nvarchar(5),D5 nvarchar(5),D6 nvarchar(5),D7 nvarchar(5),D8 nvarchar(5),D9 nvarchar(5),  
  D10 nvarchar(5),D11 nvarchar(5),D12 nvarchar(5),D13 nvarchar(5),D14 nvarchar(5),D15 nvarchar(5),D16 nvarchar(5),D17 nvarchar(5),  
  D18 nvarchar(5),D19 nvarchar(5),D20 nvarchar(5),D21 nvarchar(5),D22 nvarchar(5),D23 nvarchar(5),D24 nvarchar(5),D25 nvarchar(5),  
  D26 nvarchar(5),D27 nvarchar(5),D28 nvarchar(5),D29 nvarchar(5),D30 nvarchar(5),D31 nvarchar(5)  
 )  

 Insert into #temptable  
 (  
  EmployeeId  
 )  
 --select * from sbiometric.tprocess
 Select Distinct B.Sourceid   
  from sHrm.tEmployeeMaster EMP    
  INNER JOIN sbiometric.tprocess B ON B.Sourceid=EMP.Id  
  WHere (EMp.OrgId=@rOrgId OR @rOrgId = 0)  AND MONTH(B.AtdDate)=@rFromMonth AND YEAR(B.AtdDate)=@rFromyear   AND  ISNULL(EMP.IsOtherUser,0) = 0
  AND (EMP.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)

  update #temptable set D1='-', D2='-', D3='-', D4='-', D5='-', D6='-', D7='-', D8='-', D9='-', D10='-', D11='-', D12='-', D13='-', D14='-', D15='-',  
   D16='-', D17='-', D18='-', D19='-', D20='-', D21='-', D22='-', D23='-', D24='-', D25='-', D26='-', D27='-', D28='-', D29='-', D30='-', D31='-'  
    
  Update t1 set t1.D1 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=1  
  Update t1 set t1.D2 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=2  
  Update t1 set t1.D3 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=3  
  Update t1 set t1.D4 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=4  
  Update t1 set t1.D5 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=5  
  Update t1 set t1.D6 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=6  
  Update t1 set t1.D7 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=7  
  Update t1 set t1.D8 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=8  
  Update t1 set t1.D9 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=9  
  Update t1 set t1.D10 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=10  
  Update t1 set t1.D11 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=11  
  Update t1 set t1.D12 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=12  
  Update t1 set t1.D13 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=13  
  Update t1 set t1.D14 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=14  
  Update t1 set t1.D15 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=15  
  Update t1 set t1.D16 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=16  
  Update t1 set t1.D17 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=17  
  Update t1 set t1.D18 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=18  
  Update t1 set t1.D19 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=19  
  Update t1 set t1.D20 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=20  
  Update t1 set t1.D21 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=21  
  Update t1 set t1.D22 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=22  
  Update t1 set t1.D23 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=23  
  Update t1 set t1.D24 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=24  
  Update t1 set t1.D25 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=25  
  Update t1 set t1.D26 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=26  
  Update t1 set t1.D27 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=27  
  Update t1 set t1.D28 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=28  
  Update t1 set t1.D29 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=29  
  Update t1 set t1.D30 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=30  
  Update t1 set t1.D31 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=31  
    
  Select   
   EMp.FirstName+' ' +EMp.MiddleName+' '+emp.LastName AS Name,  
   Emp.Id As EmployeeID ,  
    @rBuilder1 AS Builder1,  
    @rBuilder2 AS Builder2,  
    t1.*,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=1  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=1 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D1,  
      
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=2  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=2 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS  D2,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=3  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=3 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D3,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=4  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=4 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D4,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=5  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=5 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D5,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=6  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=6 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D6,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=7  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=7 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D7,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=8  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=8 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D8,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=9  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=9 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D9,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=10  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=10 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D10,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=11  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=11 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D11,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=12  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=12 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D12,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=13  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=13 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D13,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=14  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=14 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D14,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=15  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=15 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D15,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=16  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=16 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D16,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=17  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=17 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D17,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=18  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=18 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D18,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=19  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=19 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D19,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=20  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=20 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D20,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=21  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=21 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D21,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=22  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=22 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D22,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=23  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=23 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D23,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=24  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=24 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D24,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=25  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=25 And EmployeeId=Emp.Id Group by EmployeeId  )  
   --   ELSE  '-' END   
   -- )AS   D25,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=26  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=26 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D26,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=27  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=27 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D27,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=28  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=28 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D28,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=29  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=29  And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D29,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=30  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=30 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D30,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=31  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=31 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS   D31,  
    sCommon.fGetDaysInMonth(@rFromMonth,@rFromyear) As DaysInMonth ,
	OM.Id AS OrgId,
	OM.Title AS OrganizationTitle 
       
      
  from sHrm.tEmployeeMaster EMP 
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EMP.OrgID   
  INNER JOIN #temptable t1 On t1.EmployeeId =EMp.Id  AND  ISNULL(EMP.IsOtherUser,0) = 0
  WHERE (EMP.OrgId=@rOrgId OR @rOrgId = 0) AND (Emp.Id = @rEmployeeId OR @rEmployeeId = 0)  
END
GO
PRINT N'Altering [sBiometric].[pRptManualPunchGet]...';


GO
 
 
 
ALTER PROCEDURE [sBiometric].[pRptManualPunchGet]    
             
   @rBuilder1 nvarchar(max)='',    
   @rBuilder2 nvarchar(max)='',    
   @rToDate date='',
   @rFromDate date='',
   @rEmployeeStatusId int=0,
   @rEmployeeId bigint = 0,
   @rOrganizationDepartmentId int = 0,
   @rLocationConfig nvarchar(50) = '',
   @rOrgId int = 0
       
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
BEGIN     
  Select 
  EM.Code AS EmployeeCode,    
   ISNULL(ECI.EmployeePhoto,0) AS EmployeePhoto,
   EM.FirstName+' ' +EM.MiddleName+' '+EM.LastName AS Name,    
   ISNULL(ECI.CheckInTime,'') AS CheckInTime,
   ISNULL(ECI.CheckOutTime,'') AS CheckOutTime,
   EM.ID As EmployeeID ,      
   @rBuilder1 AS Builder1,    
   @rBuilder2 AS Builder2,
   ISNULL(LatitudeAxis,'') AS Latitude,
   ISNULL(LongitudeAxis,'') AS Longitude,
   ISNULL(Location,'') AS Location,
   @rLocationConfig AS LocationConfig,
   CAST(ECI.AttendanceDate AS DATE) AS AttendanceDate,
   OM.Id AS OrganizationId,
   OM.Title AS OrganizationName
   
  FROM
	   sBiometric.tEmployeeCheckIn ECI      
	   INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = ECI.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	   LEFT JOIN sHrm.tEmployeeJobDetail ED ON ED.EmployeeId = EM.Id     
   WHERE 
	   (EM.Id = @rEmployeeId OR @rEmployeeId = 0) 
	   AND (EM.OrgId = @rOrgId OR @rOrgId = 0)
	   AND (CAST(ECI.AttendanceDate AS DATE) >= @rFromDate OR (ISNULL(@rFromDate,'')=''))
       AND (CAST(ECI.AttendanceDate AS DATE) <= @rToDate OR (ISNULL(@rToDate,'')=''))
	   AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)
	   AND (ED.OrganizationDepartmentId =@rOrganizationDepartmentId Or @rOrganizationDepartmentId= 0 )	   
	   AND  ISNULL(EM.IsOtherUser,0) = 0	   	   
    
	ORDER BY ECI.AttendanceDate DESC
END
GO
PRINT N'Altering [sBiometric].[pRptMonthlySummaryListGet]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pRptMonthlySummaryListGet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int = 0,
	@rDeptId int = 0,
	@rForYear int=0,
	@rForMonth int=0,	 
	@rEmployeeStatusId int=0,
	@rEmployeeId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		MT.EmployeeId,
		MT.EmpCode,
		EM.FirstName + ' ' + EM.LastName AS EmployeeName,
		MT.Tot_Attn  AS TotalPresentDays,
		MT.Tot_Abs AS TotalAbsentDays,
		MT.Tot_WeekOFF AS TotalWeekOffs,
		MT.Tot_Holiday AS TotalHolidays,
		OM.Id AS OrganizationId,
		OM.DisplayTitle AS OrganizationTitle,
		OM.OrderIndex AS OrganizationOrderIndex,
		EM.Number AS EmployeeNumber,
		DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays		
	FROM
	sBiometric.tMonthTrans MT
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId --AND SourceTypeId = 95
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	WHERE
	(EM.OrgId = @rOrgId OR @rOrgId = 0)
	AND YEAR(MT.Attn_Dt) = @rForYear
	AND (MONTH(MT.Attn_dt) = @rForMonth )
	AND (EJD.OrganizationDepartmentId = @rDeptId OR @rDeptId = 0)		 	
	AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
	AND ISNULL(EM.IsOtherUser,0) = 0 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	AND (MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
END
GO
PRINT N'Altering [sCertificate].[pRptOtherCertificateGet]...';


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

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


	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsShowPhoto = 0
	--ELSE
	--SET @lIsShowPhoto = 1
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 181 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayReligion = 0
	--ELSE
	--SET @lIsDisplayReligion = 1
	
	SELECT @lOrgGroupId = OrgGroupId FROM  sSetup.tOrganizationMaster WHERE Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue FROM sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId
	
	SELECT 	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			OC.Id,
			OC.Number,
			OC.AcademicId,
			SM.Code,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			CONVERT(nvarchar,BM.FromDate,103) AS Batch,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			OC.CertificateDate,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			ATM.Title AS AffiliationType,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			ISNULL(RM.Title,'') AS ReligionName,
			@lIsShowPhoto AS IsShowPhoto,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			OC.Remark AS ReceiptNo,
			SF.FatherName,
			SA.AdmissionDate,
			SA.LeftDate,
			DP.Title AS DepartmentName,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4,
			REPLICATE(',',OM.LetterHeadMargin) AS LetterHeadMargin,
			CT.Title AS Category,
			SF.MotherName,
			C.PermanentStreetOne,
			C.PermanentStreetTwo,
			C.PermanentStreetThree,
			C.PermanentCountry,
			C.PermanentState,
			C.PermanentCity,
			C.PermanentZipCode,
			C.PermanentContactNo,
			C.PresentStreetOne,
			C.PresentStreetTwo,
			C.PresentStreetThree,
			C.PresentCountry,
			C.PresentState,
			C.PresentCity,
			C.PresentContactNo,
			C.PresentZipCode,
			SA.PreviousStandard,
			SA.PreviousSchool, 
			SM.SUId,
			SO.AdhaarNumber,
			SO.UIDNumber,
			CM.DisplayTitle AS ClassName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			OM.PrincipalSignature,
			ISnull(AR.SourceId,0) AS StudentidForhostel,
			DM.DisplayTitle AS Divisionname,
			@lIDConfigValue AS ItemValue ,
			SM.RecordStatusId,
			SO.BirthState AS BirthState,
			CM1.DisplayTitle AS AdmissionStandard,
			CM2.DisplayTitle AS LeftStandard,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			SO.MotherTongue,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCNumber,
			CM.DisplayTitle AS CurrentStandard,
			BM.Title AS BatchTitle	
	FROM 
			sCertificate.tOtherCertificate OC
			INNER JOIN sStudent.tAcademic A ON OC.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			INNER JOIN sSetup.tAffiliationMaster AM ON OM.AffiliationId = AM.Id
			INNER JOIN sSetup.tAffiliationTypeMaster ATM ON AM.AffiliationTypeId = ATM.Id
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = SM.Id
			INNER JOIN sSetup.tDepartmentMaster DP ON CM.DepartmentId = DP.Id
			LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SO.CastCategoryId
			LEFT JOIN sStudent.tStudentCommunication C ON C.StudentId = A.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sHostel.tAssignRoom AR On AR.SourceId=A.StudentId AND AR.OrgGroupBatchId=@rOrgGroupBatchId 
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id= SA.AdmissionStandardId
			--LEFT JOIN sStudent.tStudentAdmission SA1 ON SA1.AdmissionStandardId = CM1.Id
			LEFT JOIN sSetup.tClassMaster CM2 ON CM2.Id= SA.LeftStandardId
			--LEFT JOIN sStudent.tStudentAdmission SA2 ON SA2.LeftStandardId = CM2.Id
			LEFT JOIN sCertificate.tLeaving L ON L.AcademicId=A.Id
			
	WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			AND ((OC.Number=@rNumber) OR (@rNumber=''))
			AND ((OC.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((OC.Number <= @rToNo) OR (@rToNo=''))
			AND ((OC.CertificateDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OC.CertificateDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OC.CertificateTypeId = @rCertificateTypeId) OR (@rCertificateTypeId = 0))
	END
GO
PRINT N'Altering [sCommon].[pPublishDocumentMasterGet]...';


GO

ALTER PROCEDURE [sCommon].[pPublishDocumentMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId smallint
AS
SET NOCOUNT ON

	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rTitle = sCommon.fSearchStringGet(@rTitle)

BEGIN

	SELECT PDM.Id 
		  ,PDM.Code
		  ,PDM.Title AS Name
		  ,PDM.IsObsolete
		  ,OrgGroupId
     
	  FROM sCommon.tPublishDocumentMaster PDM
     
	  WHERE 
			((PDM.Id = @rId) OR (@rId = 0))
		AND ((PDM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
		AND ((PDM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND (PDM.OrgGroupId = @rOrgGroupId)

	UNION

	SELECT PDM.Id 
		  ,PDM.Code
		  ,PDM.Title AS Name
		  ,PDM.IsObsolete
		  ,OrgGroupId
     
	  FROM sCommon.tPublishDocumentMaster PDM
     
	  WHERE 
			((PDM.Id = @rId) OR (@rId = 0))
		AND ((PDM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
		AND ((PDM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
		AND (PDM.OrgGroupId IS NULL)

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


GO
ALTER PROCEDURE [sCommunication].[pFollowupTypeMasterAdd]
	 
		@rId bigint,
		@rCode nvarchar(100),
		@rTitle nvarchar(200),
		@rOrderIndex int,
		@rIsPublish bit,
		@rIsObsolete bit = 0,
		@rOrgGroupId smallint,
		@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from [sCommunication].[tFollowupTypeMaster] where Title=@rTitle AND Code=@rCode AND OrgGroupId=@rOrgGroupId)
		BEGIN
			select -103 as Result
			RETURN
		END 
		If Exists(select Id from [sCommunication].[tFollowupTypeMaster] where OrderIndex=@rOrderIndex)
		BEGIN
			select -1003 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from [sCommunication].[tFollowupTypeMaster] where Title=@rTitle AND Code=@rCode AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
		If Exists(select Id from [sCommunication].[tFollowupTypeMaster] where OrderIndex=@rOrderIndex AND Id<>@rId)
		BEGIN
			select -1003 as Result
			RETURN
		END
	END
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
		BEGIN
		
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFollowupTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
		INSERT INTO [sCommunication].[tFollowupTypeMaster]
			   ([Id]
			   ,[Code]
			   ,[Title]
			   ,[OrderIndex]
			   ,[IsPublish]
			   ,[IsObsolete]
			   ,[OrgGroupId]
			   ,[CreatedUserId]
			   ,[CreatedDateTime])
		 VALUES
			   (@lNextNumber,
			    @rCode ,
				@rTitle ,
				@rOrderIndex ,
				@rIsPublish ,
				@rIsObsolete ,
				@rOrgGroupId ,
				@rCreatedUserId ,
				sCommon.fGetDate())

		SELECT 1 AS Result
		SELECT @lNextNumber AS Id
		END	 
	ELSE
		 BEGIN
		 SET @lNextNumber = @rId
			UPDATE [sCommunication].[tFollowupTypeMaster]
				SET 
				  [Code] = @rCode ,
				  [Title] = @rTitle ,
				  [OrderIndex] = @rOrderIndex ,
				  [IsPublish] = @rIsPublish ,
				  [IsObsolete] = @rIsObsolete ,
				  [OrgGroupId] = @rOrgGroupId ,
				  [UpdatedUserId] = @rCreatedUserId ,
				  [UpdatedDateTime] = sCommon.fGetDate()  
				WHERE [Id] = @rId
			  
			  SELECT 11 AS Result
		SELECT @lNextNumber AS Id
		 END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sCommunication].[pFollowupTypeMasterDelete]...';


GO
ALTER PROCEDURE [sCommunication].[pFollowupTypeMasterDelete]
	 
	 @rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN TRY
		
		BEGIN TRANSACTION		
			DELETE FROM [sCommunication].[tFollowupTypeAssignedTo] WHERE FollowupTypeId=@rId
			DELETE FROM [sCommunication].[tFollowupTypeMaster] WHERE Id=@rId
			SELECT 1 AS Result
	
	COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END
GO
PRINT N'Altering [sCommunication].[pStudentUploadedDocumentListGet]...';


GO

ALTER PROCEDURE [sCommunication].[pStudentUploadedDocumentListGet]
	 
	 @rSourceId bigint,
	 @rDivisionId int = 0,
	 @rBatchId int,
	 @rSyncedUploadResultId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF (@rSourceId!=0)
	BEGIN
		SELECT @rDivisionId=DivisionId FROM sStudent.tAcademic		
		 WHERE StudentId=@rSourceId AND BatchId = @rBatchId
	END
		--SELECT 
		--	@rSourceId AS SourceId,
		--	SDU.Id,
		--	SDU.Title,
		--	SDTM.Title AS DocumentType,
		--	S.Code,
		--	SDU.DocumentUploadDate,
		--	BM.OrgId,
		--	S.RollNo
		--FROM 
		--	sCommunication.tStudentDocumentUpload SDU  
		--	INNER JOIN sStudent.vStudentAcademic S ON S.DivisionId = SDU.DivisionId AND SDU.BatchId = S.BatchId 
		--	AND S.StudentId = @rSourceId AND S.BatchId = @rBatchId
		--	INNER JOIN sCommunication.tStudentDocumentTypeMaster SDTM ON SDTM.Id = SDU.StudentDocumentTypeId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = S.BatchId
		--WHERE 
		--	SDU.DivisionId=@rDivisionId
		--	AND SDU.BatchId=@rBatchId
		--	AND SDU.IsObsolete=0
		--	AND ( SDU.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
		
		--	and SDU.DocumentUploadDate <= replace(convert(varchar, sCommon.fGetDate(), 111), '/','-') 
		--		--order by SDU.DocumentUploadDate,S.RollNo,S.Code DESC

		--UNION

		SELECT 
			@rSourceId AS SourceId,
			SDU.Id,
			SDU.Title,
			PDM.Title AS DocumentType,
			S.Code,
			SDU.DocumentUploadDate,
			BM.OrgId,
			S.RollNo
		FROM 
			sCommunication.tStudentDocumentUpload SDU  
			INNER JOIN sStudent.vStudentAcademic S ON S.DivisionId = SDU.DivisionId AND SDU.BatchId = S.BatchId 
			AND S.StudentId = @rSourceId AND S.BatchId = @rBatchId
			INNER JOIN sCommon.tPublishDocumentMaster PDM ON PDM.Id = SDU.StudentDocumentTypeId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = S.BatchId
		WHERE 
			SDU.DivisionId=@rDivisionId
			AND SDU.BatchId=@rBatchId
			AND SDU.IsObsolete=0
			AND ( SDU.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
		
			and SDU.DocumentUploadDate <= replace(convert(varchar, sCommon.fGetDate(), 111), '/','-') 
		    order by SDU.DocumentUploadDate,S.RollNo,S.Code DESC
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


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

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


GO
 

ALTER PROCEDURE [sPayroll].[pRptEmployeePaybillDetail]
	
	 @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,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rStatusId int = 0
	  
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		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,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		MM.Title AS MonthName,
		ISNULL(PPE.WorkingDays,0) AS WorkingDays,
		(ISNULL(PPE.WorkingDays,0) - ISNULL(PPE.Lwp,0)) AS PresentDays,
		--ISNULL(PPE.Lwp,0) AS AbsentDays,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
		tEM.FirstName,
		tEm.LastName,
		ISNULL(ESO.AccountHolderName,'')AS AccountHolderName,
		tEM.Number,
		EM.EmployeeDesignation

		
	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 
	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 ((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 ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
END
GO
PRINT N'Altering [sSecurity].[pAppPermissionGet]...';


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

	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard 
			20097, -- View Query
			30249, -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786, --Online Learning 
			30787, --Online learning Student View
			30815, --Consolidate - Fee Status
			30813, --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,   -- Consolidate - Admission Inquiry Summary,
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App 
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951    -- Visitor Log Listing
			)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard
			20097, -- View Query
			30249,  -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786 , --Online Learning 
			30787,  --Online learning Student View
			30815,  --Consolidate - Fee Status
			30813,  --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,  -- Consolidate - Admission Inquiry Summary
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951    -- Visitor Log Listing
			) 
		) TP 
		GROUP BY TP.TaskId
	END
END
GO
PRINT N'Altering [sTimetable].[pEmployeeTimeTableGet]...';


GO
 
ALTER PROCEDURE [sTimetable].[pEmployeeTimeTableGet]
	
	@rEmployeeId bigint,
	 @rBatchId int=0,
	 @rTimeTableSchemaId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @lTableList TABLE
(
   
    LectureNumber int,   
	Sunday varchar(100) NULL,
    Monday varchar(100) NULL,
    Tuesday varchar(100) NULL,
    Wednesday varchar(100) NULL,
    Thursday varchar(100) NULL,
    Friday varchar(100) NULL,
    Saturday varchar(100) NULL,	
	SundayClassSubjectId varchar(100) NULL,
    MondayClassSubjectId varchar(100) NULL,
    TuesdayClassSubjectId varchar(100) NULL,
    WednesdayClassSubjectId varchar(100) NULL,
    ThursdayClassSubjectId varchar(100) NULL,
    FridayClassSubjectId varchar(100) NULL,
    SaturdayClassSubjectId varchar(100) NULL    
)


DECLARE @HeaderCounterStart INT=1
DECLARE @HeaderMaxCounter INT=0

SET @HeaderMaxCounter  = (select max(NoOfPeriod) as MaxLectures  From [sTimetable].[tTimeSetup] where TimeTableSchemaId=@rTimeTableSchemaId and BatchId=@rBatchId)

  WHILE (@HeaderCounterStart <= @HeaderMaxCounter)
    BEGIN
        --DECLARE @HeaderTitle varchar(100)='';
        --SET @HeaderTitle=(SELECT FieldName from @lFieldList where Id=@HeaderCounterStart)  
        --IF(SUBSTRING(@HeaderTitle, len(@HeaderTitle) - 1, 2)='Id')
        --BEGIN
        --  SET @HeaderTitle=REPLACE(@HeaderTitle, SUBSTRING(@HeaderTitle, len(@HeaderTitle) - 1, 2), '') 
        --END     
        --SET @HeaderHtml=@HeaderHtml + ('<th>'+@HeaderTitle+'</th>') 
      
			Declare @AssignSundayClassDivisionName varchar(100)
            SET @AssignSundayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=1 and LectureNumber=@HeaderCounterStart)
            
            IF(@AssignSundayClassDivisionName is NULL)
             BEGIN
              SET @AssignSundayClassDivisionName='-1'
             END 
             
            
            Declare @AssignSundaySubjectName varchar(100)
            SET @AssignSundaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=1 and LectureNumber=@HeaderCounterStart)
            
             IF(@AssignSundaySubjectName is NULL)
             BEGIN
              SET @AssignSundaySubjectName='-1'
             END 


            Declare @AssignMondayClassDivisionName varchar(100)
            SET @AssignMondayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=2 and LectureNumber=@HeaderCounterStart)
            
            IF(@AssignMondayClassDivisionName is NULL)
             BEGIN
              SET @AssignMondayClassDivisionName='-1'
             END 
             
            
            Declare @AssignMondaySubjectName varchar(100)
            SET @AssignMondaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=2 and LectureNumber=@HeaderCounterStart)
            
             IF(@AssignMondaySubjectName is NULL)
             BEGIN
              SET @AssignMondaySubjectName='-1'
             END 
            
            Declare @AssignTuesdayClassDivisionName varchar(100)
            SET @AssignTuesdayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=3 and LectureNumber=@HeaderCounterStart)
            
             IF(@AssignTuesdayClassDivisionName is NULL)
             BEGIN
              SET @AssignTuesdayClassDivisionName='-1'
             END 
            
            Declare @AssignTuesdaySubjectName varchar(100)
            SET @AssignTuesdaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=3 and LectureNumber=@HeaderCounterStart)
           
             IF(@AssignTuesdaySubjectName is NULL)
             BEGIN
              SET @AssignTuesdaySubjectName='-1'
             END 
            
            
            Declare @AssignWedenadayClassDivisionName varchar(100)
            SET @AssignWedenadayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=4 and LectureNumber=@HeaderCounterStart)
            
             IF(@AssignWedenadayClassDivisionName is NULL)
             BEGIN
              SET @AssignWedenadayClassDivisionName='-1'
             END 
            
               Declare @AssignWedenadaySubjectName varchar(100)
            SET @AssignWedenadaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=4 and LectureNumber=@HeaderCounterStart)
           
            
             IF(@AssignWedenadaySubjectName is NULL)
             BEGIN
              SET @AssignWedenadaySubjectName='-1'
             END 
            
            
            Declare @AssignThrusdayClassDivisionName nvarchar(100)
            SET @AssignThrusdayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=5 and LectureNumber=@HeaderCounterStart)
            
            
             IF(@AssignThrusdayClassDivisionName is NULL)
             BEGIN
              SET @AssignThrusdayClassDivisionName='-1'
             END 
            
            
            Declare @AssignThrusdaySubjectName nvarchar(100)
            SET @AssignThrusdaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=5 and LectureNumber=@HeaderCounterStart)
           
            IF(@AssignThrusdaySubjectName is NULL)
             BEGIN
              SET @AssignThrusdaySubjectName='-1'
             END 
            
            
            Declare @AssignFridayClassDivisionName varchar(100)
            SET @AssignFridayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=6 and LectureNumber=@HeaderCounterStart)
       
             IF(@AssignFridayClassDivisionName is NULL)
             BEGIN
              SET @AssignFridayClassDivisionName='-1'
             END 
            
       
            Declare @AssignFridaySubjectName varchar(100)
            SET @AssignFridaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=6 and LectureNumber=@HeaderCounterStart)
           
             IF(@AssignFridaySubjectName is NULL)
             BEGIN
              SET @AssignFridaySubjectName='-1'
             END 
             
            
      
            Declare @AssignSaturdayClassDivisionName varchar(100)
            SET @AssignSaturdayClassDivisionName=(SELECT VBCD.ClassDivisionName From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=7 and LectureNumber=@HeaderCounterStart)
      
            IF(@AssignSaturdayClassDivisionName is NULL)
             BEGIN
              SET @AssignSaturdayClassDivisionName='-1'
             END 
          
            Declare @AssignSaturdaySubjectName varchar(100)
            SET @AssignSaturdaySubjectName=(SELECT SM.Code From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=7 and LectureNumber=@HeaderCounterStart)
           
           IF(@AssignSaturdaySubjectName is NULL)
             BEGIN
              SET @AssignSaturdaySubjectName='-1'
             END 
           

			Declare @AssignSundayDivisionSubject varchar(100)
             Declare @AssignSundayClassDivisionId varchar(100)
             Declare @AssignSundaySubjectId varchar(100)
             
             SET @AssignSundayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=1 and LectureNumber=@HeaderCounterStart)
             SET @AssignSundaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=1 and LectureNumber=@HeaderCounterStart)
             
             IF(@AssignSundayClassDivisionId is NULL)
             BEGIN
              SET @AssignSundayClassDivisionId='-1'
             END 
              IF(@AssignSundaySubjectId is NULL)
             BEGIN
              SET @AssignSundaySubjectId='-1'
             END 
           
             
             SET @AssignSundayDivisionSubject=@AssignSundayClassDivisionId +'/' + @AssignSundaySubjectId

           
             Declare @AssignMondayDivisionSubject varchar(100)
             Declare @AssignMondayClassDivisionId varchar(100)
             Declare @AssignMondaySubjectId varchar(100)
             
             SET @AssignMondayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=2 and LectureNumber=@HeaderCounterStart)
             SET @AssignMondaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=2 and LectureNumber=@HeaderCounterStart)
             
             IF(@AssignMondayClassDivisionId is NULL)
             BEGIN
              SET @AssignMondayClassDivisionId='-1'
             END 
              IF(@AssignMondaySubjectId is NULL)
             BEGIN
              SET @AssignMondaySubjectId='-1'
             END 
           
             
             SET @AssignMondayDivisionSubject=@AssignMondayClassDivisionId +'/' + @AssignMondaySubjectId
             
             Declare @AssignTuesdayDivisionSubject varchar(100)
             Declare @AssignTuesdayClassDivisionId varchar(100)
             Declare @AssignTuesdaySubjectId varchar(100)
             
             SET @AssignTuesdayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=3 and LectureNumber=@HeaderCounterStart)
             SET @AssignTuesdaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=3 and LectureNumber=@HeaderCounterStart)
             
            IF(@AssignTuesdayClassDivisionId is NULL)
             BEGIN
              SET @AssignTuesdayClassDivisionId='-1'
             END 
              IF(@AssignTuesdaySubjectId is NULL)
             BEGIN
              SET @AssignTuesdaySubjectId='-1'
             END 
             
             SET @AssignTuesdayDivisionSubject=@AssignTuesdayClassDivisionId +'/' + @AssignTuesdaySubjectId
             
             
             Declare @AssignWednesdayDivisionSubject varchar(100)
             Declare @AssignWednesdayClassDivisionId varchar(100)
             Declare @AssignWednesdaySubjectId varchar(100)
             
             SET @AssignWednesdayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=4 and LectureNumber=@HeaderCounterStart)
             SET @AssignWednesdaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=4 and LectureNumber=@HeaderCounterStart)
             
              IF(@AssignWednesdayClassDivisionId is NULL)
             BEGIN
              SET @AssignWednesdayClassDivisionId='-1'
             END 
              IF(@AssignWednesdaySubjectId is NULL)
             BEGIN
              SET @AssignWednesdaySubjectId='-1'
             END 
             
             
             SET @AssignWednesdayDivisionSubject=@AssignWednesdayClassDivisionId +'/' + @AssignWednesdaySubjectId
             
             Declare @AssignThursdayDivisionSubject varchar(100)
             Declare @AssignThursdayClassDivisionId varchar(100)
             Declare @AssignThursdaySubjectId varchar(100)
             
             SET @AssignThursdayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=5 and LectureNumber=@HeaderCounterStart)
             SET @AssignThursdaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=5 and LectureNumber=@HeaderCounterStart)
             
             IF(@AssignThursdayClassDivisionId is NULL)
             BEGIN
              SET @AssignThursdayClassDivisionId='-1'
             END 
              IF(@AssignThursdaySubjectId is NULL)
             BEGIN
              SET @AssignThursdaySubjectId='-1'
             END 
             
             
             SET @AssignThursdayDivisionSubject=@AssignThursdayClassDivisionId +'/' + @AssignThursdaySubjectId
             
             
             Declare @AssignFridayDivisionSubject varchar(100)
             Declare @AssignFridayClassDivisionId varchar(100)
             Declare @AssignFridaySubjectId varchar(100)
             
             SET @AssignFridayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=6 and LectureNumber=@HeaderCounterStart)
             SET @AssignFridaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=6 and LectureNumber=@HeaderCounterStart)
             
             IF(@AssignFridayClassDivisionId is NULL)
             BEGIN
              SET @AssignFridayClassDivisionId='-1'
             END 
              IF(@AssignFridaySubjectId is NULL)
             BEGIN
              SET @AssignFridaySubjectId='-1'
             END 
             
             
             SET @AssignFridayDivisionSubject=@AssignFridayClassDivisionId +'/' + @AssignFridaySubjectId
             
             Declare @AssignSaturdayDivisionSubject varchar(100)
             Declare @AssignSaturdayClassDivisionId varchar(100)
             Declare @AssignSaturdaySubjectId varchar(100)
             
             SET @AssignSaturdayClassDivisionId=(SELECT VBCD.DivisionId From  sTimetable.tTimeTable T INNER JOIN sSetup.vClassDivision VBCD ON VBCD.DivisionId=T.DivisionId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=7 and LectureNumber=@HeaderCounterStart)
             SET @AssignSaturdaySubjectId=(SELECT SM.Id From  sTimetable.tTimeTable T INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=T.SubjectId  where EmployeeId=@rEmployeeId and TimeTableSchemaId=@rTimeTableSchemaId and DayId=7 and LectureNumber=@HeaderCounterStart)
             
             IF(@AssignSaturdayClassDivisionId is NULL)
             BEGIN
              SET @AssignSaturdayClassDivisionId='-1'
             END 
              IF(@AssignSaturdaySubjectId is NULL)
             BEGIN
              SET @AssignSaturdaySubjectId='-1'
             END 
             
             
             SET @AssignSaturdayDivisionSubject=@AssignSaturdayClassDivisionId +'/' + @AssignSaturdaySubjectId
             
           print @HeaderCounterStart
       print @AssignThrusdayClassDivisionName
       print @AssignThrusdaySubjectName
			--INSERT INTO @lTableList(LectureNumber,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,MondayClassSubjectId,TuesdayClassSubjectId,WednesdayClassSubjectId,ThursdayClassSubjectId,FridayClassSubjectId,SaturdayClassSubjectId)
			--values(@HeaderCounterStart,@AssignMondayClassDivisionName +'/' + @AssignMondaySubjectName,@AssignTuesdayClassDivisionName+'/' + @AssignTuesdaySubjectName,@AssignWedenadayClassDivisionName+'/' + @AssignWedenadaySubjectName,@AssignThrusdayClassDivisionName+'/' + @AssignThrusdaySubjectName,@AssignFridayClassDivisionName+'/' + @AssignFridaySubjectName,@AssignSaturdayClassDivisionName+'/' + @AssignSaturdaySubjectName,@AssignMondayDivisionSubject,@AssignTuesdayDivisionSubject,@AssignWednesdayDivisionSubject,@AssignThursdayDivisionSubject,@AssignFridayDivisionSubject,@AssignSaturdayDivisionSubject)
        
       INSERT INTO @lTableList(LectureNumber,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday,MondayClassSubjectId,TuesdayClassSubjectId,WednesdayClassSubjectId,ThursdayClassSubjectId,FridayClassSubjectId,SaturdayClassSubjectId,SundayClassSubjectId)
			values(@HeaderCounterStart,@AssignSundayClassDivisionName +'/' + @AssignSundaySubjectName,@AssignMondayClassDivisionName +'/' + @AssignMondaySubjectName,@AssignTuesdayClassDivisionName+'/' + @AssignTuesdaySubjectName,@AssignWedenadayClassDivisionName+'/' + @AssignWedenadaySubjectName,@AssignThrusdayClassDivisionName +'/' + @AssignThrusdaySubjectName,@AssignFridayClassDivisionName+'/' + @AssignFridaySubjectName,@AssignSaturdayClassDivisionName+'/' + @AssignSaturdaySubjectName,@AssignSundayDivisionSubject,@AssignMondayDivisionSubject,@AssignTuesdayDivisionSubject,@AssignWednesdayDivisionSubject,@AssignThursdayDivisionSubject,@AssignFridayDivisionSubject,@AssignSaturdayDivisionSubject)
        
        
            
        SET @HeaderCounterStart=@HeaderCounterStart+1;
    END



     select *From @lTableList
END
GO
PRINT N'Altering [sTool].[pUpgradeVersion]...';


GO

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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

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


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

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



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

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

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

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

-- update tablerowid master data from excel to table

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

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

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



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




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId

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


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

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


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




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

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

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

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


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

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

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


			
			
END


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

END


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

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

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

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

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

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

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

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

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

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

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

END
GO
PRINT N'Creating [sCommunication].[pFollowup]...';


GO
CREATE PROCEDURE [sCommunication].[pFollowup]
		@rAutoId bigint,
		@rFollowupNumber int,
		@rFollowupTypeId bigint,
		@rFollowupDate date,
		@rFollowupTime time(7),
		@rFollowupDuration int,
		@rRelationId tinyint,
		@rAcademicId bigint,
		@rFollowupRemark nvarchar(500),
		@rFollowupOtherRemark nvarchar(500)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		
	BEGIN TRANSACTION	
	
	IF(@rAutoId = 0)	
		BEGIN
			INSERT INTO [sCommunication].[tFollowup]
			   ([FollowupNumber]
			   ,[FollowupTypeId]
			   ,[FollowupDate]
			   ,[FollowupTime]
			   ,[FollowupDuration]
			   ,[RelationId]
			   ,[AcademicId]
			   ,[FollowupRemark]
			   ,[FollowupOtherRemark])
			VALUES	
				(@rFollowupNumber,
				@rFollowupTypeId,
				@rFollowupDate,
				@rFollowupTime,
				@rFollowupDuration,
				@rRelationId,
				@rAcademicId,
				@rFollowupRemark,
				@rFollowupOtherRemark)
		SELECT 1 AS Result
		END	 
	ELSE
		 BEGIN
			UPDATE [sCommunication].[tFollowup]
			SET [FollowupNumber] = @rFollowupNumber,
				[FollowupTypeId] = 	@rFollowupTypeId,
				[FollowupDate] = 	@rFollowupDate,
				[FollowupTime] = 	@rFollowupTime,
				[FollowupDuration] = 	@rFollowupDuration,
				[RelationId] = 	@rRelationId,
				[AcademicId] = 	@rAcademicId,
				[FollowupRemark] = 	@rFollowupRemark,
				[FollowupOtherRemark] = 	@rFollowupOtherRemark
			WHERE AutoId = @rAutoId
			  SELECT 11 AS Result
		 END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sCommunication].[pFollowupAdd]...';


GO
CREATE PROCEDURE [sCommunication].[pFollowupAdd]
		@rAutoId bigint=0,
		@rFollowupNumber int=0,
		@rFollowupTypeId bigint,
		@rFollowupDate date,
		@rFollowupTime time(7),
		@rFollowupDuration int,
		@rRelationId tinyint,
		@rAcademicId bigint,
		@rFollowupRemark nvarchar(500),
		@rFollowupOtherRemark nvarchar(500),
		@rFollowupRelationRemark nvarchar(500),
		@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		
	BEGIN TRANSACTION	
	
	IF(@rAutoId = 0)	
		BEGIN
		set @rFollowupNumber = (select (ISNULL(max(FollowupNumber), 0) + 1) from [sCommunication].[tFollowup] where AcademicId = @rAcademicId and FollowupTypeId = @rFollowupTypeId)
			INSERT INTO [sCommunication].[tFollowup]
			   ([FollowupNumber]
			   ,[FollowupTypeId]
			   ,[FollowupDate]
			   ,[FollowupTime]
			   ,[FollowupDuration]
			   ,[RelationId]
			   ,[AcademicId]
			   ,[FollowupRemark]
			   ,[FollowupOtherRemark]
			   ,[FollowupRelationRemark]
			   ,[CreatedUserId]
			   ,[CreatedDateTime])
			VALUES	
				(@rFollowupNumber,
				@rFollowupTypeId,
				@rFollowupDate,
				@rFollowupTime,
				@rFollowupDuration,
				@rRelationId,
				@rAcademicId,
				@rFollowupRemark,
				@rFollowupOtherRemark,
				@rFollowupRelationRemark,
				@rCreatedUserId,
				getdate())
		SELECT 1 AS Result
		END	 
	ELSE
		
		 BEGIN
			UPDATE [sCommunication].[tFollowup]
			SET [FollowupTypeId] = 	@rFollowupTypeId,
				[FollowupDate] = 	@rFollowupDate,
				[FollowupTime] = 	@rFollowupTime,
				[FollowupDuration] = 	@rFollowupDuration,
				[RelationId] = 	@rRelationId,
				[AcademicId] = 	@rAcademicId,
				[FollowupRemark] = 	@rFollowupRemark,
				[FollowupOtherRemark] = @rFollowupOtherRemark,
				[FollowupRelationRemark] = @rFollowupRelationRemark,
				[UpdatedUserId] = @rCreatedUserId,
				[UpdatedDateTime] = getdate()
			WHERE AutoId = @rAutoId
			  SELECT 11 AS Result
		 END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sCommunication].[pFollowupDelete]...';


GO
Create PROCEDURE [sCommunication].[pFollowupDelete]
	 
	 @rAutoId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN TRY
		
		BEGIN TRANSACTION		
			DELETE FROM [sCommunication].[tFollowup] WHERE AutoId=@rAutoId
			SELECT 1 AS Result
	
	COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END
GO
PRINT N'Creating [sCommunication].[pFollowupGet]...';


GO


CREATE PROCEDURE [sCommunication].[pFollowupGet]
	@rAutoId bigint=0,
	@rFollowupNumber int=0,
	@rFollowupTypeId bigint=0,
	@rCode nvarchar(20)='',
	@rName nvarchar = '',
	@rFromDate date='',
    @rToDate date=''


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rCode= sCommon.fSearchStringGet(@rCode)
SELECT F.[AutoId]
      ,F.[FollowupNumber]
      ,F.[FollowupTypeId]
      ,F.[FollowupDate]
      ,F.[FollowupTime]
      ,F.[FollowupDuration]
      ,F.[RelationId]
      ,F.[AcademicId]
      ,F.[FollowupRemark]
      ,F.[FollowupOtherRemark]
	  ,F.[FollowupRelationRemark]
	  ,FTM.[Title]
	  ,(SM.FirstName+' '+SM.MiddleName+' '+SM.LastName) AS Name
	  ,SM.Code
	  ,RM.[Title] as RelationName
	  --,CONVERT(datetime,((convert(nvarchar(10), convert(date,F.[FollowupDate])) +' '+  convert(nvarchar(10),convert(time,F.FollowupTime))))) AS FollowupDateTime
	FROM [sCommunication].[tFollowup] F 
	INNER JOIN [sCommunication].[tFollowupTypeMaster] FTM
	ON FTM.Id = F.FollowupTypeId
	INNER JOIN [sStudent].[tAcademic] SA
	ON SA.Id = F.AcademicId 
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId 
	INNER JOIN sCommon.tRelationshipMaster RM ON F.RelationId = RM.Id
	where ((F.AutoId = @rAutoId) OR (ISNULL(@rAutoId,0) = 0))
		AND ((F.FollowupNumber = @rFollowupNumber) OR (ISNULL(@rFollowupNumber,0) = 0))
		AND ((F.FollowupTypeId = @rFollowupTypeId) OR (ISNULL(@rFollowupTypeId,0) = 0))
		AND ((SM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND ((SM.FirstName LIKE ''+@rName+'%') OR (ISNULL(@rName, '') = ''))
		AND (F.FollowupDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
		AND (F.FollowupDate<=@rToDate OR ISNULL(@rToDate,'')='')
END
GO
PRINT N'Creating [sCommunication].[pFollowupHistoryGet]...';


GO


Create PROCEDURE [sCommunication].[pFollowupHistoryGet]
	@rAutoId bigint,
	@rFollowupTypeId bigint,
	@rAcademicId bigint


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT F.[AutoId]
      ,F.[FollowupNumber]
      ,F.[FollowupTypeId]
      ,F.[FollowupDate]
      ,F.[FollowupTime]
      ,F.[FollowupDuration]
      ,F.[RelationId]
      ,F.[AcademicId]
      ,F.[FollowupRemark]
      ,F.[FollowupOtherRemark]
	  ,F.[FollowupRelationRemark]
	  ,FTM.[Title]
	  ,(SM.FirstName+' '+SM.MiddleName+' '+SM.LastName) AS Name
	  ,SM.Code
	  ,RM.[Title] as RelationName
	FROM [sCommunication].[tFollowup] F 
	INNER JOIN [sCommunication].[tFollowupTypeMaster] FTM
	ON FTM.Id = F.FollowupTypeId
	INNER JOIN [sStudent].[tAcademic] SA
	ON SA.Id = F.AcademicId 
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId 
	INNER JOIN sCommon.tRelationshipMaster RM ON F.RelationId = RM.Id
	where F.AutoId <> @rAutoId
		AND F.FollowupTypeId = @rFollowupTypeId 
		AND SA.Id = @rAcademicId
END
GO
PRINT N'Creating [sCommunication].[pFollowupTypeAssignedToAdd]...';


GO
CREATE PROCEDURE [sCommunication].[pFollowupTypeAssignedToAdd]
		@rSourceTypeId smallint,
		@rSourceId bigint = 0,
		@rFollowupTypeId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		
	BEGIN TRANSACTION	
		BEGIN
			INSERT INTO [sCommunication].[tFollowupTypeAssignedTo]
			   ([SourceTypeId]
			   ,[SourceId]
			   ,[FollowupTypeId])
			VALUES
			   (@rSourceTypeId,
			   @rSourceId,
			   @rFollowupTypeId)
		SELECT 1 AS Result
		END	 
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sCommunication].[pFollowupTypeAssignedToGet]...';


GO
Create PROCEDURE [sCommunication].[pFollowupTypeAssignedToGet]
		@rFollowupTypeId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		
	BEGIN TRANSACTION	
		BEGIN
			SELECT  followupAssig.SourceTypeId
				,followupAssig.SourceId
				,followupAssig.FollowupTypeId
				,emp.ID
				,emp.Code
				,emp.FirstName
				,emp.MiddleName
				,emp.LastName

			FROM [NetVidyalaya].[sCommunication].[tFollowupTypeAssignedTo] as followupAssig
			INNER JOIN [sHrm].[tEmployeeMaster] as emp
			ON followupAssig.SourceId = emp.id
			where followupAssig.FollowupTypeId = @rFollowupTypeId

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


GO
 
 
CREATE PROCEDURE [sHostel].[pHostelSummaryDashBoardGet]
           @rHostelId int = 0,                      
           @rOrgGroupBatchId int = 0,
		   @rType int = 0,
		   @rDate date = '',
		   @rHostelAttendanceTypeId int = 0
AS
SET NOCOUNT ON
BEGIN
	IF(@rType = 1)
	BEGIN
		SELECT 		
		RM.Id,
		RM.Title,
		ISNULL(RM.StudentsPerRoom,0) AS StudentsPerRoom,
		ISNULL(COUNT(AR.SourceID),0) AS StudentsAllocated
	    
		FROM [sHostel].[tRoomMaster] RM			  			  
			  LEFT JOIN [sHostel].[tAssignRoom] AR ON AR.RoomId = RM.Id AND AR.OrgGroupBatchId=@rOrgGroupBatchId			  
	  
		WHERE 
			((RM.HostelId=@rHostelId) OR (@rHostelId=0))
			AND RM.IsObsolete=0			
			Group by RM.Id,RM.StudentsPerRoom,RM.Title
		END	
	ELSE IF(@rType = 2)
	BEGIN
		SELECT 
			(SELECT COUNT(AR.SourceId) FROM sHostel.tAssignRoom AR INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId WHERE AR.OrgGroupBatchId = @rOrgGroupBatchId AND RM.HostelId = @rHostelId) AS TotalStudents,
			COUNT(CASE WHEN EntryModeStatusId = 581 then 1 ELSE NULL END) as OutCount,
			(SELECT COUNT(AR.SourceId) FROM sHostel.tAssignRoom AR INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId WHERE AR.OrgGroupBatchId = @rOrgGroupBatchId AND RM.HostelId = @rHostelId) - COUNT(CASE WHEN EntryModeStatusId = 581 then 1 ELSE NULL END) as InCount
		FROM
			sHostel.tHostelStudentGatePass
		WHERE
			GatePassDate =  @rDate
	END
	ELSE IF(@rType = 3)
	BEGIN
		SELECT 
			(SELECT COUNT(AR.SourceId) FROM sHostel.tAssignRoom AR INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId WHERE AR.OrgGroupBatchId = @rOrgGroupBatchId AND RM.HostelId = @rHostelId) AS TotalStudents,
			COUNT(CASE WHEN IsPresent = 1 then 1 ELSE NULL END) as PresentCount,
			COUNT(CASE WHEN IsPresent = 0 then 1 ELSE NULL END) as AbsentCount,
			(SELECT COUNT(AR.SourceId) FROM sHostel.tAssignRoom AR INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId WHERE AR.OrgGroupBatchId = @rOrgGroupBatchId AND RM.HostelId = @rHostelId) - COUNT(StudentId) AS PendingCount
		FROM 
			sHostel.tAttendanceRegister
		WHERE 
			CAST(CreatedDateTime AS Date) = @rDate AND HostelId = @rHostelId AND OrgGroupBatchId = @rOrgGroupBatchId
			AND HostelAttendanceTypeId = @rHostelAttendanceTypeId 
	END
END
GO
 
  
  
 
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('21.10.29',211029,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)

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

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


GO
ALTER TABLE [sCommunication].[tAssignmentViewHistory]
    ADD [Remark] NVARCHAR (MAX) NULL;


GO
PRINT N'Creating [sAssessment].[tCCESubjectActivityMaster].[IX_tCCESubjectActivityMaster]...';


GO
CREATE NONCLUSTERED INDEX [IX_tCCESubjectActivityMaster]
    ON [sAssessment].[tCCESubjectActivityMaster]([Id] ASC, [ClassSubjectId] ASC, [GradeSetId] ASC, [OrgId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


GO
PRINT N'Creating [sAssessment].[tCCESubjectSubActivityExamScore].[IX_tCCESubjectSubActivityExamScore]...';


GO
CREATE NONCLUSTERED INDEX [IX_tCCESubjectSubActivityExamScore]
    ON [sAssessment].[tCCESubjectSubActivityExamScore]([ExamId] ASC, [AcademicId] ASC, [SubjectSubActivityId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


GO
PRINT N'Creating [sAssessment].[tCCESubjectSubActivityMaster].[IX_tCCESubjectSubActivityMaster]...';


GO
CREATE NONCLUSTERED INDEX [IX_tCCESubjectSubActivityMaster]
    ON [sAssessment].[tCCESubjectSubActivityMaster]([Id] ASC, [SubjectActivityId] ASC, [OrgId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


GO

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


GO
 
 
ALTER PROCEDURE [dbo].[pEmployeeMasterGet]
@rOrgId int = 0,
 @rBuilder1 nvarchar(max)='',
 @rBuilder2 nvarchar(max)='',
 @rEmployeeStatusId int=0,
 @rEmployeeId bigint = 0,
 @rOrgGroupId int = 0	 
AS

BEGIN
	UPDATE sHrm.tEmployeeMaster SET PunchId = NULL
	--IF EXISTS (SELECT EM.PunchId FROM sHrm.tEmployeeMaster EM INNER JOIN sBiometric.BioDetailMapping BM ON BM.EmpID = EM.Id WHERE EM.PunchId is null)
	--BEGIN
	UPDATE EM
	SET
		PunchId = BM.EmpPunchID
	FROM
	    sHrm.tEmployeeMaster EM
		INNER JOIN sBiometric.BioDetailMapping AS BM
		ON BM.EmpID = EM.Id
		WHERE PunchId is null
	--END
	
	select EM.*,isnull(EM.FirstName,'') +' '+ isnull(EM.MiddleName,'') as 'FullName',
	(SELECT Title FROM sSetup.tOrganizationMaster WHERE Id = OrgID) AS OrganizationTitle
 from sHrm.tEmployeeMaster EM
 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	where PunchId is not null
	and (EM.OrgID = @rOrgId OR @rOrgId = 0)
	AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0) 
	AND ISNULL(EM.IsOtherUser,0) = 0
	and (OM.OrgGroupId = @rOrgGroupId)
END
GO
PRINT N'Altering [sAcademic].[pOnlineLearningAssignmentViewListGet]...';


GO

 
ALTER PROCEDURE [sAcademic].[pOnlineLearningAssignmentViewListGet]
	@rOnlineLearningId bigint,
	@rIsHistory bit = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
IF(@rIsHistory = 1)
BEGIN
		 SELECT * FROM 
		(
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
			    sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningViewHistory OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
			    OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2003

			UNION ALL

			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
			    sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningViewHistory OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
			    OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2001

			UNION ALL	
																			 			  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningViewHistory OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND  OLS.SourceTypeId = 2017

			UNION ALL		
															 			 				  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark 
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningViewHistory OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2016

			UNION ALL	
																 			 				  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningViewHistory OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2005

			UNION ALL		
															 			 				  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningViewHistory OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2021
			
		) as A
		Order BY A.DivisionOrder
	END
	ELSE
	BEGIN
		SELECT * FROM 
		(
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
			    sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.StudentId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
			    OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2003

			UNION ALL

			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
			    sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
			    OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2001

			UNION ALL	
																			 			  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DepartmentId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND  OLS.SourceTypeId = 2017

			UNION ALL		
															 			 				  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark 
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.ClassId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2016

			UNION ALL	
																 			 				  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.DivisionId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2005

			UNION ALL		
															 			 				  
			SELECT 
				SD.AcademicId,
				ISNULL(SD.FirstName+' '+SD.MiddleName+' '+SD.LastName,'')as StudentName,
				SD.Code,
				SD.RollNo,
				SD.ClassName+'-'+SD.DivisionName AS Class,
				DivisionOrder,
				CASE WHEN ISNULL(OLV.IsViewReference,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewReference,0) = 0 THEN 'N' END as IsViewReference,
				CASE WHEN ISNULL(OLV.IsViewAssignment,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewAssignment,0) = 0 THEN 'N' END as IsViewAssignment,
				CASE WHEN ISNULL(OLV.IsViewResource,0) = 1 THEN 'Y' WHEN ISNULL(OLV.IsViewResource,0) = 0 THEN 'N' END as IsViewResource,
				ISNULL(OLV.AssignmentTeacherRemark,'') AS AssignmentTeacherRemark
			FROM 
				sAcademic.tOnlineLearningScope OLS 
				INNER JOIN sAcademic.tOnlineLearning OL ON OLS.OnlineLearningId = OL.Id 
				INNER JOIN sStudent.vStudentAllDetail SD ON SD.OrgId = OLS.SourceId AND SD.BatchId = OL.BatchId 
				LEFT JOIN sAcademic.tOnlineLearningView OLV ON OLV.OnlineLearningId = OL.Id AND OLV.AcademicId = SD.AcademicId
			WHERE 
				OLS.OnlineLearningId = @rOnlineLearningId AND SD.StatusId = 1 AND OLS.SourceTypeId = 2021
			
		) as A
		Order BY A.DivisionOrder
	END
END
GO
PRINT N'Altering [sAlert].[pAppNotificationGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pAppNotificationGet]     
   
 @rOSTypeId tinyint,  
 @rEventId int,  
 @rSourceTypeId smallint,  
 @rFromDate date,  
 @rToDate date,  
 @rCode nvarchar(max),  
 @rReceiverSourceTypeId int,
 @rOrgGroupId int = 0,
 @rIsHistory bit = 0
  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
  
BEGIN  

IF(@rIsHistory = 1)
BEGIN  
IF(@rCode IS NULL OR @rCode='')  
BEGIN  
 IF(@rReceiverSourceTypeId=2003)  
 BEGIN   
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   SA.Code AS Code     
     
  FROM  
   sAlert.tNotificationLogHistory NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND NL.SourceTypeId=@rReceiverSourceTypeId    
   AND OM.OrgGroupId=@rOrgGroupId
   ORDER BY NL.CreatedDateTime DESC  
 END   
 ELSE IF(@rReceiverSourceTypeId=95)  
 BEGIN   
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   tEM.Code AS Code    
     
  FROM  
   sAlert.tNotificationLogHistory NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId 
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND NL.SourceTypeId=@rReceiverSourceTypeId
   AND ISNULL(tEM.IsOtherUser,0) = 0  
   AND OM.OrgGroupId=@rOrgGroupId   
   ORDER BY NL.CreatedDateTime DESC  
 END  
 ELSE  
 BEGIN   

   SELECT DISTINCT * From
   (SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   SA.Code AS Code     
     
  FROM  
   sAlert.tNotificationLogHistory NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId 
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
   AND NL.SourceTypeId=2003
   AND OM.OrgGroupId=@rOrgGroupId
   
   UNION

   SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   SA.Code AS Code     
     
  FROM  
   sAlert.tNotificationLogHistory NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  

   INNER JOIN sStudent.tAcademic A ON A.Id=NL.SourceId
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=A.StudentId  
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
      
  WHERE  
    ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
   AND NL.SourceTypeId=2001
   AND OM.OrgGroupId=@rOrgGroupId

   UNION 
   
   SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   tEM.Code AS Code    
     
  FROM  
   sAlert.tNotificationLogHistory NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId  
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
   AND NL.SourceTypeId=95
   AND OM.OrgGroupId=@rOrgGroupId
    AND ISNULL(tEM.IsOtherUser,0) = 0
    
  -- UNION 
   
  -- SELECT   
  -- NL.Id,  
  -- NL.CreatedDateTime AS Date,  
  -- OT.Title AS OSType,  
  -- 'Custom Alert' AS EventName,  
  -- ST.Title AS SourceType,  
  -- NL.MessageTitle,  
  -- NL.NotificationMessage AS Message,
  -- '' AS Code    
     
  --FROM  
  -- sAlert.tNotificationLog NL    
  -- INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
  -- INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
  -- INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId 
  -- INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=LEFT(NL.Id,4)
  --WHERE  
  -- ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
  -- AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
  -- AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
  -- AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
  -- AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
  -- AND OM.OrgGroupId=@rOrgGroupId
   
   UNION 
   
   SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   '' AS Code    
     
  FROM  
   sAlert.tNotificationLogHistory NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=LEFT(NL.Id,4)  
   
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
   AND OM.OrgGroupId=@rOrgGroupId
   AND (NL.SourceTypeId!=2003 AND NL.SourceTypeId!=2001 AND NL.SourceTypeId!=95)
   )AS tmp
   
   ORDER BY tmp.Date DESC 
 END  
END  
ELSE  
BEGIN  
 IF(@rReceiverSourceTypeId=95)  
 BEGIN  
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,  
   tEm.Code AS Code  
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId AND NL.SourceTypeId=@rReceiverSourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId  
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND ((tEM.Code LIKE @rCode) OR ISNULL(@rCode,'')='')     
   AND ISNULL(tEM.IsOtherUser,0) = 0
   AND OM.OrgGroupId=@rOrgGroupId
   ORDER BY NL.CreatedDateTime DESC   
  END   
  Else IF(@rReceiverSourceTypeId=2003)  
  BEGIN   
     
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,  
   SA.Code AS Code
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId AND NL.SourceTypeId=@rReceiverSourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId  
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='')   
   AND OM.OrgGroupId=@rOrgGroupId
  
  ORDER BY NL.CreatedDateTime DESC  
 END  
END
END
ELSE
BEGIN
	IF(@rCode IS NULL OR @rCode='')  
BEGIN  
 IF(@rReceiverSourceTypeId=2003)  
 BEGIN   
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   SA.Code AS Code     
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND NL.SourceTypeId=@rReceiverSourceTypeId    
   AND OM.OrgGroupId=@rOrgGroupId
   ORDER BY NL.CreatedDateTime DESC  
 END   
 ELSE IF(@rReceiverSourceTypeId=95)  
 BEGIN   
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   tEM.Code AS Code    
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId 
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND NL.SourceTypeId=@rReceiverSourceTypeId
   AND ISNULL(tEM.IsOtherUser,0) = 0  
   AND OM.OrgGroupId=@rOrgGroupId   
   ORDER BY NL.CreatedDateTime DESC  
 END  
 ELSE  
 BEGIN   

   SELECT DISTINCT * From
   (SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   SA.Code AS Code     
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId 
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
   AND NL.SourceTypeId=2003
   AND OM.OrgGroupId=@rOrgGroupId
   
   UNION

   SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   SA.Code AS Code     
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  

   INNER JOIN sStudent.tAcademic A ON A.Id=NL.SourceId
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=A.StudentId  
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
      
  WHERE  
    ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
   AND NL.SourceTypeId=2001
   AND OM.OrgGroupId=@rOrgGroupId

   UNION 
   
   SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   tEM.Code AS Code    
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId  
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
   AND NL.SourceTypeId=95
   AND OM.OrgGroupId=@rOrgGroupId
    AND ISNULL(tEM.IsOtherUser,0) = 0
    
  -- UNION 
   
  -- SELECT   
  -- NL.Id,  
  -- NL.CreatedDateTime AS Date,  
  -- OT.Title AS OSType,  
  -- 'Custom Alert' AS EventName,  
  -- ST.Title AS SourceType,  
  -- NL.MessageTitle,  
  -- NL.NotificationMessage AS Message,
  -- '' AS Code    
     
  --FROM  
  -- sAlert.tNotificationLog NL    
  -- INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
  -- INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
  -- INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId 
  -- INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=LEFT(NL.Id,4)
  --WHERE  
  -- ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
  -- AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
  -- AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
  -- AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
  -- AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
  -- AND OM.OrgGroupId=@rOrgGroupId
   
   UNION 
   
   SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   '' AS Code    
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=LEFT(NL.Id,4)  
   
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
   AND OM.OrgGroupId=@rOrgGroupId
   AND (NL.SourceTypeId!=2003 AND NL.SourceTypeId!=2001 AND NL.SourceTypeId!=95)
   )AS tmp
   
   ORDER BY tmp.Date DESC 
 END  
END  
ELSE  
BEGIN  
 IF(@rReceiverSourceTypeId=95)  
 BEGIN  
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,  
   tEm.Code AS Code  
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId AND NL.SourceTypeId=@rReceiverSourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId  
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND ((tEM.Code LIKE @rCode) OR ISNULL(@rCode,'')='')     
   AND ISNULL(tEM.IsOtherUser,0) = 0
   AND OM.OrgGroupId=@rOrgGroupId
   ORDER BY NL.CreatedDateTime DESC   
  END   
  Else IF(@rReceiverSourceTypeId=2003)  
  BEGIN   
     
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,  
   SA.Code AS Code
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId AND NL.SourceTypeId=@rReceiverSourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId  
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='')   
   AND OM.OrgGroupId=@rOrgGroupId
  
  ORDER BY NL.CreatedDateTime DESC  
 END  
END
END
END
GO
PRINT N'Altering [sAlert].[pSMSHistoryGet]...';


GO

ALTER PROCEDURE [sAlert].[pSMSHistoryGet]
	
	@rOrgId smallint,
	@rStatusId int,
	@rContactId nvarchar(50),
	@rEventId int,
	@rSourceEvent nvarchar(50),
	@rUserName nvarchar(100),
	@rAlertModeId tinyint,
	@rFromDate date,
	@rToDate date,
	@rOrgGroupId int,
	@rCode nvarchar(max),
	@rReceiverSourceTypeId int,
	@rIsHistory bit = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF(@rIsHistory = 1)
BEGIN
IF(@rCode IS NULL OR @rCode='')
BEGIN
	IF(@rReceiverSourceTypeId=0)
	BEGIN	
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				'' AS Code				
		FROM
				sAlert.tAlertLogHistory AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId) 
			
			ORDER BY AL.CreatedDateTime DESC
	END	
	
	ELSE IF(@rReceiverSourceTypeId=2003)
	BEGIN	
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code				
		FROM
				sAlert.tAlertLogHistory AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId	
			
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId)	
			ORDER BY AL.CreatedDateTime DESC
	END
	ELSE IF(@rReceiverSourceTypeId=95)
	BEGIN	
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				tEM.Code AS Code				
		FROM
				sAlert.tAlertLogHistory AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 					
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId)	
			ORDER BY AL.CreatedDateTime DESC
	END
	ELSE 
	BEGIN
		SELECT DISTINCT tmp1.* From(
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code				
		FROM
				sAlert.tAlertLogHistory AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=2003			
			AND OM.OrgGroupId = @rOrgGroupId	
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLogHistory AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId 
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (U.DisplayTitle like 'SysSuperAdmin') OR  (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND AL.ReceiverSourceTypeId=2001
		AND OM.OrgGroupId = @rOrgGroupId		
	
	UNION
	SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				tEM.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=95			
			AND OM.OrgGroupId = @rOrgGroupId	
		
		UNION
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				'' AS Code				
		FROM
				sAlert.tAlertLogHistory AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			
			--AND (AL.ReceiverSourceTypeId NOT IN (95,2001,2003))
			
			AND ((AL.ReceiverSourceTypeId=0 OR @rReceiverSourceTypeId=0))	
			--ORDER BY AL.CreatedDateTime DESC	
	
	)AS tmp1				
			ORDER BY tmp1.CreatedDateTime DESC
	END
END

ELSE
BEGIN
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			tEM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((tEM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
		
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SA.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='')
END		
		
--SELECT DISTINCT OM.Title, D.Code,OM.OrderIndex,D.OrderIndex FROM sSetup.tDivisionMaster D
--INNER JOIN ssetup.tOrganizationMaster OM
--ON D.OrgId = OM.Id
--WHERE D.Id IN
--(
--select DivisionId from sStudent.tAcademic A INNER JOIN
--sStudent.tStudentCommunication SC ON A.StudentId = SC.StudentId
--INNER JOIN SAlert.tAlertLog AL ON SC.ParentContactNo = AL.ContactId
--AND AL.OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = 1141 )
--AND AL.AlertModeId = 2)
--order by  OM.OrderIndex,D.OrderIndex

END
ELSE 
BEGIN
	IF(@rCode IS NULL OR @rCode='')
BEGIN
	IF(@rReceiverSourceTypeId=0)
	BEGIN	
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				'' AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId) 
			
			ORDER BY AL.CreatedDateTime DESC
	END	
	
	ELSE IF(@rReceiverSourceTypeId=2003)
	BEGIN	
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId	
			
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId)	
			ORDER BY AL.CreatedDateTime DESC
	END
	ELSE IF(@rReceiverSourceTypeId=95)
	BEGIN	
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				tEM.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 					
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId)	
			ORDER BY AL.CreatedDateTime DESC
	END
	ELSE 
	BEGIN
		SELECT DISTINCT tmp1.* From(
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=2003			
			AND OM.OrgGroupId = @rOrgGroupId	
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId 
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (U.DisplayTitle like 'SysSuperAdmin') OR  (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND AL.ReceiverSourceTypeId=2001
		AND OM.OrgGroupId = @rOrgGroupId		
	
	UNION
	SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				tEM.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=95			
			AND OM.OrgGroupId = @rOrgGroupId	
		
		UNION
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				'' AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			
			--AND (AL.ReceiverSourceTypeId NOT IN (95,2001,2003))
			
			AND ((AL.ReceiverSourceTypeId=0 OR @rReceiverSourceTypeId=0))	
			--ORDER BY AL.CreatedDateTime DESC	
	
	)AS tmp1				
			ORDER BY tmp1.CreatedDateTime DESC
	END
END

ELSE
BEGIN
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			tEM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((tEM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
		
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SA.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (((AL.StatusId=@rStatusId AND @rStatusId = 0) OR (@rStatusId=-1) OR (AL.StatusId <> 0 AND @rStatusId = 1)))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (U.DisplayTitle like 'SysSuperAdmin') OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='')
END		
END
END
GO
PRINT N'Altering [sAssessment].[pRptPassFailAnalysisSubjectWise]...';


GO


ALTER PROCEDURE [sAssessment].[pRptPassFailAnalysisSubjectWise]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rSubject nvarchar(MAX)='',
	 @rClassStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		 
	 select 	
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
		CS.Id AS ClassSubjectId,
		SM.Id AS SubjectId,
		SM.Code AS SubjectName,
		Sm.OrderIndex As SubjectOrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		CM.OrderIndex AS ClassOrderIndex,
	 

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS PassStudent,
  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
		INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS FailStudent ,
	  ED.Minimum AS SubjectMinimum,
	  ED.Maximum AS SubjectMaximum
	  
	  
	 from		
		sAssessment.tExamMaster EM 
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=CS.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = CS.ClassId AND CM.BatchId = @rBatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON CLM.OrgId = OM.Id

	WHERE 		
		
		EM.BatchId = @rBatchId 
		AND  ((@rClassId > 0 AND cs.ClassId=@rClassId)
		OR (@rClassId = 0 AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')))		
		AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
		AND	CM.BatchId = @rBatchId
		AND EM.ExamSubGroupId = @rExamSubGroupId
		AND EM.BatchId = @rBatchId
		AND (ISNULL(SM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
		
END



-- UNION ALL
  
 --  select 	
	--	@rBuilder1 AS Builder1,
	--	Cm.Classid As ClassId,
	--	Dm.id As DivisionId,
	--	Cm.ClassName As Classname,
	--	DM.DisplayTitle As DivisionName,
	--	CS.Id AS ClassSubjectId,
	--	SM.Id AS SubjectId,
	--	SM.Code AS SubjectName,
	--	Sm.OrderIndex As SubjectOrderIndex,
	--	DM.OrderIndex AS DivisionOrderIndex,
	--	CM.OrderIndex AS ClassOrderIndex,
	 

	--  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	--	INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	--	INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	--	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
	--	INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS PassStudent,
  
	--(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	--	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	--	INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	--	INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
	--	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
	--	INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId  
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	--  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS FailStudent 
	  
	  
	-- from		
	--	sAssessment.tExamMaster EM 
	--	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
	--	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	--	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	--	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
	--	INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=CS.ClassId
	--	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
	--	INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = CS.ClassId AND CM.BatchId = @rBatchId
	--	INNER JOIN sSetup.tOrganizationMaster OM ON CLM.OrgId = OM.Id

	--WHERE 		
		
	--	EM.BatchId = @rBatchId 
	--	AND (CS.ClassId=@rClassId OR @rClassId=0) 
	--	AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
	--	AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
	--	AND	CM.BatchId = @rBatchId
	--	AND EM.ExamSubGroupId = @rExamSubGroupId
	--	AND EM.BatchId = @rBatchId
	--	AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
GO
PRINT N'Altering [sAssessment].[pRptResultListGet]...';


GO
 
ALTER PROCEDURE [sAssessment].[pRptResultListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rDepartmentid int=0,
	 @rStatus int =1,
	 @rGenderId int,
	 @rClassStatusId int=0,
	 @rResultStatus nvarchar(20)='',
	 @rMultiCode nvarchar(max)='',
	 @rOrderBy int = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			Convert(nvarchar(20),A.Id) AS   AcademicIdText,	
	CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
	CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
	CONVERT (nvarchar(20),@rBatchId) AS BatchIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0))AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			SM.Code,
			  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			 DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			EM.IsMarksInDecimal,
			SI.StudentPhoto,
			EM.DisplayTitle,
			OM.SmallAddress1,
			R.ResultRemark,
			R.OtherRemark1,
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			SR.ResultRemark2,
			Em.GradeSetId,
			R.ResultStatus,
			SR.ResultRemark1,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			EI.EmployeeSign,
			EM.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsOnPrePrinted,
			Em.IsDisplayPhoto,
			SR.PresentDays ,			
			SR.TotalDays,
			EM.DecimalFormat,
			CM.Id AS ClassId
      
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId=A.Id AND SR.ExamId = EM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			
			 
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (EM.ClassId=@rClassId OR @rClassId=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 ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		AND ((A.Id =@rAcademicId) OR (@rAcademicId=0))
		
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		ANd SM.StatusId= @rStatus
		AND ((SO.GenderId=@rGenderId) OR (@rGenderId=0))
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND (ISNULL(SM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')

		ORDER BY 
			CASE @rOrderBy WHEN 0 THEN SM.Code END , 
			CASE @rOrderBy WHEN 1 THEN R.RankNumber END , 
			CASE @rOrderBy WHEN 2 THEN A.RollNo END, 
			CASE @rOrderBy WHEN 3 THEN SM.FirstName END,
			CASE @rOrderBy WHEN 4 THEN R.TotalObtain END
			
END
GO
PRINT N'Altering [sAssessment].[pRptWeekStudentAnalysisListSubjectWiseGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptWeekStudentAnalysisListSubjectWiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
 
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	                           
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rSubjectId int=0,
	 @rGroupId int=0,
	 @rTop int=0,
	 @rClass nvarchar(max)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
SELECT r1.*
FROM
(	SELECT 	
			 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			ROW_NUMBER() OVER(PARTITION BY 
				CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END  ORDER BY RD.Obtain ASC) rn,
			
			
			ESGM.Title AS Exam,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName  AS Name,
			
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.Percentage,
			EM.IsMarksInDecimal,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,
			Sbj.Title AS SubjectName,
			Sbj.Id AS SubjectId,
			RD.Obtain ,
			R.TotalMarks,
			ED.Maximum,
			RD.SubjectGrade
			  
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId		
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId =R.Id	
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id = RD.ExamDetailId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId=A.AcademicId
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			 INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			  INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
			INNER JOIN sSetup.tClassSubject CS ON ED.ClassSubjectId = CS.Id 
			
			INNER JOIN sSetup.tSubjectMaster Sbj ON Sbj.Id  = CS.SubjectId
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		AND Sbj.Id=@rSubjectId
		AND (ISNULL(A.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))	
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
	    AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))
	)r1
	WHERE (r1.rn <= @rTop Or @rTop = 0)
END
GO
PRINT N'Altering [sAttendance].[pStudentSubjectwisePresenceGet]...';


GO
ALTER PROCEDURE [sAttendance].[pStudentSubjectwisePresenceGet]
	 	@rBatchId int,
	 	@rUserSourceId bigint
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
		SELECT 
			sCommon.fGetMonthName(MONTH(SR.AttendanceDate)) AS MonthName,
			
			SM.Title AS SubjectName,
			
			ISNULL((SELECT COUNT(S.AcademicId) 
			FROM sAttendance.tStudentRegister S
			WHERE S.AcademicId = SR.AcademicId 
			AND S.AttendanceTypeId = 5 
			AND SR.SubjectId = S.SubjectId			
			GROUP BY MONTH(S.AttendanceDate) HAVING MONTH(S.AttendanceDate) = MONTH(SR.AttendanceDate)
			),0) AS Total,
			
			ISNULL((SELECT COUNT(S.AcademicId) 
			FROM sAttendance.tStudentRegister S
			WHERE S.AcademicId =SR.AcademicId 
			AND S.AttendanceTypeId = 5 AND S.IsPresent = 1
			AND SR.SubjectId = S.SubjectId			
			GROUP BY MONTH(S.AttendanceDate) HAVING MONTH(S.AttendanceDate) = MONTH(SR.AttendanceDate)
			),0) AS Attended
		
		FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId AND SR.AttendanceTypeId = 5 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = SR.SubjectId 
		WHERe
			SA.BatchId = @rBatchId 
			AND (SA.StudentId = @rUserSourceId OR @rUserSourceId = 0)
			GROUP BY YEAR(SR.AttendanceDate),Month(SR.AttendanceDate),SM.Title,SR.AcademicId,SR.SubjectId
END
GO
PRINT N'Altering [sAudit].[pActivityLogGet]...';


GO


ALTER PROCEDURE [sAudit].[pActivityLogGet]
	@rOrgGroupId int,
	@rOrgId int,
	@rUserName nvarchar(100),
	@rScreenName nvarchar(100),
	@rActivity nvarchar(500),
	@rFromDate date,
	@rToDate date,
	@rOSTypeId tinyint=0,
	@rIsHistory bit = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
SET @rScreenName = sCommon.fSearchStringGet(@rScreenName)
SET @rActivity = sCommon.fSearchStringGet(@rActivity)
SET @rToDate = DATEADD(day,1,@rToDate)

	IF(@rIsHistory = 1)
	BEGIN
       SELECT 
            AL.OrgGroupId,
            AL.OrgId,
            OM.Title AS OrganizationName,
            AL.UserId,
			U.DisplayTitle AS UserName,
			U.LoginTitle,
			U.SessionId,
			S.Title AS ScreenName,
			AL.AuditDate,
			(CASE WHEN AL.ScreenId=126
				  THEN AL.Activity		
			      WHEN AL.ScreenId=20878
				  THEN AL.Activity		
				  WHEN AL.ScreenId=30179
				  THEN AL.Activity
				  WHEN AL.ScreenId=20196
				  THEN AL.Activity
				  WHEN AL.ScreenId=30788
				  THEN AL.Activity
				  WHEN AL.ScreenId=30780
				  THEN AL.Activity
				  WHEN AL.ScreenId=30790
				  THEN AL.Activity
			 ELSE SUBSTRING(AL.Activity, CHARINDEX(' ', AL.Activity)+1, LEN(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1))  END)AS  Activity,			
			ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
			ISNULL(AL.RecordDetail,'') AS RecordDetail,
			ISNULL(OS.Title,'') AS OSType
			
       FROM 
		   sAudit.tActivityLogHistory AL
		   INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
		   INNER JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId
		   LEFT JOIN sAlert.tOSType OS ON OS.Id = AL.OSTypeId
       WHERE
		   AL.OrgGroupId = @rOrgGroupId
		   AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
		   AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
		   AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
		   AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))
		   AND (AL.AuditDate >= @rFromDate)
		   AND (AL.AuditDate <= @rToDate)
		   AND ((AL.OSTypeId = @rOSTypeId) OR (@rOSTypeId=0))
       ORDER BY 
			AL.AuditDate DESC
	END
	ELSE
	BEGIN
		SELECT 
            AL.OrgGroupId,
            AL.OrgId,
            OM.Title AS OrganizationName,
            AL.UserId,
			U.DisplayTitle AS UserName,
			U.LoginTitle,
			U.SessionId,
			S.Title AS ScreenName,
			AL.AuditDate,
			(CASE WHEN AL.ScreenId=126
				  THEN AL.Activity		
			      WHEN AL.ScreenId=20878
				  THEN AL.Activity		
				  WHEN AL.ScreenId=30179
				  THEN AL.Activity
				  WHEN AL.ScreenId=20196
				  THEN AL.Activity
				  WHEN AL.ScreenId=30788
				  THEN AL.Activity
				  WHEN AL.ScreenId=30780
				  THEN AL.Activity
				  WHEN AL.ScreenId=30790
				  THEN AL.Activity
			 ELSE SUBSTRING(AL.Activity, CHARINDEX(' ', AL.Activity)+1, LEN(AL.Activity)-(CHARINDEX(' ', AL.Activity)-1))  END)AS  Activity,			
			ISNULL(AL.RecordSourceId,0) AS RecordSourceId,
			ISNULL(AL.RecordDetail,'') AS RecordDetail,
			ISNULL(OS.Title,'') AS OSType
			
       FROM 
		   sAudit.tActivityLog AL
		   INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AL.OrgId
		   INNER JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId
		   LEFT JOIN sAlert.tOSType OS ON OS.Id = AL.OSTypeId
       WHERE
		   AL.OrgGroupId = @rOrgGroupId
		   AND ((AL.OrgId = @rOrgId) OR (@rOrgId=0))
		   AND ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))
		   AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))
		   AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))
		   AND (AL.AuditDate >= @rFromDate)
		   AND (AL.AuditDate <= @rToDate)
		   AND ((AL.OSTypeId = @rOSTypeId) OR (@rOSTypeId=0))
       ORDER BY 
			AL.AuditDate DESC
	END
END
GO
PRINT N'Altering [sBiometric].[pBiometricReportData]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pBiometricReportData]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int,
	@rDeptId int,
	@rForYear int=0,
	@rForMonth int=0,
	@rIsFirstIn bit=0,
	@rIsLastOut bit=0,
	@rIsOT bit=0,
	@rIsLateBy	bit=0,
	@rIsEarlyBy bit=0,
	@rIsDuration  bit=0,
	@rEmployeeStatusId int=0,
	@rEmployeeId bigint = 0,
	@rOrgGroupId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

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

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

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

		case when @Days >= 29 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,29,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D29,
		case when @Days >= 30 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,30,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D30,
		case when @Days >= 31 then [sHrm].[fWeekHOffGetBio](T.EmployeeId, @rForYear,@rForMonth,31,@lBatchID,ED.OrganizationDepartmentId,@rOrgId) end AS D31,


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


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 @lEmpDepartmentID 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))

truncate table #TempMonthTrans

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,@lEmpDepartmentID = OrganizationDepartmentId  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)

		DECLARE @weekoffstatus nvarchar(20)

		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@rEmployeeId , @rForYear ,@rForMonth ,@rDay ,@rBatchId ,@rDepartmentId ,@rOrgId , @rBiometricStatus )
		SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(@lDate)  ,Month(@lDate), @lDay, @lBatchId,@lEmpDepartmentID,@rOrgId)		
		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(''' + convert(nvarchar(15),@lDate) + 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) + ')


		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 ''' +@weekoffstatus +''' in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
						When ''' +@weekoffstatus +''' Not in (''-'',''XX'') 
						Then ''' +@weekoffstatus +''' 
						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 
						INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId AND (ED.OrganizationDepartmentId ='''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+'''= 0 )
						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 (ISNULL(T1.SourceTypeId,95) = 95 OR T1.SourceTypeId = 0)'				
						
		Execute(@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1			
	END

	--SELECT * FROM #TempMonthTrans
	
	SET @strQuery = 'select  Day(T.Attn_Date), T.*,isnull(A.TotAbsent,0) AS TotAbsent,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,isnull(TotEarly,0) AS TotEarly,
	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,
	OM.Id AS OrgId,
	OM.Title AS OrganizationTitle
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID 
	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'',''PW'',''PH'') 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 IN (''W'',''PW'',''PHW'') group by EmployeeId) 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  (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0)
	AND (Emp.OrgId = ' + convert(nvarchar(15),@rOrgId) + ' OR ' + convert(nvarchar(15),@rOrgId) + ' = 0)
	AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') AND (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 TotEarly,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as IsFirstIn,
	--'' as IsLastOut,
	--'' as IsOT,
	--'' as IsLateBy,
	--'' as IsEarlyBy,
	--'' as IsDuration,
	--'' as OrgId,
	--'' as OrganizationTitle
END
GO
PRINT N'Altering [sBiometric].[pRptDateWiseTimeSheetSummary]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pRptDateWiseTimeSheetSummary]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rToDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 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',
	 @rEmployeeStatusId int=0,
	 @rOrgGroupId int = 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 
INNER 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 
AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)
AND ISNULL(EM.IsOtherUser,0) = 0 


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 @lEmpDepartmentID 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,Leave nvarchar(100),DayNumber nvarchar(8),PresentStatus nvarchar(25),
		FirstIn nvarchar(20),LastOut nvarchar(20),OverTime nvarchar(20),LateBy nvarchar(20),Duration nvarchar(20),EarlyBy nvarchar(20))

truncate table #TempMonthTrans

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,@lEmpDepartmentID = OrganizationDepartmentId  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)

		DECLARE @weekoffstatus nvarchar(20)

		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@rEmployeeId , @rForYear ,@rForMonth ,@rDay ,@rBatchId ,@rDepartmentId ,@rOrgId , @rBiometricStatus )
		SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(@lDate)  ,Month(@lDate), @lDay, @lBatchId,@lEmpDepartmentID,@rOrgId)		
		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(''' + convert(nvarchar(15),@lDate) + 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) + ')

		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 ''' +@weekoffstatus +''' in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
						When ''' +@weekoffstatus +''' Not in (''-'',''XX'') 
						Then ''' +@weekoffstatus +''' 
						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 
						INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId AND (ED.OrganizationDepartmentId ='''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+'''= 0 )
						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 (ISNULL(T1.SourceTypeId,95) = 95 OR T1.SourceTypeId = 0)'				
						
		Execute(@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1			
	END
	--Select * from #TempMonthTrans
	
	UPDATE tmp 
	SET PresentStatus='A'
	FROM  #TempMonthTrans tmp
	INNER JOIN sHrm.tLeave L ON tmp.EmployeeId=L.EmployeeId
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE L.StatusId = 550 AND L.EmployeeId = tmp.EmployeeId AND CAST(Attn_Date AS DATE) BETWEEN L.FromDate AND L.ToDate

	UPDATE tmp 
	SET Leave=LTM.Code + '/' + CASE WHEN L.LeavePeriodId = 1 THEN '1' WHEN L.LeavePeriodId = 2  THEN  '0.5' ELSE '0.25' END
	FROM  #TempMonthTrans tmp
	INNER JOIN sHrm.tLeave L ON tmp.EmployeeId=L.EmployeeId
	INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
	WHERE L.StatusId = 550 AND L.EmployeeId = tmp.EmployeeId AND CAST(Attn_Date AS DATE) BETWEEN L.FromDate AND L.ToDate


	--Select * from #TempMonthTrans

	SET @strQuery = 'select  Day(T.Attn_Date), T.*,isnull(A.TotAbsent,0) AS TotAbsent,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,isnull(TotEarly,0) AS TotEarly,
	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,
	OM.Id AS OrgId,
	OM.Title AS OrganizationTitle
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID
	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'',''PW'',''PH'') 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 IN (''W'',''PW'',''PHW'') group by EmployeeId) 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 (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0) AND (len((''' + @rGRadeId + '''))= 1 AND EmployeeGradeId > 0 ) Or
   (len((''' + @rGRadeId + ''')) > 1 AND EmployeeGradeId in(' + convert(nvarchar(100),@rGRadeId) + ')) AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') 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 Leave,
	--'' as EmployeeId,	
	--'' 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 TotEarly,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as IsFirstIn,
	--'' as IsLastOut,
	--'' as IsOT,
	--'' as IsLateBy,
	--'' as IsEarlyBy,
	--'' as IsDuration,
	--'' as OrgId,
	--'' as OrganizationTitle
END
GO
PRINT N'Altering [sBiometric].[pRptEmployeeCheckInGet]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pRptEmployeeCheckInGet]    
      
   @rOrgId int ,    
   @rBuilder1 nvarchar(max)='',    
   @rBuilder2 nvarchar(max)='',    
   @rdate date='',
   @rEmployeeStatusId int=0,
   @rEmployeeId bigint = 0,
   @rOrgGroupId int = 0    
       
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
BEGIN     
  Select     
   convert(binary,null,0) as EmployeePhoto ,    
   EMp.FirstName+' ' +EMp.MiddleName+' '+emp.LastName AS Name,    
   case B.CheckInTime when null then null when '' then null else B.CheckInTime end as CheckInTime,
   Emp.id As EmployeeID ,
   case B.CheckOutTime when null then null when '' then null else B.CheckOutTime end as CheckOutTime,   
   B.SourceId,    
   @rBuilder1 AS Builder1,    
   @rBuilder2 AS Builder2,
   OM.Id AS OrgId,
   OM.Title AS OrganizationTitle      
  from     
   sHrm.tEmployeeMaster EMP      
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EMP.OrgId
   --LEFT JOIN sBiometric.tEmployeeCheckIn B ON B.EmployeeID=EMP.Id    
   --and EMp.OrgId=@rORgId  ANd @rDate=convert(date,B.CheckInTime)    
   LEFT JOIN sBiometric.tProcess B ON B.SourceId=EMP.Id
   ANd @rDate=convert(date,B.AtdDate)
   WHERE (Emp.Id = @rEmployeeId OR @rEmployeeId = 0) AND (EMp.OrgId=@rORgId OR @rORgId = 0)
   AND OM.OrgGroupId = @rOrgGroupId AND(EMP.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)  AND  ISNULL(EMP.IsOtherUser,0) = 0     
   
    
END
GO
PRINT N'Altering [sBiometric].[pRptEmployeeWiseMonthlyAttendanceGet]...';


GO
 

ALTER PROCEDURE [sBiometric].[pRptEmployeeWiseMonthlyAttendanceGet]  
    
  @rOrgId int ,  
   @rBuilder1 nvarchar(max)='',  
   @rBuilder2 nvarchar(max)='' ,  
   @rFromMonth int=0,  
   @rFromyear int=0,
   @rEmployeeStatusId int=0  ,
   @rEmployeeId bigint = 0,
   @rOrgGroupId int = 0
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
  
 CREATE Table #temptable  
 (  
  EmployeeId bigint,  
  D1 nvarchar(5),D2 nvarchar(5),D3 nvarchar(5),D4 nvarchar(5),D5 nvarchar(5),D6 nvarchar(5),D7 nvarchar(5),D8 nvarchar(5),D9 nvarchar(5),  
  D10 nvarchar(5),D11 nvarchar(5),D12 nvarchar(5),D13 nvarchar(5),D14 nvarchar(5),D15 nvarchar(5),D16 nvarchar(5),D17 nvarchar(5),  
  D18 nvarchar(5),D19 nvarchar(5),D20 nvarchar(5),D21 nvarchar(5),D22 nvarchar(5),D23 nvarchar(5),D24 nvarchar(5),D25 nvarchar(5),  
  D26 nvarchar(5),D27 nvarchar(5),D28 nvarchar(5),D29 nvarchar(5),D30 nvarchar(5),D31 nvarchar(5)  
 )  

 Insert into #temptable  
 (  
  EmployeeId  
 )  
 --select * from sbiometric.tprocess
 Select Distinct B.Sourceid   
  from sHrm.tEmployeeMaster EMP    
  INNER JOIN sbiometric.tprocess B ON B.Sourceid=EMP.Id  
  WHere (EMp.OrgId=@rOrgId OR @rOrgId = 0)  AND MONTH(B.AtdDate)=@rFromMonth AND YEAR(B.AtdDate)=@rFromyear   AND  ISNULL(EMP.IsOtherUser,0) = 0
  AND (EMP.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)

  update #temptable set D1='-', D2='-', D3='-', D4='-', D5='-', D6='-', D7='-', D8='-', D9='-', D10='-', D11='-', D12='-', D13='-', D14='-', D15='-',  
   D16='-', D17='-', D18='-', D19='-', D20='-', D21='-', D22='-', D23='-', D24='-', D25='-', D26='-', D27='-', D28='-', D29='-', D30='-', D31='-'  
    
  Update t1 set t1.D1 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=1  
  Update t1 set t1.D2 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=2  
  Update t1 set t1.D3 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=3  
  Update t1 set t1.D4 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=4  
  Update t1 set t1.D5 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=5  
  Update t1 set t1.D6 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=6  
  Update t1 set t1.D7 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=7  
  Update t1 set t1.D8 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=8  
  Update t1 set t1.D9 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=9  
  Update t1 set t1.D10 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=10  
  Update t1 set t1.D11 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=11  
  Update t1 set t1.D12 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=12  
  Update t1 set t1.D13 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=13  
  Update t1 set t1.D14 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=14  
  Update t1 set t1.D15 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=15  
  Update t1 set t1.D16 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=16  
  Update t1 set t1.D17 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=17  
  Update t1 set t1.D18 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=18  
  Update t1 set t1.D19 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=19  
  Update t1 set t1.D20 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=20  
  Update t1 set t1.D21 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=21  
  Update t1 set t1.D22 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=22  
  Update t1 set t1.D23 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=23  
  Update t1 set t1.D24 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=24  
  Update t1 set t1.D25 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=25  
  Update t1 set t1.D26 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=26  
  Update t1 set t1.D27 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=27  
  Update t1 set t1.D28 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=28  
  Update t1 set t1.D29 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=29  
  Update t1 set t1.D30 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=30  
  Update t1 set t1.D31 = 'P' From #temptable t1 inner join sbiometric.tprocess B ON t1.EmployeeId = B.Sourceid AND ISNULL(CheckInTime,'')!='' AND DAY(AtdDate)=31  
    
  Select   
   EMp.FirstName+' ' +EMp.MiddleName+' '+emp.LastName AS Name,  
   Emp.Id As EmployeeID ,  
    @rBuilder1 AS Builder1,  
    @rBuilder2 AS Builder2,  
    t1.*,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=1  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=1 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D1,  
      
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=2  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=2 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS  D2,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=3  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=3 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D3,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=4  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=4 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D4,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=5  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=5 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D5,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=6  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=6 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D6,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=7  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=7 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D7,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=8  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=8 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D8,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=9  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=9 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D9,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=10  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=10 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D10,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=11  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=11 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D11,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=12  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=12 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D12,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=13  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=13 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D13,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=14  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=14 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D14,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=15  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=15 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D15,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=16  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=16 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D16,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=17  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=17 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D17,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=18  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=18 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D18,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=19  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=19 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D19,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=20  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=20 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D20,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=21  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=21 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D21,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=22  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=22 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D22,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=23  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=23 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D23,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=24  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=24 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D24,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=25  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=25 And EmployeeId=Emp.Id Group by EmployeeId  )  
   --   ELSE  '-' END   
   -- )AS   D25,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=26  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=26 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D26,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=27  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=27 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D27,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=28  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=28 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D28,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=29  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=29  And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D29,  
   --( CASE   
   -- WHEN Day(B.AttendanceDate)=30  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=30 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS D30,  
   -- ( CASE   
   -- WHEN Day(B.AttendanceDate)=31  
   -- THEN    
   -- (Select 'P' from sBiometric.tEmployeeCheckIn where  ISNULL(CheckInTime,'')!='' AND DAY(AttendanceDate)=31 And EmployeeId=Emp.Id Group by EmployeeId )  
   --   ELSE  '-' END   
   -- )AS   D31,  
    sCommon.fGetDaysInMonth(@rFromMonth,@rFromyear) As DaysInMonth ,
	OM.Id AS OrgId,
	OM.Title AS OrganizationTitle 
       
      
  from sHrm.tEmployeeMaster EMP 
  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EMP.OrgID   
  INNER JOIN #temptable t1 On t1.EmployeeId =EMp.Id  AND  ISNULL(EMP.IsOtherUser,0) = 0
  WHERE (EMP.OrgId=@rOrgId OR @rOrgId = 0) AND (Emp.Id = @rEmployeeId OR @rEmployeeId = 0)  
  AND OM.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Altering [sBiometric].[pRptManualPunchGet]...';


GO
 
 
 
ALTER PROCEDURE [sBiometric].[pRptManualPunchGet]    
             
   @rBuilder1 nvarchar(max)='',    
   @rBuilder2 nvarchar(max)='',    
   @rToDate date='',
   @rFromDate date='',
   @rEmployeeStatusId int=0,
   @rEmployeeId bigint = 0,
   @rOrganizationDepartmentId int = 0,
   @rLocationConfig nvarchar(50) = '',
   @rOrgId int = 0,
   @rOrgGroupId int = 0
       
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
BEGIN     
  Select 
  EM.Code AS EmployeeCode,    
   ISNULL(ECI.EmployeePhoto,0) AS EmployeePhoto,
   EM.FirstName+' ' +EM.MiddleName+' '+EM.LastName AS Name,    
   ISNULL(ECI.CheckInTime,'') AS CheckInTime,
   ISNULL(ECI.CheckOutTime,'') AS CheckOutTime,
   EM.ID As EmployeeID ,      
   @rBuilder1 AS Builder1,    
   @rBuilder2 AS Builder2,
   ISNULL(LatitudeAxis,'') AS Latitude,
   ISNULL(LongitudeAxis,'') AS Longitude,
   ISNULL(Location,'') AS Location,
   @rLocationConfig AS LocationConfig,
   CAST(ECI.AttendanceDate AS DATE) AS AttendanceDate,
   OM.Id AS OrganizationId,
   OM.Title AS OrganizationName
   
  FROM
	   sBiometric.tEmployeeCheckIn ECI      
	   INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = ECI.EmployeeId
	   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	   LEFT JOIN sHrm.tEmployeeJobDetail ED ON ED.EmployeeId = EM.Id     
   WHERE 
	   (EM.Id = @rEmployeeId OR @rEmployeeId = 0) 
	   AND (EM.OrgId = @rOrgId OR @rOrgId = 0)
	   AND (CAST(ECI.AttendanceDate AS DATE) >= @rFromDate OR (ISNULL(@rFromDate,'')=''))
       AND (CAST(ECI.AttendanceDate AS DATE) <= @rToDate OR (ISNULL(@rToDate,'')=''))
	   AND (EM.StatusId = @rEmployeeStatusId) OR (ISNULL(@rEmployeeStatusId,0)=0)
	   AND (ED.OrganizationDepartmentId =@rOrganizationDepartmentId Or @rOrganizationDepartmentId= 0 )	
	   AND (OM.OrgGroupId = @rOrgGroupId)   
	   AND  ISNULL(EM.IsOtherUser,0) = 0	   	   
    
	ORDER BY ECI.AttendanceDate DESC
END
GO
PRINT N'Altering [sBiometric].[pRptMonthlySummaryListGet]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pRptMonthlySummaryListGet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int = 0,
	@rDeptId int = 0,
	@rForYear int=0,
	@rForMonth int=0,	 
	@rEmployeeStatusId int=0,
	@rEmployeeId bigint = 0,
	@rOrgGroupId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		MT.EmployeeId,
		MT.EmpCode,
		EM.FirstName + ' ' + EM.LastName AS EmployeeName,
		MT.Tot_Attn  AS TotalPresentDays,
		MT.Tot_Abs AS TotalAbsentDays,
		MT.Tot_WeekOFF AS TotalWeekOffs,
		MT.Tot_Holiday AS TotalHolidays,
		OM.Id AS OrganizationId,
		OM.DisplayTitle AS OrganizationTitle,
		OM.OrderIndex AS OrganizationOrderIndex,
		EM.Number AS EmployeeNumber,
		DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays		
	FROM
	sBiometric.tMonthTrans MT
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId --AND SourceTypeId = 95
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	WHERE
	(EM.OrgId = @rOrgId OR @rOrgId = 0)
	AND YEAR(MT.Attn_Dt) = @rForYear
	AND (MONTH(MT.Attn_dt) = @rForMonth )
	AND (EJD.OrganizationDepartmentId = @rDeptId OR @rDeptId = 0)		 	
	AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
	AND ISNULL(EM.IsOtherUser,0) = 0 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	AND (MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND (OM.OrgGroupId = @rOrgGroupId)
END
GO
PRINT N'Altering [sCommunication].[pFollowupTypeMasterAdd]...';


GO
ALTER PROCEDURE [sCommunication].[pFollowupTypeMasterAdd]
	 
		@rId bigint,
		@rCode nvarchar(100),
		@rTitle nvarchar(200),
		@rOrderIndex int,
		@rIsPublish bit,
		@rIsObsolete bit = 0,
		@rOrgGroupId smallint,
		@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from [sCommunication].[tFollowupTypeMaster] where Code=@rCode AND OrgGroupId=@rOrgGroupId)
		BEGIN
			select -102 as Result
			RETURN
		END 
		If Exists(select Id from [sCommunication].[tFollowupTypeMaster] where Title=@rTitle AND OrgGroupId=@rOrgGroupId)
		BEGIN
			select -103 as Result
			RETURN
		END
		If Exists(select Id from [sCommunication].[tFollowupTypeMaster] where OrderIndex=@rOrderIndex AND OrgGroupId=@rOrgGroupId)
		BEGIN
			select -1003 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If  Exists(select Id from [sCommunication].[tFollowupTypeMaster] where Code=@rCode AND Id<>@rId AND OrgGroupId=@rOrgGroupId)
		Begin
			select -102 as Result
			RETURN
		End
		If  Exists(select Id from [sCommunication].[tFollowupTypeMaster] where Title=@rTitle AND Id<>@rId AND OrgGroupId=@rOrgGroupId)
		Begin
			select -103 as Result
			RETURN
		End
		If Exists(select Id from [sCommunication].[tFollowupTypeMaster] where OrderIndex=@rOrderIndex  AND Id<>@rId AND OrgGroupId=@rOrgGroupId)
		BEGIN
			select -1003 as Result
			RETURN
		END
	END
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
		BEGIN
		
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFollowupTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
		INSERT INTO [sCommunication].[tFollowupTypeMaster]
			   ([Id]
			   ,[Code]
			   ,[Title]
			   ,[OrderIndex]
			   ,[IsPublish]
			   ,[IsObsolete]
			   ,[OrgGroupId]
			   ,[CreatedUserId]
			   ,[CreatedDateTime])
		 VALUES
			   (@lNextNumber,
			    @rCode ,
				@rTitle ,
				@rOrderIndex ,
				@rIsPublish ,
				@rIsObsolete ,
				@rOrgGroupId ,
				@rCreatedUserId ,
				sCommon.fGetDate())

		SELECT 1 AS Result
		SELECT @lNextNumber AS Id
		END	 
	ELSE
		 BEGIN
		 SET @lNextNumber = @rId
			UPDATE [sCommunication].[tFollowupTypeMaster]
				SET 
				  [Code] = @rCode ,
				  [Title] = @rTitle ,
				  [OrderIndex] = @rOrderIndex ,
				  [IsPublish] = @rIsPublish ,
				  [IsObsolete] = @rIsObsolete ,
				  [OrgGroupId] = @rOrgGroupId ,
				  [UpdatedUserId] = @rCreatedUserId ,
				  [UpdatedDateTime] = sCommon.fGetDate()  
				WHERE [Id] = @rId
			  
			  SELECT 11 AS Result
		SELECT @lNextNumber AS Id
		 END  	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sCommunication].[pFollowupTypeMasterDelete]...';


GO
ALTER PROCEDURE [sCommunication].[pFollowupTypeMasterDelete]
	 
	 @rId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
If  Exists(select AutoId from [sCommunication].[tFollowup] where FollowupTypeId = @rId)
		Begin
			select -102 as Result
			RETURN
		End
BEGIN 
	BEGIN TRY
		
		BEGIN TRANSACTION		
			DELETE FROM [sCommunication].[tFollowupTypeAssignedTo] WHERE FollowupTypeId=@rId
			DELETE FROM [sCommunication].[tFollowupTypeMaster] WHERE Id=@rId
			SELECT 1 AS Result
	
	COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END
GO
PRINT N'Altering [sCommunication].[pPollListGet]...';


GO

ALTER PROCEDURE [sCommunication].[pPollListGet]
	 @rId bigint = 0,
	 @rOrgGroupBatchId int,
	 @rCreatedUserId bigint,
	 @rSourceTypeId smallint,
	 @rCreatedDateTime datetime=''
	 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
If(@rSourceTypeId = 95)
BEGIN	 
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote,
			(SELECT U.DisplayTitle FROM sSecurity.tUser U WHERE U.Id = P.CreatedUserId) AS DisplayTitle			
  FROM 
            sCommunication.tPoll P			
            LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
  WHERE 
  
			((P.Id = @rId) OR (@rId = 0)) 
			AND P.CreatedUSerId = @rCreatedUserId
			AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((convert(date,P.CreatedDateTime)=CONVERT(date,@rCreatedDateTime)) OR (ISNull(@rCreatedDateTime,'')=''))
	
	--UNION
	
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
 -- FROM 
 --           sCommunication.tPoll P
 --           LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
 --   AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
END
ELSE IF(@rSourceTypeId = 2003)
BEGIN
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote,
			U.DisplayTitle			
		
  FROM 
            sCommunication.tPoll P
         INNER JOIN sCommunication.tPollMember PM ON PM.PollId=P.Id AND PM.SourceTypeId=2005
         INNER JOIN sStudent.vStudentAcademic SA ON SA.DivisionId=PM.SourceId AND SA.IsActiveBatch = 1
         INNER JOIN sSecurity.tUser U ON U.SourceId=SA.StudentId AND U.SourceTypeId=@rSourceTypeId AND U.Id=@rCreatedUserId
         LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
         
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((convert(date,P.CreatedDateTime)=CONVERT(date,@rCreatedDateTime)) OR (ISNull(@rCreatedDateTime,'')=''))
	
	
	--UNION
	
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
 -- FROM 
 --           sCommunication.tPoll P
 --            LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
 --    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
END

ELSE 

BEGIN
	--SELECT 
	
	--		P.Id as PollId,
	--		P.Title AS PollTitle,
	--		P.Remark AS PollRemark,
	--		P.IsOwnAnswer,
	--		P.IsOpen,
	--		P.CreatedDateTime AS PollCreatedDateTime,
	--		ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
	--		(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote
			
 -- FROM 
 --           sCommunication.tPoll P
 --        INNER JOIN sCommunication.tPollMember PM ON PM.PollId=P.Id AND PM.SourceTypeId=2005
 --        INNER JOIN sStudent.vStudentAcademic SA ON SA.DivisionId=PM.SourceId
 --        INNER JOIN sSecurity.tUser U ON U.SourceId=SA.StudentId AND U.SourceTypeId=@rSourceTypeId AND U.Id=@rCreatedUserId
 --         LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
 -- WHERE 
  
 --     ((P.Id = @rId) OR (@rId = 0))
	--AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	--UNION
	
	SELECT 
	
			P.Id as PollId,
			P.Title AS PollTitle,
			P.Remark AS PollRemark,
			P.IsOwnAnswer,
			P.IsOpen,
			P.CreatedDateTime AS PollCreatedDateTime,
			ISNULL(PR.CreatedUserId,0) AS PollResultUserId,
			(SELECT  ISNULL(Count(1),0) FROM sCommunication.tPollResult PR WHERE PR.PollId=P.Id) AS TotalPollVote,
			(SELECT U.DisplayTitle FROM sSecurity.tUser U WHERE U.Id = P.CreatedUserId) AS DisplayTitle			
  FROM 
            sCommunication.tPoll P			
            LEFT JOIN sCommunication.tPollResult PR ON P.Id = PR.PollId AND  PR.CreatedUSerId = @rCreatedUserId
  WHERE 
  
      ((P.Id = @rId) OR (@rId = 0))
    AND ((P.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND ((P.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((convert(date,P.CreatedDateTime)=CONVERT(date,@rCreatedDateTime)) OR (ISNull(@rCreatedDateTime,'')=''))
	
END


END
GO
PRINT N'Altering [sEExam].[pTestParticipantResultGet]...';


GO
ALTER PROCEDURE [sEExam].[pTestParticipantResultGet]
 
			@rBuilder1 nvarchar(max)='',
			@rTestId int,		 
			@rSourceTypeID int = 0,
			@rSourceId bigint = 0,
			@rBatchId int=0
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN   

DECLARE @1TestAssignStatusId int

 
IF(@rSourceTypeID = 2003)
   BEGIN
	 SELECT  
	     @rBuilder1 AS Builder1,
		 VSA.RollNo,
		 VSA.Name,
		 VSA.Code,
		 P.SourceId,
		 P.SourceTypeId,	
	     ISNULL(P.TotalMarks,0) AS TotalMarks,
		 ISNULL(P.ScoredMarks,0) AS ScoredMarks,
		 ISNULL(P.TotalQuestions,0) AS TotalQuestions,
		 ISNULL(P.RightQuestions,0) AS RightQuestions,
		 ISNULL(P.WrongQuestions,0) AS WrongQuestions,
		 --(ISNULL(P.WrongQuestions,0) - (ISNULL(P.NotAttemptedQuestions,0)+ ISNULL(P.SkippQuestions,0))) AS WrongQuestions,
		 ISNULL(P.NotAttemptedQuestions,0) AS NotAttemptedQuestions,
		 ISNULL(P.SkippQuestions,0) AS SkippQuestions,
		 'Student' AS TypeName,
		 VSA.ClassName+'-'+VSA.DivisionName As ClassName,
		 ISNULL(TM.IsMarkInDecimal,0) AS IsMarkInDecimal,
		 P.Id AS TestParticipantId,
		 VSA.AcademicId,
		 TM.Title As TestName,
		 P.TestStatusId
		 --TM.IsMarkInDecimal
		 FROM sEExam.tTestParticipant P INNER JOIN sEExam.tTestMaster TM ON TM.Id = P.TestId
		 INNER JOIN sStudent.vStudentAcademic VSA ON VSA.StudentId = P.SourceId AND P.SourceTypeId=2003
		 Where (SourceTypeId = @rSourceTypeID OR @rSourceTypeID = 0) AND TestId = @rTestId
		 AND TestStatusId != 0 AND (P.SourceId = @rSourceId or @rSourceId = 0)
		 AND TM.BatchId=@rBatchId AND VSA.BatchId=@rBatchId
		
		ORDER BY DivisionId, VSA.RollNo ASC
		END
		ELSE 
		     Select 	
			 @rBuilder1 AS Builder1,		
			 ECD.Code AS RollNo,
			 ECD.EmployeeName AS Name,
			 ECD.Code,
			 P.SourceId,
			 P.SourceTypeId,			
			 ISNULL(P.TotalMarks,0) AS TotalMarks,
			 ISNULL(P.ScoredMarks,0) AS ScoredMarks,
			 ISNULL(P.TotalQuestions,0) AS TotalQuestions,
			 ISNULL(P.RightQuestions,0) AS RightQuestions,
			 ISNULL(P.WrongQuestions,0) AS WrongQuestions,
			 ISNULL(P.SkippQuestions,0) AS SkippQuestions,
			 ISNULL(P.NotAttemptedQuestions,0) AS NotAttemptedQuestions,
		     'Employee' AS TypeName,
		     ECD.DepartmentName AS ClassName,
		     ISNULL(TM.IsMarkInDecimal,0) AS IsMarkInDecimal,
		     P.Id AS TestParticipantId,
			 P.TestStatusId
		     --TM.IsMarkInDecimal
			 
			 FROM sEExam.tTestParticipant P INNER JOIN sEExam.tTestMaster TM ON TM.Id = P.TestId
			 INNER JOIN sHrm.vEmployeeCommonDetail ECD ON ECD.EmployeeId = P.SourceId 
			 AND TestStatusId != 0 
 
			 Where (SourceTypeId = @rSourceTypeID OR @rSourceTypeID = 0) AND TestId = @rTestId   
			  AND TestStatusId != 0  AND (P.SourceId = @rSourceId or @rSourceId = 0)
			  AND TM.BatchId=@rBatchId
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


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

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


GO

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


GO
 
 
ALTER PROCEDURE [sFee].[pMobileFeeReceiptDetailsGet]
		
		@rAcademicId bigint=0,
		@rReceiptId bigint =0,
		@rType nvarchar(20)=''
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	IF(@rType = 'FeeReceiptList')
		BEGIN
			SELECT 
				R.Id AS ReceiptId,
				ISNULL(RBM.Title,'') AS ReceiptBookTitle,
				R.ReceiptNumber,
				R.ReceiptDate,
				R.ReceiptAmount
			FROM sFee.tReceipt R
				INNER JOIN sStudent.tAcademic A ON A.Id = R.SourceId
				INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=R.ReceiptBookId
			WHERE 
				R.SourceTypeId = 2001
				AND	A.Id = @rAcademicId
		END
	ELSE IF(@rType = 'FeeReceiptDetails')
		BEGIN
			SELECT
				R.Id AS ReceiptId,
				R.ReceiptNumber,
				SA.ClassId,
				SA.DivisionId,
				SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
				SA.RollNo,
				SA.Code,
				SA.Name,
				ISNULL(PTM.Title,'') AS PayType,
				CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
				ISNULL(ChequeDate,'01/01/0001') As ChequeDate,
				ISNULL(R.BankName,'') AS BankName,
				R.ReceiptAmount,
				R.ReceiptDate,
				R.CreatedUserId,
				ISNULL(U.DisplayTitle,'') AS UserName,
				ISNULL(RBM.Title,'') AS ReceiptBookTitle,
				ISNULL(RBM.BankName,'') AS ReceiptBookBank,
				ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
				ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,
				R.Remark,
				R.DiscountAmount,
				ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,
				SA.OrgId,
				SA.OrganizationName,
				ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,
				ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,
				ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,
				ISNULL(R.CGSTAmount,0) AS CGSTAmount,
				ISNULL(R.SGSTAmount,0) AS SGSTAmount,
				SA.OrgGroupBatchId AS BatchId,
				SA.BatchName
			FROM 
				sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA
					ON SA.AcademicId=R.SourceId 
				INNER JOIN sFinanceCommon.tPayTypeMaster PTM
					ON PTM.Id=R.PayTypeId
				INNER JOIN sFee.tReceiptBookMaster RBM 
					ON RBM.Id=R.ReceiptBookId
				LEFT JOIN sSecurity.tUser U
					ON U.Id=R.CreatedUserId
			WHERE 
				R.SourceTypeId = 2001
				AND R.Id = @rReceiptId 
		END

	
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='',
			@rClassId int = 0,
			@rOrgIds nvarchar(max) = '',
			@rReceiptPrintGroupId nvarchar(100)=''
	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,
			
			--changes by Jash on 06/11/2020--%
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),ISNULL(FR.PaymentTransactionId,''))  END AS ChequeNo,
			--CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo
			--	WHEN ISNULL(PT.BankTransactionId,'') = '' THEN  CONVERT(nvarchar(20),FR.PaymentTransactionId)
			--	ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) +' - '+ CONVERT(nvarchar(20),PT.BankTransactionId) END AS ChequeNo,
			--%


			--ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,			
			
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN '' 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,
			
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			(CASE WHEN  U.SourceTypeId = 2003 
			  THEN -- Navrachana
				'Online Generated'
				ELSE ISNULL(U.DisplayTitle,'') END) AS UserName,
			--ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0  THEN 
			--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	
				  
			  
			(CASE WHEN  RBM.ReportId = 20576
			      THEN -- HM patel report
				  [sFee].[fReceiptMonthDetailGet](FR.ID,0)
			      WHEN RBM.ReportId = 30457 
			      THEN
				  [sFee].[fReceiptMonthDetailGet](FR.ID,1)		
			      WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
				  [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Head wise Month name in detail
				  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN				
				  [sFee].[fFeeMonthNameGet](FR.ID,FM.Id) -- Fee wise Month name in detail
			ELSE '' END) 
			AS MonthDetail,    

			
			(CASE WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
					 Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
					sFee.tReceipt FR1				
					INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
					INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
					INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
					INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
					Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					Order By FS1.StartDate
					FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' )    -- Fee Head wise Fee Duration
				  WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN
					FS.FeeDuration -- Fee wise Fee Duration
				 ELSE '' END) AS FeeDuration,
			
			--Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
			--sFee.tReceipt FR1				
			--INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
			--INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
			--INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
			--INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
			--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
			----Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			-- Order By FS.StartDate
			--FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' ) AS FeeDuration,
			
			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			'' AS CurrencyCode,
			'' 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,
	        '' AS ItemValue ,
	        SF.FatherName,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,

			(ISNULL((CASE WHEN SC.PresentStreetOne IS NOT NULL AND SC.PresentStreetOne!='' THEN ''+ SC.PresentStreetOne END),'')+
			ISNULL((CASE WHEN SC.PresentStreetTwo IS NOT NULL AND SC.PresentStreetTwo!=''  THEN ', '+ SC.PresentStreetTwo END),'')+
			ISNULL((CASE WHEN SC.PresentStreetThree IS NOT NULL AND SC.PresentStreetThree!=''  THEN ', '+ SC.PresentStreetThree END),'')+
			ISNULL((CASE WHEN SC.PresentCity IS NOT NULL AND SC.PresentCity!=''  THEN ', ' + SC.PresentCity  END),'')+
			ISNULL((CASE WHEN SC.PresentState IS NOT NULL AND SC.PresentState!=''  THEN  ', '+ SC.PresentState END),'')+
			ISNULL((CASE WHEN SC.PresentZipCode IS NOT NULL AND SC.PresentZipCode!=''  THEN  ', '+ SC.PresentZipCode  END),''))
			 AS PresentAdress,
			--ISNULL(SC.PresentStreetOne +','+ SC.PresentStreetTwo +','+ SC.PresentStreetThree +','+ SC.PresentCity +','+ SC.PresentState +'-'+ SC.PresentZipCode ,'') AS PresentAdress,
			SC.ParentContactNo,
			ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount,
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,0),0) END) AS PendingFeeAmount,
			SA.FirstName,
			SA.LastName,
			ISNULL([sFee].[fFeeAmountSumGet](FR.SourceId),0) AS FeeAmount,
			ISNULL([sFee].[fFeeReceiptDiscountSumGet](FR.SourceId),0) AS ExemptionAmountSum,
			[sFee].[fTransportBusRouteGet](SA.StudentId,FR.OrgGroupBatchId) AS TransportBusRoute,
			ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
			ISNULL(FHM.Number,0) AS FeeHeadNumber,
			ISNULL(FM.Number,0) AS FeeNumber
	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
END
GO
PRINT N'Altering [sFee].[pRptStudentLedgerGet]...';


GO

ALTER PROC [sFee].[pRptStudentLedgerGet]

	 @rAcademicId bigint,
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(20)='',
	 @rDepositHeadId int,
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
     @rBatchId int
AS
BEGIN
WITH Tb0 as
( 
			SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
		     DA.CreatedDateTime,
		     '' AS ExpenseType,
			 VA.RollNo,
			 SA.AdmissionNumber
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = VA.StudentId
			Where 
		   ((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.DepositHeadId = @rDepositHeadId)
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
		    --AND VA.BatchId = @rBatchId
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
		    DAJ. CreatedDateTime,
		   ISNULL(ETM.Title,'')AS ExpenseType,
		   VA.RollNo,
		   SA.AdmissionNumber
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  INNER JOIN sFee.tFeeDepositExpenseTypeMaster ETM ON ETM.Id =DAJ.FeeDepositExpenseTypeId
			  INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = VA.StudentId
			Where 
			((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
		  -- AND VA.BatchId = @rBatchId
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
		    DR.CreatedDateTime,
		     '' AS ExpenseType,
			 VA.RollNo,
			 SA.AdmissionNumber
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			  INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = VA.StudentId
			Where 
			((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			--AND VA.BatchId = @rBatchId
)
,Tb1 as
( 
	SELECT DepositDate,Credit,Debit,Row_Number() over (order by CreatedDateTime asc) as OrderId,AcademicId,Code,SUId,StudentName,Class ,CreatedDateTime,ExpenseType,RollNo,AdmissionNumber FROM Tb0
)
  SELECT T1.DepositDate,
         T1.[Credit],
         T1.[Debit],(Sum(T2.Credit) - Sum(T2.Debit)) as Balance,
         T1.SUId,
         CASE WHEN @rIsBasedOnSUId=0 THEN  T1.Code Else ISNULL(T1.SUId,'') END AS Code,
         T1.StudentName,
         T1.Class,
        T1.CreatedDateTime,
        T1.ExpenseType,
		T1.RollNo,
		T1.AdmissionNumber
		 FROM Tb1 as T1
		 INNER JOIN Tb1 as T2 ON T1.OrderId >= T2.OrderId
		 Group By T1.DepositDate,T1.Credit,T1.Debit,T1.AcademicId,T1.SUId,T1.Code,T1.StudentName,T1.Class,T1.CreatedDateTime,T1.ExpenseType,T1.RollNo,T1.AdmissionNumber
		 Order by T1.CreatedDateTime 
END
GO
PRINT N'Altering [sHrm].[pRptEmployeeIcardGet]...';


GO

ALTER PROCEDURE [sHrm].[pRptEmployeeIcardGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId smallint,
	@rOrgId smallint,
	@rStrEmployeeId nvarchar(max),
	@rEmployeeTypeId [int],
	@rDepartmentId [int]= 0,
	@rGradeId [int]= 0,
	@rDesignationId [int]= 0,
	@rGenderId [int]= 0,		
	@rEmployeeId [bigint]= 0,
	@rAgeFrom nvarchar(10),
	@rAgeTo nvarchar(10),
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeGroupId smallint,
	@rEmployeeStatusId smallint,
	@rIsShowBarcode bit=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT		
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ECD.EmployeeId,
	        ECD.Code,	      	
			ECD.EmployeeName, 	 								 
			ECD.DepartmentId,  			
			ECD.DepartmentName,
		    ECD.MobileNumber,
		    ECD.EmployeeDesignation,
		    ECD.PhoneNoCompany,
		    ECD.BloodGroup,
		    ECD.DateOfBirth,
			EI.EmployeePhoto,
		    OM.Title AS OrgName,
		    OM.PrincipalSignature,
			ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,
			ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,
			ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,
			ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,	
		    OM.OrgLogo AS ICardLogo,
			ICO.ICardBackground,	
			ICO.ICardBackBackground,						
			ISNULL(ICO.LabelColor,'Black') AS LabelColor,
			ISNULL(ICO.DetailColor,'Black') AS DetailColor,
			ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,
			ISNULL(EC.PresentStreetOne,'') AS PresentStreetOne,
			ISNULL(EC.PresentStreetTwo,'') AS PresentStreetTwo,
			ISNULL(EC.PresentStreetThree,'') AS PresentStreetThree,
			ISNULL(EC.PresentCity,'') AS PresentCity,
			ISNULL(EC.PresentState,'') AS PresentState,
			ISNULL(EC.PresentCountry,'') AS PresentCountry,
			ISNULL(EC.PresentZipCode,'') AS PresentZipCode,
			ECD.DateofJoining,
			EI.EmployeeSign,
			@rIsShowBarcode As IsShowBarcode,
			ISNULL(EC.EmergencyStreetOne,'') AS EmergencyStreetOne,
			ISNULL(EC.EmergencyStreetTwo,'') AS EmergencyStreetTwo,
			ISNULL(EC.EmergencyStreetThree,'') AS EmergencyStreetThree,
			ISNULL(EC.EmergencyCity,'') AS EmergencyCity,
			ISNULL(EC.EmergencyState,'') AS EmergencyState,
			ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(PanNumber,'') AS PanNumber,
			EC.EmergencyContactNo AS EmergencyContactNo,
			EPD.Qualification AS Qualification,
			ISNULL(EM.MiddleName,'')AS FatherName
		FROM 
			sHrm.vEmployeeCommonDetail ECD
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=ECD.OrgID
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeeICardOrg ICO ON ECD.OrgId = ICO.OrgId
			LEFT JOIN sHrm.tEmployeeCommunications EC ON ECD.EmployeeId = EC.EmployeeId
			LEFT JOIN sHrm.tEmployeeStatutoryAndOther EO ON EO.EmployeeId = ECD.EmployeeId
			LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EO.EmployeeId
			--LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on ECD.EmployeeId=EFD.EmployeeId 
			--LEFT JOIN sCommon.tRelationshipMaster RM on EFD.RelationshipId=RM.Id AND RM.Id=2
			LEFT JOIN sHrm.tEmployeeMaster EM on EM.Id = ECD.EmployeeId
			
		WHERE
		((ECD.Code LIKE @rEmployeeCode)OR @rEmployeeCode = '' )
	   AND (ISNULL(ECD.EmployeeId,0) NOT IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rStrEmployeeId,',')) OR @rStrEmployeeId='') 
	   AND (ECD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	   AND (ECD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	   AND (ECD.EmployeeStatusId = @rEmployeeStatusId OR @rEmployeeStatusId = 0)
	   AND (ECD.EmployeeGroupId=@rEmployeeGroupId OR @rEmployeeGroupId=0)
	   AND (ECD.EmployeeGradeId = @rGradeId OR @rGradeId = 0)
	   AND (ECD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 	   
	   AND (ECD.GenderId = @rGenderId OR @rGenderId = 0)  	    
	   AND (ECD.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)	   
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	   --AND ((DATEDIFF(yy,ECD.DateOfBirth,GETDATE()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	   AND  ECD.OrgId = @rOrgId
	   AND ISNULL(ECD.IsOtherUser,0)=0
	  
END
GO
PRINT N'Altering [sLibrary].[pBookLogListViewGet]...';


GO
ALTER PROCEDURE [sLibrary].[pBookLogListViewGet]
	 @rReaderSourceTypeId smallint=2003,
	 @rAcademicId bigint,
	 @rOrgId smallint,
	 @rBatchId int
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lBookgrid VARCHAR(max)=''

SELECT  @lBookgrid = @lBookgrid + '<tr>
  <td align="left" scope="col">' +  Isnull(LM.Title,'') + '</td>
	<td align="left" scope="col">' + ISNULL(BM.Code,'')+ '</td>	
	<td align="left" scope="col">' + isnull(BM.Title,'') + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(BL.LogDate,''),103) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(BL.DueDate,''),103) + '</td>
	<td align="left" scope="col">' + CASE WHEN SM.Title = 'Available' THEN  'Returned' ELSE ISNULL(SM.Title,'') END + '</td>
</tr>'	
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005 AND BL.LibraryId = IS1.LibraryId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId AND SM.IsObsolete = 0 AND SM.StatusTypeId=106
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE ((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		 AND BL.IsCurrentStatus=1
		AND ((BL.StatusId=521) OR (BL.StatusId=523))
		AND (BL.OrgId=@rOrgId)
		AND (BL.BatchId=@rBatchId)
		AND SA.AcademicId=@rAcademicId
	select isnull(@lBookgrid,'') as Bookgrid
END
GO
PRINT N'Altering [sOp].[pPaymentTransactionDetailGet]...';


GO

 

ALTER PROCEDURE [sOp].[pPaymentTransactionDetailGet]
	@rOrgGroupId smallint=0,
	@rOrgId int=0,
	@rBatchId int=0,
	@rReferenceNo bigint=0,
	@rFunctionalityId int,
	@rReceiptBookId bigint
AS
SET NOCOUNT ON

BEGIN
	IF(@rFunctionalityId = 1)
	BEGIN
		SELECT  
			TSM.Title As TransactionStatus,
			FM.Title AS Functionality,
			PT.PayAmount,
			PT.PayDateTime,
			CONVERT(nvarchar(20),SM.Code) AS Code,
			SM.FirstName + ' ' + SM.LastName AS Name,
			CM.DisplayTitle +' - '+ DM.DisplayTitle AS ClassName,
			PT.Id AS PaymentTransactionId,
			ISNULL(OS.Title,'') AS OSType,
			ISNULL(PT.BankTransactionId,0) AS BankTransactionId,
			ISNULL(PT.PaymentGatewayId,0) AS PaymentGatewayId,
			BM.Title AS Batch,
			A.RollNo,
			SC.ParentContactNo,
			SC.ParentEmail,
			ISNULL(PGM.Title+'/'+GP.Title,'') AS PaymentGateway,
			ISNULL(R.ReceiptNumber,0) AS ReceiptNumber
		FROM 
			sOp.tPaymentTransaction PT 
			LEFT JOIN sAlert.tOSType OS ON OS.Id = PT.OSTypeId                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
			INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.ID = PT.TransactionStatusId
			INNER JOIN sOp.tFunctionalityMaster FM ON FM.Id = PT.FunctionalityId
			INNER JOIN sStudent.tAcademic A ON A.Id = PT.PayerSourceId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			LEFT JOIN sOp.tpaymentGatewayMaster PGM ON PT.PaymentGatewayId = PGM.Id
			LEFT JOIN sFee.tReceipt R ON R.PaymentTransactionId = PT.Id
			INNER JOIN 
			(
				SELECT OP.Id,RB.Id as ReceiptBookId FROM sFee.tOnlineFee OP 
				INNER JOIN  sFee.tReceiptBookMaster RB ON RB.Id = OP.ReceiptBookId
				WHERE RB.Id = @rReceiptBookId
			) O ON O.Id = PT.TransactionSourceId AND TransactionSourceTypeId = 2024
			INNER JOIN sOp.tGatewayProductReceiptBookMapping GPRM ON GPRM.ReceiptBookId = O.ReceiptBookId --AND ISNULL(GPRM.IsObsolete,0) = 0
			INNER JOIN sOp.tGatewayConfiguration GC ON GC.PaymentGatewayId = PGM.Id AND GC.OrgGroupId = @rOrgGroupId
			INNER JOIN sOp.tGatewayProduct GP ON GP.GatewayConfigurationId = GC.Id AND GP.Id = GPRM.GatewayProductId
		WHERE 
			 (PT.FunctionalityId = 1)
			 AND OM.OrgGroupId = @rOrgGroupId
			 AND OM.Id = @rOrgId
			 AND BM.Id = @rBatchId
			 AND (PT.Id= @rReferenceNo OR @rReferenceNo=0)
	END
	ELSE IF(@rFunctionalityId = 2)
	BEGIN
		SELECT  
			TSM.Title As TransactionStatus,
			FM.Title AS Functionality,
			PT.PayAmount,
			PT.PayDateTime,
			CONVERT(nvarchar(20),AF.FormNo) AS Code,
			AF.FirstName + ' ' + AF.LastName AS Name,
			CM.DisplayTitle AS ClassName,
			PT.Id AS PaymentTransactionId,
			ISNULL(OS.Title,'') AS OSType,
			ISNULL(PT.BankTransactionId,0) AS BankTransactionId,
			ISNULL(PT.PaymentGatewayId,0) AS PaymentGatewayId,
			BM.Title AS Batch,
			0 AS RollNo,
			AF.ContactNo AS ParentContactNo,
			AF.ContactEmail AS ParentEmail,
			ISNULL(PGM.Title+'/'+GP.Title,'') AS PaymentGateway,
			ISNULL(R.ReceiptNumber,0) AS ReceiptNumber
		FROM 
			sOp.tPaymentTransaction PT           
			LEFT JOIN sAlert.tOSType OS ON OS.Id = PT.OSTypeId                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
			INNER JOIN sOp.tTransactionStatusMaster TSM ON TSM.ID = PT.TransactionStatusId
			INNER JOIN sOp.tFunctionalityMaster FM ON FM.Id = PT.FunctionalityId
			INNER JOIN sAdmission.tAdmissionForm AF ON AF.Id = PT.PayerSourceId
			INNER JOIN sAdmission.tAdmissionCriteria AC ON AC.BatchId=AF.BatchId AND AC.ClassId=AF.ForClassId 
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = AC.ReceiptBookId AND RBM.Id = @rReceiptBookId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			INNER JOIN sOp.tpaymentGatewayMaster PGM ON PT.PaymentGatewayId = PGM.Id
			LEFT JOIN sFee.tReceipt R ON R.PaymentTransactionId = PT.Id
			LEFT JOIN sOp.tGatewayProductReceiptBookMapping GPRM ON GPRM.ReceiptBookId = RBM.Id --AND ISNULL(GPRM.IsObsolete,0) = 0
			INNER JOIN sOp.tGatewayConfiguration GC ON GC.PaymentGatewayId = PGM.Id AND GC.OrgGroupId = @rOrgGroupId
			INNER JOIN sOp.tGatewayProduct GP ON GP.GatewayConfigurationId = GC.Id AND GP.Id = GPRM.GatewayProductId
		WHERE 
				(PT.FunctionalityId = 2)
			 AND OM.OrgGroupId = @rOrgGroupId
			 AND OM.Id = @rOrgId
			 AND BM.Id = @rBatchId
			 AND (PT.Id= @rReferenceNo OR @rReferenceNo=0)
	END
END
GO
PRINT N'Altering [sSecurity].[pUserLogDetailGet]...';


GO
 
 
ALTER PROCEDURE [sSecurity].[pUserLogDetailGet]
	@rOrgId [smallint],
	@rDisplayTitle [nvarchar](100),
	@rLoginTitle [nvarchar](20),
	@rRoleId int,
	@rSourceTypeId smallint,
	@rSourceCode nvarchar(20),
	@rSourcename nvarchar(100),
	@rIsCommon bit,
	@rOrgGroupId smallint,
	@rFromDate date,
	@rToDate date,
	@rOsTypeId smallint=0,
	@rIsHistory bit = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SET @rDisplayTitle = sCommon.fSearchStringGet(@rDisplayTitle)
SET @rLoginTitle = sCommon.fSearchStringGet(@rLoginTitle) 
SET @rSourceCode= sCommon.fSearchStringGet(@rSourceCode)
SET @rSourceName= sCommon.fSearchStringGet(@rSourcename)

SET @rToDate = DATEADD(day,1,@rToDate)

IF(@rIsHistory = 1)
BEGIN
IF(@rSourceTypeId = 2003)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Student' AS UserSourceTypeName,
			Users.IsObsolete,
			SN.Code AS EmployeeCode,
			SN.Name AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users			
			INNER JOIN sStudent.vStudentName SN
				ON SN.StudentId = Users.SourceId AND Users.SourceTypeId = @rSourceTypeId						
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SN.BatchId  AND BM.IsActive = 1
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLogHistory UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  
		 AND((SN.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((SN.Name like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))               
		  Order By UL.Id DESC
END
ELSE IF(@rSourceTypeId = 95)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Employee' AS UserSourceTypeName,
			Users.IsObsolete,
			Emp.Code AS EmployeeCode,
			(Emp.FirstName +  ' ' + Emp.LastName) AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users			
			INNER JOIN sHrm.vExtEmployeeMaster Emp
				ON Emp.Id = Users.SourceId AND Users.SourceTypeId = @rSourceTypeId							
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLogHistory UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  
		 AND((Emp.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((Emp.EmployeeName like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))           
		  Order By UL.Id DESC
END
ELSE IF(@rSourceTypeId = 1)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Other' AS UserSourceTypeName,
			Users.IsObsolete,
			Users.DisplayTitle AS EmployeeCode,
			Users.LoginTitle AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users						
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLogHistory UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  		  
		 AND((Users.DisplayTitle like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((Users.DisplayTitle like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))                            
		  Order By UL.Id DESC
END       
END
ELSE
BEGIN
	IF(@rSourceTypeId = 2003)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Student' AS UserSourceTypeName,
			Users.IsObsolete,
			SN.Code AS EmployeeCode,
			SN.Name AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users			
			INNER JOIN sStudent.vStudentName SN
				ON SN.StudentId = Users.SourceId AND Users.SourceTypeId = @rSourceTypeId						
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SN.BatchId  AND BM.IsActive = 1
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLog UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  
		 AND((SN.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((SN.Name like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))               
		  Order By UL.Id DESC
END
ELSE IF(@rSourceTypeId = 95)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Employee' AS UserSourceTypeName,
			Users.IsObsolete,
			Emp.Code AS EmployeeCode,
			(Emp.FirstName +  ' ' + Emp.LastName) AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users			
			INNER JOIN sHrm.vExtEmployeeMaster Emp
				ON Emp.Id = Users.SourceId AND Users.SourceTypeId = @rSourceTypeId							
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLog UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  
		 AND((Emp.Code like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((Emp.EmployeeName like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))           
		  Order By UL.Id DESC
END
ELSE IF(@rSourceTypeId = 1)
BEGIN
	SELECT 
            Users.Id,
			Users.DisplayTitle,
			Users.LoginTitle,
			Users.SourceId AS UserSourceId,
			Users.SourceTypeId AS UserSourceTypeId,
			'Other' AS UserSourceTypeName,
			Users.IsObsolete,
			Users.DisplayTitle AS EmployeeCode,
			Users.LoginTitle AS UserFullName,
			Uprof.ElectronicSignature AS ElectronicSignature,
            CASE WHEN Users.IsObsolete = 1 THEN 'Y' ELSE 'N' END AS ObsoleteDisplay,
            UR.RoleId,
            R.Title AS RoleName,
            Users.OrgId,
            Users.ValidUpto AS ValidUptoDate,                     
            OM.Title AS OrgName,
            UL.LoggedInDateTime,
            CASE WHEN UL.LoggedOutDateTime = '1900-01-01 00:00:00.000' THEN '' ELSE UL.LoggedOutDateTime END AS LoggedOutDateTime,
            UL.SessionId,
            OST.Title AS OSTypeTitle,
			UL.LoggedInIp
            
       FROM sSecurity.tUser Users						
			LEFT JOIN sSecurity.tUserProfile Uprof
				ON Users.Id = Uprof.UserId
			INNER JOIN sSecurity.tUserRole UR 
				ON UR.UserId=Users.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND (UR.RoleId=@rRoleId OR @rRoleId=0)
			INNER JOIN sSecurity.tRole R 
				ON R.Id=UR.RoleId AND (R.OrgGroupId=@rOrgGroupId)
			INNER JOIN sSetup.tOrganizationMaster OM 
				ON OM.Id = Users.OrgId
			INNER JOIN sSecurity.tUserLog UL
				ON Users.Id=UL.UserId
			LEFT JOIN sAlert.tOSType OST 
			    ON OST.Id=UL.OSTypeId	
			
        WHERE ((Users.OrgId = @rOrgId) OR (@rOrgId=0))
	      AND ((ISNULL(Users.SourceTypeId,1) = @rSourceTypeId) OR (@rSourceTypeId=0))
		  AND ((Users.DisplayTitle LIKE @rDisplayTitle) OR (@rDisplayTitle = ''))
          AND ((LoginTitle LIKE @rLoginTitle) OR (@rLoginTitle = ''))   
          AND (UL.LoggedInDateTime >= @rFromDate)
		 AND (UL.LoggedInDateTime < @rToDate)  
		 AND ((OST.Id = @rOsTypeId) OR (@rOsTypeId=0))  		  
		 AND((Users.DisplayTitle like @rSourceCode) OR (ISNULL(@rSourceCode,'') = '')) AND((Users.DisplayTitle like @rSourceName) OR (ISNULL(@rSourceName,'') = ''))                            
		  Order By UL.Id DESC
END  
END
END
GO
PRINT N'Altering [sSetup].[pHistoryTransfer]...';


GO
 
ALTER PROCEDURE [sSetup].[pHistoryTransfer]
	 @rType smallint = 0,
	 @rDate date = ''
	 	 	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN
BEGIN TRY
		BEGIN TRANSACTION 
	IF(@rType = 1) -- Copy To History Table
	BEGIN

	INSERT INTO [sAlert].[tAlertLogHistory] SELECT * FROM [sAlert].[tAlertLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tAlertLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAlert].[tNotificationLogHistory] SELECT * FROM [sAlert].[tNotificationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tNotificationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAlert].[tWhatsAppLogHistory] SELECT * FROM [sAlert].[tWhatsAppLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	DELETE FROM [sAlert].[tWhatsAppLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sAudit].[tActivityLogHistory] SELECT * FROM [sAudit].[tActivityLog] WHERE CAST(AuditDate AS DATE) < @rDate
	DELETE FROM [sAudit].[tActivityLog] WHERE CAST(AuditDate AS DATE) < @rDate

	--INSERT INTO [sAudit].[tOperationLogHistory] SELECT * FROM [sAudit].[tOperationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sAudit].[tOperationLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	--INSERT INTO [sHrm].[tLeaveBalanceLogHistory] SELECT * FROM [sHrm].[tLeaveBalanceLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sHrm].[tLeaveBalanceLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	--INSERT INTO [sLibrary].[tBookLogHistory] SELECT * FROM [sLibrary].[tBookLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sLibrary].[tBookLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	--INSERT INTO [sRecruitment].[tRecruitmentStatusLogHistory] SELECT * FROM [sRecruitment].[tRecruitmentStatusLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
	--DELETE FROM [sRecruitment].[tRecruitmentStatusLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate

	INSERT INTO [sSecurity].[tUserLogHistory] SELECT * FROM [sSecurity].[tUserLog] WHERE CAST(LoggedInDateTime AS DATE) < @rDate
	DELETE FROM [sSecurity].[tUserLog] WHERE CAST(LoggedInDateTime AS DATE) < @rDate

	INSERT INTO [sSystem].[tBackupLogHistory] SELECT * FROM [sSystem].[tBackupLog] WHERE CAST(BackupDateTime AS DATE) < @rDate
	DELETE FROM [sSystem].[tBackupLog] WHERE CAST(BackupDateTime AS DATE) < @rDate

	INSERT INTO [sAcademic].[tClassworkViewHistory] SELECT * FROM [sAcademic].[tClassworkView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sAcademic].[tClassworkView] WHERE CAST(ViewByDateTime AS DATE) < @rDate

	INSERT INTO [sAcademic].[tOnlineLearningViewHistory] (OnlineLearningId,AcademicId,IsViewReference,IsViewAssignment,IsViewResource,ViewByUserId,LastViewByDateTime,AssignmentTeacherRemark) SELECT OnlineLearningId,AcademicId,IsViewReference,IsViewAssignment,IsViewResource,ViewByUserId,LastViewByDateTime,AssignmentTeacherRemark FROM [sAcademic].[tOnlineLearningView] WHERE CAST(LastViewByDateTime AS DATE) < @rDate
	DELETE FROM [sAcademic].[tOnlineLearningView] WHERE CAST(LastViewByDateTime AS DATE) < @rDate

	INSERT INTO  [sCommunication].[tAssignmentViewHistory] SELECT * FROM [sCommunication].[tAssignmentView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sCommunication].[tAssignmentView] WHERE CAST(ViewByDateTime AS DATE) < @rDate

	INSERT INTO  [sCommunication].[tCircularViewHistory] SELECT * FROM [sCommunication].[tCircularView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	DELETE FROM [sCommunication].[tCircularView] WHERE CAST(ViewByDateTime AS DATE) < @rDate
	
	SELECT 1 AS MSG
	END
	ELSE IF(@rType = 2) -- Delete From Exception Table
	BEGIN 
		DELETE FROM [sSystem].[tExceptionLog] WHERE CAST(CreatedDateTime AS DATE) < @rDate
		SELECT 1 AS MSG
	END
	COMMIT TRANSACTION			 
	END TRY
	
	BEGIN CATCH 
		SELECT ERROR_MESSAGE() AS MSG
		ROLLBACK TRANSACTION		
	END CATCH	
END
GO
PRINT N'Altering [sSetup].[pOrganizationMasterGet]...';


GO
ALTER PROCEDURE [sSetup].[pOrganizationMasterGet]
	 
	 @rId int = 0,
	 @rCode nvarchar(20)='',
	 @rTitle nvarchar(100)='',
	 @rOrgGroupId smallint='',
	 @rIsSearch bit=0,
	 @rStatus nvarchar(5)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	 IF(@rIsSearch=1)
		BEGIN
			SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END


		DECLARE @lIsObsolete bit = 0
		If(@rStatus='1')
			SET @lIsObsolete = 0
		else If(@rStatus='2')
			SET @lIsObsolete = 1

		PRINT(@lIsObsolete)
		PRINT(@rStatus)
	 
	SELECT 
	
			OM.Id,
			OM.Code,
			OM.Title,
			OM.DisplayTitle,
			OM.AffiliationId,
			AM.Title AS AffiliationTitle,
			OM.LanguageId,
			LM.Title AS LanguageTitle,
			--OM.InstituteTypeId,
			--ITM.Title AS InstituteTypeTitle,
			--OM.InstituteSubTypeId,
			--ISTM.Title AS InstituteSubTypeTitle,
			OM.StreetOne,
			OM.StreetTwo,			 
			OM.StreetThree,
			OM.CityName,
			OM.StateName,
			OM.CountryName,
			OM.ZipCode,
			OM.HomePage,
			OM.PhoneNo,
			OM.FaxNo,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,			 
			OM.CreatedUserId,
			OM.CreatedDateTime,
			OM.UpdatedUserId,
			OM.UpdatedDateTime,
			OM.IsObsolete,
			OM.OrgGroupId,
			OM.OrgLogo,
			ISNULL(OM.WeekOffs,0) AS WeekOffs ,
			--OM.IcardOrgTitle,
			--OM.IcardAddress1,
			--OM.ICardAddress2,
			--OM.ICardAddress3,
			--OM.LabelColor,
			--OM.DetailColor,
			--OM.HeaderColor,
			ISNULL(OM.OrgSubGroupId,0) AS OrgSubGroupId, 
			--OB.Code AS BatchName,
			--OB.FromDate,
			--OB.ToDate,
			ISNULL(OM.EmployeeId,0) AS EmployeeId,
		    ISNULL(EM.Code,'') AS EmployeeCode,
		    ISNULL(EM.FirstName,'')+ ' ' + ISNULL(EM.MiddleName,'')+ ' ' + ISNULL(EM.LastName,'') AS EmployeeName,
			ISNULL(OM.OrderIndex,0) AS OrderIndex,
			ISNULL(OM.TermPatternId,0) AS TermPatternId,
			ISNULL(OM.StudentNameFormatId,0) AS NameFormateId,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			ISNULL(OM.DegreeAwarded,'') AS DegreeAwarded,
			ISNULL(OM.ShortCode,'') AS ShortCode,
			ISNULL(OM.NoOfTerm,'') AS NoOfTerm,
			ISNULL(OM.LetterHeadMargin,0) AS LetterHeadMargin,
			ISNULL(OM.University,'') AS University,
			ISNULL(OM.FooterSignature,'') AS FooterSignature,
			ISNULL(om.Email,'') AS  Email,
			ISNULL(OOD.TaxOfficeDetail,'') AS TaxOfficeDetail,
			ISNULL(OOD.TANNumber,'')TANNumber,
			ISNULL(OOD.PANNumber,'')PANNumber,
			ISNULL(OOD.TaxCertifyAuthorityName,'')TaxCertifyAuthorityName,
			ISNULL(OOD.TaxCertifyAuthorityFatherName,'')TaxCertifyAuthorityFatherName,
			ISNULL(OOD.TaxCertifyAuthorityRelation,'')TaxCertifyAuthorityRelation,
			ISNULL(OOD.TaxCertifyAuthorityDesignation,'')TaxCertifyAuthorityDesignation,
			ISNULL(OM.OrgTypeCaption,'') AS  OrgTypeCaption,
			ISNULL(OOD.AccountNumber,'') As AccountNumber,
			ISNULL(OOD.GSTINNo,'') As GSTINNo,
			ISNULL(OOD.HSNSACCode,'') As HSNSACCode,
			ISNULL(OM.EmployeeFirstWeekOffDayId,0) AS EmployeeFirstWeekOffDayId,
			ISNULL(OM.EmployeeFirstWeekOffRuleId,0) AS EmployeeFirstWeekOffRuleId,
			ISNULL(Om.EmployeeSecondWeekOffDayId,0)As EmployeeSecondWeekOffDayId,
			ISNULL(OM.EmployeeSecondWeekOffRuleId,0)As EmployeeSecondWeekOffRuleId,
			ISNULL(OM.StudentFirstWeekOffDayId,0)As StudentFirstWeekOffDayId,
			ISNULL(OM.StudentFirstWeekOffRuleId,0)As StudentFirstWeekOffRuleId,
			ISNULL(OM.StudentSecondWeekOffDayId,0)As StudentSecondWeekOffDayId,
			ISNULL(OM.StudentSecondWeekOffRuleId,0) As StudentSecondWeekOffRuleId,
			ISNULL(OOD.PFEstablishmentCode,'') As PFEstablishmentCode,
			ISNULL(OM.OrgHeader,'') As OrgHeader,
			ISNULL(OM.EmployeeNameFormatId,0) AS EmployeeNameFormatId
      
  FROM 
            sSetup.tOrganizationMaster OM
           INNER JOIN sSetup.tAffiliationMaster AM
				ON AM.Id=OM.AffiliationId
				INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
		  -- INNER JOIN sSetup.tInstituteTypeMaster ITM
				--ON ITM.Id=OM.InstituteTypeId
		  -- INNER JOIN sSetup.tInstituteSubTypeMaster ISTM
				--ON ISTM.Id=OM.InstituteSubTypeId
		   INNER JOIN sSetup.tLanguageMaster LM
				ON LM.Id=OM.LanguageId
		  -- INNER JOIN sSetup.tOrgGroupBatchMaster OB 
				--ON OB.OrgGroupId=OM.OrgGroupId 
		   LEFT JOIN sHrm.tEmployeeMaster EM 
				ON EM.Id = OM.EmployeeId AND EM.IsObsolete = 0
			LEFT JOIN sSetup.tOrganizationOtherDetail AS OOD on OOD.OrgId=OM.id
  WHERE 
  
        ((OM.Id = @rId) OR (@rId = 0))
		AND ((OM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND ((OM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
		AND ((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
		AND (OM.Id != 1)		
		 AND ISNULL(OGM.IsObsolete,0) = 0
		 AND ISNULL(EM.IsOtherUser,0) = 0
		 AND ((ISNULL(OM.IsObsolete,0) =  @lIsObsolete) OR (ISNULL(@rStatus,'')=''))
		
 ORDER BY OM.OrderIndex
END
GO
PRINT N'Creating [sAdmission].[pGetDropDownLists]...';


GO
  
CREATE PROCEDURE  [sAdmission].[pGetDropDownLists]
	-- Add the parameters for the stored procedure here
	@rOrgId int =0,
	@rOrgGroupId int = 0,
	@rUserId bigint,
	@rBatchId int = 0,
	@rClassId int = 0,
	@rType int = 0
AS
if(@rType = 1)
BEGIN
	declare  @lStatusRes nvarchar(max)='', @lOrganizationRes nvarchar(max)='',@lStatusdropdown nvarchar(max)=''
	declare @lGenderdropdown nvarchar(max)='',@lReligiondropdown nvarchar(max)='',@lcastdropdown nvarchar(max)=''
	declare @lblooddropdown nvarchar(max)='', @lClassRes nvarchar(max)='', @lDivisionRes nvarchar(max)=''
	declare @lSavedReport nvarchar(max)=''
	 
    -- Insert statements for procedure here

	
	select @lStatusRes = @lStatusRes + '<option value="1">Active</option>'
	select @lStatusRes = @lStatusRes + '<option value="2">InActive</option>'
	select @lStatusRes = @lStatusRes + '<option value="3">Left</option>'


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


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


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

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


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

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

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

	select @lSavedReport = @lSavedReport + '<option value="0"> -- Select -- </option>'
					select @lSavedReport =  @lSavedReport + '<option value="' + convert(varchar,SCS.Id)+ '">' + SCS.Title + '</option>'
					from sStudent.tStudentCustomSearch SCS
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
					LEFT JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId 
					WHERE (SCS.CreatedUserId = @rUserId) OR (SCS.IsCommon = 1) OR (SCS.IsCommonForOrg = 1)

	select  @lClassRes as ClassRes,@lDivisionRes as DivisionRes, @lStatusRes as StatusRes,@lGenderdropdown As Gendercheckboxlist,@lReligiondropdown As Religionchklist,@lcastdropdown as castcategorychklist,@lblooddropdown AS bloodgrpchklist,@lOrganizationRes as OrganizationRes,@lSavedReport AS SavedReportList
END	


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

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

		select @lBatchRes1 as BatchRes, @lclassdivRes as classdivRes
END

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

	select @lclassdropdown = @lclassdropdown + '<option value="' + convert( NVARCHAR,DivisionId) + '">' + REPLACE(ClassDivisionName, '''', '') + '</option>'
	from sSetup.vBatchClassDivision where IsObsolete = 0 and BatchId = @rBatchId order by OrderIndex
	
	select @lClassRes1 as ClassRes, @lclassdropdown as ClassCheckBoxList
END

if(@rType = 4)
BEGIN
declare @lDivisionRes1 nvarchar(max)=''
	select @lDivisionRes1 = @lDivisionRes1 + '<option value="0"> -- ALL -- </option>'
	select @lDivisionRes1 = @lDivisionRes1 + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sSetup.tDivisionMaster where IsObsolete = 0 and ClassId = @rClassId order by OrderIndex
	
	select @lDivisionRes1 as DivisionRes
END
GO
 
 
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('21.11.15',211115,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)

GO 
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('21.12.03',211203,'BEGIN','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO 
 
GO
PRINT N'Creating [sAdmission].[tAdmissionCustomSearch]...';


GO
CREATE TABLE [sAdmission].[tAdmissionCustomSearch] (
    [Id]                  INT            NULL,
    [Title]               NVARCHAR (50)  NOT NULL,
    [ColumnName]          NVARCHAR (MAX) NOT NULL,
    [OrderBy]             NVARCHAR (MAX) NOT NULL,
    [OrgId]               SMALLINT       NOT NULL,
    [BatchId]             INT            NOT NULL,
    [ClassId]             NVARCHAR (20)  NOT NULL,
    [FormNo]              NVARCHAR (20)  NOT NULL,
    [FromFormNo]          BIGINT         NULL,
    [ToFormNo]            BIGINT         NULL,
    [StatusId]            NVARCHAR (MAX) NOT NULL,
    [ClassIds]            NVARCHAR (MAX) NOT NULL,
    [FirstName]           NVARCHAR (50)  NOT NULL,
    [LastName]            NVARCHAR (50)  NOT NULL,
    [FatherName]          NVARCHAR (50)  NOT NULL,
    [MotherName]          NVARCHAR (50)  NOT NULL,
    [DOBFromDate]         DATE           NOT NULL,
    [DOBToDate]           DATE           NOT NULL,
    [DOAFromDate]         DATE           NOT NULL,
    [DOAToDate]           DATE           NOT NULL,
    [Country]             NVARCHAR (50)  NOT NULL,
    [State]               NVARCHAR (50)  NULL,
    [City]                NVARCHAR (50)  NOT NULL,
    [ContactNo]           NVARCHAR (50)  NULL,
    [GenderId]            NVARCHAR (MAX) NOT NULL,
    [ReligionId]          NVARCHAR (MAX) NOT NULL,
    [CastCategoryId]      NVARCHAR (MAX) NOT NULL,
    [Nationality]         NVARCHAR (MAX) NOT NULL,
    [BloodGroupId]        NVARCHAR (MAX) NOT NULL,
    [MotherTongueId]      NVARCHAR (MAX) NOT NULL,
    [PreviousSchool]      NVARCHAR (MAX) NOT NULL,
    [FatherQualification] NVARCHAR (MAX) NOT NULL,
    [MotherQualification] NVARCHAR (MAX) NOT NULL,
    [FatherOccupation]    NVARCHAR (MAX) NOT NULL,
    [MotherOccupation]    NVARCHAR (MAX) NOT NULL,
    [IsCommonUsers]       BIT            NOT NULL,
    [IsCommonForOrg]      BIT            NOT NULL,
    [CreatedUserId]       BIGINT         NOT NULL,
    [CreatedDateTime]     DATETIME       NOT NULL,
    [UpdatedUserId]       BIGINT         NULL,
    [UpdatedDateTime]     DATETIME       NULL
);


GO

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


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

IF(@rTypeId=1)
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CONVERT(VARCHAR(20),CS.SubjectCode,106) + ' - ' +
			(
			CASE  
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab , '
			WHEN  E.IsMarksInDecimal = 1 then
			CONVERT(VARCHAR(11),RD.Obtain)
			WHEN E.IsMarksInDecimal = 0 then
			CONVERT(VARCHAR(11),CAST(RD.Obtain AS INT))
			END)
			    + ' , '
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		 
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END
ELSE
BEGIN
	(SELECT @lResult  = COALESCE(@lResult ,'') 
			+ CONVERT(VARCHAR(11),CS.SubjectCode,106) + ' - ' +
			(
			CASE  
			WHEN RD.IsPresent IS NULL THEN ''
			WHEN RD.IsPresent = 0 THEN 'Ab'
			ELSE
			ISNULL(RD.SubjectGrade,'')
			END)
			    + ' , '
	FROM sAssessment.tResult R 
		INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId=R.Id
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster E ON R.ExamId = E.Id 
		INNER JOIN sSetup.vClassSubject CS ON CS.ClassSubjectId=ED.ClassSubjectId
		 
	WHERE
		R.Id=@rResultId
		AND ((CS.SubjectId=@rSubjectId) OR @rSubjectId=0)
		)
		
  SET @lResult = LEFT(@lResult, LEN(@lResult) - 1)
END
    RETURN @lResult 
END
GO
PRINT N'Altering [sPayroll].[vPayrollColumnName]...';


GO

 

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

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


GO

 
ALTER PROCEDURE [sAcademic].[pOnlineLearningAllStudentAttendanceAdd]
	
	@rStrXml nvarchar(MAX),
	@rEmployeeId bigint,
    @rAttendanceTypeId tinyint,
    --@rSubjectId int=0,
    @rRepeatCount tinyint=0,
    @rAttendanceGroupId int=0,
    --@rPeriodNo int=0 ,
	@rAbsentReasonId int=0,
	@rAttendanceRemark nvarchar(10)='',
	@rAttendanceTagId int=0,
	@rCreatedUserId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	
	IF EXISTS ( SELECT	
			1			
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				AttendanceDate Date,
				IsPresent bit,
				PeriodNo int,
				SubjectId bigint
				
			  ) A 
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId = A.AcademicId
		AND SR.AttendanceDate = A.AttendanceDate AND SR.SubjectId = A.SubjectId)
		BEGIN
          SELECT -101 AS Result
		END

		ELSE
		BEGIN
		
		INSERT INTO sAttendance.tStudentRegister 
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			AttendanceTagId,
			PeriodNo,
			AttendanceGroupId,
			AttendanceRemark
			)
		SELECT	
		DISTINCT	
			A.AcademicId,
			@rEmployeeId,
			@rAttendanceTypeId,
		    A.AttendanceDate,
			A.SubjectId,
			A.PeriodNo,
			--ISNULL(@rRepeatCount,0),
			A.IsPresent,
			ISNULL(@rAbsentReasonId,0),
			@rCreatedUserId,
			sCommon.fGetDate(),
			'',
			'',
			@rAttendanceTagId,
			A.PeriodNo,
			@rAttendanceGroupId,
			@rAttendanceRemark
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				AttendanceDate Date,
				IsPresent bit,
				PeriodNo int,
				SubjectId bigint
				
			  ) A 
		LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId = A.AcademicId
		AND SR.AttendanceDate = A.AttendanceDate AND SR.PeriodNo = A.PeriodNo
		AND SR.SubjectId = A.SubjectId
		WHERE SR.AcademicId IS NULL AND SR.AttendanceDate IS NULL AND SR.PeriodNo IS NULL
		AND SR.SubjectId IS NULL

		Select 1 AS Result
		END
END
GO
PRINT N'Altering [sAdmission].[pGetDropDownLists]...';


GO
  
ALTER PROCEDURE  [sAdmission].[pGetDropDownLists]
	-- Add the parameters for the stored procedure here
	@rOrgId int =0,
	@rOrgGroupId int = 0,
	@rUserId bigint,
	@rBatchId int = 0,
	@rClassId int = 0,
	@rType int = 0
AS
if(@rType = 1)
BEGIN
	declare  @lStatusRes nvarchar(max)='', @lOrganizationRes nvarchar(max)='',@lStatusdropdown nvarchar(max)=''
	declare @lGenderdropdown nvarchar(max)='',@lReligiondropdown nvarchar(max)='',@lcastdropdown nvarchar(max)=''
	declare @lblooddropdown nvarchar(max)='', @lClassRes nvarchar(max)='', @lDivisionRes nvarchar(max)=''
	declare @lSavedReport nvarchar(max)='', @lclassdropdown2 nvarchar(max)='', @lAvailableRes nvarchar(max)=''
	declare @lReportList nvarchar(max)=''
	 
    -- Insert statements for procedure here

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



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


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

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

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


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

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

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

	select @lSavedReport = @lSavedReport + '<option value="0"> -- Select -- </option>'
					select @lSavedReport =  @lSavedReport + '<option value="' + convert(varchar,ACS.Id)+ '">' + ACS.Title + '</option>'
					from sAdmission.tAdmissionCustomSearch ACS
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ACS.OrgId AND OM.OrgGroupId = @rOrgGroupId
					LEFT JOIN sSecurity.tUser U ON U.Id=ACS.CreatedUserId 
					WHERE (ACS.CreatedUserId = @rUserId) OR (ACS.IsCommonUsers = 1) OR (ACS.IsCommonForOrg = 1)
	
			 --SELECT 
			 --ISNULL(DM.Id,0) AS DisplayFieldId
			--,ISNULL(DM.Name,'') AS Name
			 -- ,ISNULL(DM.FieldSource,'') AS FieldSource 
			--,(CASE WHEN DO.DisplayFieldId Is Null THEN 'False'  ELSE 'True' END) AS Selected 
			--,(CASE WHEN DO.IsFieldMandatory Is Null THEN 'False' WHEN DO.IsFieldMandatory = 1 THEN 'True' ELSE 'False' END) AS IsMandatory 
      
			--FROM sConfig.tDisplayFieldMaster DM
			-- LEFT JOIN sConfig.tDisplayFieldOrg DO ON DM.Id=DO.DisplayFieldId
				--AND DO.OrgId=@rOrgId
			--WHERE (DM.FieldSource=@rFieldSource) 
			SET @lAvailableRes = @lAvailableRes + '<option value="1">Organization</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="2">Batch</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="3">FormNo</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="4">StudentName</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="5">Class</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="6">Gender</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="7">BirthDate</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="8">Status</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="9">City</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="10">MobileNo</option>'
			SET @lAvailableRes = @lAvailableRes + '<option value="11">ContactEmail</option>'
		   select @lAvailableRes = @lAvailableRes + '<option value="' + Convert(varchar(max), ISNULL(DM.Id,0)) + '">' + Convert(varchar(max),ISNULL(DM.Name,'')) + '</option>'
				FROM sConfig.tDisplayFieldMaster DM				
				WHERE (DM.FieldSource='Admission Form') 

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


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


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

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

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

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

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

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


GO
 
ALTER PROCEDURE [sAssessment].[pRptResultListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rDepartmentid int=0,
	 @rStatus int =1,
	 @rGenderId int,
	 @rClassStatusId int=0,
	 @rResultStatus nvarchar(20)='',
	 @rMultiCode nvarchar(max)='',
	 @rOrderBy int = 0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			Convert(nvarchar(20),A.Id) AS   AcademicIdText,	
	CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
	CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
	CONVERT (nvarchar(20),@rBatchId) AS BatchIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0))AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			SM.Code,
			  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			 DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			EM.IsMarksInDecimal,
			SI.StudentPhoto,
			EM.DisplayTitle,
			OM.SmallAddress1,
			R.ResultRemark,
			R.OtherRemark1,
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			SR.ResultRemark2,
			Em.GradeSetId,
			R.ResultStatus,
			SR.ResultRemark1,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			EI.EmployeeSign,
			EM.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsOnPrePrinted,
			Em.IsDisplayPhoto,
			SR.PresentDays ,			
			SR.TotalDays,
			EM.DecimalFormat,
			CM.Id AS ClassId,
			@rOrderBy AS OrderBy
      
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId=A.Id AND SR.ExamId = EM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			
			 
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (EM.ClassId=@rClassId OR @rClassId=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 ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		AND ((A.Id =@rAcademicId) OR (@rAcademicId=0))
		
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		ANd SM.StatusId= @rStatus
		AND ((SO.GenderId=@rGenderId) OR (@rGenderId=0))
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND (ISNULL(SM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')

		ORDER BY 
			CASE @rOrderBy WHEN 0 THEN SM.Code END , 
			CASE @rOrderBy WHEN 1 THEN R.RankNumber END , 
			CASE @rOrderBy WHEN 2 THEN A.RollNo END, 
			CASE @rOrderBy WHEN 3 THEN SM.FirstName END,
			CASE @rOrderBy WHEN 4 THEN R.TotalObtain END
			
END
GO
PRINT N'Altering [sBiometric].[pBiometricDailyReportGet]...';


GO
 
 
ALTER PROCEDURE [sBiometric].[pBiometricDailyReportGet]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 0,	
	 @rStatus nvarchar(max) = '',
	 @rEmployeeStatusId int=0,
	 @rOrderBy smallint = 0,
	 @rOrgGroupId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
DECLARE  @rToDate Date
SET @rToDate = @rFromDate

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 
AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
AND ISNULL(EM.IsOtherUser,0) = 0 

DECLARE @lCount int
DECLARE @lCount1 int
Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lMonth as nvarchar(3)
DECLARE @lYear as nvarchar(4)

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)
		Select @lMonth = RIGHT('00' + CAST(DATEPART(MM,@lDate) AS varchar(2)), 2)
		Select @lYear  = RIGHT('0000' + CAST(DATEPART(yyyy,@lDate) AS varchar(4)), 4)
		
		set @lQuery = 'INSERT INTO #TempMonthTrans
						SELECT Distinct ' + convert(nvarchar(15),@lEmployeeId) + ',''' + convert(nvarchar(15),@lDate) + ''',
						substring(DATENAME( dw, ''' + convert(nvarchar(15),@lDate) + '''),1,3) AS DN1,
											 

											 CASE When [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', ' + convert(nvarchar(10),@lYear) + ',' + convert(nvarchar(10),@lMonth) + ',' + convert(nvarchar(15),@lDay)+',
											 ' + convert(nvarchar(15),@lBatchId) + ',' + Convert(nvarchar(10),@rOrganizationDepartmentId) + ',' + convert(nvarchar(10),@rOrgId) + ') <> ''-'' then 
											 [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', ' + convert(nvarchar(10),@lYear) + ',' + convert(nvarchar(10),@lMonth) + ',' + convert(nvarchar(15),@lDay)+',
											 ' + convert(nvarchar(15),@lBatchId) + ',' + Convert(nvarchar(10),@rOrganizationDepartmentId) + ',' + convert(nvarchar(10),@rOrgId) + ') 
											 else D'+convert(nvarchar(15),@lDay)+' end AS 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)'
						--print @lQuery
			execute (@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1	
	END
	
	
	--Select * from #TempMonthTrans
	--return
	

	SET @strQuery = 'select Day(T.Attn_Date), T.*,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	Emp.Code AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,''' +CAST(@rOrderBy AS NVARCHAR(3)) + ''' AS OrderBy,
	DM.Displaytitle DeptName, Emp.Number AS Number,	OM.Id AS OrgId, OM.Title AS OrganizationTitle
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0 
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Emp.OrgID
	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 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 PresentStatus IN ' + @rStatus + ' AND (T.EmployeeId = ' + convert(nvarchar(15),@rEmployeeId) + ' OR ' + convert(nvarchar(15),@rEmployeeId) + ' = 0)
	AND (OM.OrgGroupId = ' + convert(nvarchar(15),@rOrgGroupId) + ') Order By T.Attn_Date,T.EmployeeId'
	--WHERE (PresentStatus IN '+ '''' + @rStatus + '''' + ' OR (PresentStatus like ''%L%'')) Order By T.Attn_Date,T.EmployeeId' 


	--WHERE 1=1 and (ED.EmployeeGradeId in (' + convert(nvarchar(100),@rGRadeId) + ') OR (' + convert(nvarchar(100),@rGRadeId) + ') = 0) )' 
	
	
	print (@strQuery)
	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 TotEarly,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as IsFirstIn,
	--'' as IsLastOut,
	--'' as IsOT,
	--'' as IsLateBy,
	--'' as IsEarlyBy,
	--'' as IsDuration,
	--'' as OrderBy,
	--'' as Number,
	--'' as OrgId,
	--'' as OrganizationTitle
END

	--CASE 
	--					When [sHrm].[fWeekHOffGetBio](' + 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) + ') in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
	--					When [sHrm].[fWeekHOffGetBio](' + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',' + CONVERT(nvarchar(13),@rOrganizationDepartmentId) + ',' + convert(nvarchar(15),@rOrgId) + ') Not in (''-'',''XX'') 
	--					Then [sHrm].[fWeekHOffGetBio](' + 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
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 sAlumni.tStudentMapping WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tUserFeedback WHERE CAST(LEFT(UserId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeExpense WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId


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

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

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

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

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


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

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


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

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


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

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


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

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

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

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


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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

DELETE FROM sAdmission.tAdmissionCustomSearch WHERE OrgId = @rOrgId


--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 [sFee].[pAccountMappingGet]...';


GO

ALTER PROCEDURE [sFee].[pAccountMappingGet]
				
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='', 
		   @rClassId int,
           @rAdmissionCategoryId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptBookId int,
		   @rPayTypeId int = 0
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			ISNULL(FS.Id,0)AS FeeSetupId,
			ISNULL(AM.FeeSetupId,0)AS AMFeeSetupId,
			ISNULL(FS.ClassId,0)AS ClassId,
			ISNULL(CM.Title,'') AS ClassName,
			ISNULL(FS.AdmissionCategoryId,0) AS AdmissionCategoryId,
			ISNULL(FS.BatchId,0)AS BatchId,
			ISNULL(FM.Id,0)AS FeeId,
			ISNULL(FM.Title,'') AS FeeTitle,
			ISNULL(FHM.Id,0) AS FeeHeadId,
			ISNULL(FHM.Title,'') AS FeeHeadName,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(AYM.AccountId,0) AS AccountId,
			ISNULL(AM.CreditLedgerId,0) AS CreditLedgerId,
			ISNULL(AM.DebitLedgerId,0) AS DebitLedgerId,
			ISNULL(AM.AccountingYearId,0) AS AccountingYearId,
			ISNULL(AM.PayTypeId,0) AS AMPayTypeId,
			ISNULL(PTM.Id,0) AS PayTypeId,
			ISNULL(PTM.Title,'') AS PayTypeName
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId 
		AND (FS.ClassId=@rClassId) AND (FS.AdmissionCategoryId=@rAdmissionCategoryId) AND (FS.BatchId=@rBatchId)
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId AND (RBM.Id = @rReceiptBookId OR @rReceiptBookId=0)
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=FS.ClassId		
		CROSS JOIN (SELECT PTM.Id,PTM.Title FROM sFinanceCommon.tPayTypeMaster PTM WHERE (PTM.Id = @rPayTypeId OR @rPayTypeId = 0)) PTM
		LEFT JOIN sFee.tAccountMapping AM ON AM.FeeSetupId=FS.Id AND AM.PayTypeId=PTM.Id
		LEFT JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
		LEFT JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=CLM.AccountingYearId AND AYM.Id=DLM.AccountingYearId
WHERE 
		FM.OrgGroupId=@rOrgGroupId		
ORDER BY FM.OrderIndex,PTM.Id

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


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

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


GO
 
 
ALTER PROCEDURE [sFee].[pFeeSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rBatchId int=0,
	@rDepartmentId int =0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'FeeList')
		BEGIN
			SELECT COUNT(SA.AcademicId)AS TotalCount,COUNT(T.PaidCount) AS PaidCount,(COUNT(SA.AcademicId)-COUNT(T.PaidCount))AS UnPaidCount
			, COUNT(PS.AcademicId) AS PartialCount
			FROM sStudent.vStudentAcademic SA 
			LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,SA.AcademicId AS AcademicId FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId
			)T ON T.AcademicId = SA.AcademicId 

			LEFT JOIN 
			(
				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 0
					AND ISNULL(FS1.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.Amount,0.00) > 0
					
				UNION 

				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 1
					AND ISNULL(FS1.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.Amount,0.00) > 0
					
			) PS ON PS.AcademicId=SA.AcademicId

			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND SA.StatusId =1
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))	
		END
	ELSE IF(@rType = 'FeeGraph')
		BEGIN
			SELECT CM.Id,CM.Title,ISNULL(T.TotalCount,0)AS TotalCount,COUNT(T1.PaidCount) AS PaidCount,(ISNULL((T.TotalCount),0)-COUNT(T1.PaidCount))AS UnPaidCount,CM.OrderIndex
		FROM sStudent.vStudentAcademic SA
			LEFT JOIN sSetup.tClassMaster CM ON  CM.Id = SA.ClassId
			LEFT JOIN 
			(SELECT COUNT(AcademicId) AS TotalCount,ClassId AS ClassId FROM sStudent.vStudentAcademic
			WHERE ((OrgId=@rOrgId)OR(@rOrgId=0)) AND ((BatchId=@rBatchId) OR (@rBatchId=0))AND StatusId =1
			GROUP BY ClassId
			)T ON T.ClassId = CM.Id	
			LEFT JOIN(
			SELECT COUNT(SA.AcademicId)as PaidCount,SA.AcademicId AS AcademicId,SA.ClassId AS ClassId FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			LEFT JOIN sSetup.tClassMaster CM ON  CM.Id = SA.ClassId
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))AND SA.StatusId =1
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId,SA.ClassId
			)T1 ON T1.AcademicId = SA.AcademicId  AND CM.Id = SA.ClassId
			WHERE ((CM.OrgId =@rOrgId)OR(@rOrgId=0))
			AND SA.StatusId =1
			GROUP BY CM.Title, CM.Id,T.TotalCount,CM.OrderIndex
			ORDER BY CM.OrderIndex
		END
	ELSE IF (@rType = 'FeeListDetails')
		BEGIN
		SELECT SA.RollNo,SA.Name,SA.Code, ISNULL(T.AcademicId,0) AS Pending, ISNULL(PS.AcademicId,0) AS [Partial],'' AS [Status]
			FROM sStudent.vStudentAcademic SA 
			LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,SA.AcademicId AS AcademicId, SA.Code,SA.Name FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId, SA.Code,SA.Name
			)T ON T.AcademicId = SA.AcademicId
			LEFT JOIN 
			(
				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 0
					AND ISNULL(FS1.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.Amount,0.00) > 0
					
				UNION 

				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
				SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
				FROM sFee.tReceiptDetail RD
				INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				WHERE R.SourceTypeId = 2001
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				Group By R.SourceId,FS.Id
				) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
				SELECT Distinct SourceId 
				FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 1
					AND ISNULL(FS1.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.Amount,0.00) > 0
					
			) PS ON PS.AcademicId=SA.AcademicId


			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND SA.StatusId =1
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))	 			
		END
END
GO
PRINT N'Altering [sFee].[pMyFeeGet]...';


GO
  
-- exec [sFee].[pMyFeeGet] 1201000000102,2001,120100001,0,'CollectionGroup'  
ALTER PROCEDURE [sFee].[pMyFeeGet]    
      
  @rSourceId bigint ,  --1201000000102  
  @rSourceTypeId int,  --2001  
  @rBatchId int,  --120100001  
  @rStudentId bigint =0,  
  @rDisplay varchar(20)=''  
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    BEGIN      
 if (@rStudentId <> 0)    
 SELECT @rSourceId = Id, @rSourceTypeId = 2001 FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId    
  DECLARE @lClassId int    
  DECLARE @lAdmissionCategoryId int    
  SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId    
    
  -----------------------------------------------------------------------------------------------------------------------------------------  
  
  create table #TempTable  
  (id int identity(1,1),Feeid bigint,FeeName nvarchar(100),FeeSetupId bigint,isOptional tinyint,IsVariable tinyint,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),  
  NotApplicableAmount decimal(12,2),Remark Varchar(Max),OrderIndex int,ReceiptNumber int,ReceiptDate Date,ReceiptBookId bigint,CollectionGroupId Bigint,  
  Col_StartDate Date,Col_EndDate Date,CollectionGroup varchar(100),FeeHeadid Bigint,FeeHead nvarchar(100),FeeDuration Varchar(100))  
  
  
  Insert into #TempTable  
  
SELECT     
   FM.Id AS FeeId,    
   FM.Title AS FeeName,    
   FS.Id AS FeeSetupId,    
   ISNULL(FS.IsOptional,0)AS IsOptional,    
   ISNULL(FS.IsVariable,0)AS IsVariable,    
   ISNULL(FS.Amount,0)AS Amount,    
   ISNULL(FS.StartDate,'1900-01-01')AS StartDate,    
   ISNULL(FS.EndDate,'1900-01-01')AS EndDate,    
   ISNULL(FA.VariableAmount,0.00)AS FAAmount,    
   ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,    
   ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,    
   ISNULL(R.PaidAmount,0) AS PaidAmount,    
   ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,    
   ISNULL(FA.NotApplicableAmount,0.00) AS NotApplicableAmount,    
   ISNULL(FA.Remark,'') AS Remark,    
   FM.OrderIndex,    
   0 AS ReceiptNumber,    
   '1900-01-01'AS ReceiptDate,    
   ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,    
   ISNULL(FS.CollectionGroupId,0) AS CollectionGroupId,  
   ISNULL(CGM.StartDate,'') as Col_StartDate,  
 ISNULL(CGM.EndDate,'') as Col_EndDate,  
   ISNULL(CGM.Title,'') AS CollectionGroup,    
   FM.FeeHeadId,    
   FHM.Title AS FeeHead,    
   FS.FeeDuration    
  FROM     
   sFee.tFeeMaster FM    
  INNER JOIN     
  (    
   SELECT     
    FS1.FeeId,    
    FS1.Id,    
    ISNULL(FS1.IsOptional,0)AS IsOptional,    
    ISNULL(FS1.IsVariable,0)AS IsVariable,    
    ISNULL(FS1.Amount,0)AS Amount,    
    ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,    
    ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,    
    FS1.BatchId,    
    ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,    
    ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,  
    ISNULL(FS1.FeeDuration,'')  AS FeeDuration    
   FROM sFee.tFeeSetup FS1    
          
    WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0    
    AND FS1.BatchId = @rBatchId    
    UNION ALL    
        
   SELECT     
    FS1.FeeId,    
    FS1.Id,    
    ISNULL(FS1.IsOptional,0)AS IsOptional,    
    ISNULL(FS1.IsVariable,0)AS IsVariable,    
    ISNULL(FS1.Amount,0)AS Amount,    
    ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,    
    ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,    
    FS1.BatchId,    
    ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,    
    ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId ,   
    ISNULL(FS1.FeeDuration,'') AS FeeDuration    
         
   FROM sFee.tFeeSetup FS1    
        
  INNER JOIN sFee.tFeeOptional FO    
   ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND(FO.SourceTypeId=@rSourceTypeId)    
   WHERE    
    FS1.BatchId = @rBatchId    
   AND FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1    
  ) FS ON FS.FeeId=FM.Id    
  INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId    
  LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId    
  LEFT JOIN sFee.tFeeAllocation FA    
   ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)    
  LEFT JOIN    
  (    
      SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId    
      FROM    
      sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id       
   WHERE          
    R.SourceId= @rSourceId    
   AND ((R.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))    
   AND R.IsObsolete = 0     
   AND R.BatchId = @rBatchId    
    GROUP BY FeeSetupId    
  ) R ON R.FeeSetupId = FS.Id     
WHERE     
 FS.BatchId=@rBatchId    
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC   
   
 --------------------------------------------------------------------------------------------  
 -- Get Group Wise Data ---  
  
 IF(@rDisplay = 'Fee Head')  
 BEGIN  
 Print @rDisplay + '1'  
   
 Create Table #temp_head  
 (id int identity(1,1),FeeHeadid Bigint,FeeHead nvarchar(200),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),  
 NotApplicableAmount decimal(12,2))  
  
 Insert into #temp_head  
 select FeeHeadid,FeeHead,sum(Amount) as Amount,min(StartDate) as StartDate,Max(EndDate) as EndDate,sum(FAAmount) as FAAmount,  
 sum(DiscountAmount) as DiscountAmount,sum(AdditionalAmount) as AdditionalAmount,sum(PaidAmount) as PaidAmount,  
 sum(PendingAmount) as PendingAmount,sum(NotApplicableAmount) as NotApplicableAmount--,Remark,ReceiptDate,ReceiptBookId,CollectionGroupID,CollectionGroup  
 from #TempTable  
 group by Feeheadid,FeeHead  
  
 Declare @i int  
  
 while(@i<= (Select Count(*) from #temp_head))  
 BEGIN  
 Update #temp_head set StartDate = (Select min(StartDate) from #tempTable A Where A.FeeHeadid = #temp_head.FeeHeadid) where id=@i  
 Update #temp_head set EndDate = (Select Max(EndDate) from #tempTable A Where A.FeeHeadid = #temp_head.FeeHeadid) where id=@i  
 PRINT 1  
 END  
  
 select FeeHeadid as Feeid,FeeHead as FeeName,PendingAmount,'' as IsVariable,  
 '' as FeeSetupId,'' as Remark,'' as ReceiptNumber,'' as ReceiptDate,'' as CollectionGroupId,FeeHeadid,0 as IsOptional,  
 (case when FAAmount>0 then FAAmount else Amount + AdditionalAmount - DiscountAmount - NotApplicableAmount End) as Amount ,  
 StartDate,EndDate,FAAmount,DiscountAmount,AdditionalAmount,PaidAmount,PendingAmount,NotApplicableAmount,'' as FeeDuration from #temp_head  
   
 END  
  
 ELSE IF(@rDisplay = 'Collection Group')  
 BEGIN  
  
 select CollectionGroupID as Feeid,CollectionGroup as FeeName, sum(PendingAmount) as PendingAmount,CollectionGroupID as FeeHeadid,  
 '' as IsVariable,'' as FeeSetupId,'' as Remark,'' as ReceiptNumber,'' as ReceiptDate,'' as CollectionGroupId,0 as IsOptional,  
 (case when sum(FAAmount)>0 then sum(FAAmount) else sum(Amount) + sum(AdditionalAmount) - sum(DiscountAmount) - sum(NotApplicableAmount) End) as Amount ,  
 Col_startDate as StartDate,Col_EndDate as EndDate,sum(FAAmount) as FAAmount,sum(DiscountAmount) as DiscountAmount,  
 sum(AdditionalAmount) as AdditionalAmount,sum(PaidAmount) as PaidAmount,sum(PendingAmount) as PendingAmount,  
 sum(NotApplicableAmount) as NotApplicableAmount,'' as FeeDuration from #TempTable  
 group by CollectionGroupID,CollectionGroup,Col_startDate,Col_EndDate  
  
 END  
  
 ELSE  
 BEGIN  
  
 select CollectionGroupID as Feeid,FeeName,PendingAmount,   
 '' as IsVariable,'' as FeeSetupId,'' as Remark,'' as ReceiptNumber,'' as ReceiptDate,'' as CollectionGroupId,0 as IsOptional,  
 CollectionGroupID as FeeHeadid,  
 (FAAmount + Amount + AdditionalAmount) - (DiscountAmount + NotApplicableAmount) as Amount ,  
 StartDate,EndDate,FAAmount,DiscountAmount, AdditionalAmount,PaidAmount,PendingAmount,NotApplicableAmount,'' as FeeDuration from #TempTable  
  
 END  
  
END
GO
PRINT N'Altering [sFee].[pRptFeeSummaryGet]...';


GO

 
ALTER PROCEDURE [sFee].[pRptFeeSummaryGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	
	IF(@rReportId=20624)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status
			
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo
	END
	ELSE IF (@rReportId=20842 OR @rReportId=10150 OR @rReportId=30714 OR @rReportId=30831)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status
			
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			INNER JOIN sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo
	END
	ELSE IF(@rReportId=30655)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  ISNULL(FA.NotApplicableAmount,0) > 0) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo
	END
	ELSE IF(@rReportId=30799)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R1.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(R1.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			ISNULL(R2.TotalReceiptAmount,0.00) AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId,R.TotalReceiptAmount
			
			) R1 ON R1.FeeSetupId = FS.Id AND SA.AcademicId = R1.SourceId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 1) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId,R.TotalReceiptAmount
			
			) R2 ON R2.FeeSetupId = FS.Id AND SA.AcademicId = R2.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo 
	END
	ELSE IF(@rReportId=30825)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					--AND (tSA.AdmissionDate <= @rUptoDate)
					AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA1.StatusId = 1))
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			--AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		--AND (tSA.AdmissionDate <= @rUptoDate)
		AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA.StatusId = 1))
		 --AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo 
	END
	--ELSE IF(@rReportId=30821)
	--BEGIN
	--	SELECT 
	--		@rBuilder1 AS Builder1,
	--		@rBuilder2 AS Builder2,
	--		@rIsDetail AS IsDetail,
	--		@rIsFilter As IsFilter,
	--		@rIsHeader As IsHeader, 
	--		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
	--		SA.AcademicId,
	--		SA.RollNo,
	--		SA.Name,
	--		SA.Code,
	--		SA.ClassId,
	--		SA.DivisionId,
	--		SA.ClassName,
	--		SA.DivisionName,
	--		SA.DivisionOrder AS DivisionOrderIndex,
	--		SA.ClassOrderIndex AS ClassOrderIndex,
	--		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
	--		FS.Id AS FeeSetupId,
	--		ISNULL(FS.IsVariable,0)AS IsVariable,
	--		ISNULL(FS.Amount,0)AS Amount,
	--		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
	--		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
	--		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
	--		ISNULL(R.DiscountAmount,0.00)AS DiscountAmount,
	--		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
	--		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
	--		ISNULL(R.PaidAmount,0) AS PaidAmount,
	--		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
	--		ISNULL(FA.Remark,'') AS Remark,
	--		FS.ReceiptBookId,
	--		FS.FeeName,
	--		FS.FeeCode,
	--		SA.OrgId,
	--		O.DisplayTitle AS OrgName,
	--		O.OrderIndex AS OrgOrderIndex,
	--		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
	--		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
	--		SA.DepartmentId,
	--		SA.DepartmentName,
	--		SA.ExemptionTypeId,
	--		ISNULL(ETM.Title,'') AS ExemptionType,
	--		FHM.Id AS FeeHeadId,
	--		FHM.Title AS FeeHeadName,
	--		FHM.OrderIndex AS FeeHeadOrderIndex,
	--		@rFeeGroupId As FeeGroup,
	--		SA.OrgGroupBatchId AS BatchId,
	--		SA.BatchName AS BatchName,
	--		0.00 AS CancelAmount,
	--		(Select ISNULL(SUM(R.DiscountAmount),0) FROM  sFee.tReceipt R Where R.SourceId=SA.AcademicId)AS Discount
	--  FROM 
	--		sStudent.vStudentAcademic SA
	--		INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
	--		INNER JOIN 
	--		(
	--			SELECT 
	--				FS1.FeeId,
	--				FS1.Id,
	--				ISNULL(FS1.IsOptional,0)AS IsOptional,
	--				ISNULL(FS1.IsVariable,0)AS IsVariable,
	--				ISNULL(FS1.Amount,0)AS Amount,
	--				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
	--				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
	--				FS1.BatchId,
	--				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
	--				SA1.AcademicId,
	--				FM.Title AS FeeName,
	--				FM.Code AS FeeCode,
	--				FM.FeeHeadId
	--			FROM sFee.tFeeSetup FS1
	--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	--			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
	--			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	--			WHERE 
	--				((FS1.ClassId=@rClassId) OR (@rClassId=0))
	--				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	--				AND (FS1.IsOptional=0)
	--				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--				UNION ALL
					
	--			SELECT 
	--				FS1.FeeId,
	--				FS1.Id,
	--				ISNULL(FS1.IsOptional,0)AS IsOptional,
	--				ISNULL(FS1.IsVariable,0)AS IsVariable,
	--				ISNULL(FS1.Amount,0)AS Amount,
	--				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
	--				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
	--				FS1.BatchId,
	--				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
	--				SA1.AcademicId,
	--				FM.Title AS FeeName,
	--				FM.Code As FeeCode,
	--				FM.FeeHeadId
	--			FROM sFee.tFeeSetup FS1
	--		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	--		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
	--		AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	--			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
	--			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--		WHERE
	--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
	--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	--			AND (FS1.IsOptional=1)
	--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
	--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
	--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--			AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
	--		) FS ON FS.AcademicId=SA.AcademicId
	--		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
	--		LEFT JOIN
	--		(
	--			SELECT 
	--					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,R.DiscountAmount
	--			FROM
	--					sFee.tReceipt R 
	--				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
	--				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
	--				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
	--				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
	--				INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
	--				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
	--				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
	--			WHERE		
	--				(R.SourceTypeId = 2001)
	--				AND (R.IsObsolete = 0) 
	--				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	--				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	--				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--				AND (R.ReceiptDate <= @rUptoDate)
	--				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
	--				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	--				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
	--				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--				--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--				AND (tSA.AdmissionDate <= @rUptoDate)
	--					GROUP BY FeeSetupId,R.SourceId,R.DiscountAmount
			
	--		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
	--		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
	--		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
	--		 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
	--		 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
	--		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	--		 LEFT JOIN
	--		(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
	--		INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
	--		INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
	--		ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	--		WHERE	
	--		((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
	--		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
	--		AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
	--		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--		--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	--		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--		AND ((SA.Code=@rCode) OR (@rCode=''))
	--		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	--		AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	--		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	--		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	--		 AND (
	--				 (@rFilterId = 0) -- All
	--				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
	--				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
	--				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
	--				 )	
	--	AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
	--	AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--	--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--	AND (tSA.AdmissionDate <= @rUptoDate)
	--	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
	--	Order by SA.RollNo 
	--END
	ELSE IF(@rReportId=30920)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.StatusId,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

			--CASE WHEN ISNULL(DiscountRemark,'') ='' THEN ''
			--ELSE
			(STUFF((SELECT  ','+DiscountRemark	FROM sFee.tFeeAllocation WHERE SourceId = FA.SourceId	
			ORDER BY DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) as ExampltedRemark,

			''  AdditionalRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
			AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
			AND (tSA.AdmissionDate <= @rUptoDate)
		Order by SA.RollNo
	END

	ELSE
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.StatusId,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

			CASE WHEN ISNULL(DiscountRemark,'') ='' THEN ''
			ELSE
			(STUFF((SELECT  ','+DiscountRemark	FROM sFee.tFeeAllocation WHERE SourceId = FA.SourceId	
			ORDER BY DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) END as ExampltedRemark,

			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId) END  as ExampltedRemark,

			--CASE WHEN ISNULL(FA.AdditionalRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,3) END as AdditionalRemark,
			''  AdditionalRemark,
			--CASE WHEN ISNULL(FA.NotApplicableRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,4) END as NotApplicableRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo
	END
	
	
	
END
GO
PRINT N'Altering [sPayroll].[pPayrollGenerateReport]...';


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

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

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


GO
 
ALTER PROCEDURE [sRecruitment].[pCandidateDetailExportGet]
(
		@rOrgGroupID smallint, 
		@rVacancyId int=0,		
		@rCandidateNumber int=0, 
		@rFirstName nvarchar(100), 
		@rLastName nvarchar(100),
		@rRecruitmentStatusId smallint,
		@rFromDate date=null,
		@rToDate date=null ,
		@rIsQualificationDetail bit = 0
		
	
 )
AS
SET NOCOUNT ON

BEGIN
 
 		--SET @rCandidateNumber = ISNULL( sCommon.fSearchStringGet(@rCandidateNumber),0)
		SET @rFirstname = ISNULL( sCommon.fSearchStringGet(@rFirstname),'')
		SET @rLastName = ISNULL( sCommon.fSearchStringGet(@rLastName),'')
		
		IF(@rIsQualificationDetail = 0)
		BEGIN
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				--RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				--RSL.RecruitmentStatusId AS RecruitmentStatusId
				CM.RecruitmentStatusId,
				GM.Title AS Gender,
				ISNULL(MS.Title,'') AS MaritalStatus,
				ISNULL(RM.Title,'') AS Religion,
				ISNULL(CCM.Title,'') AS CastCategory,
				ISNULL(CM.FamilyCast,'') AS FamilyCast,
				ISNULL(CM.Qualification,'')AS Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				CM.LastDrawnSalary,
				CM.ExpectedSalary,
				ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
				ISNULL([PresentStreetOne],'') AS PresentStreetOne,
				ISNULL([PresentStreetTwo],'') AS PresentStreetTwo,
				ISNULL([PresentStreetThree],'') AS PresentStreetThree,
				ISNULL([PresentCountry],'') AS PresentCountry,
				ISNULL([PresentState],'') AS PresentState,
				ISNULL([PresentCity],'') AS PresentCity,
				ISNULL([PresentZipCode],'') AS PresentZipCode,
				ISNULL([PresentContactNo],'') AS PresentContactNo,
				ISNULL([PermanentStreetOne],'') AS PermanentStreetOne,
				ISNULL([PermanentStreetTwo],'') AS PermanentStreetTwo,
				ISNULL([PermanentStreetThree],'') AS PermanentStreetThree,
				ISNULL([PermanentCountry],'') AS PermanentCountry,
				ISNULL([PermanentState],'') AS PermanentState,
				ISNULL([PermanentCity],'') AS PermanentCity,
				ISNULL([PermanentZipCode],'') AS PermanentZipCode,
				ISNULL([PermanentContactNo],'') AS PermanentContactNo,
				CM.CreatedDateTime,
				CM.MainSubject,
				ISNULL(DM.Title,'') AS Reference,
				ISNULL(OM.Title,'') AS Organization
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			
			INNER JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id		
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id = CM.MaritalStatusId	
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId
			LEFT JOIN sRecruitment.tCandidateCommunications CC ON CC.CandidateId = CM.Id
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id = CM.ReferenceId AND DM.DataTypeId = 13 AND DM.IsObsolete = 0
			LEFT JOIN sRecruitment.tAssignOrganization AO ON AO.VacancyId = CM.VacancyId AND AO.OrgId = CM.OrgId
			LEFT JOIN sSetup.tOrganizationMaster OM ON AO.OrgId = OM.Id

		WHERE 
		--RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
		--		AND
				((CM.CandidateNumber=@rCandidateNumber ) OR (@rCandidateNumber = 0))
			AND ((CM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((CM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((VM.Id = @rVacancyId) OR (@rVacancyId = 0))	
			AND ((CM.RecruitmentStatusId = @rRecruitmentStatusId) OR (@rRecruitmentStatusId = 0))	
			AND CM.OrgGroupID = @rOrgGroupID
			AND ((CONVERT(date,CM.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,CM.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
			ORDER BY CM.CandidateNumber
		END
		ELSE
		BEGIN
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				--RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				--RSL.RecruitmentStatusId AS RecruitmentStatusId
				CM.RecruitmentStatusId,
				GM.Title AS Gender,
				ISNULL(MS.Title,'') AS MaritalStatus,
				ISNULL(RM.Title,'') AS Religion,
				ISNULL(CCM.Title,'') AS CastCategory,
				ISNULL(CM.FamilyCast,'') AS FamilyCast,
				ISNULL(CM.Qualification,'')AS Qualification,
				CM.MobileNo,
				CM.PersonalEmail,
				CM.LastDrawnSalary,
				CM.ExpectedSalary,
				ISNULL(CM.AdditionalRemark,'')AS AdditionalRemark,
				ISNULL([PresentStreetOne],'') AS PresentStreetOne,
				ISNULL([PresentStreetTwo],'') AS PresentStreetTwo,
				ISNULL([PresentStreetThree],'') AS PresentStreetThree,
				ISNULL([PresentCountry],'') AS PresentCountry,
				ISNULL([PresentState],'') AS PresentState,
				ISNULL([PresentCity],'') AS PresentCity,
				ISNULL([PresentZipCode],'') AS PresentZipCode,
				ISNULL([PresentContactNo],'') AS PresentContactNo,
				ISNULL([PermanentStreetOne],'') AS PermanentStreetOne,
				ISNULL([PermanentStreetTwo],'') AS PermanentStreetTwo,
				ISNULL([PermanentStreetThree],'') AS PermanentStreetThree,
				ISNULL([PermanentCountry],'') AS PermanentCountry,
				ISNULL([PermanentState],'') AS PermanentState,
				ISNULL([PermanentCity],'') AS PermanentCity,
				ISNULL([PermanentZipCode],'') AS PermanentZipCode,
				ISNULL([PermanentContactNo],'') AS PermanentContactNo,
				CM.CreatedDateTime,
				CM.MainSubject,
				ISNULL(DM.Title,'') AS Reference,
				ISNULL(OM.Title,'') AS Organization,
				ISNULL(CQ.ExamPassed,'') AS ExamPassed,
				ISNULL(CQ.PassYear,'') AS PassYear,
				CQ.Percentage,
				ISNULL(CQ.Grade,'') AS Grade,
				ISNULL(CQ.InstituteDetail,'') AS InstituteDetail,
				ISNULL(CQ.BoardDetail,'') AS BoardDetail,
				ISNULL(CQ.Subjects,'') AS Subjects,
				ISNULL(CQ.Remark,'') AS Remark
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			
			INNER JOIN sCommon.tGenderMaster GM ON CM.GenderId = GM.Id		
			LEFT JOIN sCommon.tMaritalStatusMaster MS ON MS.Id = CM.MaritalStatusId	
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = CM.ReligionId
			LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = CM.CastCategoryId
			LEFT JOIN sRecruitment.tCandidateCommunications CC ON CC.CandidateId = CM.Id
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id = CM.ReferenceId AND DM.DataTypeId = 13 AND DM.IsObsolete = 0
			LEFT JOIN sRecruitment.tAssignOrganization AO ON AO.VacancyId = CM.VacancyId AND AO.OrgId = CM.OrgId
			LEFT JOIN sSetup.tOrganizationMaster OM ON AO.OrgId = OM.Id
			LEFT JOIN sRecruitment.tCandidateQualification CQ ON CQ.CandidateId = CM.Id

		WHERE 
		--RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
		--		AND
				((CM.CandidateNumber=@rCandidateNumber ) OR (@rCandidateNumber = 0))
			AND ((CM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((CM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((VM.Id = @rVacancyId) OR (@rVacancyId = 0))	
			AND ((CM.RecruitmentStatusId = @rRecruitmentStatusId) OR (@rRecruitmentStatusId = 0))	
			AND CM.OrgGroupID = @rOrgGroupID
			AND ((CONVERT(date,CM.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,CM.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
			ORDER BY CM.CandidateNumber
		END
END
GO
PRINT N'Altering [sStudent].[pRptStudentInformationFormGet]...';


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

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

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


GO
 
 
ALTER PROCEDURE [sTimetable].[pRptTimeTableProxyListGet]
	   
	  @rBatchId int,
	  @rEmployeeId bigint,
	  --@rDayId smallint,
	  --@rLectureNo smallint,
	  @rTimeTableSchemaId int,
	  @rProxyDate date,
	  @rBuilder1 nvarchar(max)='',
	  @rClassId int=0,
	  @rDivisionId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN    
	SELECT 	 
	--PS.Id AS ProxySettingId,
	Cm.Title+ '/'+DV.Title AS DivisionName,
	ISNULL(PS.EmployeeId,0) AS EmployeeId,
	ISNULL(PS.SubjectId,0) AS SubjectId,
	ISNULL(Em.FirstName,'') + ' '+ISNULL(em.LastName,'') AS ProxyEmployee,  
	ISNULL(SM.Title,'') AS ProxySubject,
	PS.DivisionId,
	ISNULL(PS.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),Ps.LectureNumber),'') AS DayLacture,
	ISNULL(SMT.Title,'') AS Subject,
	@rBuilder1 AS Builder,
    ISNULL(Em1.FirstName,'') + ' '+ISNULL(EM1.LastName,'') AS Teachername  ,
    EM1.Id As TeacherId,
    SMT.OrderIndex
	
	FROM 
	sTimetable.tProxySetting PS
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = PS.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = PS.EmployeeId
	INNER JOIN sCommon.tDayMaster DM ON DM.Id = PS.DayId
	INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = PS.DivisionId
	INNER JOIN sSetup.tClassMaster CM On CM.Id=DV.ClassId
    INNER JOIN sTimetable.tTimeTable TT  ON TT.Id=PS.TimeTableId AND PS.TimeTableSchemaId = TT.TimeTableSchemaId
    INNER JOIN sSetup.tSubjectMaster SMT ON SMT.Id = TT.SubjectId 
   INNER JOIN sHrm.tEmployeeMaster EM1  ON TT.EmployeeId=EM1.Id
  

	WHERE 
	    PS.BatchId = @rBatchId  AND  PS.TimeTableSchemaId =@rTimeTableSchemaId
	    AND PS.ProxyDate = @rProxyDate
	    AND ((TT.EmployeeId= @rEmployeeId) OR(@rEmployeeId=0))
	    AND((PS.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	     AND((DV.ClassId=@rClassId) OR (@rClassId=0))
		 AND  ISNULL(EM.IsOtherUser,0) = 0 AND  ISNULL(EM1.IsOtherUser,0) = 0
	END
GO
PRINT N'Creating [sAdmission].[pAdmissionCustomSearchGet]...';


GO
 
CREATE PROCEDURE [sAdmission].[pAdmissionCustomSearchGet]
	
	@rPageIndex int = null, 
	@rOrgId smallint,
	@rBatchId int,
	@rClassId int,
	@rClassIds nvarchar(max)='',
	@rFormNo nvarchar(max)='',
	@rFromFormNo nvarchar(max)='',
	@rToFormNo nvarchar(max)='',
	@rStatusId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rFatherName nvarchar(50)='',
	@rMotherName nvarchar(50)='',
	@rDOBFromDate Date = '',
	@rDOBToDate Date = '',
	@rDOAFromDate Date = '',
	@rDOAToDate Date = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rContactNo nvarchar(50) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rNationality nvarchar(max) = '',
	@rMotherTongue nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = ''
AS
BEGIN
 
	SET NOCOUNT ON;

   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 @rDOBToDate <> '9999-12-31'
		SET @rDOBToDate = DATEADD(d,1,@rDOBToDate)
	If @rDOAToDate <> '9999-12-31'
		SET @rDOAToDate = DATEADD(d,1,@rDOAToDate)

		SELECT * INTO #MyAdmissionSearchList
	FROM
	(SELECT OM.Title AS Organization, BM.Title AS Batch, AF.FormNo AS FormNo, AF.FirstName + ' '+  AF.LastName AS Name,CM.Title AS Class,
		SM.Title as Status, AF.Id as AdmissionId, AF.BatchId as BatchId,ROW_NUMBER() OVER (ORDER BY FormNo asc) as RowIndex
		from sAdmission.tAdmissionForm AF		
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		INNER JOIN  sCommon.tStatusMaster SM ON AF.StatusId = SM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFD ON AFD.AdmissionFormId = AF.Id
		WHERE ((AF.OrgId = @rOrgId ) OR (@rOrgId = 0))
				AND ((AF.BatchId = @rBatchId) OR (@rBatchId = 0))
				AND ((AF.ForClassId = @rClassId) OR (@rClassId = 0))
				AND ((ISNULL(AF.ForClassId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rClassIds,',')) OR (@rClassIds='')))
				AND ((AF.FormNo = @rFormNo) OR (@rFormNo = ''))
				AND ((AF.FormNo  >= @rFromFormNo) OR (ISNULL(@rFromFormNo,'') = ''))
				AND (( AF.FormNo  <= @rToFormNo) OR (ISNULL(@rToFormNo,'') = ''))
				AND (AF.StatusId = @rStatusId)
				AND ((AF.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
				AND ((AF.LastName Like @rLastName + '%') OR (@rLastName = ''))
				AND (( AF.DateOfBirth  >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
				AND (( AF.DateOfBirth  <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
				--AND (( CAST(AF.CreatedDateTime AS Date)  >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
				--AND (( CAST(AF.CreatedDateTime AS Date)  <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
				AND ((Convert(nvarchar(12),AF.CreatedDateTime) >=  @rDOAFromDate) OR (@rDOAFromDate=''))
				AND ((Convert(nvarchar(12),AF.CreatedDateTime) <=  @rDOAToDate) OR (@rDOAToDate=''))
				AND ((ISNULL(AF.Country,'') Like @rCountry + '%')OR(@rCountry = ''))
				AND ((ISNULL(AF.State,'') Like @rState + '%')OR(@rState = ''))
				AND ((ISNULL(AF.City,'') Like @rCity + '%')OR(@rCity = ''))
				AND ((AF.ContactNo=@rContactNo) OR (@rContactNo=0))
				AND (ISNULL(AF.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
				AND (ISNULL(AF.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
				AND (ISNULL(AF.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
				AND ((AF.Nationality Like '%' + @rNationality+ '%') OR (@rNationality = ''))
				AND (ISNULL(AF.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
				AND ((AF.MotherTongue Like '%' + @rMotherTongue+ '%') OR (@rMotherTongue = ''))
				AND ((AF.PreviousSchool Like '%' + @rPreviousSchool+ '%') OR (@rPreviousSchool = ''))
				AND ((AFD.FatherQualification Like '%' + @rFatherQualification+ '%') OR (@rFatherQualification = ''))
				AND ((AFD.MotherQualification Like '%' + @rMotherQualification+ '%') OR (@rMotherQualification = ''))
				AND ((AFD.FatherOccupation Like '%' + @rFatherOccupation+ '%') OR (@rFatherOccupation = ''))
				AND ((AFD.MotherOccupation Like '%' + @rMotherOccupation+ '%') OR (@rMotherOccupation = ''))
				) AS AdmissionCustomSearch

			select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
			print(@rPageIndex)
			declare @lTotalRecords int, @lPageSize int = 10, @lResult nvarchar(max) = '', @lPaging nvarchar(max) = ''
			select @lTotalRecords = COUNT(*) FROM #MyAdmissionSearchList
			print(@lTotalRecords)
			select @lPaging = dbo.fnc_SearchPagingFormat(@rPageIndex, @lTotalRecords, @lPageSize)
			print(@lPaging)
			
			Select *
			from #MyAdmissionSearchList
			WHERE RowIndex BETWEEN ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
			select @lPaging as Paging,@lTotalRecords as TotalRecords
END
GO
PRINT N'Creating [sAdmission].[pAdmissionGenerateReport]...';


GO
 
CREATE PROCEDURE [sAdmission].[pAdmissionGenerateReport]
 
	@rId bigint,
	@rClassId int,
	@rClassIds nvarchar(max)='',
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rFormNo [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rFatherName nvarchar(50)='',
	@rMotherName nvarchar(50)='',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rMotherTongue nvarchar(max) = '',
	@rNationality nvarchar(max) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9999-12-31',
	@rBatchId int,
	@rFromFormNo nvarchar(20), 
	@rToFormNo nvarchar(20),
	@rContactNo nvarchar(50) = '',
	@rReportName nvarchar(50) ='',
	@rPageIndex int,
	@rSavedReport nvarchar(50)='', 
	@rCreatedUserId bigint,
	@rIsCommon bit = 0,
	@rIsCommonForOrg bit = 0

AS
BEGIN
	 
	SET NOCOUNT ON;

    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 @rDOBToDate <> '9999-12-31'
		SET @rDOBToDate = DATEADD(d,1,@rDOBToDate)
	If @rDOAToDate <> '9999-12-31'
		SET @rDOAToDate = DATEADD(d,1,@rDOAToDate)
		
		IF(@rReportName != '' AND @rId = 0)
		BEGIN
			DECLARE @lNextNumber BIGINT 
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
			--PRINT(@lNextNumber)
			INSERT INTO sAdmission.tAdmissionCustomSearch
			(
				Id,Title,ColumnName,OrderBy,OrgId,BatchId, ClassId, FormNo, FromFormNo, ToFormNo,StatusId,ClassIds,FirstName,LastName,FatherName, 
				MotherName, DOBFromDate,DOBToDate,DOAFromDate,DOAToDate,Country,State,City,ContactNo,GenderId,ReligionId,CastCategoryId,
				Nationality,BloodGroupId,MotherTongueId,PreviousSchool,FatherQualification,MotherQualification,FatherOccupation,MotherOccupation,
				IsCommonUsers,IsCommonForOrg, CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
			)
			VALUES
			(
				@lNextNumber,@rReportName,@rColumnName,@rOrderBy,@rOrgId,@rBatchId,@rClassId,@rFormNo,@rFromFormNo,@rToFormNo,@rStatusId,@rClassIds,@rFirstName,@rLastName,
				@rFatherName,@rMotherName,@rDOBFromDate,@rDOBToDate,@rDOAFromDate,@rDOAToDate,@rCountry,@rState,
				@rCity,@rContactNo,@rGenderId,@rReligionId,@rCastCategoryId,@rNationality,@rBloodGroupId,@rMotherTongue,
				@rPreviousSchool,@rFatherQualification,@rMotherQualification,@rFatherOccupation,@rMotherOccupation,
				@rIsCommon,@rIsCommonForOrg,@rCreatedUserId,sCommon.fGetDate(),'',''
			)
		END

	SELECT * INTO #MyAdmissionSearchTable 
	FROM
	(SELECT  CASE 
			WHEN AF.BloodGroupId = 1 THEN 'A+'
			WHEN AF.BloodGroupId = 2 THEN 'A-'
			WHEN AF.BloodGroupId = 3 THEN 'B+'
			WHEN AF.BloodGroupId = 4 THEN 'B-'
			WHEN AF.BloodGroupId = 5 THEN 'O+'
			WHEN AF.BloodGroupId = 6 THEN 'O-'
			WHEN AF.BloodGroupId = 7 THEN 'AB+'
			WHEN AF.BloodGroupId = 8 THEN 'AB-'
			WHEN AF.BloodGroupId = 9 THEN '-'
		END AS BloodGroup, 
		CASE 
			WHEN AFD.LiveWithId = 1 THEN 'Both'
			WHEN AFD.LiveWithId = 2 THEN 'Father'
			WHEN AFD.LiveWithId = 3 THEN 'Mother'
			WHEN AFD.LiveWithId = 4 THEN 'Guardian'
		END AS LiveWith,
		CASE 
			WHEN AF.GenderId = 1 THEN 'Male'
			WHEN AF.GenderId = 2 THEN 'Female'
		END AS Gender,AF.Id,AF.FormNo as FormNo,AF.FirstName,AF.MiddleName,AF.LastName as SurName,AF.FirstName + ' '+  AF.LastName AS StudentName,AF.DateOfBirth,AF.OrgId,AF.BatchId,AF.StatusId,AF.StreetOne,AF.StreetTwo,AF.StreetThree,AF.Country,AF.State,AF.City,
	   AF.ZipCode,AF.ContactNo,AF.ContactEmail,AF.Remark,AF.PreviousSchool,AF.MeritMarks,AF.MeritGrade,AF.GenderId,AF.ReligionId,AF.FamilyCast,AF.FamilySubCast,AF.CastCategoryId,AF.StudentId,AF.FormPassword,AF.Nationality,AF.MotherTongue,
	   AF.IsPysicalDeformity,AF.PysicalDeformityRemark,AF.IsMajorIllness,AF.MajorIllnessRemark,AF.IsAllergy,AF.AllergyRemark,AF.BirthPlace,AF.BirthTaluka,AF.BirthDistrict,
	   AF.BloodGroupId,AF.AdhaarNumber,AF.BirthState,AF.BirthCountry,AF.OriginalStudentPhoto,AF.OtherInformation as OtherInformation,CASE WHEN AF.IsHostelRequired = 0 THEN 'No' WHEN AF.IsHostelRequired = 1 THEN 'Yes' END AS HostelRequired,
	   CASE WHEN AF.IsTransportRequired = 0 THEN 'No' WHEN AF.IsTransportRequired = 1 THEN 'Yes' END AS TransportRequired,OM.Title as Organization, OM.AffiliationId,BM.Title as Batch, BM.FromDate, BM.ToDate, SM.Title as Status,CM.Title as Class,RM.Title AS Religion,
	   APA1.AcademicYear as FatherAcademicYear,APA1.AdmissionClass as FatherAdmissionClass,APA1.InstituteName as FatherInstituteName,APA1.InstituteCity as FatherInstituteCity,APA1.InstituteAffiliaton as FatherInstituteAffiliation,APA1.Language as FatherMediumOfStudy,
	   APA2.AcademicYear as MotherAcademicYear,APA2.AdmissionClass as MotherAdmissionClass,APA2.InstituteName as MotherInstituteName,APA2.InstituteCity as MotherInstituteCity,APA2.InstituteAffiliaton as MotherInstituteAffiliation,APA2.Language as MotherMediumOfStudy,
	   APA3.AcademicYear as GuardianAcademicYear, APA3.AdmissionClass as GuardianAdmissionClass,APA3.InstituteName as GuardianInstituteName,APA3.InstituteCity as GuardianInstituteCity,APA3.InstituteAffiliaton as GuardianInstituteAffiliation,APA3.Language as GuardianMediumOfStudy,
	   RSM.Title,(STUFF((SELECT ',' + ReferenceDetail FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceDetail,(STUFF((SELECT ',' + ReferenceName FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceName,
	   (STUFF((SELECT ',' + ReferenceRelation FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceRelation,(STUFF((SELECT ',' + ReferenceContactNo FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceContactNo,
	   AFSA.AcademicYear as StudentAcademicYear,AFSA.AdmissionClass as StudentAdmissionClass,(STUFF((SELECT ',' + SiblingName FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingName,(STUFF((SELECT ',' + SiblingRelation FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingRelation,
	   (STUFF((SELECT ',' + SiblingStandard FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingStandard,(STUFF((SELECT ',' + SiblingSchool FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingSchool,
	   (STUFF((SELECT ',' + Code FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS Code,
	   AFSA.InstituteName as StudentInstituteName,AFSA.InstituteCity as StudentInstituteCity,AFSA.InstituteAffiliaton as StudentInstituteAffiliation, AFSA.Result, AFSA.Language,AFD.FatherName, AFD.FatherDateOfBirth,AFD.FatherOccupation,AFD.FatherQualification,AFD.FatherContactNo,AFD.FatherMail,
	   AFD.FatherOfficeAddress,AFD.FatherIncome,AFD.MotherName,AFD.MOtherDateOfBirth,AFD.MotherOccupation,AFD.MotherQualification,AFD.MotherContactNo,AFD.MotherMail,AFD.MotherOfficeAddress, AFD.MotherIncome,AFD.RelationshipName,AFD.RelativeName,AFD.RelativeDateOfBirth,
	   AFD.RelativeOccupation,AFD.RelativeQualification,AFD.RelativeContactNo,AFD.RelativeMail,AFD.RelativeOfficeAddress,AFD.RelativeIncome,AFD.FatherPhoto,AFD.MotherPhoto,AFD.RelativePhoto,AFD.FatherOrganization,AFD.FatherDesignation,AFD.FatherOfficePhone,
	   AFD.MotherOrganization,AFD.MotherDesignation,AFD.MotherOfficePhone,AFD.RelativeOrganization,AFD.RelativeDesignation,AFD.RelativeOfficePhone,AFD.IsFatherExStudent,AFD.FatherPassOutYear,AFD.IsMotherExStudent,
	   AFD.MotherPassOutYear, AFD.IsRelativeExStudent,AFD.RelativePassOutYear,AFD.FatherAdhaarNumber,AFD.OriginalFatherPhoto,AFD.OriginalMotherPhoto,AFD.OriginalRelativePhoto,AFD.MotherAadhaarNumber,AFD.RelativeAadhaarNumber
		from sAdmission.tAdmissionForm AF
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		INNER JOIN  sCommon.tStatusMaster SM ON AF.StatusId = SM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = AF.ReligionId
		LEFT JOIN sAdmission.tAdmissionFormParentAcademic APA1 ON APA1.AdmissionFormId = AF.Id AND APA1.RelationShipId = 1
		LEFT JOIN sAdmission.tAdmissionFormParentAcademic APA2 ON APA2.AdmissionFormId = AF.Id AND APA2.RelationShipId = 2
		LEFT JOIN sAdmission.tAdmissionFormParentAcademic APA3 ON APA3.AdmissionFormId = AF.Id AND APA3.RelationShipId = 7
		LEFT JOIN sCommon.tRelationshipMaster RSM ON RSM.Id = APA1.RelationshipId
		LEFT JOIN sCommon.tRelationshipMaster RSM1 ON RSM1.Id = APA2.RelationshipId
		LEFT JOIN sCommon.tRelationshipMaster RSM2 ON RSM2.Id = APA3.RelationshipId
		--LEFT JOIN sAdmission.tAdmissionFormReference AFR ON AFR.AdmissionFormId = AF.Id
		--LEFT JOIN sAdmission.tAdmissionFormSibling AFS ON AFS.AdmissionFormId = AF.Id
		LEFT JOIN sAdmission.tAdmissionFormStudentAcademic AFSA ON AFSA.AdmissionFormId = AF.Id
		LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFD ON AFD.AdmissionFormId = AF.Id
		WHERE ((AF.OrgId = @rOrgId ) OR (@rOrgId = 0))
				AND ((AF.BatchId = @rBatchId) OR (@rBatchId = 0))
				AND ((AF.ForClassId = @rClassId) OR (@rClassId = 0))
			    AND ((ISNULL(AF.ForClassId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rClassIds,',')) OR (@rClassIds='')))
				AND ((AF.FormNo = @rFormNo) OR (@rFormNo = ''))
				AND ((AF.FormNo  >= @rFromFormNo) OR (ISNULL(@rFromFormNo,'') = ''))
				AND ((AF.FormNo  <= @rToFormNo) OR (ISNULL(@rToFormNo,'') = ''))
			    AND (AF.StatusId = @rStatusId)
				AND ((AF.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
				AND ((AF.LastName Like @rLastName + '%')OR(@rLastName = ''))
				AND (( AF.DateOfBirth  >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
				AND (( AF.DateOfBirth  <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
				--AND (( CAST(AF.CreatedDateTime AS Date)  >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
				--AND (( CAST(AF.CreatedDateTime AS Date)  <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
				AND ((Convert(nvarchar(12),AF.CreatedDateTime) >=  @rDOAFromDate) OR (@rDOAFromDate=''))
			    AND ((Convert(nvarchar(12),AF.CreatedDateTime) <=  @rDOAToDate) OR (@rDOAToDate=''))
				AND ((ISNULL(AF.Country,'') Like @rCountry + '%')OR(@rCountry = ''))
				AND ((ISNULL(AF.State,'') Like @rState + '%')OR(@rState = ''))
				AND ((ISNULL(AF.City,'') Like @rCity + '%')OR(@rCity = ''))
				AND ((AF.ContactNo=@rContactNo) OR (@rContactNo=0))
				AND (ISNULL(AF.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
				AND (ISNULL(AF.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
				AND (ISNULL(AF.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
				AND ((AF.Nationality Like '%' + @rNationality+ '%') OR (@rNationality = ''))
				AND (ISNULL(AF.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
				AND ((AF.MotherTongue Like '%' + @rMotherTongue+ '%') OR (@rMotherTongue = ''))
				AND ((AF.PreviousSchool Like '%' + @rPreviousSchool+ '%') OR (@rPreviousSchool = ''))
				AND ((AFD.FatherQualification Like '%' + @rFatherQualification+ '%') OR (@rFatherQualification = ''))
				AND ((AFD.MotherQualification Like '%' + @rMotherQualification+ '%') OR (@rMotherQualification = ''))
				AND ((AFD.FatherOccupation Like '%' + @rFatherOccupation+ '%') OR (@rFatherOccupation = ''))
				AND ((AFD.MotherOccupation Like '%' + @rMotherOccupation+ '%') OR (@rMotherOccupation = '')) 
				) AS AdmissionReportGeneration

		--SELECT * FROM #MyAdmissionSearchTable
	

		Declare @lSQL nvarchar(max) =''
		if (@rOrderBy = '' OR @rOrderBy = NULL)
			SET @lSQL = @lSQL + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable '
		else 
		SET @lSQL = @lSQL + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable GROUP BY ' +@rColumnName+ ' ORDER BY ' +@rOrderBy+ ';'
		print(@lSQL)
		exec (@lSQL)

		DROP TABLE #MyAdmissionSearchTable 
END
GO
PRINT N'Creating [sAttendance].[pRptDailyStatusGet]...';


GO
 

CREATE PROCEDURE [sAttendance].[pRptDailyStatusGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint = 0,
	 @rBatchId int = 0,
	 @rClassId int = 0,
	 @rDivisionId int = 0,
	 @rAttendanceTypeId tinyint = 1,	 
	 @rFromDate date = '',
	 @rToDate date = '',	 
	 @rDepartmentId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	-- *Start - for Report data set refresh do not delete
	--SELECT
	--'' AS AttendanceDate,
	--'' AS Builder1,
	--'' AS Builder2,
	--	'' AS ClassDivisionName,
	--	'' AS ClassTeacherName,
	--	'' AS WeekOffStatus,
	--	'' AS PresentStatus,
	--	0 AS TotalCount,
	--	0 AS PresentCount,
	--	0 AS AbsentCount,
	--	'' AS UpdatedDateTime
	--End  *
	
	DECLARE @lSearchDate date = ''
	DECLARE @lYear smallint = ''
	DECLARE @lMonth smallint = ''
	DECLARE @lDate smallint = ''

	CREATE TABLE #TempDates (AttendanceDate date, DivisionId int)
	WHILE @rFromDate <= @rToDate
	BEGIN 
		INSERT INTO #TempDates VALUES (@rFromDate, @rDivisionId)
		SET @rFromDate = DATEADD(DD, 1, @rFromDate)
	END

	SET @lYear = YEAR(@rFromDate)
	SET @lMonth = MONTH(@rFromDate)
	SET @lDate = DAY(@rFromDate)
	SET @lSearchDate = @rFromDate

	SELECT
			T.AttendanceDate, 			
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,	
			vCD.ClassDivisionName,
			ISNULL(EM.FirstName+' '+ EM.LastName,'') AS ClassTeacherName,
			[sAttendance].[fWeekHOffGet](YEAR(T.AttendanceDate),MONTH(T.AttendanceDate),DAY(T.AttendanceDate),@rBatchId,A.ClassId,A.DivisionId,'',@rOrgId) AS WeekOffStatus, 
			CASE WHEN COUNT(SR.AcademicId)=0 THEN CASE WHEN (Select [sCommon].[fCountAbsentStudent](A.DivisionId,  @rBatchId,T.AttendanceDate,@rAttendanceTypeId,0)) =0 THEN 'Pending' ELSE 'Complete' END ELSE 'Complete' END AS PresentStatus, 
            sCommon.fCountDivisionStudent(A.DivisionId,@rBatchId) AS TotalCount, 
            [sCommon].[fCountAbsentStudent](A.DivisionId,@rBatchId,T.AttendanceDate,@rAttendanceTypeId,1) AS PresentCount,
            [sCommon].[fCountAbsentStudent](A.DivisionId,@rBatchId,T.AttendanceDate,@rAttendanceTypeId,0) AS AbsentCount,
			ISNULL(MAX(SR.UpdatedDateTime),MAX(SR.CreatedDateTime)) as UpdatedDateTime
    FROM 
			#TempDates T
			INNER JOIN sStudent.tAcademic A ON A.DivisionId = T.DivisionId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId AND SM.StatusId=1 
			INNER JOIN sSetup.vClassDivision vCD ON vCD.ClassId=A.ClassId 
            AND vCD.DivisionId=A.DivisionId AND A.OrgId=vCD.OrgId AND A.OrgId=@rOrgId AND A.BatchId=@rBatchId AND vCD.IsObsolete=0 
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = vCD.DivisionId 
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            LEFT JOIN sAttendance.tStudentRegister SR ON A.Id = SR.AcademicId AND SR.AttendanceDate=T.AttendanceDate 
            AND SR.AttendanceTypeId = @rAttendanceTypeId 
			AND SR.IsPresent=1 
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND (vCD.ClassId = @rClassId)
			AND (vCD.DivisionId = @rDivisionId)
            GROUP BY A.DivisionId,A.BatchId,vCD.ClassDivisionName,vCD.OrderIndex,EM.FirstName,EM.LastName,SM.StatusId,A.ClassId,T.AttendanceDate
            ORDER BY vCD.OrderIndex		
			
	
END
GO
 
 
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('21.12.03',211203,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO